{"record":{"id":"5cd17c2f780ba250","repo":"mastra-ai/mastra","slug":"failed-to-parse-existing-package-json-at-targetp","errorCode":null,"errorMessage":"Failed to parse existing package.json at ${targetPkgPath}: ${e instanceof Error ? e.message : String(e)}","messagePattern":"Failed to parse existing package\\.json at (.+?): (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/agent-builder/src/workflows/template-builder/template-builder.ts","lineNumber":405,"sourceCode":"    console.info('Package merge step starting...');\n    const { slug, packageInfo } = inputData;\n    const targetPath = resolveTargetPath(inputData, requestContext);\n\n    try {\n      const targetPkgPath = join(targetPath, 'package.json');\n\n      let targetPkgRaw = '{}';\n      try {\n        targetPkgRaw = await readFile(targetPkgPath, 'utf-8');\n      } catch {\n        console.warn(`No existing package.json at ${targetPkgPath}, creating a new one`);\n      }\n\n      let targetPkg: any;\n      try {\n        targetPkg = JSON.parse(targetPkgRaw || '{}');\n      } catch (e) {\n        throw new Error(\n          `Failed to parse existing package.json at ${targetPkgPath}: ${e instanceof Error ? e.message : String(e)}`,\n        );\n      }\n\n      const ensureObj = (o: any) => (o && typeof o === 'object' ? o : {});\n\n      targetPkg.dependencies = ensureObj(targetPkg.dependencies);\n      targetPkg.devDependencies = ensureObj(targetPkg.devDependencies);\n      targetPkg.peerDependencies = ensureObj(targetPkg.peerDependencies);\n      targetPkg.scripts = ensureObj(targetPkg.scripts);\n\n      const tplDeps = ensureObj(packageInfo.dependencies);\n      const tplDevDeps = ensureObj(packageInfo.devDependencies);\n      const tplPeerDeps = ensureObj(packageInfo.peerDependencies);\n      const tplScripts = ensureObj(packageInfo.scripts);\n\n      const existsAnywhere = (name: string) =>\n        name in targetPkg.dependencies || name in targetPkg.devDependencies || name in targetPkg.peerDependencies;","sourceCodeStart":387,"sourceCodeEnd":423,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/agent-builder/src/workflows/template-builder/template-builder.ts#L387-L423","documentation":"The template-builder workflow attempted to JSON.parse an existing package.json found in the cloned template directory, but the file content is not valid JSON. This error wraps the underlying parse exception and includes the file path plus the original JSON.parse message (e.g. 'Unexpected token ... in JSON at position N') so you can locate the malformed syntax.","triggerScenarios":"The template repository being cloned contains a package.json with syntax errors: trailing commas, comments, BOM characters, truncated files (bad commit/partial checkout), or a non-JSON placeholder file at that path. JSON.parse(targetPkgRaw || '{}') only falls back when the file is empty, not when it is invalid.","commonSituations":"Cloning a hand-edited or generated template whose package.json was written with comments (JSON5/JSONC), a tool wrote a corrupt file, a git LFS/partial clone truncated it, or the wrong file (e.g. an error page) ended up at the path.","solutions":["Open the package.json at the path named in the error and fix the JSON syntax at the position given in the wrapped JSON.parse message","Validate the template's package.json with a linter (node -e 'JSON.parse(require(\"fs\").readFileSync(\"package.json\",\"utf8\"))') before publishing the template","Re-clone the template repository to rule out a truncated/partial checkout","If the template legitimately uses JSONC, convert it to strict JSON or pre-process comments out before parse"],"exampleFix":"// before (template package.json)\n{ \"name\": \"tmpl\", \"version\": \"1.0.0\", }\n// after\n{ \"name\": \"tmpl\", \"version\": \"1.0.0\" }","handlingStrategy":"validation","validationCode":"import { readFileSync } from 'node:fs';\nexport function assertValidJsonFile(path: string) {\n  const raw = readFileSync(path, 'utf8').replace(/^\\uFEFF/, '');\n  try { JSON.parse(raw); } catch (e) {\n    throw new Error(`${path} is not valid JSON: ${e instanceof Error ? e.message : e}`);\n  }\n}\n// run against the template's package.json before invoking the template-builder workflow","typeGuard":"export function isParseableJson(raw: string): boolean {\n  try { JSON.parse(raw); return true; } catch { return false; }\n}","tryCatchPattern":"try {\n  await templateBuilderWorkflow.start(...);\n} catch (e) {\n  if (e instanceof Error && e.message.includes('Failed to parse existing package.json')) {\n    // surface path+parse detail to the template author\n  }\n  throw e;\n}","preventionTips":["Validate every template's package.json in CI before publishing the template","Strip BOM and disallow comments/trailing commas (strict JSON only)","Commit generated package.json via tooling, never hand-edits without a JSON lint step","Re-clone and verify templates after ref bumps to catch truncated checkouts"],"tags":["json","parse","template-builder","filesystem"],"backgroundTag":"json-parse-failed","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}