mastra-ai/mastra · error

Failed to parse existing package.json at ${targetPkgPath}: $

Error message

Failed to parse existing package.json at ${targetPkgPath}: ${e instanceof Error ? e.message : String(e)}

What it means

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.

Source

Thrown at packages/agent-builder/src/workflows/template-builder/template-builder.ts:405

    console.info('Package merge step starting...');
    const { slug, packageInfo } = inputData;
    const targetPath = resolveTargetPath(inputData, requestContext);

    try {
      const targetPkgPath = join(targetPath, 'package.json');

      let targetPkgRaw = '{}';
      try {
        targetPkgRaw = await readFile(targetPkgPath, 'utf-8');
      } catch {
        console.warn(`No existing package.json at ${targetPkgPath}, creating a new one`);
      }

      let targetPkg: any;
      try {
        targetPkg = JSON.parse(targetPkgRaw || '{}');
      } catch (e) {
        throw new Error(
          `Failed to parse existing package.json at ${targetPkgPath}: ${e instanceof Error ? e.message : String(e)}`,
        );
      }

      const ensureObj = (o: any) => (o && typeof o === 'object' ? o : {});

      targetPkg.dependencies = ensureObj(targetPkg.dependencies);
      targetPkg.devDependencies = ensureObj(targetPkg.devDependencies);
      targetPkg.peerDependencies = ensureObj(targetPkg.peerDependencies);
      targetPkg.scripts = ensureObj(targetPkg.scripts);

      const tplDeps = ensureObj(packageInfo.dependencies);
      const tplDevDeps = ensureObj(packageInfo.devDependencies);
      const tplPeerDeps = ensureObj(packageInfo.peerDependencies);
      const tplScripts = ensureObj(packageInfo.scripts);

      const existsAnywhere = (name: string) =>
        name in targetPkg.dependencies || name in targetPkg.devDependencies || name in targetPkg.peerDependencies;

View on GitHub (pinned to 75dd419e61)

Solutions

  1. 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
  2. Validate the template's package.json with a linter (node -e 'JSON.parse(require("fs").readFileSync("package.json","utf8"))') before publishing the template
  3. Re-clone the template repository to rule out a truncated/partial checkout
  4. If the template legitimately uses JSONC, convert it to strict JSON or pre-process comments out before parse

Example fix

// before (template package.json)
{ "name": "tmpl", "version": "1.0.0", }
// after
{ "name": "tmpl", "version": "1.0.0" }
Defensive patterns

Strategy: validation

Validate before calling

import { readFileSync } from 'node:fs';
export function assertValidJsonFile(path: string) {
  const raw = readFileSync(path, 'utf8').replace(/^\uFEFF/, '');
  try { JSON.parse(raw); } catch (e) {
    throw new Error(`${path} is not valid JSON: ${e instanceof Error ? e.message : e}`);
  }
}
// run against the template's package.json before invoking the template-builder workflow

Type guard

export function isParseableJson(raw: string): boolean {
  try { JSON.parse(raw); return true; } catch { return false; }
}

Try / catch

try {
  await templateBuilderWorkflow.start(...);
} catch (e) {
  if (e instanceof Error && e.message.includes('Failed to parse existing package.json')) {
    // surface path+parse detail to the template author
  }
  throw e;
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Understand the failure class

Related errors


AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30). Data as JSON: /api/errors/5cd17c2f780ba250. Report an issue: GitHub.