{"record":{"id":"311657edbfded8ba","repo":"yamadashy/repomix","slug":"failed-to-generate-json-output-error-instanceof","errorCode":null,"errorMessage":"Failed to generate JSON output: ${error instanceof Error ? error.message : 'Unknown error'}","messagePattern":"Failed to generate JSON output: (.+?)","errorType":"exception","errorClass":"RepomixError","httpStatus":null,"severity":"error","filePath":"src/core/output/outputGenerate.ts","lineNumber":222,"sourceCode":"        staged: renderContext.gitDiffStaged,\n      },\n    }),\n    ...(renderContext.gitLogEnabled && {\n      gitLogs: renderContext.gitLogCommits?.map((commit) => ({\n        date: commit.date,\n        message: commit.message,\n        files: commit.files,\n      })),\n    }),\n    ...(renderContext.instruction && {\n      instruction: renderContext.instruction,\n    }),\n  };\n\n  try {\n    return JSON.stringify(jsonDocument, null, 2);\n  } catch (error) {\n    throw new RepomixError(\n      `Failed to generate JSON output: ${error instanceof Error ? error.message : 'Unknown error'}`,\n      error instanceof Error ? { cause: error } : undefined,\n    );\n  }\n};\n\nconst generateHandlebarOutput = async (\n  config: RepomixConfigMerged,\n  renderContext: RenderContext,\n  processedFiles?: ProcessedFile[],\n): Promise<string> => {\n  try {\n    const compiledTemplate = getCompiledTemplate(config.output.style);\n    return `${compiledTemplate(renderContext).trim()}\\n`;\n  } catch (error) {\n    if (error instanceof RangeError && error.message === 'Invalid string length') {\n      let largeFilesInfo = '';\n      if (processedFiles && processedFiles.length > 0) {","sourceCodeStart":204,"sourceCodeEnd":240,"githubUrl":"https://github.com/yamadashy/repomix/blob/f465ad909315a22120636baf03fa5e28701a50cb/src/core/output/outputGenerate.ts#L204-L240","documentation":"JSON.stringify threw while serializing the assembled jsonDocument, so Repomix rethrows as this RepomixError with the original error as `cause`. The usual underlying reason is a circular reference or BigInt value in the document tree.","triggerScenarios":"generateParsableJsonOutput(renderContext) builds a document containing a value JSON.stringify cannot handle (circular structure, BigInt, unstable objects) and the stringify call throws.","commonSituations":"Programmatic use where renderContext/file metadata contains circular references (e.g. objects referencing parents); custom file processors injecting BigInt sizes; upstream bugs in metadata assembly.","solutions":["Inspect `error.cause` — circular structure usually names the offending object path.","Ensure any custom file data merged into the output contains only JSON-safe values (no BigInt/circular refs).","Update repomix if triggered by stock config — report it as a bug.","Pre-sanitize: JSON.parse(JSON.stringify(payload)) or use a safe-stringify helper for custom data."],"exampleFix":"// before\nfile.metadata.parent = filesRoot; // circular\n// after\ndelete file.metadata.parent; // keep document JSON-safe","handlingStrategy":"try-catch","validationCode":"function assertJsonSafe(obj: unknown, seen = new Set()): void {\n  if (obj && typeof obj === 'object') {\n    if (seen.has(obj)) throw new Error('Circular reference');\n    seen.add(obj);\n    for (const v of Object.values(obj)) assertJsonSafe(v, seen);\n  } else if (typeof obj === 'bigint') throw new Error('BigInt not JSON-safe');\n}","typeGuard":"const isJsonSafe = (v: unknown, seen = new Set()): boolean => {\n  if (typeof v === 'bigint') return false;\n  if (v && typeof v === 'object') {\n    if (seen.has(v)) return false;\n    seen.add(v);\n    return Object.values(v).every(x => isJsonSafe(x, seen));\n  }\n  return true;\n};","tryCatchPattern":"try {\n  const json = await generateOutput({ ...config, output: { ...config.output, style: 'json' } }, ctx);\n} catch (e) {\n  if (e instanceof RepomixError && e.message.startsWith('Failed to generate JSON output')) {\n    console.error('JSON build failed:', (e as { cause?: Error }).cause?.message);\n  }\n}","preventionTips":["Never attach circular or BigInt values to render context/file metadata.","Sanitize custom data with a safe-stringify step before generation.","Inspect error.cause to find the offending field.","Report stock-config occurrences upstream as bugs."],"tags":["json","output","serialization"],"backgroundTag":"json-stringify-failed","analyzedSha":"f465ad909315a22120636baf03fa5e28701a50cb","analyzedAt":"2026-08-29T01:27:42.024Z","schemaVersion":2},"datasetVersion":"2026-08-29T02:17:18.158Z"}