@iroaxel/arcena 4.3.157 → 4.3.159

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -4,9 +4,9 @@ import {
4
4
  GGBoss,
5
5
  Worker,
6
6
  buildBossSystemPrompt
7
- } from "./chunk-OWJSBNAJ.js";
8
- import "./chunk-KZJPLEZU.js";
9
- import "./chunk-YKKUCYNE.js";
7
+ } from "./chunk-3OUGQLYU.js";
8
+ import "./chunk-BRK5DUUL.js";
9
+ import "./chunk-JJAPXAWB.js";
10
10
  import {
11
11
  init_esm_shims
12
12
  } from "./chunk-YNWFCUMR.js";
@@ -3,12 +3,12 @@ import {
3
3
  fetchPixelEntries,
4
4
  listAllErrors,
5
5
  runPixelInstall
6
- } from "./chunk-KZJPLEZU.js";
7
- import "./chunk-YKKUCYNE.js";
6
+ } from "./chunk-BRK5DUUL.js";
7
+ import "./chunk-JJAPXAWB.js";
8
8
  import "./chunk-YNWFCUMR.js";
9
9
  export {
10
10
  fetchPixelEntries,
11
11
  listAllErrors,
12
12
  runPixelInstall
13
13
  };
14
- //# sourceMappingURL=pixel-I5TTXQ4I.js.map
14
+ //# sourceMappingURL=pixel-6SQS5RZ6.js.map
@@ -2,7 +2,7 @@ import { createRequire as __createRequire } from "node:module"; const require =
2
2
  import {
3
3
  DEFAULT_INGEST_URL,
4
4
  source_default
5
- } from "./chunk-YKKUCYNE.js";
5
+ } from "./chunk-JJAPXAWB.js";
6
6
  import {
7
7
  init_esm_shims
8
8
  } from "./chunk-YNWFCUMR.js";
@@ -938,4 +938,4 @@ export {
938
938
  preparePixelFix,
939
939
  runQueue
940
940
  };
941
- //# sourceMappingURL=pixel-fix-UIPF4UIQ.js.map
941
+ //# sourceMappingURL=pixel-fix-GYPVA5LT.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iroaxel/arcena",
3
- "version": "4.3.157",
3
+ "version": "4.3.159",
4
4
  "type": "module",
5
5
  "description": "Orchestrator agent that drives multiple arcicoder sessions across projects from a single chat",
6
6
  "license": "MIT",
@@ -33,7 +33,7 @@
33
33
  "zod": "^4.4.3",
34
34
  "@iroaxel/gg-agent": "4.3.166",
35
35
  "@iroaxel/gg-ai": "4.3.166",
36
- "@iroaxel/arcicoder": "4.3.166"
36
+ "@iroaxel/arcicoder": "4.3.168"
37
37
  },
38
38
  "optionalDependencies": {
39
39
  "@huggingface/transformers": "^3.6.0",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/index.js","../../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/ansi-styles/index.js","../../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/vendor/supports-color/index.js","../../../node_modules/.pnpm/chalk@5.6.2/node_modules/chalk/source/utilities.js","../../gg-pixel/src/adapters/node.ts","../../gg-pixel/src/core/stack.ts","../../gg-pixel/src/core/fingerprint.ts","../../gg-pixel/src/code-context.ts","../../gg-pixel/src/core/queue.ts","../../gg-pixel/src/core/sinks/node-http.ts","../../gg-pixel/src/core/sinks/http.ts","../../gg-pixel/src/core/sinks/local-sqlite.ts","../../gg-pixel/src/install.ts","../../gg-pixel/src/verify.ts","../../gg-pixel/src/index.ts"],"sourcesContent":["import ansiStyles from '#ansi-styles';\nimport supportsColor from '#supports-color';\nimport { // eslint-disable-line import/order\n\tstringReplaceAll,\n\tstringEncaseCRLFWithFirstIndex,\n} from './utilities.js';\n\nconst {stdout: stdoutColor, stderr: stderrColor} = supportsColor;\n\nconst GENERATOR = Symbol('GENERATOR');\nconst STYLER = Symbol('STYLER');\nconst IS_EMPTY = Symbol('IS_EMPTY');\n\n// `supportsColor.level` → `ansiStyles.color[name]` mapping\nconst levelMapping = [\n\t'ansi',\n\t'ansi',\n\t'ansi256',\n\t'ansi16m',\n];\n\nconst styles = Object.create(null);\n\nconst applyOptions = (object, options = {}) => {\n\tif (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {\n\t\tthrow new Error('The `level` option should be an integer from 0 to 3');\n\t}\n\n\t// Detect level if not set manually\n\tconst colorLevel = stdoutColor ? stdoutColor.level : 0;\n\tobject.level = options.level === undefined ? colorLevel : options.level;\n};\n\nexport class Chalk {\n\tconstructor(options) {\n\t\t// eslint-disable-next-line no-constructor-return\n\t\treturn chalkFactory(options);\n\t}\n}\n\nconst chalkFactory = options => {\n\tconst chalk = (...strings) => strings.join(' ');\n\tapplyOptions(chalk, options);\n\n\tObject.setPrototypeOf(chalk, createChalk.prototype);\n\n\treturn chalk;\n};\n\nfunction createChalk(options) {\n\treturn chalkFactory(options);\n}\n\nObject.setPrototypeOf(createChalk.prototype, Function.prototype);\n\nfor (const [styleName, style] of Object.entries(ansiStyles)) {\n\tstyles[styleName] = {\n\t\tget() {\n\t\t\tconst builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);\n\t\t\tObject.defineProperty(this, styleName, {value: builder});\n\t\t\treturn builder;\n\t\t},\n\t};\n}\n\nstyles.visible = {\n\tget() {\n\t\tconst builder = createBuilder(this, this[STYLER], true);\n\t\tObject.defineProperty(this, 'visible', {value: builder});\n\t\treturn builder;\n\t},\n};\n\nconst getModelAnsi = (model, level, type, ...arguments_) => {\n\tif (model === 'rgb') {\n\t\tif (level === 'ansi16m') {\n\t\t\treturn ansiStyles[type].ansi16m(...arguments_);\n\t\t}\n\n\t\tif (level === 'ansi256') {\n\t\t\treturn ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_));\n\t\t}\n\n\t\treturn ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_));\n\t}\n\n\tif (model === 'hex') {\n\t\treturn getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_));\n\t}\n\n\treturn ansiStyles[type][model](...arguments_);\n};\n\nconst usedModels = ['rgb', 'hex', 'ansi256'];\n\nfor (const model of usedModels) {\n\tstyles[model] = {\n\t\tget() {\n\t\t\tconst {level} = this;\n\t\t\treturn function (...arguments_) {\n\t\t\t\tconst styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]);\n\t\t\t\treturn createBuilder(this, styler, this[IS_EMPTY]);\n\t\t\t};\n\t\t},\n\t};\n\n\tconst bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);\n\tstyles[bgModel] = {\n\t\tget() {\n\t\t\tconst {level} = this;\n\t\t\treturn function (...arguments_) {\n\t\t\t\tconst styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]);\n\t\t\t\treturn createBuilder(this, styler, this[IS_EMPTY]);\n\t\t\t};\n\t\t},\n\t};\n}\n\nconst proto = Object.defineProperties(() => {}, {\n\t...styles,\n\tlevel: {\n\t\tenumerable: true,\n\t\tget() {\n\t\t\treturn this[GENERATOR].level;\n\t\t},\n\t\tset(level) {\n\t\t\tthis[GENERATOR].level = level;\n\t\t},\n\t},\n});\n\nconst createStyler = (open, close, parent) => {\n\tlet openAll;\n\tlet closeAll;\n\tif (parent === undefined) {\n\t\topenAll = open;\n\t\tcloseAll = close;\n\t} else {\n\t\topenAll = parent.openAll + open;\n\t\tcloseAll = close + parent.closeAll;\n\t}\n\n\treturn {\n\t\topen,\n\t\tclose,\n\t\topenAll,\n\t\tcloseAll,\n\t\tparent,\n\t};\n};\n\nconst createBuilder = (self, _styler, _isEmpty) => {\n\t// Single argument is hot path, implicit coercion is faster than anything\n\t// eslint-disable-next-line no-implicit-coercion\n\tconst builder = (...arguments_) => applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));\n\n\t// We alter the prototype because we must return a function, but there is\n\t// no way to create a function with a different prototype\n\tObject.setPrototypeOf(builder, proto);\n\n\tbuilder[GENERATOR] = self;\n\tbuilder[STYLER] = _styler;\n\tbuilder[IS_EMPTY] = _isEmpty;\n\n\treturn builder;\n};\n\nconst applyStyle = (self, string) => {\n\tif (self.level <= 0 || !string) {\n\t\treturn self[IS_EMPTY] ? '' : string;\n\t}\n\n\tlet styler = self[STYLER];\n\n\tif (styler === undefined) {\n\t\treturn string;\n\t}\n\n\tconst {openAll, closeAll} = styler;\n\tif (string.includes('\\u001B')) {\n\t\twhile (styler !== undefined) {\n\t\t\t// Replace any instances already present with a re-opening code\n\t\t\t// otherwise only the part of the string until said closing code\n\t\t\t// will be colored, and the rest will simply be 'plain'.\n\t\t\tstring = stringReplaceAll(string, styler.close, styler.open);\n\n\t\t\tstyler = styler.parent;\n\t\t}\n\t}\n\n\t// We can move both next actions out of loop, because remaining actions in loop won't have\n\t// any/visible effect on parts we add here. Close the styling before a linebreak and reopen\n\t// after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92\n\tconst lfIndex = string.indexOf('\\n');\n\tif (lfIndex !== -1) {\n\t\tstring = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);\n\t}\n\n\treturn openAll + string + closeAll;\n};\n\nObject.defineProperties(createChalk.prototype, styles);\n\nconst chalk = createChalk();\nexport const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0});\n\nexport {\n\tmodifierNames,\n\tforegroundColorNames,\n\tbackgroundColorNames,\n\tcolorNames,\n\n\t// TODO: Remove these aliases in the next major version\n\tmodifierNames as modifiers,\n\tforegroundColorNames as foregroundColors,\n\tbackgroundColorNames as backgroundColors,\n\tcolorNames as colors,\n} from './vendor/ansi-styles/index.js';\n\nexport {\n\tstdoutColor as supportsColor,\n\tstderrColor as supportsColorStderr,\n};\n\nexport default chalk;\n","const ANSI_BACKGROUND_OFFSET = 10;\n\nconst wrapAnsi16 = (offset = 0) => code => `\\u001B[${code + offset}m`;\n\nconst wrapAnsi256 = (offset = 0) => code => `\\u001B[${38 + offset};5;${code}m`;\n\nconst wrapAnsi16m = (offset = 0) => (red, green, blue) => `\\u001B[${38 + offset};2;${red};${green};${blue}m`;\n\nconst styles = {\n\tmodifier: {\n\t\treset: [0, 0],\n\t\t// 21 isn't widely supported and 22 does the same thing\n\t\tbold: [1, 22],\n\t\tdim: [2, 22],\n\t\titalic: [3, 23],\n\t\tunderline: [4, 24],\n\t\toverline: [53, 55],\n\t\tinverse: [7, 27],\n\t\thidden: [8, 28],\n\t\tstrikethrough: [9, 29],\n\t},\n\tcolor: {\n\t\tblack: [30, 39],\n\t\tred: [31, 39],\n\t\tgreen: [32, 39],\n\t\tyellow: [33, 39],\n\t\tblue: [34, 39],\n\t\tmagenta: [35, 39],\n\t\tcyan: [36, 39],\n\t\twhite: [37, 39],\n\n\t\t// Bright color\n\t\tblackBright: [90, 39],\n\t\tgray: [90, 39], // Alias of `blackBright`\n\t\tgrey: [90, 39], // Alias of `blackBright`\n\t\tredBright: [91, 39],\n\t\tgreenBright: [92, 39],\n\t\tyellowBright: [93, 39],\n\t\tblueBright: [94, 39],\n\t\tmagentaBright: [95, 39],\n\t\tcyanBright: [96, 39],\n\t\twhiteBright: [97, 39],\n\t},\n\tbgColor: {\n\t\tbgBlack: [40, 49],\n\t\tbgRed: [41, 49],\n\t\tbgGreen: [42, 49],\n\t\tbgYellow: [43, 49],\n\t\tbgBlue: [44, 49],\n\t\tbgMagenta: [45, 49],\n\t\tbgCyan: [46, 49],\n\t\tbgWhite: [47, 49],\n\n\t\t// Bright color\n\t\tbgBlackBright: [100, 49],\n\t\tbgGray: [100, 49], // Alias of `bgBlackBright`\n\t\tbgGrey: [100, 49], // Alias of `bgBlackBright`\n\t\tbgRedBright: [101, 49],\n\t\tbgGreenBright: [102, 49],\n\t\tbgYellowBright: [103, 49],\n\t\tbgBlueBright: [104, 49],\n\t\tbgMagentaBright: [105, 49],\n\t\tbgCyanBright: [106, 49],\n\t\tbgWhiteBright: [107, 49],\n\t},\n};\n\nexport const modifierNames = Object.keys(styles.modifier);\nexport const foregroundColorNames = Object.keys(styles.color);\nexport const backgroundColorNames = Object.keys(styles.bgColor);\nexport const colorNames = [...foregroundColorNames, ...backgroundColorNames];\n\nfunction assembleStyles() {\n\tconst codes = new Map();\n\n\tfor (const [groupName, group] of Object.entries(styles)) {\n\t\tfor (const [styleName, style] of Object.entries(group)) {\n\t\t\tstyles[styleName] = {\n\t\t\t\topen: `\\u001B[${style[0]}m`,\n\t\t\t\tclose: `\\u001B[${style[1]}m`,\n\t\t\t};\n\n\t\t\tgroup[styleName] = styles[styleName];\n\n\t\t\tcodes.set(style[0], style[1]);\n\t\t}\n\n\t\tObject.defineProperty(styles, groupName, {\n\t\t\tvalue: group,\n\t\t\tenumerable: false,\n\t\t});\n\t}\n\n\tObject.defineProperty(styles, 'codes', {\n\t\tvalue: codes,\n\t\tenumerable: false,\n\t});\n\n\tstyles.color.close = '\\u001B[39m';\n\tstyles.bgColor.close = '\\u001B[49m';\n\n\tstyles.color.ansi = wrapAnsi16();\n\tstyles.color.ansi256 = wrapAnsi256();\n\tstyles.color.ansi16m = wrapAnsi16m();\n\tstyles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);\n\tstyles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);\n\n\t// From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js\n\tObject.defineProperties(styles, {\n\t\trgbToAnsi256: {\n\t\t\tvalue(red, green, blue) {\n\t\t\t\t// We use the extended greyscale palette here, with the exception of\n\t\t\t\t// black and white. normal palette only has 4 greyscale shades.\n\t\t\t\tif (red === green && green === blue) {\n\t\t\t\t\tif (red < 8) {\n\t\t\t\t\t\treturn 16;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (red > 248) {\n\t\t\t\t\t\treturn 231;\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Math.round(((red - 8) / 247) * 24) + 232;\n\t\t\t\t}\n\n\t\t\t\treturn 16\n\t\t\t\t\t+ (36 * Math.round(red / 255 * 5))\n\t\t\t\t\t+ (6 * Math.round(green / 255 * 5))\n\t\t\t\t\t+ Math.round(blue / 255 * 5);\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToRgb: {\n\t\t\tvalue(hex) {\n\t\t\t\tconst matches = /[a-f\\d]{6}|[a-f\\d]{3}/i.exec(hex.toString(16));\n\t\t\t\tif (!matches) {\n\t\t\t\t\treturn [0, 0, 0];\n\t\t\t\t}\n\n\t\t\t\tlet [colorString] = matches;\n\n\t\t\t\tif (colorString.length === 3) {\n\t\t\t\t\tcolorString = [...colorString].map(character => character + character).join('');\n\t\t\t\t}\n\n\t\t\t\tconst integer = Number.parseInt(colorString, 16);\n\n\t\t\t\treturn [\n\t\t\t\t\t/* eslint-disable no-bitwise */\n\t\t\t\t\t(integer >> 16) & 0xFF,\n\t\t\t\t\t(integer >> 8) & 0xFF,\n\t\t\t\t\tinteger & 0xFF,\n\t\t\t\t\t/* eslint-enable no-bitwise */\n\t\t\t\t];\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi256: {\n\t\t\tvalue: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t\tansi256ToAnsi: {\n\t\t\tvalue(code) {\n\t\t\t\tif (code < 8) {\n\t\t\t\t\treturn 30 + code;\n\t\t\t\t}\n\n\t\t\t\tif (code < 16) {\n\t\t\t\t\treturn 90 + (code - 8);\n\t\t\t\t}\n\n\t\t\t\tlet red;\n\t\t\t\tlet green;\n\t\t\t\tlet blue;\n\n\t\t\t\tif (code >= 232) {\n\t\t\t\t\tred = (((code - 232) * 10) + 8) / 255;\n\t\t\t\t\tgreen = red;\n\t\t\t\t\tblue = red;\n\t\t\t\t} else {\n\t\t\t\t\tcode -= 16;\n\n\t\t\t\t\tconst remainder = code % 36;\n\n\t\t\t\t\tred = Math.floor(code / 36) / 5;\n\t\t\t\t\tgreen = Math.floor(remainder / 6) / 5;\n\t\t\t\t\tblue = (remainder % 6) / 5;\n\t\t\t\t}\n\n\t\t\t\tconst value = Math.max(red, green, blue) * 2;\n\n\t\t\t\tif (value === 0) {\n\t\t\t\t\treturn 30;\n\t\t\t\t}\n\n\t\t\t\t// eslint-disable-next-line no-bitwise\n\t\t\t\tlet result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red));\n\n\t\t\t\tif (value === 2) {\n\t\t\t\t\tresult += 60;\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\tenumerable: false,\n\t\t},\n\t\trgbToAnsi: {\n\t\t\tvalue: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)),\n\t\t\tenumerable: false,\n\t\t},\n\t\thexToAnsi: {\n\t\t\tvalue: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)),\n\t\t\tenumerable: false,\n\t\t},\n\t});\n\n\treturn styles;\n}\n\nconst ansiStyles = assembleStyles();\n\nexport default ansiStyles;\n","import process from 'node:process';\nimport os from 'node:os';\nimport tty from 'node:tty';\n\n// From: https://github.com/sindresorhus/has-flag/blob/main/index.js\n/// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) {\nfunction hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) {\n\tconst prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--');\n\tconst position = argv.indexOf(prefix + flag);\n\tconst terminatorPosition = argv.indexOf('--');\n\treturn position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);\n}\n\nconst {env} = process;\n\nlet flagForceColor;\nif (\n\thasFlag('no-color')\n\t|| hasFlag('no-colors')\n\t|| hasFlag('color=false')\n\t|| hasFlag('color=never')\n) {\n\tflagForceColor = 0;\n} else if (\n\thasFlag('color')\n\t|| hasFlag('colors')\n\t|| hasFlag('color=true')\n\t|| hasFlag('color=always')\n) {\n\tflagForceColor = 1;\n}\n\nfunction envForceColor() {\n\tif ('FORCE_COLOR' in env) {\n\t\tif (env.FORCE_COLOR === 'true') {\n\t\t\treturn 1;\n\t\t}\n\n\t\tif (env.FORCE_COLOR === 'false') {\n\t\t\treturn 0;\n\t\t}\n\n\t\treturn env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);\n\t}\n}\n\nfunction translateLevel(level) {\n\tif (level === 0) {\n\t\treturn false;\n\t}\n\n\treturn {\n\t\tlevel,\n\t\thasBasic: true,\n\t\thas256: level >= 2,\n\t\thas16m: level >= 3,\n\t};\n}\n\nfunction _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) {\n\tconst noFlagForceColor = envForceColor();\n\tif (noFlagForceColor !== undefined) {\n\t\tflagForceColor = noFlagForceColor;\n\t}\n\n\tconst forceColor = sniffFlags ? flagForceColor : noFlagForceColor;\n\n\tif (forceColor === 0) {\n\t\treturn 0;\n\t}\n\n\tif (sniffFlags) {\n\t\tif (hasFlag('color=16m')\n\t\t\t|| hasFlag('color=full')\n\t\t\t|| hasFlag('color=truecolor')) {\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (hasFlag('color=256')) {\n\t\t\treturn 2;\n\t\t}\n\t}\n\n\t// Check for Azure DevOps pipelines.\n\t// Has to be above the `!streamIsTTY` check.\n\tif ('TF_BUILD' in env && 'AGENT_NAME' in env) {\n\t\treturn 1;\n\t}\n\n\tif (haveStream && !streamIsTTY && forceColor === undefined) {\n\t\treturn 0;\n\t}\n\n\tconst min = forceColor || 0;\n\n\tif (env.TERM === 'dumb') {\n\t\treturn min;\n\t}\n\n\tif (process.platform === 'win32') {\n\t\t// Windows 10 build 10586 is the first Windows release that supports 256 colors.\n\t\t// Windows 10 build 14931 is the first release that supports 16m/TrueColor.\n\t\tconst osRelease = os.release().split('.');\n\t\tif (\n\t\t\tNumber(osRelease[0]) >= 10\n\t\t\t&& Number(osRelease[2]) >= 10_586\n\t\t) {\n\t\t\treturn Number(osRelease[2]) >= 14_931 ? 3 : 2;\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\tif ('CI' in env) {\n\t\tif (['GITHUB_ACTIONS', 'GITEA_ACTIONS', 'CIRCLECI'].some(key => key in env)) {\n\t\t\treturn 3;\n\t\t}\n\n\t\tif (['TRAVIS', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') {\n\t\t\treturn 1;\n\t\t}\n\n\t\treturn min;\n\t}\n\n\tif ('TEAMCITY_VERSION' in env) {\n\t\treturn /^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;\n\t}\n\n\tif (env.COLORTERM === 'truecolor') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'xterm-kitty') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'xterm-ghostty') {\n\t\treturn 3;\n\t}\n\n\tif (env.TERM === 'wezterm') {\n\t\treturn 3;\n\t}\n\n\tif ('TERM_PROGRAM' in env) {\n\t\tconst version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);\n\n\t\tswitch (env.TERM_PROGRAM) {\n\t\t\tcase 'iTerm.app': {\n\t\t\t\treturn version >= 3 ? 3 : 2;\n\t\t\t}\n\n\t\t\tcase 'Apple_Terminal': {\n\t\t\t\treturn 2;\n\t\t\t}\n\t\t\t// No default\n\t\t}\n\t}\n\n\tif (/-256(color)?$/i.test(env.TERM)) {\n\t\treturn 2;\n\t}\n\n\tif (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {\n\t\treturn 1;\n\t}\n\n\tif ('COLORTERM' in env) {\n\t\treturn 1;\n\t}\n\n\treturn min;\n}\n\nexport function createSupportsColor(stream, options = {}) {\n\tconst level = _supportsColor(stream, {\n\t\tstreamIsTTY: stream && stream.isTTY,\n\t\t...options,\n\t});\n\n\treturn translateLevel(level);\n}\n\nconst supportsColor = {\n\tstdout: createSupportsColor({isTTY: tty.isatty(1)}),\n\tstderr: createSupportsColor({isTTY: tty.isatty(2)}),\n};\n\nexport default supportsColor;\n","// TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.\nexport function stringReplaceAll(string, substring, replacer) {\n\tlet index = string.indexOf(substring);\n\tif (index === -1) {\n\t\treturn string;\n\t}\n\n\tconst substringLength = substring.length;\n\tlet endIndex = 0;\n\tlet returnValue = '';\n\tdo {\n\t\treturnValue += string.slice(endIndex, index) + substring + replacer;\n\t\tendIndex = index + substringLength;\n\t\tindex = string.indexOf(substring, endIndex);\n\t} while (index !== -1);\n\n\treturnValue += string.slice(endIndex);\n\treturn returnValue;\n}\n\nexport function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {\n\tlet endIndex = 0;\n\tlet returnValue = '';\n\tdo {\n\t\tconst gotCR = string[index - 1] === '\\r';\n\t\treturnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\\r\\n' : '\\n') + postfix;\n\t\tendIndex = index + 1;\n\t\tindex = string.indexOf('\\n', endIndex);\n\t} while (index !== -1);\n\n\treturnValue += string.slice(endIndex);\n\treturn returnValue;\n}\n","import { randomUUID } from \"node:crypto\";\nimport { parseStack } from \"../core/stack.js\";\nimport { fingerprint } from \"../core/fingerprint.js\";\nimport { captureCodeContext } from \"../code-context.js\";\nimport { EventQueue } from \"../core/queue.js\";\nimport type { Level, ReportInput, Sink, WireEvent } from \"../core/types.js\";\n\nexport interface NodeAdapterOptions {\n projectKey: string;\n runtime: string;\n sink: Sink;\n captureConsoleErrors: boolean;\n captureConsoleWarnings: boolean;\n captureUnhandledRejections: boolean;\n captureUncaughtExceptions: boolean;\n}\n\nexport interface NodeAdapter {\n report(input: ReportInput): void;\n flush(): Promise<void>;\n close(): Promise<void>;\n}\n\nexport function installNodeAdapter(opts: NodeAdapterOptions): NodeAdapter {\n const queue = new EventQueue(opts.sink);\n const detach: Array<() => void> = [];\n\n const enqueueError = (err: unknown, level: Level, manual: boolean) => {\n try {\n const event = buildEvent(err, level, manual, opts.projectKey, opts.runtime);\n queue.enqueue(event);\n } catch {\n // never let pixel break the host program\n }\n };\n\n const enqueueErrorSync = (err: unknown, level: Level, manual: boolean) => {\n try {\n const event = buildEvent(err, level, manual, opts.projectKey, opts.runtime);\n queue.enqueueSync(event);\n } catch {\n // never let pixel break the host program\n }\n };\n\n if (opts.captureUncaughtExceptions) {\n const handler = (err: Error) => enqueueErrorSync(err, \"fatal\", false);\n process.on(\"uncaughtExceptionMonitor\", handler);\n detach.push(() => process.off(\"uncaughtExceptionMonitor\", handler));\n }\n\n if (opts.captureUnhandledRejections) {\n const handler = (reason: unknown) => enqueueErrorSync(reason, \"error\", false);\n process.on(\"unhandledRejection\", handler);\n detach.push(() => process.off(\"unhandledRejection\", handler));\n }\n\n if (opts.captureConsoleErrors) {\n detach.push(patchConsole(\"error\", (args) => enqueueError(consoleError(args), \"error\", false)));\n }\n\n if (opts.captureConsoleWarnings) {\n detach.push(patchConsole(\"warn\", (args) => enqueueError(consoleError(args), \"warning\", false)));\n }\n\n const onBeforeExit = () => {\n void queue.flush();\n };\n process.on(\"beforeExit\", onBeforeExit);\n detach.push(() => process.off(\"beforeExit\", onBeforeExit));\n\n return {\n report(input: ReportInput) {\n const level = input.level ?? \"error\";\n if (input.error !== undefined) {\n try {\n const event = buildEvent(input.error, level, true, opts.projectKey, opts.runtime);\n if (input.message) event.message = input.message;\n queue.enqueue(event);\n } catch {\n // never let pixel break the host program\n }\n return;\n }\n const err = new Error(input.message);\n err.name = \"ManualReport\";\n enqueueError(err, level, true);\n },\n flush: () => queue.flush(),\n close: async () => {\n for (const fn of detach) fn();\n await queue.close();\n },\n };\n}\n\nfunction buildEvent(\n err: unknown,\n level: Level,\n manual: boolean,\n projectKey: string,\n runtime: string,\n): WireEvent {\n const { type, message, stackString } = normalize(err);\n const stack = parseStack(stackString);\n return {\n event_id: randomUUID(),\n project_key: projectKey,\n fingerprint: fingerprint(type, stack),\n type,\n message,\n stack,\n code_context: captureCodeContext(stack),\n runtime,\n manual_report: manual,\n level,\n occurred_at: new Date().toISOString(),\n };\n}\n\nfunction normalize(err: unknown): { type: string; message: string; stackString?: string } {\n if (err instanceof Error) {\n return { type: err.name || \"Error\", message: err.message, stackString: err.stack };\n }\n if (typeof err === \"string\") {\n return { type: \"StringError\", message: err };\n }\n try {\n return { type: \"UnknownError\", message: JSON.stringify(err) };\n } catch {\n return { type: \"UnknownError\", message: String(err) };\n }\n}\n\nfunction consoleError(args: unknown[]): unknown {\n for (const a of args) if (a instanceof Error) return a;\n return new Error(args.map(stringify).join(\" \"));\n}\n\nfunction stringify(x: unknown): string {\n if (typeof x === \"string\") return x;\n try {\n return JSON.stringify(x);\n } catch {\n return String(x);\n }\n}\n\ntype ConsoleMethod = \"error\" | \"warn\";\n\nfunction patchConsole(method: ConsoleMethod, onCall: (args: unknown[]) => void): () => void {\n const original = console[method];\n console[method] = (...args: unknown[]) => {\n try {\n onCall(args);\n } catch {\n // never let pixel break the host program\n }\n original.apply(console, args);\n };\n return () => {\n console[method] = original;\n };\n}\n","import type { StackFrame } from \"./types.js\";\n\nconst FRAME_WITH_FN = /^\\s*at\\s+(.+?)\\s+\\((.+?):(\\d+):(\\d+)\\)\\s*$/;\nconst FRAME_NO_FN = /^\\s*at\\s+(.+?):(\\d+):(\\d+)\\s*$/;\n\nexport function parseStack(stack: string | undefined): StackFrame[] {\n if (!stack) return [];\n const frames: StackFrame[] = [];\n for (const line of stack.split(\"\\n\")) {\n const withFn = FRAME_WITH_FN.exec(line);\n if (withFn) {\n const file = withFn[2];\n frames.push({\n fn: withFn[1],\n file,\n line: Number(withFn[3]),\n col: Number(withFn[4]),\n in_app: isInApp(file),\n });\n continue;\n }\n const noFn = FRAME_NO_FN.exec(line);\n if (noFn) {\n const file = noFn[1];\n frames.push({\n fn: \"<anon>\",\n file,\n line: Number(noFn[2]),\n col: Number(noFn[3]),\n in_app: isInApp(file),\n });\n }\n }\n return frames;\n}\n\nfunction isInApp(file: string): boolean {\n if (!file) return false;\n if (file.startsWith(\"node:\")) return false;\n if (file.startsWith(\"internal/\")) return false;\n if (file.includes(\"/node_modules/\")) return false;\n return true;\n}\n","import { createHash } from \"node:crypto\";\nimport type { StackFrame } from \"./types.js\";\n\nexport function fingerprint(type: string, stack: StackFrame[]): string {\n const top = stack[0];\n const normalized = top\n ? `${type}|${normalizeFile(top.file)}|${top.fn || \"<anon>\"}|${top.line}`\n : `${type}|<no-stack>`;\n return createHash(\"sha256\").update(normalized).digest(\"hex\").slice(0, 16);\n}\n\nfunction normalizeFile(file: string): string {\n return file\n .replace(/^file:\\/\\//, \"\")\n .replace(/^.*\\/node_modules\\//, \"node_modules/\")\n .replace(/\\?.*$/, \"\");\n}\n","import { readFileSync, existsSync } from \"node:fs\";\nimport type { CodeContext, StackFrame } from \"./core/types.js\";\n\nconst WINDOW = 2;\nconst cache = new Map<string, string[] | null>();\n\nexport function captureCodeContext(stack: StackFrame[]): CodeContext | null {\n const top = stack.find((f) => isReadable(f.file));\n if (!top) return null;\n const lines = loadLines(top.file);\n if (!lines) return null;\n const start = Math.max(0, top.line - 1 - WINDOW);\n const end = Math.min(lines.length, top.line + WINDOW);\n return {\n file: top.file,\n error_line: top.line,\n lines: lines.slice(start, end),\n };\n}\n\nfunction isReadable(file: string): boolean {\n if (!file || file.startsWith(\"node:\")) return false;\n if (file.includes(\"/node_modules/\")) return false;\n return file.startsWith(\"/\") || file.startsWith(\"file://\");\n}\n\nfunction loadLines(file: string): string[] | null {\n const path = file.replace(/^file:\\/\\//, \"\");\n if (cache.has(path)) return cache.get(path) ?? null;\n if (!existsSync(path)) {\n cache.set(path, null);\n return null;\n }\n try {\n const lines = readFileSync(path, \"utf8\").split(\"\\n\");\n cache.set(path, lines);\n return lines;\n } catch {\n cache.set(path, null);\n return null;\n }\n}\n","import type { Sink, WireEvent } from \"./types.js\";\n\nconst MAX_BUFFER = 100;\nconst BASE_DELAY_MS = 200;\nconst MAX_DELAY_MS = 5_000;\n\nexport class EventQueue {\n private readonly buffer: WireEvent[] = [];\n private draining = false;\n private closed = false;\n\n constructor(private readonly sink: Sink) {}\n\n enqueue(event: WireEvent): void {\n if (this.closed) return;\n if (this.buffer.length >= MAX_BUFFER) {\n this.buffer.shift();\n }\n this.buffer.push(event);\n void this.drain();\n }\n\n enqueueSync(event: WireEvent): void {\n if (this.closed) return;\n if (this.sink.emitSync) {\n try {\n this.sink.emitSync(event);\n return;\n } catch {\n // fall through to async path\n }\n }\n this.enqueue(event);\n }\n\n async flush(): Promise<void> {\n while (this.buffer.length > 0 || this.draining) {\n await new Promise((r) => setTimeout(r, 10));\n }\n }\n\n async close(): Promise<void> {\n await this.flush();\n this.closed = true;\n if (this.sink.close) await this.sink.close();\n }\n\n private async drain(): Promise<void> {\n if (this.draining) return;\n this.draining = true;\n let attempt = 0;\n while (this.buffer.length > 0) {\n const event = this.buffer[0];\n try {\n await this.sink.emit(event);\n this.buffer.shift();\n attempt = 0;\n } catch (err) {\n attempt++;\n if (attempt >= 5) {\n // Drop the event but make the loss observable — silent data loss\n // from the error tracker is the worst possible failure mode.\n console.warn(\n `[gg-pixel] dropping event after 5 failed deliveries: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n this.buffer.shift();\n attempt = 0;\n continue;\n }\n const delay = Math.min(BASE_DELAY_MS * 2 ** (attempt - 1), MAX_DELAY_MS);\n await new Promise((r) => setTimeout(r, delay));\n }\n }\n this.draining = false;\n }\n}\n","import { spawnSync } from \"node:child_process\";\nimport { HttpSink } from \"./http.js\";\nimport type { WireEvent } from \"../types.js\";\n\n/**\n * Node-only HTTP sink that adds a synchronous `emitSync` path for fatal\n * events.\n *\n * Why: when `uncaughtExceptionMonitor` fires, Node tears the process down\n * before any pending async work can complete — meaning a normal `fetch()` to\n * the ingest endpoint loses the most important event (the fatal one).\n * Sentry's Node SDK solves this for serverless environments by spawning\n * an external HTTP client synchronously. We do the same with `curl`, which\n * ships with macOS, every modern Linux distro, and Windows 10 1803+.\n *\n * Tradeoff: ~100ms latency per fatal event (curl process spin-up). Fatal\n * events are rare so this is acceptable. Pending non-fatal events still in\n * the async queue at crash time may be lost — flushing them sync would\n * block the fatal handler for seconds in the worst case.\n */\nexport class NodeHttpSink extends HttpSink {\n constructor(\n private readonly url: string,\n fetchFn?: typeof fetch,\n ) {\n super(url, fetchFn);\n }\n\n emitSync(event: WireEvent): void {\n const body = JSON.stringify(event);\n const result = spawnSync(\n \"curl\",\n [\n \"--silent\",\n \"--show-error\",\n \"-X\",\n \"POST\",\n \"-H\",\n \"content-type: application/json\",\n \"-H\",\n `x-pixel-key: ${event.project_key}`,\n \"--data-binary\",\n \"@-\",\n \"--max-time\",\n \"3\",\n this.url,\n ],\n { input: body, encoding: \"utf8\" },\n );\n if (result.error || result.status !== 0) {\n // Best-effort. We're already in a fatal handler; can't retry async.\n console.warn(\n `[gg-pixel] sync emit failed: ${result.error?.message ?? result.stderr ?? \"unknown\"}`,\n );\n }\n }\n}\n","import type { Sink, WireEvent } from \"../types.js\";\n\nexport class HttpSink implements Sink {\n private readonly fetchFn: typeof fetch;\n\n constructor(\n private readonly ingestUrl: string,\n fetchFn?: typeof fetch,\n ) {\n // CRITICAL: in browsers `fetch` is `window.fetch` and requires `this === window`.\n // Storing it as a property and calling via `this.fetchFn(...)` strips that\n // binding and throws \"Illegal invocation\". Bind to globalThis on assignment.\n // Tests can still inject a custom fetchFn (no binding needed for plain fns).\n this.fetchFn = fetchFn ?? globalThis.fetch.bind(globalThis);\n }\n\n async emit(event: WireEvent): Promise<void> {\n const body = JSON.stringify(event);\n // `keepalive: true` lets the request survive page unload (browser).\n // `mode: \"cors\"` is the explicit default but stating it makes the\n // intent clear and avoids surprises on stricter contexts.\n const res = await this.fetchFn(this.ingestUrl, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n \"x-pixel-key\": event.project_key,\n },\n body,\n keepalive: typeof window !== \"undefined\",\n mode: typeof window !== \"undefined\" ? \"cors\" : undefined,\n });\n if (!res.ok) {\n throw new Error(`pixel ingest failed: ${res.status}`);\n }\n }\n}\n","import { homedir } from \"node:os\";\nimport { mkdirSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join } from \"node:path\";\nimport type { Sink, WireEvent } from \"../types.js\";\n\n// `better-sqlite3` is loaded lazily and is NOT declared as a peer dep.\n// Apps that only use the HTTP sink (the common case) don't need it installed —\n// keeping it out of both the eager import graph and the package manifest avoids\n// the deprecated `prebuild-install` warning and a Windows native-build attempt\n// at every `npm install`. Users who pick `kind: \"local\"` install it themselves.\nconst requireBSQ = createRequire(import.meta.url);\n\ninterface BSqStatement {\n run(args: Record<string, unknown>): unknown;\n}\ninterface BSqDb {\n pragma(s: string): unknown;\n exec(s: string): void;\n prepare(s: string): BSqStatement;\n close(): unknown;\n}\ntype BSqCtor = new (path: string) => BSqDb;\n\nfunction loadBetterSqlite3(): BSqCtor {\n try {\n const mod = requireBSQ(\"better-sqlite3\") as BSqCtor | { default: BSqCtor };\n return typeof mod === \"function\" ? mod : mod.default;\n } catch (err) {\n throw new Error(\n '@iroaxel/gg-pixel: `kind: \"local\"` requires `better-sqlite3` to be installed. ' +\n \"Install it with `npm install better-sqlite3` (or your package manager's equivalent). \" +\n `Underlying error: ${(err as Error).message}`,\n { cause: err },\n );\n }\n}\n\nconst SCHEMA = `\n CREATE TABLE IF NOT EXISTS events (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n event_id TEXT NOT NULL UNIQUE,\n project_key TEXT NOT NULL,\n fingerprint TEXT NOT NULL,\n type TEXT NOT NULL,\n message TEXT NOT NULL,\n stack TEXT NOT NULL,\n code_context TEXT,\n runtime TEXT NOT NULL,\n manual_report INTEGER NOT NULL DEFAULT 0,\n level TEXT NOT NULL,\n occurred_at TEXT NOT NULL,\n ingested_at TEXT NOT NULL DEFAULT (datetime('now'))\n );\n CREATE INDEX IF NOT EXISTS events_fingerprint ON events(project_key, fingerprint);\n CREATE INDEX IF NOT EXISTS events_occurred ON events(occurred_at);\n`;\n\nexport class LocalSqliteSink implements Sink {\n private readonly db: BSqDb;\n private readonly insert: BSqStatement;\n\n constructor(path?: string) {\n const Database = loadBetterSqlite3();\n const resolved = path ?? join(homedir(), \".gg\", \"errors.db\");\n mkdirSync(dirname(resolved), { recursive: true });\n this.db = new Database(resolved);\n this.db.pragma(\"journal_mode = WAL\");\n this.db.exec(SCHEMA);\n this.insert = this.db.prepare(`\n INSERT INTO events (\n event_id, project_key, fingerprint, type, message, stack, code_context,\n runtime, manual_report, level, occurred_at\n ) VALUES (\n @event_id, @project_key, @fingerprint, @type, @message, @stack, @code_context,\n @runtime, @manual_report, @level, @occurred_at\n )\n `);\n }\n\n emitSync(event: WireEvent): void {\n this.insert.run({\n event_id: event.event_id,\n project_key: event.project_key,\n fingerprint: event.fingerprint,\n type: event.type,\n message: event.message,\n stack: JSON.stringify(event.stack),\n code_context: event.code_context ? JSON.stringify(event.code_context) : null,\n runtime: event.runtime,\n manual_report: event.manual_report ? 1 : 0,\n level: event.level,\n occurred_at: event.occurred_at,\n });\n }\n\n async emit(event: WireEvent): Promise<void> {\n this.emitSync(event);\n }\n\n async close(): Promise<void> {\n this.db.close();\n }\n}\n","import {\n existsSync,\n readFileSync,\n writeFileSync,\n appendFileSync,\n mkdirSync,\n readdirSync,\n} from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, relative, resolve, sep } from \"node:path\";\nimport { spawnSync } from \"node:child_process\";\n\nimport type * as BabelParser from \"@babel/parser\";\nimport type * as BabelTypes from \"@babel/types\";\nimport type * as Recast from \"recast\";\n\nconst nodeRequire = createRequire(import.meta.url);\n\nexport const DEFAULT_INGEST_URL = \"https://gg-pixel-server.buzzbeamaustralia.workers.dev\";\n\nexport interface InstallOptions {\n cwd?: string;\n ingestUrl?: string;\n projectName?: string;\n fetchFn?: typeof fetch;\n skipPackageInstall?: boolean;\n homeDir?: string;\n}\n\nexport interface InstallResult {\n projectId: string;\n projectKey: string;\n /**\n * Per-project bearer secret returned by the server on creation. Stored in\n * ~/.gg/projects.json and required for every /api/* call (read/list/patch/\n * delete). Never leaves the user's machine — never inlined into source.\n */\n projectSecret: string;\n projectName: string;\n projectKind: ProjectKind;\n /** Resolved root of the user's project (the dir containing package.json /\n * pyproject.toml / go.mod / Gemfile, depending on kind). Needed by the\n * verifier so it can spawn a probe child from the right cwd. */\n projectRoot: string;\n initFilePath: string;\n envFilePath: string;\n projectsJsonPath: string;\n packageManager: PackageManager | PythonPackageManager;\n packageInstalled: boolean;\n entryWiring: EntryWiringResult;\n /** True when an existing project mapping was reused instead of minting a fresh one. */\n reused: boolean;\n /** Hybrid frameworks: a second init file (e.g. server-side for Next.js). */\n secondaryInit?: { path: string; description: string };\n /** Honest disclaimers — surfaced in the CLI summary. */\n warnings: string[];\n}\n\nexport type EntryWiringResult =\n | { kind: \"injected\"; entryPath: string }\n | { kind: \"already_present\"; entryPath: string }\n | { kind: \"no_entry_found\" }\n | { kind: \"skipped\"; reason: string };\n\ninterface PackageJson {\n name?: string;\n type?: string;\n main?: string;\n module?: string;\n bin?: string | Record<string, string>;\n browser?: unknown;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n}\n\nexport type PackageManager = \"pnpm\" | \"yarn\" | \"bun\" | \"npm\";\n\nexport type ProjectKind =\n | \"node\"\n | \"browser\"\n | \"python\"\n | \"nextjs\"\n | \"sveltekit\"\n | \"nuxt\"\n | \"remix\"\n | \"electron\"\n | \"tauri\"\n | \"react-native\"\n | \"cloudflare-workers\"\n | \"go\"\n | \"ruby\";\n\nexport type PythonPackageManager = \"uv\" | \"poetry\" | \"pipenv\" | \"pip\";\n\nexport async function install(opts: InstallOptions = {}): Promise<InstallResult> {\n const cwd = resolve(opts.cwd ?? process.cwd());\n const ingestUrl = (opts.ingestUrl ?? DEFAULT_INGEST_URL).replace(/\\/+$/, \"\");\n const fetchFn = opts.fetchFn ?? fetch;\n const home = opts.homeDir ?? homedir();\n\n // Detect project kind. We pick the closest (deepest) root when multiple\n // markers exist — polyglot monorepos commonly have everything at root.\n const nodeRoot = findProjectRoot(cwd);\n const pythonRoot = findPythonProjectRoot(cwd);\n const goRoot = findGoProjectRoot(cwd);\n const rubyRoot = findRubyProjectRoot(cwd);\n\n if (!nodeRoot && !pythonRoot && !goRoot && !rubyRoot) {\n throw new Error(\n `No project found at ${cwd}: looked for package.json, pyproject.toml/setup.py/requirements.txt/Pipfile, go.mod, Gemfile/*.gemspec.`,\n );\n }\n\n const closestRoot = pickClosestRoot([nodeRoot, pythonRoot, goRoot, rubyRoot]);\n\n if (closestRoot === goRoot && goRoot) {\n return installGo({ projectRoot: goRoot, opts, ingestUrl, fetchFn, home });\n }\n if (closestRoot === rubyRoot && rubyRoot) {\n return installRuby({ projectRoot: rubyRoot, opts, ingestUrl, fetchFn, home });\n }\n if (closestRoot === pythonRoot && pythonRoot) {\n return installPython({ projectRoot: pythonRoot, opts, ingestUrl, fetchFn, home });\n }\n\n // Node / browser / hybrid framework path.\n if (!nodeRoot) {\n throw new Error(\"Internal: closest root is Node but nodeRoot is null\");\n }\n const pkgPath = join(nodeRoot, \"package.json\");\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf8\")) as PackageJson;\n const projectName = opts.projectName ?? pkg.name ?? nodeRoot.split(\"/\").pop() ?? \"unnamed\";\n const kind = detectJsProjectKind(pkg, nodeRoot);\n\n const projectsJsonPath = join(home, \".gg\", \"projects.json\");\n const envFilePath = join(nodeRoot, \".env\");\n\n const existing = findMappingByPath(projectsJsonPath, nodeRoot);\n const existingKey = readEnvKey(envFilePath, \"GG_PIXEL_KEY\");\n let created: CreatedProject;\n let reused = false;\n // Reusing requires *all three* — id, publishable key, and the secret —\n // because the secret is now mandatory for every management call. If any\n // is missing (e.g. legacy install before secrets existed), mint fresh.\n if (existing && existing.secret && existingKey) {\n created = { id: existing.id, key: existingKey, secret: existing.secret };\n reused = true;\n } else {\n created = await createProject(fetchFn, ingestUrl, projectName);\n }\n\n const pm = detectPackageManager(nodeRoot);\n const packageInstalled = opts.skipPackageInstall\n ? false\n : runInstall(nodeRoot, pm, \"@iroaxel/gg-pixel\");\n\n // Dispatch to per-framework wiring.\n const wired = wireFramework({\n kind,\n projectRoot: nodeRoot,\n pkg,\n projectKey: created.key,\n ingestUrl,\n });\n\n // .env: write the key for runtimes that read it from process.env (Node servers,\n // Electron main, Next.js server, etc). Pure browser apps don't need it (key\n // is inlined into the init file).\n if (kind !== \"browser\" && kind !== \"tauri\") {\n writeEnvKey(envFilePath, \"GG_PIXEL_KEY\", created.key);\n }\n\n writeProjectsMapping(projectsJsonPath, created.id, projectName, nodeRoot, created.secret);\n\n return {\n projectId: created.id,\n projectKey: created.key,\n projectSecret: created.secret,\n projectName,\n projectKind: kind,\n projectRoot: nodeRoot,\n initFilePath: wired.primaryInitPath,\n envFilePath,\n projectsJsonPath,\n packageManager: pm,\n packageInstalled,\n entryWiring: wired.entryWiring,\n reused,\n secondaryInit: wired.secondaryInit,\n warnings: wired.warnings,\n };\n}\n\ninterface CreatedProject {\n id: string;\n key: string;\n secret: string;\n}\n\nfunction findMappingByPath(\n projectsJsonPath: string,\n projectRoot: string,\n): { id: string; name: string; path: string; secret?: string } | null {\n if (!existsSync(projectsJsonPath)) return null;\n let map: Record<string, { name: string; path: string; secret?: string }>;\n try {\n map = JSON.parse(readFileSync(projectsJsonPath, \"utf8\")) as typeof map;\n } catch {\n return null;\n }\n // If the same path appears in multiple entries (e.g. legacy entries from a\n // pre-secret install plus a newer entry from a re-install), prefer the\n // entry that has a secret — otherwise the install logic falls into the\n // \"no secret stored\" branch and mints yet another fresh project.\n let fallback: { id: string; name: string; path: string; secret?: string } | null = null;\n for (const [id, entry] of Object.entries(map)) {\n if (entry.path !== projectRoot) continue;\n if (entry.secret) return { id, ...entry };\n if (!fallback) fallback = { id, ...entry };\n }\n return fallback;\n}\n\nfunction readEnvKey(envPath: string, key: string): string | null {\n if (!existsSync(envPath)) return null;\n try {\n const content = readFileSync(envPath, \"utf8\");\n const match = new RegExp(`^${key}=(.+)$`, \"m\").exec(content);\n return match?.[1]?.trim() ?? null;\n } catch {\n return null;\n }\n}\n\nfunction findProjectRoot(start: string): string | null {\n let dir = start;\n for (let i = 0; i < 20; i++) {\n if (existsSync(join(dir, \"package.json\"))) return dir;\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n return null;\n}\n\nasync function createProject(\n fetchFn: typeof fetch,\n ingestUrl: string,\n name: string,\n): Promise<CreatedProject> {\n const res = await fetchFn(`${ingestUrl}/api/projects`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({ name }),\n });\n if (!res.ok) {\n throw new Error(`POST /api/projects failed: ${res.status} ${await safeText(res)}`);\n }\n const body = (await res.json()) as { id: string; key: string; secret: string };\n if (!body.id || !body.key || !body.secret) {\n throw new Error(\"response missing id/key/secret\");\n }\n return { id: body.id, key: body.key, secret: body.secret };\n}\n\nasync function safeText(r: Response): Promise<string> {\n try {\n return await r.text();\n } catch {\n return \"\";\n }\n}\n\nexport function detectPackageManager(projectRoot: string): PackageManager {\n if (existsSync(join(projectRoot, \"pnpm-lock.yaml\"))) return \"pnpm\";\n // Bun 1.2+ defaults to the text-based `bun.lock`; older versions used the\n // binary `bun.lockb`. Either lockfile means this is a Bun project — falling\n // through to npm partially mutates `node_modules` in a layout incompatible\n // with `bun.lock`, leaving the user to rm -rf and re-bun-install to recover.\n if (existsSync(join(projectRoot, \"bun.lock\")) || existsSync(join(projectRoot, \"bun.lockb\"))) {\n return \"bun\";\n }\n if (existsSync(join(projectRoot, \"yarn.lock\"))) return \"yarn\";\n return \"npm\";\n}\n\nfunction runInstall(projectRoot: string, pm: PackageManager, pkg: string): boolean {\n const cmd = pm;\n // npm prints `npm audit` warnings + `npm fund` solicitations on every install.\n // That output is about the user's *existing* project — irrelevant to pixel.\n // The other package managers don't show this noise by default.\n const args = pm === \"npm\" ? [\"install\", pkg, \"--no-audit\", \"--no-fund\"] : [\"add\", pkg];\n const result = spawnSync(cmd, args, { cwd: projectRoot, stdio: \"inherit\" });\n return result.status === 0;\n}\n\nexport function renderInitFile(ingestUrl: string, projectKey?: string): string {\n const fallback = projectKey ? ` || ${JSON.stringify(projectKey)}` : \"\";\n return `import { initPixel } from \"@iroaxel/gg-pixel\";\n\nconst key = process.env.GG_PIXEL_KEY${fallback};\nif (key) {\n initPixel({\n projectKey: key,\n sink: { kind: \"http\", ingestUrl: ${JSON.stringify(`${ingestUrl}/ingest`)} },\n });\n}\n`;\n}\n\nexport function renderInitFileCjs(ingestUrl: string, projectKey?: string): string {\n const fallback = projectKey ? ` || ${JSON.stringify(projectKey)}` : \"\";\n return `const { initPixel } = require(\"@iroaxel/gg-pixel\");\n\nconst key = process.env.GG_PIXEL_KEY${fallback};\nif (key) {\n initPixel({\n projectKey: key,\n sink: { kind: \"http\", ingestUrl: ${JSON.stringify(`${ingestUrl}/ingest`)} },\n });\n}\n`;\n}\n\nexport function writeEnvKey(envPath: string, key: string, value: string): void {\n if (existsSync(envPath)) {\n const current = readFileSync(envPath, \"utf8\");\n const lineRegex = new RegExp(`^${key}=.*$`, \"m\");\n if (lineRegex.test(current)) {\n writeFileSync(envPath, current.replace(lineRegex, `${key}=${value}`), \"utf8\");\n return;\n }\n const sep = current.endsWith(\"\\n\") || current.length === 0 ? \"\" : \"\\n\";\n appendFileSync(envPath, `${sep}${key}=${value}\\n`, \"utf8\");\n return;\n }\n writeFileSync(envPath, `${key}=${value}\\n`, \"utf8\");\n}\n\nexport function wireEntryFile(\n projectRoot: string,\n initFilePath: string,\n pkg: PackageJson,\n): EntryWiringResult {\n const entryPath = findEntryFile(projectRoot, pkg);\n if (!entryPath) return { kind: \"no_entry_found\" };\n\n let content: string;\n try {\n content = readFileSync(entryPath, \"utf8\");\n } catch (err) {\n return { kind: \"skipped\", reason: `unreadable: ${(err as Error).message}` };\n }\n\n if (content.includes(\"gg-pixel.init\")) {\n return { kind: \"already_present\", entryPath };\n }\n\n // Compute import specifier relative to the entry file.\n const fromDir = dirname(entryPath);\n let spec = relative(fromDir, initFilePath).split(sep).join(\"/\");\n if (!spec.startsWith(\".\")) spec = \"./\" + spec;\n\n const isCjs = isCommonJsEntry(entryPath, pkg);\n const importLine = isCjs\n ? `require(${JSON.stringify(spec)});`\n : `import ${JSON.stringify(spec)};`;\n\n // Inject at the top — after a shebang line and any leading \"use strict\",\n // but before all other code, so pixel hooks run before anything else.\n const lines = content.split(\"\\n\");\n let insertAt = 0;\n if (lines[0]?.startsWith(\"#!\")) insertAt = 1;\n while (\n insertAt < lines.length &&\n /^\\s*(?:[\"']use strict[\"']|\\/\\/|\\/\\*)/.test(lines[insertAt] ?? \"\")\n ) {\n insertAt++;\n }\n\n const updated = [...lines.slice(0, insertAt), importLine, ...lines.slice(insertAt)].join(\"\\n\");\n writeFileSync(entryPath, updated, \"utf8\");\n return { kind: \"injected\", entryPath };\n}\n\nfunction findEntryFile(projectRoot: string, pkg: PackageJson): string | null {\n const tryPath = (rel: string): string | null => {\n const p = join(projectRoot, rel);\n if (existsSync(p)) return p;\n // If user pointed `main` at .js but only the .ts source exists (common in TS projects).\n if (rel.endsWith(\".js\")) {\n const ts = join(projectRoot, rel.replace(/\\.js$/, \".ts\"));\n if (existsSync(ts)) return ts;\n }\n return null;\n };\n\n if (typeof pkg.bin === \"string\") {\n const found = tryPath(pkg.bin);\n if (found) return found;\n }\n if (pkg.bin && typeof pkg.bin === \"object\") {\n for (const value of Object.values(pkg.bin)) {\n if (typeof value === \"string\") {\n const found = tryPath(value);\n if (found) return found;\n }\n }\n }\n if (pkg.main) {\n const found = tryPath(pkg.main);\n if (found) return found;\n }\n if (pkg.module) {\n const found = tryPath(pkg.module);\n if (found) return found;\n }\n\n // Fall back to common conventions.\n const candidates = [\n \"src/index.ts\",\n \"src/index.tsx\",\n \"src/index.js\",\n \"src/index.mjs\",\n \"src/main.ts\",\n \"src/main.tsx\",\n \"src/main.js\",\n \"src/server.ts\",\n \"src/server.js\",\n \"src/app.ts\",\n \"src/app.js\",\n \"src/cli.ts\",\n \"src/cli.js\",\n \"index.ts\",\n \"index.tsx\",\n \"index.js\",\n \"index.mjs\",\n \"main.ts\",\n \"main.js\",\n \"server.ts\",\n \"server.js\",\n \"app.ts\",\n \"app.js\",\n ];\n for (const c of candidates) {\n const found = tryPath(c);\n if (found) return found;\n }\n return null;\n}\n\nfunction isCommonJsEntry(entryPath: string, pkg: PackageJson): boolean {\n if (entryPath.endsWith(\".cjs\")) return true;\n if (entryPath.endsWith(\".mjs\")) return false;\n if (entryPath.endsWith(\".ts\") || entryPath.endsWith(\".tsx\")) return false;\n // .js → governed by package.json type (default is \"commonjs\")\n return pkg.type !== \"module\";\n}\n\n// ── Framework detection + wiring ────────────────────────────────────\n\nexport function detectJsProjectKind(pkg: PackageJson, projectRoot: string): ProjectKind {\n const all = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };\n // Order matters: more specific first (Electron + React = electron, not browser).\n if (\n existsSync(join(projectRoot, \"wrangler.toml\")) ||\n existsSync(join(projectRoot, \"wrangler.jsonc\")) ||\n existsSync(join(projectRoot, \"wrangler.json\"))\n ) {\n return \"cloudflare-workers\";\n }\n if (\"electron\" in all) return \"electron\";\n if (existsSync(join(projectRoot, \"src-tauri\")) || \"@tauri-apps/api\" in all) return \"tauri\";\n if (\"react-native\" in all) return \"react-native\";\n if (\"next\" in all) return \"nextjs\";\n if (\"@sveltejs/kit\" in all) return \"sveltekit\";\n if (\"nuxt\" in all || \"nuxt3\" in all) return \"nuxt\";\n if (\"@remix-run/react\" in all || \"@remix-run/node\" in all) return \"remix\";\n if (isBrowserProject(pkg, projectRoot)) return \"browser\";\n return \"node\";\n}\n\ninterface WiringInput {\n kind: ProjectKind;\n projectRoot: string;\n pkg: PackageJson;\n projectKey: string;\n ingestUrl: string;\n}\n\ninterface WiringResult {\n primaryInitPath: string;\n entryWiring: EntryWiringResult;\n secondaryInit?: { path: string; description: string };\n warnings: string[];\n}\n\nfunction wireFramework(w: WiringInput): WiringResult {\n switch (w.kind) {\n case \"node\":\n return wireNode(w);\n case \"browser\":\n return wireBrowser(w);\n case \"nextjs\":\n return wireNextjs(w);\n case \"sveltekit\":\n return wireSveltekit(w);\n case \"nuxt\":\n return wireNuxt(w);\n case \"remix\":\n return wireRemix(w);\n case \"electron\":\n return wireElectron(w);\n case \"tauri\":\n return wireTauri(w);\n case \"react-native\":\n return wireReactNative(w);\n case \"cloudflare-workers\":\n return wireWorkers(w);\n case \"python\":\n case \"go\":\n case \"ruby\":\n throw new Error(`Internal: ${w.kind} should have been handled earlier`);\n }\n}\n\nfunction wireNode({ projectRoot, pkg, projectKey, ingestUrl }: WiringInput): WiringResult {\n const initPath = join(projectRoot, \"gg-pixel.init.mjs\");\n writeFileSync(initPath, renderInitFile(ingestUrl, projectKey), \"utf8\");\n return {\n primaryInitPath: initPath,\n entryWiring: wireEntryFile(projectRoot, initPath, pkg),\n warnings: [],\n };\n}\n\nfunction wireBrowser({ projectRoot, pkg, projectKey, ingestUrl }: WiringInput): WiringResult {\n const initPath = join(projectRoot, \"gg-pixel.init.mjs\");\n writeFileSync(initPath, renderBrowserInitFile(ingestUrl, projectKey), \"utf8\");\n return {\n primaryInitPath: initPath,\n entryWiring: wireEntryFile(projectRoot, initPath, pkg),\n warnings: [],\n };\n}\n\nfunction wireNextjs({ projectRoot, projectKey, ingestUrl }: WiringInput): WiringResult {\n // Next.js auto-loads `instrumentation.ts` for the server. No entry wiring needed.\n // For the client, we drop a registration script and import it from the root layout.\n const warnings: string[] = [];\n\n // ── Server: instrumentation.ts ─────────────\n const serverInitPath = pickPath(projectRoot, [\"instrumentation.ts\", \"instrumentation.js\"]);\n const finalServerPath = serverInitPath ?? join(projectRoot, \"instrumentation.ts\");\n writeNextInstrumentation(finalServerPath, ingestUrl, projectKey);\n\n // ── next.config: mark @iroaxel/gg-pixel as a server-external package\n // so Next's bundler doesn't try to compile better-sqlite3 (a native\n // module) when bundling API routes / Server Components.\n patchNextConfig(projectRoot);\n\n // ── Client: drop a Client Component that initializes pixel only on the\n // browser, then render it from the root layout. We can't just import\n // a `.mjs` from layout.tsx — server-side rendering of pages like\n // /_not-found would evaluate `window.onerror = ...` and blow up.\n const clientInitPath = join(projectRoot, \"gg-pixel.client.tsx\");\n writeFileSync(clientInitPath, renderNextClientComponent(ingestUrl, projectKey), \"utf8\");\n\n const layoutPath = findNextLayout(projectRoot);\n let entryWiring: EntryWiringResult;\n if (!layoutPath) {\n warnings.push(\n 'Could not auto-wire the Next.js client init — no app/layout.{tsx,jsx} or pages/_app.{tsx,jsx} found. Add `<GGPixelClient />` from \"./gg-pixel.client\" to your root layout/_app.',\n );\n entryWiring = { kind: \"no_entry_found\" };\n } else {\n entryWiring = injectNextClientComponent(layoutPath, clientInitPath);\n }\n\n return {\n primaryInitPath: clientInitPath,\n entryWiring,\n secondaryInit: {\n path: finalServerPath,\n description: \"Next.js server instrumentation (auto-loaded by Next runtime)\",\n },\n warnings,\n };\n}\n\nfunction writeNextInstrumentation(path: string, ingestUrl: string, projectKey?: string): void {\n const existing = existsSync(path) ? readFileSync(path, \"utf8\") : \"\";\n const cleaned = stripLegacyPixelContent(existing);\n const block = nextInstrumentationBlock(ingestUrl, projectKey);\n const next = upsertPixelBlock(cleaned, block);\n if (next !== existing) writeFileSync(path, next, \"utf8\");\n}\n\nfunction nextInstrumentationBlock(ingestUrl: string, projectKey?: string): string {\n const fallback = projectKey ? ` ?? ${JSON.stringify(projectKey)}` : \"\";\n return `// Next.js auto-loads this file on server start. Pixel hooks the\n// uncaughtExceptionMonitor + unhandledRejection events for API routes,\n// Server Components, and route handlers.\nexport async function register() {\n if (process.env.NEXT_RUNTIME === \"nodejs\") {\n const { initPixel } = await import(\"@iroaxel/gg-pixel\");\n initPixel({\n projectKey: process.env.GG_PIXEL_KEY${fallback},\n sink: { kind: \"http\", ingestUrl: ${JSON.stringify(`${ingestUrl}/ingest`)} },\n });\n }\n}`;\n}\n\nfunction findNextLayout(projectRoot: string): string | null {\n const candidates = [\n \"app/layout.tsx\",\n \"app/layout.jsx\",\n \"app/layout.ts\",\n \"src/app/layout.tsx\",\n \"src/app/layout.jsx\",\n \"pages/_app.tsx\",\n \"pages/_app.jsx\",\n \"src/pages/_app.tsx\",\n \"src/pages/_app.jsx\",\n ];\n for (const c of candidates) {\n const p = join(projectRoot, c);\n if (existsSync(p)) return p;\n }\n return null;\n}\n\nfunction renderNextClientComponent(ingestUrl: string, projectKey: string): string {\n return `\"use client\";\n// Client-only pixel init. Rendered from the root layout. The \"use client\"\n// directive guarantees this module never executes during server-side\n// rendering — \\`window.onerror\\` references would otherwise crash builds.\nimport { useEffect } from \"react\";\nimport { initPixel } from \"@iroaxel/gg-pixel/browser\";\n\nlet inited = false;\n\nexport default function GGPixelClient() {\n useEffect(() => {\n if (inited) return;\n inited = true;\n initPixel({\n projectKey: ${JSON.stringify(projectKey)},\n ingestUrl: ${JSON.stringify(ingestUrl)},\n });\n }, []);\n return null;\n}\n`;\n}\n\nfunction injectNextClientComponent(layoutPath: string, clientInitPath: string): EntryWiringResult {\n let content: string;\n try {\n content = readFileSync(layoutPath, \"utf8\");\n } catch (err) {\n return { kind: \"skipped\", reason: `unreadable: ${(err as Error).message}` };\n }\n if (content.includes(\"GGPixelClient\") || content.includes(\"@iroaxel/gg-pixel\")) {\n return { kind: \"already_present\", entryPath: layoutPath };\n }\n const fromDir = dirname(layoutPath);\n let spec = relative(fromDir, clientInitPath).split(sep).join(\"/\");\n if (!spec.startsWith(\".\")) spec = \"./\" + spec;\n // Strip the .tsx extension for cleanest imports.\n spec = spec.replace(/\\.tsx$/, \"\");\n\n // Try AST-first so we land <GGPixelClient /> as the first child of <body>\n // (i.e., a sibling of any auth-gate / provider tree wrapping {children}),\n // not deeply nested where it would only init after the gate resolves.\n const astResult = injectClientComponentViaAst(layoutPath, content, spec);\n if (astResult) return astResult;\n\n // Fallback: previous regex behaviour. Used when the file doesn't parse as\n // TSX (extremely rare — would require syntactically broken code) or when\n // we can't locate the JSX `<body>` element through the AST.\n return injectClientComponentViaRegex(layoutPath, content, spec);\n}\n\n/**\n * Parse the layout, find `<body>`, and prepend `<GGPixelClient />` to its\n * children list. Also adds the import. Uses recast so untouched code stays\n * byte-identical (only the inserted nodes are reformatted).\n *\n * Returns null on any AST issue so the caller can fall back to regex.\n */\nfunction injectClientComponentViaAst(\n layoutPath: string,\n content: string,\n importSpec: string,\n): EntryWiringResult | null {\n let recast: typeof Recast;\n let bp: typeof BabelParser;\n let bt: typeof BabelTypes;\n try {\n recast = nodeRequire(\"recast\") as typeof Recast;\n bp = nodeRequire(\"@babel/parser\") as typeof BabelParser;\n bt = nodeRequire(\"@babel/types\") as typeof BabelTypes;\n } catch {\n return null;\n }\n\n let ast: ReturnType<typeof recast.parse>;\n try {\n ast = recast.parse(content, {\n parser: {\n parse: (src: string) =>\n bp.parse(src, {\n sourceType: \"module\",\n plugins: [\"jsx\", \"typescript\"],\n allowImportExportEverywhere: true,\n tokens: true,\n }),\n },\n });\n } catch {\n return null;\n }\n\n const program = (ast as { program: { body: Array<unknown> } }).program;\n if (!program || !Array.isArray(program.body)) return null;\n\n const bodyEl = findFirstJsxElementByName(ast, \"body\");\n if (!bodyEl) return null; // No <body> — let the regex fallback handle / warn.\n\n // 1. Prepend <GGPixelClient /> to <body>'s children. Use a JSXText with a\n // newline so the output reads naturally even when recast reformats.\n const newComponent = bt.jsxElement(\n bt.jsxOpeningElement(bt.jsxIdentifier(\"GGPixelClient\"), [], true),\n null,\n [],\n true,\n );\n const leadingText = bt.jsxText(\"\\n \");\n const trailingText = bt.jsxText(\"\\n \");\n bodyEl.children = [leadingText, newComponent, trailingText, ...bodyEl.children];\n\n // 2. Insert the import after the last existing import statement.\n const importDecl = bt.importDeclaration(\n [bt.importDefaultSpecifier(bt.identifier(\"GGPixelClient\"))],\n bt.stringLiteral(importSpec),\n );\n const body = program.body as Array<{ type: string }>;\n let insertAt = 0;\n for (let i = 0; i < body.length; i++) {\n if (body[i]?.type === \"ImportDeclaration\") insertAt = i + 1;\n }\n body.splice(insertAt, 0, importDecl as unknown as { type: string });\n\n let out: string;\n try {\n out = recast.print(ast).code;\n } catch {\n return null;\n }\n writeFileSync(layoutPath, out, \"utf8\");\n return { kind: \"injected\", entryPath: layoutPath };\n}\n\n/**\n * Walks the AST and returns the first JSXElement whose opening name matches.\n * Uses string type checks rather than babel's typed predicates so we don't\n * have to coerce loosely-typed walkers through narrow predicate signatures.\n *\n * Recast's parsed AST isn't a clean Babel tree — it wraps nodes and attaches\n * `original`/`tokens`/`loc`/`comments` back-references that share substructure.\n * A naive recursive walker over `Object.keys` revisits those references and on\n * real Next.js root layouts (`<html><body>...</body></html>`) blows the stack.\n * Guard with a `WeakSet` of visited objects, a depth cap, and a skip-list for\n * the metadata keys that aren't part of the syntactic tree.\n */\nexport function findFirstJsxElementByName(\n ast: unknown,\n name: string,\n): { children: unknown[] } | null {\n let found: { children: unknown[] } | null = null;\n const seen = new WeakSet<object>();\n const MAX_DEPTH = 500;\n const SKIP_KEYS = new Set([\n \"loc\",\n \"tokens\",\n \"original\",\n \"comments\",\n \"leadingComments\",\n \"trailingComments\",\n \"innerComments\",\n \"range\",\n \"start\",\n \"end\",\n ]);\n function walk(node: unknown, depth: number): void {\n if (found || !node || typeof node !== \"object\") return;\n if (depth > MAX_DEPTH) return;\n if (seen.has(node as object)) return;\n seen.add(node as object);\n if (Array.isArray(node)) {\n for (const c of node) walk(c, depth + 1);\n return;\n }\n const n = node as Record<string, unknown> & { type?: string };\n if (n.type === \"JSXElement\") {\n const opening = n.openingElement as\n | { type?: string; name?: { type?: string; name?: string } }\n | undefined;\n if (opening?.type === \"JSXOpeningElement\" && opening.name) {\n const namedNode = opening.name;\n if (namedNode.type === \"JSXIdentifier\" && namedNode.name === name) {\n found = n as unknown as { children: unknown[] };\n return;\n }\n }\n }\n for (const key of Object.keys(n)) {\n if (SKIP_KEYS.has(key)) continue;\n walk(n[key], depth + 1);\n }\n }\n walk(ast, 0);\n return found;\n}\n\nfunction injectClientComponentViaRegex(\n layoutPath: string,\n content: string,\n spec: string,\n): EntryWiringResult {\n const importLine = `import GGPixelClient from ${JSON.stringify(spec)};`;\n const lines = content.split(\"\\n\");\n let insertImportAt = 0;\n for (let i = 0; i < lines.length; i++) {\n if (/^\\s*import\\s/.test(lines[i] ?? \"\")) insertImportAt = i + 1;\n }\n lines.splice(insertImportAt, 0, importLine);\n\n const updated = lines.join(\"\\n\");\n const childrenIdx = updated.lastIndexOf(\"{children}\");\n if (childrenIdx === -1) {\n writeFileSync(layoutPath, updated, \"utf8\");\n return {\n kind: \"skipped\",\n reason: \"added import but couldn't find {children} to render <GGPixelClient />\",\n };\n }\n const before = updated.slice(0, childrenIdx);\n const after = updated.slice(childrenIdx);\n const finalContent = before + \"<GGPixelClient />\\n \" + after;\n writeFileSync(layoutPath, finalContent, \"utf8\");\n return { kind: \"injected\", entryPath: layoutPath };\n}\n\n/**\n * Adds `@iroaxel/gg-pixel` to `serverExternalPackages` in the user's\n * next.config.{ts,mjs,js,cjs}. Required so Next's bundler doesn't statically\n * follow `better-sqlite3` (an optional native peer dep) when the SDK is\n * imported server-side.\n *\n * Uses `magicast` (Babel-backed AST surgery) so we handle the long tail of\n * config shapes the previous regex implementation mangled:\n * - wrappers like `withSentryConfig(config)` / `withMDX({...})`\n * - object spreads `{ ...baseConfig, foo: bar }`\n * - `module.exports = function() { return {...}; }`\n * - `satisfies NextConfig`, `as const`, generic type assertions\n * - existing arrays containing comments or trailing commas\n *\n * Falls back to the original line-injection only when magicast can't load\n * the config (extremely rare — would require syntactically invalid JS/TS).\n */\nfunction patchNextConfig(projectRoot: string): void {\n const candidates = [\"next.config.ts\", \"next.config.mjs\", \"next.config.js\", \"next.config.cjs\"];\n let configPath: string | null = null;\n for (const c of candidates) {\n const p = join(projectRoot, c);\n if (existsSync(p)) {\n configPath = p;\n break;\n }\n }\n if (!configPath) {\n configPath = join(projectRoot, \"next.config.ts\");\n writeFileSync(\n configPath,\n `import type { NextConfig } from \"next\";\\n\\nconst nextConfig: NextConfig = {\\n // Keeps Next's bundler from trying to compile better-sqlite3 (native dep).\\n serverExternalPackages: [\"@iroaxel/gg-pixel\"],\\n};\\n\\nexport default nextConfig;\\n`,\n \"utf8\",\n );\n return;\n }\n patchNextConfigViaAst(configPath);\n}\n\nconst PIXEL_PKG = \"@iroaxel/gg-pixel\";\n\nfunction patchNextConfigViaAst(configPath: string): void {\n const original = readFileSync(configPath, \"utf8\");\n if (original.includes(PIXEL_PKG)) return; // already wired\n\n // Lazy require so the rest of install.ts doesn't pay the magicast import\n // cost for non-Next.js projects. magicast is in `dependencies` so it's\n // always installed; the require resolves synchronously.\n let parseModule: (code: string) => MagicastModule;\n let generateCode: (m: MagicastModule) => { code: string };\n try {\n const mod = nodeRequire(\"magicast\") as {\n parseModule: typeof parseModule;\n generateCode: typeof generateCode;\n };\n parseModule = mod.parseModule;\n generateCode = mod.generateCode;\n } catch {\n return patchNextConfigViaRegex(configPath, original);\n }\n\n let module_: MagicastModule;\n try {\n module_ = parseModule(original);\n } catch {\n return patchNextConfigViaRegex(configPath, original);\n }\n\n // Resolve the config object regardless of how it's exported.\n const cfg = resolveNextConfigObject(module_);\n if (!cfg) {\n // Wrapped in a function call we can't unwrap (e.g. defineConfig(() => ({}))\n // returning a closure). Fall back to regex injection.\n return patchNextConfigViaRegex(configPath, original);\n }\n\n // Add to existing array, or create one. Magicast surfaces array nodes as\n // proxies that respond to `includes` / `push` regardless of source shape;\n // we cast through `unknown` because magicast's type surface for nested\n // values is intentionally loose.\n type ArrLike = { includes(v: string): boolean; push(v: string): void };\n const existing = cfg.serverExternalPackages as unknown;\n const isArrayLike =\n Array.isArray(existing) ||\n (typeof existing === \"object\" &&\n existing !== null &&\n (existing as { $type?: string }).$type === \"array\");\n if (isArrayLike) {\n const arr = existing as ArrLike;\n if (arr.includes(PIXEL_PKG)) return;\n arr.push(PIXEL_PKG);\n } else {\n cfg.serverExternalPackages = [PIXEL_PKG];\n }\n\n const out = generateCode(module_).code;\n if (out !== original) writeFileSync(configPath, out, \"utf8\");\n}\n\n/**\n * Walks the magicast module to find the NextConfig object literal, regardless\n * of whether the user wraps it in `withSomething(...)`, exports as `default`\n * vs CJS, or assigns to a const first. Returns the proxied object the caller\n * can mutate, or null if it's a function/expression we can't statically reach.\n */\ninterface MagicastObject {\n [key: string]: unknown;\n $type?: string;\n $args?: unknown[];\n}\ninterface MagicastModule {\n exports: { default?: MagicastObject } & Record<string, MagicastObject | undefined>;\n $code?: string;\n}\n\nfunction resolveNextConfigObject(mod: MagicastModule): MagicastObject | null {\n const root: MagicastObject | undefined =\n mod.exports.default ?? (mod.exports as MagicastObject | undefined);\n if (!root) return null;\n return unwrapWrappers(root);\n}\n\n/**\n * Many real configs are `withSomething(realConfig)` (Sentry, MDX, PWA, bundle-\n * analyzer, etc.). Walk into the first object-literal argument we can find.\n * If the wrapper takes a function (`defineConfig(() => ({...}))`), we bail —\n * mutating closure bodies via magicast isn't reliable.\n */\nfunction unwrapWrappers(node: MagicastObject): MagicastObject | null {\n let cur = node;\n for (let i = 0; i < 6; i++) {\n if (cur.$type === \"function-call\") {\n const args = cur.$args ?? [];\n const objArg = args.find(\n (a): a is MagicastObject =>\n typeof a === \"object\" && a !== null && (a as MagicastObject).$type !== \"function-call\",\n );\n if (!objArg) return null; // function-as-arg → can't mutate safely\n cur = objArg;\n continue;\n }\n if (cur.$type === \"object\" || cur.$type === undefined) return cur;\n return null;\n }\n return null;\n}\n\nfunction patchNextConfigViaRegex(configPath: string, content: string): void {\n if (content.includes(PIXEL_PKG)) return;\n if (content.includes(\"serverExternalPackages\")) {\n const updated = content.replace(\n /serverExternalPackages\\s*:\\s*\\[([^\\]]*)\\]/,\n (_match: string, inside: string) => {\n const trimmed = inside.trim();\n const sep = trimmed.length > 0 ? \", \" : \"\";\n return `serverExternalPackages: [${trimmed}${sep}${JSON.stringify(PIXEL_PKG)}]`;\n },\n );\n if (updated !== content) writeFileSync(configPath, updated, \"utf8\");\n return;\n }\n const objStart =\n /(const\\s+\\w+\\s*(?::\\s*\\w+)?\\s*=\\s*\\{|module\\.exports\\s*=\\s*\\{|export\\s+default\\s*\\{)/;\n const m = objStart.exec(content);\n if (m) {\n const insertAt = m.index + m[0].length;\n const updated =\n content.slice(0, insertAt) +\n `\\n serverExternalPackages: [${JSON.stringify(PIXEL_PKG)}],` +\n content.slice(insertAt);\n writeFileSync(configPath, updated, \"utf8\");\n }\n}\n\nfunction wireSveltekit({ projectRoot, projectKey, ingestUrl }: WiringInput): WiringResult {\n // SvelteKit auto-loads src/hooks.server.ts and src/hooks.client.ts.\n const serverPath = join(projectRoot, \"src/hooks.server.ts\");\n const clientPath = join(projectRoot, \"src/hooks.client.ts\");\n if (!existsSync(dirname(serverPath))) mkdirSync(dirname(serverPath), { recursive: true });\n\n upsertPixelBlockInFile(\n serverPath,\n `import { initPixel } from \"@iroaxel/gg-pixel\";\ninitPixel({\n projectKey: process.env.GG_PIXEL_KEY ?? ${JSON.stringify(projectKey)},\n sink: { kind: \"http\", ingestUrl: ${JSON.stringify(`${ingestUrl}/ingest`)} },\n});`,\n );\n upsertPixelBlockInFile(\n clientPath,\n `import { initPixel } from \"@iroaxel/gg-pixel/browser\";\ninitPixel({\n projectKey: ${JSON.stringify(projectKey)},\n ingestUrl: ${JSON.stringify(ingestUrl)},\n});`,\n );\n return {\n primaryInitPath: clientPath,\n entryWiring: { kind: \"injected\", entryPath: clientPath },\n secondaryInit: {\n path: serverPath,\n description: \"SvelteKit server hooks (auto-loaded)\",\n },\n warnings: [],\n };\n}\n\nfunction wireNuxt({ projectRoot, projectKey, ingestUrl }: WiringInput): WiringResult {\n // Nuxt auto-loads plugins/*.client.ts and plugins/*.server.ts.\n const pluginsDir = join(projectRoot, \"plugins\");\n mkdirSync(pluginsDir, { recursive: true });\n const serverPath = join(pluginsDir, \"gg-pixel.server.ts\");\n const clientPath = join(pluginsDir, \"gg-pixel.client.ts\");\n writeFileSync(\n serverPath,\n `import { initPixel } from \"@iroaxel/gg-pixel\";\\nexport default defineNuxtPlugin(() => {\\n initPixel({\\n projectKey: process.env.GG_PIXEL_KEY ?? ${JSON.stringify(projectKey)},\\n sink: { kind: \"http\", ingestUrl: ${JSON.stringify(`${ingestUrl}/ingest`)} },\\n });\\n});\\n`,\n \"utf8\",\n );\n writeFileSync(\n clientPath,\n `import { initPixel } from \"@iroaxel/gg-pixel/browser\";\\nexport default defineNuxtPlugin(() => {\\n initPixel({\\n projectKey: ${JSON.stringify(projectKey)},\\n ingestUrl: ${JSON.stringify(ingestUrl)},\\n });\\n});\\n`,\n \"utf8\",\n );\n return {\n primaryInitPath: clientPath,\n entryWiring: { kind: \"injected\", entryPath: clientPath },\n secondaryInit: { path: serverPath, description: \"Nuxt server plugin (auto-loaded)\" },\n warnings: [],\n };\n}\n\nfunction wireRemix({ projectRoot, projectKey, ingestUrl }: WiringInput): WiringResult {\n // Remix uses app/entry.server.tsx and app/entry.client.tsx.\n const serverPath = pickPath(projectRoot, [\"app/entry.server.tsx\", \"app/entry.server.jsx\"]);\n const clientPath = pickPath(projectRoot, [\"app/entry.client.tsx\", \"app/entry.client.jsx\"]);\n const warnings: string[] = [];\n\n // Drop a small init module to import.\n const clientInitPath = join(projectRoot, \"gg-pixel.client.mjs\");\n writeFileSync(clientInitPath, renderBrowserInitFile(ingestUrl, projectKey), \"utf8\");\n\n if (clientPath) {\n injectImport(clientPath, clientInitPath);\n } else {\n warnings.push(\n \"No app/entry.client.tsx found. Run `npx remix reveal` then re-run pixel install.\",\n );\n }\n\n // Server-side: write a small init we import from entry.server.\n const serverInitPath = join(projectRoot, \"gg-pixel.server.mjs\");\n writeFileSync(serverInitPath, renderInitFile(ingestUrl), \"utf8\");\n let serverEntry: EntryWiringResult = { kind: \"no_entry_found\" };\n if (serverPath) {\n serverEntry = injectImport(serverPath, serverInitPath);\n } else {\n warnings.push(\n \"No app/entry.server.tsx found. Run `npx remix reveal` then re-run pixel install.\",\n );\n }\n void serverEntry;\n\n return {\n primaryInitPath: clientInitPath,\n entryWiring: clientPath\n ? { kind: \"injected\", entryPath: clientPath }\n : { kind: \"no_entry_found\" },\n secondaryInit: { path: serverInitPath, description: \"Remix server init\" },\n warnings,\n };\n}\n\nfunction wireElectron({ projectRoot, pkg, projectKey, ingestUrl }: WiringInput): WiringResult {\n const warnings: string[] = [];\n const isMainEsm = pkg.type === \"module\";\n const mainInitPath = isMainEsm\n ? join(projectRoot, \"gg-pixel.main.mjs\")\n : join(projectRoot, \"gg-pixel.main.cjs\");\n writeFileSync(\n mainInitPath,\n isMainEsm ? renderInitFile(ingestUrl, projectKey) : renderInitFileCjs(ingestUrl, projectKey),\n \"utf8\",\n );\n\n // ── Main entry resolution: pkg.main might point at compiled output\n // (e.g. dist/main/index.js for TS-compiled apps like pocket-agent).\n // We prefer the source file so the import survives `npm run build`.\n const mainEntry = resolveMainEntryFromPkg(projectRoot, pkg);\n let mainWiring: EntryWiringResult = { kind: \"no_entry_found\" };\n if (mainEntry && existsSync(mainEntry)) {\n mainWiring = injectImport(mainEntry, mainInitPath);\n }\n\n // ── Renderer: HTML-with-CSP apps use the IIFE bundle; module-system\n // apps use the .mjs init.\n const htmlFiles = findRendererHtmlFiles(projectRoot);\n let rendererInitPath: string;\n if (htmlFiles.length > 0) {\n const rendererDir = dirname(htmlFiles[0]!);\n rendererInitPath = join(rendererDir, \"gg-pixel.browser.iife.js\");\n if (!copyIifeBundle(projectRoot, rendererInitPath)) {\n warnings.push(\n \"Could not copy gg-pixel browser IIFE bundle — install @iroaxel/gg-pixel and re-run.\",\n );\n }\n let wiredAny = false;\n for (const html of htmlFiles) {\n const r = patchRendererHtml(html, rendererInitPath, projectKey, ingestUrl);\n // Both \"patched\" (changed on disk) and \"already\" (no-op because the\n // file is up to date with the current key) count as success.\n if (r === \"patched\" || r === \"already\") wiredAny = true;\n }\n if (!wiredAny) {\n warnings.push(\n `Found HTML files in ${rendererDir} but couldn't patch any — they may have unusual CSP or no <head>.`,\n );\n }\n } else {\n rendererInitPath = join(projectRoot, \"gg-pixel.renderer.mjs\");\n writeFileSync(rendererInitPath, renderBrowserInitFile(ingestUrl, projectKey), \"utf8\");\n const rendererEntry = pickPath(projectRoot, [\n \"src/renderer/index.ts\",\n \"src/renderer/index.tsx\",\n \"src/renderer/index.js\",\n \"src/renderer/main.ts\",\n \"src/renderer/main.tsx\",\n \"src/renderer/main.js\",\n \"renderer/index.ts\",\n \"renderer/index.tsx\",\n \"renderer/index.js\",\n \"renderer.ts\",\n \"renderer.tsx\",\n \"renderer.js\",\n // `src/renderer.{ts,tsx,js}` is the convention used by multi-window\n // Electron apps that keep all renderer entries in src/.\n \"src/renderer.ts\",\n \"src/renderer.tsx\",\n \"src/renderer.js\",\n \"src/index.tsx\",\n \"src/index.jsx\",\n \"src/main.tsx\",\n \"src/main.jsx\",\n ]);\n if (rendererEntry) injectImport(rendererEntry, rendererInitPath);\n else\n warnings.push(\n 'Could not auto-detect the Electron renderer entry. Add `import \"./gg-pixel.renderer.mjs\";` to the top of your renderer entry file.',\n );\n }\n\n return {\n primaryInitPath: rendererInitPath,\n entryWiring: { kind: \"injected\", entryPath: rendererInitPath },\n secondaryInit: {\n path: mainInitPath,\n description:\n \"Electron main-process init\" +\n (mainWiring.kind === \"injected\" ? ` (wired into ${mainEntry})` : \"\"),\n },\n warnings,\n };\n}\n\nfunction resolveMainEntryFromPkg(projectRoot: string, pkg: PackageJson): string | null {\n if (pkg.main) {\n const sourceCandidates: string[] = [];\n const main = pkg.main;\n // dist/X.js → src/X.ts (most common TS-compiled layout)\n if (/^(dist|build|\\.next|out)\\//.test(main)) {\n const swap = main.replace(/^(dist|build|\\.next|out)\\//, \"src/\");\n if (swap.endsWith(\".js\")) {\n sourceCandidates.push(swap.replace(/\\.js$/, \".ts\"));\n sourceCandidates.push(swap.replace(/\\.js$/, \".tsx\"));\n }\n sourceCandidates.push(swap);\n }\n if (main.endsWith(\".js\")) {\n sourceCandidates.push(main.replace(/\\.js$/, \".ts\"));\n sourceCandidates.push(main.replace(/\\.js$/, \".tsx\"));\n }\n for (const c of sourceCandidates) {\n const p = join(projectRoot, c);\n if (existsSync(p)) return p;\n }\n const literal = join(projectRoot, main);\n if (existsSync(literal)) return literal;\n }\n return pickPath(projectRoot, [\n \"main.js\",\n \"main.ts\",\n \"src/main.js\",\n \"src/main.ts\",\n \"src/main/index.ts\",\n \"src/main/index.js\",\n \"electron/main.js\",\n \"electron/main.ts\",\n ]);\n}\n\n// Directories the installer scans for renderer HTML files. `src` covers the\n// common multi-window Electron pattern where each window has a paired\n// `src/<name>.html` + `src/<name>.ts` entry (shortformed-style apps).\nconst RENDERER_HTML_DIRS = [\"ui\", \"renderer\", \"src/renderer\", \"src\", \"public\", \"static\"];\n\nfunction findRendererHtmlFiles(projectRoot: string): string[] {\n for (const dir of RENDERER_HTML_DIRS) {\n const root = join(projectRoot, dir);\n if (!existsSync(root)) continue;\n const html: string[] = [];\n let entries: string[];\n try {\n entries = readdirSync(root);\n } catch {\n continue;\n }\n for (const e of entries) {\n if (!e.endsWith(\".html\")) continue;\n const p = join(root, e);\n try {\n const c = readFileSync(p, \"utf8\");\n if (/<meta[^>]+content-security-policy/i.test(c) || /<script[\\s>]/i.test(c)) {\n html.push(p);\n }\n } catch {\n // ignore\n }\n }\n if (html.length > 0) return html;\n }\n return [];\n}\n\nfunction copyIifeBundle(projectRoot: string, dest: string): boolean {\n const candidates = [\n join(projectRoot, \"node_modules/@iroaxel/gg-pixel/dist/browser.iife.global.js\"),\n join(projectRoot, \"node_modules/@iroaxel/gg-pixel/dist/browser.iife.js\"),\n ];\n for (const c of candidates) {\n if (existsSync(c)) {\n try {\n writeFileSync(dest, readFileSync(c, \"utf8\"), \"utf8\");\n return true;\n } catch {\n // continue\n }\n }\n }\n return false;\n}\n\n// HTML comment that delimits the auto-injected gg-pixel block in renderer\n// HTML. Used both to recognise an existing injection (so re-installs replace\n// it instead of stacking) and as the human-readable header on fresh writes.\nconst PIXEL_HTML_MARKER = \"<!-- gg-pixel: auto-wired by arcicoder pixel install -->\";\n\nfunction patchRendererHtml(\n htmlPath: string,\n iifePath: string,\n projectKey: string,\n ingestUrl: string,\n): \"patched\" | \"already\" | \"not-applicable\" {\n let content: string;\n try {\n content = readFileSync(htmlPath, \"utf8\");\n } catch {\n return \"not-applicable\";\n }\n\n // Strip any existing gg-pixel injection (legacy or recent) before re-emitting\n // with the current key. Detected by the comment marker; conservative match\n // ends at the first `</script>` after the second injected `<script>` tag.\n const original = content;\n const markerIdx = content.indexOf(PIXEL_HTML_MARKER);\n if (markerIdx !== -1) {\n // Two consecutive script tags follow the marker. Find the close of the\n // SECOND one, then eat trailing whitespace/newline.\n const firstScriptEnd = content.indexOf(\"</script>\", markerIdx);\n const secondScriptEnd =\n firstScriptEnd !== -1\n ? content.indexOf(\"</script>\", firstScriptEnd + \"</script>\".length)\n : -1;\n if (secondScriptEnd !== -1) {\n let stripEnd = secondScriptEnd + \"</script>\".length;\n while (stripEnd < content.length && /\\s/.test(content[stripEnd]!)) stripEnd++;\n // Walk back past leading newline/whitespace before the marker so we\n // don't leave a blank line in the head.\n let stripStart = markerIdx;\n while (stripStart > 0 && /[ \\t]/.test(content[stripStart - 1]!)) stripStart--;\n if (stripStart > 0 && content[stripStart - 1] === \"\\n\") stripStart--;\n content = content.slice(0, stripStart) + content.slice(stripEnd);\n }\n }\n\n const ingestOrigin = new URL(ingestUrl).origin;\n // Match content=\"...\" OR content='...'. Critical: don't use `[^\"']` for\n // the inner — CSPs legitimately contain `'self'` etc., which would halt\n // a `[^\"']+` match at the first single-quote and corrupt the directive.\n content = content.replace(\n /(<meta[^>]+http-equiv=[\"']?content-security-policy[\"']?[^>]*content=)(\"([^\"]+)\"|'([^']+)')/i,\n (\n _match: string,\n before: string,\n _all: string,\n dq: string | undefined,\n sq: string | undefined,\n ) => {\n const quote = dq !== undefined ? '\"' : \"'\";\n const csp = dq !== undefined ? dq : (sq as string);\n let updated = csp;\n if (/connect-src\\s/i.test(csp)) {\n if (!csp.includes(ingestOrigin)) {\n updated = csp.replace(/(connect-src[^;]*)/i, `$1 ${ingestOrigin}`);\n }\n } else {\n updated = csp.trim().replace(/;?$/, `; connect-src 'self' ${ingestOrigin};`);\n }\n return before + quote + updated + quote;\n },\n );\n\n const relScript = relative(dirname(htmlPath), iifePath).split(sep).join(\"/\");\n const inject = `\\n ${PIXEL_HTML_MARKER}\\n <script src=\"${relScript}\"></script>\\n <script>\\n if (window.GGPixel) GGPixel.initPixel({ projectKey: ${JSON.stringify(projectKey)}, ingestUrl: ${JSON.stringify(ingestUrl)} });\\n </script>\\n`;\n if (/<head[^>]*>/i.test(content)) {\n content = content.replace(/(<head[^>]*>)/i, `$1${inject}`);\n } else if (/<html[^>]*>/i.test(content)) {\n content = content.replace(/(<html[^>]*>)/i, `$1<head>${inject}</head>`);\n } else {\n return \"not-applicable\";\n }\n if (content === original) return \"already\";\n writeFileSync(htmlPath, content, \"utf8\");\n return \"patched\";\n}\n\nfunction wireTauri({ projectRoot, pkg, projectKey, ingestUrl }: WiringInput): WiringResult {\n // Tauri frontend = web. Use Browser SDK on the JS side.\n // The Rust backend has no SDK yet — we say so honestly.\n const initPath = join(projectRoot, \"gg-pixel.init.mjs\");\n writeFileSync(initPath, renderBrowserInitFile(ingestUrl, projectKey), \"utf8\");\n const entryWiring = wireEntryFile(projectRoot, initPath, pkg);\n return {\n primaryInitPath: initPath,\n entryWiring,\n warnings: [\n \"Tauri Rust backend is not instrumented — no Rust SDK exists yet. Frontend errors are captured.\",\n ],\n };\n}\n\nfunction wireWorkers({ projectRoot, projectKey, ingestUrl }: WiringInput): WiringResult {\n // Cloudflare Workers / Vercel Edge / etc. The user's worker exports a default\n // object with fetch/scheduled/queue handlers. We can't safely refactor their\n // default export with regex, so we drop a snippet showing the wrap pattern\n // and warn the user.\n const initPath = join(projectRoot, \"gg-pixel.workers.snippet.ts\");\n writeFileSync(\n initPath,\n `// gg-pixel — Cloudflare Workers wiring snippet.\n// Auto-generated by arcicoder pixel install. Wrap your default export with\n// withPixel(...) so any throw in your handler is auto-reported. Example:\n//\n// import { withPixel } from \"@iroaxel/gg-pixel/workers\";\n//\n// export default withPixel(\n// { projectKey: ${JSON.stringify(projectKey)} },\n// {\n// async fetch(req, env, ctx) { /* your code */ },\n// async scheduled(evt, env, ctx) { /* your code */ },\n// },\n// );\n//\n// For manual reports inside a handler:\n//\n// import { reportPixel } from \"@iroaxel/gg-pixel/workers\";\n// reportPixel(ctx, { projectKey: ${JSON.stringify(projectKey)} }, {\n// message: \"user clicked the broken button\",\n// });\n//\n// Your project_key is publishable — safe to commit.\n\nimport { withPixel, reportPixel } from \"@iroaxel/gg-pixel/workers\";\nexport const PIXEL_KEY = ${JSON.stringify(projectKey)};\nexport const PIXEL_INGEST = ${JSON.stringify(ingestUrl)};\nexport { withPixel, reportPixel };\n`,\n \"utf8\",\n );\n return {\n primaryInitPath: initPath,\n entryWiring: { kind: \"no_entry_found\" },\n warnings: [\n `Cloudflare Workers default exports can't be auto-wrapped safely. Open ${initPath} for a 3-line snippet you can paste into your worker.`,\n ],\n };\n}\n\nfunction wireReactNative({ projectRoot }: WiringInput): WiringResult {\n // RN's JS engine is neither a real browser nor Node. Our current SDKs\n // don't reliably hook it. Be honest rather than ship something broken.\n return {\n primaryInitPath: join(projectRoot, \"(not-installed)\"),\n entryWiring: { kind: \"skipped\", reason: \"react-native SDK not built yet\" },\n warnings: [\n \"React Native is not yet supported — its JS runtime is neither browser nor Node.\",\n \"A dedicated React Native SDK will be a future slice.\",\n ],\n };\n}\n\n// ── small helpers used by the per-framework writers ────────────────\n\nfunction pickPath(root: string, candidates: string[]): string | null {\n for (const c of candidates) {\n const p = join(root, c);\n if (existsSync(p)) return p;\n }\n return null;\n}\n\n// Wrap an auto-generated snippet between markers so re-installs (which mint\n// a fresh project_id+key+secret when the local mapping is legacy) can replace\n// the previous block in-place instead of bailing on a \"looks already wired\"\n// check and leaving a stale key behind. User code outside the markers is\n// preserved untouched.\nconst PIXEL_MARK_BEGIN = \"// >>> gg-pixel auto-generated — do not edit between these markers <<<\";\nconst PIXEL_MARK_END = \"// >>> /gg-pixel <<<\";\n\nexport function wrapPixelBlock(content: string): string {\n return `${PIXEL_MARK_BEGIN}\\n${content.replace(/\\s+$/, \"\")}\\n${PIXEL_MARK_END}\\n`;\n}\n\n/**\n * If `existing` already contains a markered gg-pixel block, replace it with a\n * freshly-wrapped `block`. Otherwise append the wrapped block to the end of\n * `existing`. Idempotent when the new block matches the existing one.\n */\nexport function upsertPixelBlock(existing: string, block: string): string {\n const wrapped = wrapPixelBlock(block);\n const beginIdx = existing.indexOf(PIXEL_MARK_BEGIN);\n if (beginIdx !== -1) {\n const endIdx = existing.indexOf(PIXEL_MARK_END, beginIdx);\n if (endIdx !== -1) {\n const after = endIdx + PIXEL_MARK_END.length;\n const trailNL = existing[after] === \"\\n\" ? 1 : 0;\n return existing.slice(0, beginIdx) + wrapped + existing.slice(after + trailNL);\n }\n }\n if (existing.length === 0) return wrapped;\n const sep = existing.endsWith(\"\\n\") ? \"\" : \"\\n\";\n return existing + sep + \"\\n\" + wrapped;\n}\n\nfunction upsertPixelBlockInFile(filePath: string, block: string): void {\n const existing = existsSync(filePath) ? readFileSync(filePath, \"utf8\") : \"\";\n const cleaned = stripLegacyPixelContent(existing);\n const next = upsertPixelBlock(cleaned, block);\n if (next !== existing) writeFileSync(filePath, next, \"utf8\");\n}\n\n/**\n * Remove unmarkered gg-pixel content emitted by older versions of the\n * installer so re-installs don't end up with two `register()` exports\n * (or two `initPixel(...)` calls) — one legacy + one in the new markered\n * block. Conservative: only operates outside the marker delimiters.\n */\nexport function stripLegacyPixelContent(content: string): string {\n if (!content.includes(\"@iroaxel/gg-pixel\")) return content;\n\n const beginIdx = content.indexOf(PIXEL_MARK_BEGIN);\n const endIdx = beginIdx === -1 ? -1 : content.indexOf(PIXEL_MARK_END, beginIdx);\n const insideMarkers = (start: number, end: number): boolean =>\n beginIdx !== -1 && endIdx !== -1 && start >= beginIdx && end <= endIdx + PIXEL_MARK_END.length;\n\n // Walk the source and collect ranges to delete. Patterns:\n // 1. `[leading // comment lines] export async function register() { … gg-pixel … }`\n // — Next.js `instrumentation.ts` from the pre-marker installer.\n // 2. `[leading // comment lines] import { initPixel } … initPixel({ … });`\n // — SvelteKit hooks from the pre-marker installer.\n const ranges: Array<{ start: number; end: number }> = [];\n\n // (1) brace-balanced register() containing @iroaxel/gg-pixel.\n // The capture group is INSIDE the match — comments are part of m[0], not\n // before it — so blockStart is just m.index (skipping a leading newline if\n // we anchored on `\\n`).\n const registerRe =\n /(?:^|\\n)((?:[ \\t]*\\/\\/[^\\n]*\\n)*)[ \\t]*export\\s+async\\s+function\\s+register\\s*\\(\\s*\\)\\s*\\{/g;\n let m: RegExpExecArray | null;\n while ((m = registerRe.exec(content)) !== null) {\n const blockStart = m.index + (content[m.index] === \"\\n\" ? 1 : 0);\n const openBraceIdx = m.index + m[0].length - 1;\n let depth = 1;\n let i = openBraceIdx + 1;\n while (i < content.length && depth > 0) {\n const ch = content[i];\n if (ch === \"{\") depth++;\n else if (ch === \"}\") depth--;\n i++;\n }\n if (depth !== 0) continue;\n const blockEnd = i;\n const blockText = content.slice(blockStart, blockEnd);\n if (!blockText.includes(\"@iroaxel/gg-pixel\")) continue;\n if (insideMarkers(blockStart, blockEnd)) continue;\n const trailingNL = content[blockEnd] === \"\\n\" ? 1 : 0;\n ranges.push({ start: blockStart, end: blockEnd + trailingNL });\n }\n\n // (2) `import { initPixel } from \"@iroaxel/gg-pixel[/...]\"` followed within\n // ~2KB by a balanced `initPixel({ … });` call. Same comment-inside-match\n // rule as (1).\n const importRe =\n /(?:^|\\n)((?:[ \\t]*\\/\\/[^\\n]*\\n)*)[ \\t]*import\\s*\\{\\s*initPixel[^}]*\\}\\s*from\\s*\"@iroaxel\\/gg-pixel(?:\\/[\\w-]+)?\"\\s*;?\\s*\\n/g;\n while ((m = importRe.exec(content)) !== null) {\n const blockStart = m.index + (content[m.index] === \"\\n\" ? 1 : 0);\n // Find `initPixel({` after the import statement and brace-match the call.\n const callIdx = content.indexOf(\"initPixel(\", importRe.lastIndex);\n if (callIdx === -1 || callIdx - importRe.lastIndex > 2048) continue;\n const openParen = content.indexOf(\"(\", callIdx);\n let depth = 1;\n let i = openParen + 1;\n while (i < content.length && depth > 0) {\n const ch = content[i];\n if (ch === \"(\" || ch === \"{\") depth++;\n else if (ch === \")\" || ch === \"}\") depth--;\n i++;\n }\n if (depth !== 0) continue;\n // Eat the trailing semicolon + spaces + newline.\n while (i < content.length && (content[i] === \";\" || content[i] === \" \")) i++;\n const trailingNL = content[i] === \"\\n\" ? 1 : 0;\n const blockEnd = i + trailingNL;\n if (insideMarkers(blockStart, blockEnd)) continue;\n ranges.push({ start: blockStart, end: blockEnd });\n }\n\n if (ranges.length === 0) return content;\n ranges.sort((a, b) => b.start - a.start);\n let out = content;\n for (const r of ranges) out = out.slice(0, r.start) + out.slice(r.end);\n return out.replace(/\\n{3,}/g, \"\\n\\n\");\n}\n\nfunction injectImport(entryPath: string, initFilePath: string): EntryWiringResult {\n let content: string;\n try {\n content = readFileSync(entryPath, \"utf8\");\n } catch (err) {\n return { kind: \"skipped\", reason: `unreadable: ${(err as Error).message}` };\n }\n const initBasename = initFilePath.split(sep).pop() ?? \"gg-pixel.init.mjs\";\n if (content.includes(initBasename) || content.includes(\"@iroaxel/gg-pixel\")) {\n return { kind: \"already_present\", entryPath };\n }\n const fromDir = dirname(entryPath);\n let spec = relative(fromDir, initFilePath).split(sep).join(\"/\");\n if (!spec.startsWith(\".\")) spec = \"./\" + spec;\n // Detect CJS by content: .cjs, or .js using `require(` and lacking ESM markers.\n // Electron's main.js is the canonical case here.\n const isCjs =\n entryPath.endsWith(\".cjs\") ||\n (entryPath.endsWith(\".js\") &&\n /\\brequire\\s*\\(/.test(content) &&\n !/\\bimport\\s+/.test(content) &&\n !/\\bexport\\s+/.test(content));\n const importLine = isCjs\n ? `require(${JSON.stringify(spec)});`\n : `import ${JSON.stringify(spec)};`;\n const lines = content.split(\"\\n\");\n let insertAt = 0;\n if (lines[0]?.startsWith(\"#!\")) insertAt = 1;\n while (\n insertAt < lines.length &&\n /^\\s*(?:[\"']use strict[\"']|\\/\\/|\\/\\*)/.test(lines[insertAt] ?? \"\")\n ) {\n insertAt++;\n }\n const updated = [...lines.slice(0, insertAt), importLine, ...lines.slice(insertAt)].join(\"\\n\");\n writeFileSync(entryPath, updated, \"utf8\");\n return { kind: \"injected\", entryPath };\n}\n\n// ── /Framework wiring ───────────────────────────────────────────────\n\nexport function isBrowserProject(pkg: PackageJson, projectRoot: string): boolean {\n const all = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };\n const browserishDeps = [\n \"react\",\n \"react-dom\",\n \"vue\",\n \"@vue/runtime-core\",\n \"svelte\",\n \"next\",\n \"vite\",\n \"@vitejs/plugin-react\",\n \"@angular/core\",\n \"solid-js\",\n \"preact\",\n \"@remix-run/react\",\n \"astro\",\n \"qwik\",\n \"@sveltejs/kit\",\n \"expo\",\n ];\n if (browserishDeps.some((d) => d in all)) return true;\n if (pkg.browser !== undefined) return true;\n if (existsSync(join(projectRoot, \"index.html\"))) return true;\n if (existsSync(join(projectRoot, \"public\", \"index.html\"))) return true;\n return false;\n}\n\nexport function renderBrowserInitFile(ingestUrl: string, projectKey: string): string {\n return `// gg-pixel init — auto-generated by arcicoder pixel install.\n// The project_key is publishable (designed to live in browser bundles).\nimport { initPixel } from \"@iroaxel/gg-pixel/browser\";\n\ninitPixel({\n projectKey: ${JSON.stringify(projectKey)},\n ingestUrl: ${JSON.stringify(ingestUrl)},\n});\n`;\n}\n\n// ── Python ──────────────────────────────────────────────────────────\n\nconst PYTHON_MARKERS = [\"pyproject.toml\", \"setup.py\", \"requirements.txt\", \"Pipfile\"];\n\nexport function findPythonProjectRoot(start: string): string | null {\n let dir = start;\n for (let i = 0; i < 20; i++) {\n if (PYTHON_MARKERS.some((m) => existsSync(join(dir, m)))) return dir;\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n return null;\n}\n\nexport function detectPythonPackageManager(projectRoot: string): PythonPackageManager {\n if (existsSync(join(projectRoot, \"uv.lock\"))) return \"uv\";\n if (existsSync(join(projectRoot, \"poetry.lock\"))) return \"poetry\";\n if (existsSync(join(projectRoot, \"Pipfile.lock\"))) return \"pipenv\";\n return \"pip\";\n}\n\nfunction pickClosestRoot(roots: Array<string | null>): string | null {\n let best: string | null = null;\n for (const r of roots) {\n if (!r) continue;\n if (!best || r.length > best.length) best = r;\n }\n return best;\n}\n\nconst GO_MARKER = \"go.mod\";\nconst RUBY_MARKERS = [\"Gemfile\"];\n\nexport function findGoProjectRoot(start: string): string | null {\n let dir = start;\n for (let i = 0; i < 20; i++) {\n if (existsSync(join(dir, GO_MARKER))) return dir;\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n return null;\n}\n\nexport function findRubyProjectRoot(start: string): string | null {\n let dir = start;\n for (let i = 0; i < 20; i++) {\n for (const m of RUBY_MARKERS) {\n if (existsSync(join(dir, m))) return dir;\n }\n // Also catch *.gemspec files at this level.\n try {\n const entries = readdirSync(dir);\n if (entries.some((e) => e.endsWith(\".gemspec\"))) return dir;\n } catch {\n // ignore\n }\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n return null;\n}\n\ninterface NativeInstallContext {\n projectRoot: string;\n opts: InstallOptions;\n ingestUrl: string;\n fetchFn: typeof fetch;\n home: string;\n}\n\nasync function installGo(ctx: NativeInstallContext): Promise<InstallResult> {\n const { projectRoot, opts, ingestUrl, fetchFn, home } = ctx;\n const projectName =\n opts.projectName ?? readGoModuleName(projectRoot) ?? projectRoot.split(\"/\").pop() ?? \"unnamed\";\n const projectsJsonPath = join(home, \".gg\", \"projects.json\");\n const envFilePath = join(projectRoot, \".env\");\n\n const existing = findMappingByPath(projectsJsonPath, projectRoot);\n const existingKey = readEnvKey(envFilePath, \"GG_PIXEL_KEY\");\n let created: CreatedProject;\n let reused = false;\n if (existing && existing.secret && existingKey) {\n created = { id: existing.id, key: existingKey, secret: existing.secret };\n reused = true;\n } else {\n created = await createProject(fetchFn, ingestUrl, projectName);\n }\n\n const packageInstalled = opts.skipPackageInstall ? false : runGoGet(projectRoot);\n\n const initFilePath = join(projectRoot, \"gg_pixel_init.go\");\n writeFileSync(\n initFilePath,\n `// gg-pixel init — auto-generated by arcicoder pixel install.\npackage main\n\nimport (\n\t\"os\"\n\tgg \"github.com/kenkaiiii/gg-pixel-go\"\n)\n\nfunc init() {\n\tkey := os.Getenv(\"GG_PIXEL_KEY\")\n\tif key == \"\" {\n\t\tkey = ${JSON.stringify(created.key)}\n\t}\n\t_ = gg.Init(gg.Options{ProjectKey: key, IngestURL: ${JSON.stringify(`${ingestUrl}/ingest`)}})\n}\n`,\n \"utf8\",\n );\n\n writeEnvKey(envFilePath, \"GG_PIXEL_KEY\", created.key);\n writeProjectsMapping(projectsJsonPath, created.id, projectName, projectRoot, created.secret);\n\n return {\n projectId: created.id,\n projectKey: created.key,\n projectSecret: created.secret,\n projectName,\n projectKind: \"go\",\n projectRoot,\n initFilePath,\n envFilePath,\n projectsJsonPath,\n packageManager: \"pip\",\n packageInstalled,\n entryWiring: { kind: \"no_entry_found\" },\n reused,\n warnings: [\n \"Add `defer ggpixel.Recover()` near the top of your main() so panics are captured before the process exits.\",\n ],\n };\n}\n\nfunction readGoModuleName(projectRoot: string): string | null {\n try {\n const content = readFileSync(join(projectRoot, \"go.mod\"), \"utf8\");\n const match = /^\\s*module\\s+(\\S+)\\s*$/m.exec(content);\n if (!match) return null;\n return match[1]!.split(\"/\").pop() ?? null;\n } catch {\n return null;\n }\n}\n\nfunction runGoGet(projectRoot: string): boolean {\n const result = spawnSync(\"go\", [\"get\", \"github.com/kenkaiiii/gg-pixel-go@latest\"], {\n cwd: projectRoot,\n stdio: \"inherit\",\n });\n return result.status === 0;\n}\n\nasync function installRuby(ctx: NativeInstallContext): Promise<InstallResult> {\n const { projectRoot, opts, ingestUrl, fetchFn, home } = ctx;\n const projectName =\n opts.projectName ?? readRubyAppName(projectRoot) ?? projectRoot.split(\"/\").pop() ?? \"unnamed\";\n const projectsJsonPath = join(home, \".gg\", \"projects.json\");\n const envFilePath = join(projectRoot, \".env\");\n\n const existing = findMappingByPath(projectsJsonPath, projectRoot);\n const existingKey = readEnvKey(envFilePath, \"GG_PIXEL_KEY\");\n let created: CreatedProject;\n let reused = false;\n if (existing && existing.secret && existingKey) {\n created = { id: existing.id, key: existingKey, secret: existing.secret };\n reused = true;\n } else {\n created = await createProject(fetchFn, ingestUrl, projectName);\n }\n\n const packageInstalled = opts.skipPackageInstall ? false : runRubyInstall(projectRoot);\n\n const initFilePath = join(projectRoot, \"gg_pixel_init.rb\");\n writeFileSync(\n initFilePath,\n `# gg-pixel init — auto-generated by arcicoder pixel install.\nrequire \"gg_pixel\"\nGGPixel.init(\n project_key: ENV[\"GG_PIXEL_KEY\"] || ${JSON.stringify(created.key)},\n ingest_url: ${JSON.stringify(`${ingestUrl}/ingest`)},\n)\n`,\n \"utf8\",\n );\n\n writeEnvKey(envFilePath, \"GG_PIXEL_KEY\", created.key);\n writeProjectsMapping(projectsJsonPath, created.id, projectName, projectRoot, created.secret);\n\n return {\n projectId: created.id,\n projectKey: created.key,\n projectSecret: created.secret,\n projectName,\n projectKind: \"ruby\",\n projectRoot,\n initFilePath,\n envFilePath,\n projectsJsonPath,\n packageManager: \"pip\",\n packageInstalled,\n entryWiring: { kind: \"no_entry_found\" },\n reused,\n warnings: [\n `Add \\`require \"./gg_pixel_init\"\\` at the top of your entry script (often \\`config/application.rb\\` for Rails, \\`app.rb\\` for Sinatra, or your main file).`,\n ],\n };\n}\n\nfunction readRubyAppName(projectRoot: string): string | null {\n try {\n const entries = readdirSync(projectRoot);\n const gemspec = entries.find((e) => e.endsWith(\".gemspec\"));\n if (!gemspec) return null;\n return gemspec.replace(/\\.gemspec$/, \"\");\n } catch {\n return null;\n }\n}\n\nfunction runRubyInstall(projectRoot: string): boolean {\n // Prefer bundler if a Gemfile exists.\n if (existsSync(join(projectRoot, \"Gemfile\"))) {\n // Append to Gemfile if not present.\n try {\n const content = readFileSync(join(projectRoot, \"Gemfile\"), \"utf8\");\n if (!content.includes(\"gg_pixel\")) {\n writeFileSync(\n join(projectRoot, \"Gemfile\"),\n content + (content.endsWith(\"\\n\") ? \"\" : \"\\n\") + 'gem \"gg_pixel\"\\n',\n \"utf8\",\n );\n }\n } catch {\n // ignore\n }\n const r = spawnSync(\"bundle\", [\"install\"], { cwd: projectRoot, stdio: \"inherit\" });\n if (r.status === 0) return true;\n }\n const r2 = spawnSync(\"gem\", [\"install\", \"gg_pixel\"], { cwd: projectRoot, stdio: \"inherit\" });\n return r2.status === 0;\n}\n\ninterface PythonInstallContext {\n projectRoot: string;\n opts: InstallOptions;\n ingestUrl: string;\n fetchFn: typeof fetch;\n home: string;\n}\n\nasync function installPython(ctx: PythonInstallContext): Promise<InstallResult> {\n const { projectRoot, opts, ingestUrl, fetchFn, home } = ctx;\n const projectName =\n opts.projectName ?? readPyprojectName(projectRoot) ?? projectRoot.split(\"/\").pop() ?? \"unnamed\";\n\n const projectsJsonPath = join(home, \".gg\", \"projects.json\");\n const envFilePath = join(projectRoot, \".env\");\n\n const existing = findMappingByPath(projectsJsonPath, projectRoot);\n const existingKey = readEnvKey(envFilePath, \"GG_PIXEL_KEY\");\n let created: CreatedProject;\n let reused = false;\n if (existing && existing.secret && existingKey) {\n created = { id: existing.id, key: existingKey, secret: existing.secret };\n reused = true;\n } else {\n created = await createProject(fetchFn, ingestUrl, projectName);\n }\n\n const pm = detectPythonPackageManager(projectRoot);\n const packageInstalled = opts.skipPackageInstall ? false : runPythonInstall(projectRoot, pm);\n\n const initFilePath = join(projectRoot, \"gg_pixel_init.py\");\n writeFileSync(initFilePath, renderPythonInitFile(ingestUrl, created.key), \"utf8\");\n\n writeEnvKey(envFilePath, \"GG_PIXEL_KEY\", created.key);\n writeProjectsMapping(projectsJsonPath, created.id, projectName, projectRoot, created.secret);\n\n const entryWiring = wirePythonEntry(projectRoot, initFilePath);\n\n return {\n projectId: created.id,\n projectKey: created.key,\n projectSecret: created.secret,\n projectName,\n projectKind: \"python\",\n projectRoot,\n initFilePath,\n envFilePath,\n projectsJsonPath,\n packageManager: pm,\n packageInstalled,\n entryWiring,\n reused,\n warnings: [],\n };\n}\n\nfunction readPyprojectName(projectRoot: string): string | null {\n const path = join(projectRoot, \"pyproject.toml\");\n if (!existsSync(path)) return null;\n try {\n const content = readFileSync(path, \"utf8\");\n const match = /^\\s*name\\s*=\\s*[\"']([^\"']+)[\"']/m.exec(content);\n return match?.[1] ?? null;\n } catch {\n return null;\n }\n}\n\nfunction runPythonInstall(projectRoot: string, pm: PythonPackageManager): boolean {\n const cmd =\n pm === \"uv\"\n ? [\"uv\", [\"add\", \"gg-pixel\"]]\n : pm === \"poetry\"\n ? [\"poetry\", [\"add\", \"gg-pixel\"]]\n : pm === \"pipenv\"\n ? [\"pipenv\", [\"install\", \"gg-pixel\"]]\n : [\"pip\", [\"install\", \"gg-pixel\"]];\n const result = spawnSync(cmd[0] as string, cmd[1] as string[], {\n cwd: projectRoot,\n stdio: \"inherit\",\n });\n if (result.status === 0) return true;\n // Fallback: many systems only have `pip3` on PATH.\n if (pm === \"pip\") {\n const r2 = spawnSync(\"pip3\", [\"install\", \"gg-pixel\"], {\n cwd: projectRoot,\n stdio: \"inherit\",\n });\n if (r2.status === 0) return true;\n const r3 = spawnSync(\"python3\", [\"-m\", \"pip\", \"install\", \"gg-pixel\"], {\n cwd: projectRoot,\n stdio: \"inherit\",\n });\n return r3.status === 0;\n }\n return false;\n}\n\nexport function renderPythonInitFile(ingestUrl: string, projectKey: string): string {\n return `\"\"\"gg-pixel init — auto-generated by arcicoder pixel install.\n\nThis file initializes error tracking. Importing it (which the install step\nwires into your entry file) registers the global Python error handlers.\n\"\"\"\nimport os\n\nimport gg_pixel\n\ngg_pixel.init_pixel(\n project_key=os.environ.get(\"GG_PIXEL_KEY\") or ${JSON.stringify(projectKey)},\n ingest_url=${JSON.stringify(`${ingestUrl}/ingest`)},\n)\n`;\n}\n\nfunction wirePythonEntry(projectRoot: string, initFilePath: string): EntryWiringResult {\n const entryPath = findPythonEntryFile(projectRoot);\n if (!entryPath) return { kind: \"no_entry_found\" };\n\n let content: string;\n try {\n content = readFileSync(entryPath, \"utf8\");\n } catch (err) {\n return { kind: \"skipped\", reason: `unreadable: ${(err as Error).message}` };\n }\n\n if (content.includes(\"gg_pixel_init\")) {\n return { kind: \"already_present\", entryPath };\n }\n\n // Compute import name from the relative path. gg_pixel_init.py at root →\n // `gg_pixel_init`. For nested, the user can adjust manually.\n const fromDir = dirname(entryPath);\n const rel = relative(fromDir, initFilePath).split(sep).join(\"/\");\n let moduleSpec: string;\n if (rel === \"gg_pixel_init.py\") {\n moduleSpec = \"gg_pixel_init\";\n } else if (rel.startsWith(\"../\")) {\n // Init is above the entry — Python imports don't traverse via path,\n // so insert via sys.path manipulation as a fallback.\n moduleSpec = \"gg_pixel_init\";\n } else {\n // Same-or-deeper directory: use module path.\n moduleSpec = rel.replace(/\\.py$/, \"\").replace(/\\//g, \".\");\n }\n\n const importLine = `import ${moduleSpec} # noqa: F401, E402 -- gg-pixel`;\n\n const lines = content.split(\"\\n\");\n let insertAt = 0;\n if (lines[0]?.startsWith(\"#!\")) insertAt = 1;\n // Skip encoding declarations and module docstrings.\n while (insertAt < lines.length && /^\\s*(?:#.*coding[:=]|[\"']{3}|#)/.test(lines[insertAt] ?? \"\")) {\n insertAt++;\n }\n\n const updated = [...lines.slice(0, insertAt), importLine, ...lines.slice(insertAt)].join(\"\\n\");\n writeFileSync(entryPath, updated, \"utf8\");\n return { kind: \"injected\", entryPath };\n}\n\nfunction findPythonEntryFile(projectRoot: string): string | null {\n const tryPath = (rel: string): string | null => {\n const p = join(projectRoot, rel);\n return existsSync(p) ? p : null;\n };\n const candidates = [\n \"main.py\",\n \"app.py\",\n \"server.py\",\n \"manage.py\",\n \"wsgi.py\",\n \"asgi.py\",\n \"__main__.py\",\n \"src/main.py\",\n \"src/app.py\",\n \"src/server.py\",\n \"src/__main__.py\",\n ];\n for (const c of candidates) {\n const found = tryPath(c);\n if (found) return found;\n }\n return null;\n}\n\n// ── /Python ─────────────────────────────────────────────────────────\n\nexport function writeProjectsMapping(\n projectsJsonPath: string,\n projectId: string,\n name: string,\n path: string,\n secret?: string,\n): void {\n mkdirSync(dirname(projectsJsonPath), { recursive: true });\n let map: Record<string, { name: string; path: string; secret?: string }> = {};\n if (existsSync(projectsJsonPath)) {\n try {\n map = JSON.parse(readFileSync(projectsJsonPath, \"utf8\")) as typeof map;\n } catch {\n // start fresh on corrupt file\n }\n }\n const entry: { name: string; path: string; secret?: string } = { name, path };\n if (secret) entry.secret = secret;\n map[projectId] = entry;\n writeFileSync(projectsJsonPath, `${JSON.stringify(map, null, 2)}\\n`, \"utf8\");\n}\n","/**\n * Post-install verification.\n *\n * Mature SDKs (Sentry, PostHog, Datadog) all skip this — the wizard ends with\n * \"looks good!\" if file writes succeeded, even when the wired code never ran\n * a single byte. That's how every silent-failure bug we've debugged this\n * session got past the installer (stale project keys, orphaned init files,\n * sandboxed Electron renderers, missing dotenv, broken bundler copy steps).\n *\n * verifyInstall fires a synthetic event end-to-end after wiring completes:\n * spawn a Node child in the user's project, import the SDK, report a probe,\n * then poll the project's error list with the bearer secret. If the probe\n * doesn't round-trip, we know the install is broken NOW instead of weeks\n * later when an end-user finally hits a real error.\n */\n\nimport { spawn as nodeSpawn, type ChildProcess, type SpawnOptions } from \"node:child_process\";\nimport { writeFileSync, unlinkSync, mkdirSync, existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\n\nconst PROBE_FINGERPRINT_PREFIX = \"__pixel_install_probe__\";\n\nexport interface VerifyOptions {\n projectId: string;\n projectKey: string;\n /** Per-project bearer secret used to query the error list. */\n projectSecret: string;\n /** Backend root, e.g. \"https://gg-pixel-server.buzzbeamaustralia.workers.dev\" (no trailing /ingest). */\n ingestUrl: string;\n /** User's project root — the cwd we spawn the probe from for `node_modules` resolution. */\n projectRoot: string;\n fetchFn?: typeof fetch;\n spawnFn?: typeof nodeSpawn;\n /** Skip the spawned child probe entirely; useful for non-Node kinds (browser, RN). */\n skipChildProbe?: boolean;\n /** Max time to wait for the probe to appear in the error list. Default 5s. */\n timeoutMs?: number;\n}\n\nexport type VerifyOutcome =\n | {\n kind: \"ok\";\n /** Which path delivered the probe successfully. */\n method: \"child_process\" | \"direct_ingest\";\n latencyMs: number;\n }\n | {\n kind: \"failed\";\n reason: string;\n hint?: string;\n };\n\n/**\n * Returns true if the fingerprint string was produced by an install probe.\n * Used by the overlay/listing code to hide probes if cleanup ever fails.\n */\nexport function isInstallProbeFingerprint(fingerprint: string | null | undefined): boolean {\n return typeof fingerprint === \"string\" && fingerprint.startsWith(PROBE_FINGERPRINT_PREFIX);\n}\n\nexport async function verifyInstall(opts: VerifyOptions): Promise<VerifyOutcome> {\n const fetchFn = opts.fetchFn ?? fetch;\n const spawnFn = opts.spawnFn ?? nodeSpawn;\n const timeoutMs = opts.timeoutMs ?? 5000;\n const ingest = opts.ingestUrl.replace(/\\/+$/, \"\");\n const fingerprint = `${PROBE_FINGERPRINT_PREFIX}${randomBytes(6).toString(\"hex\")}`;\n const start = Date.now();\n\n // Try child-process probe first (more useful — exercises user's node_modules\n // resolution, network access, and Node version compat). Fall back to a\n // direct-fetch ingest from the installer process if the child fails.\n let method: \"child_process\" | \"direct_ingest\";\n let probeError: string | null = null;\n if (opts.skipChildProbe) {\n try {\n await postDirectIngest({\n ingestUrl: ingest,\n projectKey: opts.projectKey,\n fingerprint,\n fetchFn,\n });\n method = \"direct_ingest\";\n } catch (err) {\n return {\n kind: \"failed\",\n reason: \"Direct ingest failed\",\n hint: (err as Error).message,\n };\n }\n } else {\n try {\n await runChildProbe({\n projectRoot: opts.projectRoot,\n ingestUrl: ingest,\n projectKey: opts.projectKey,\n fingerprint,\n spawnFn,\n });\n method = \"child_process\";\n } catch (err) {\n probeError = (err as Error).message;\n try {\n await postDirectIngest({\n ingestUrl: ingest,\n projectKey: opts.projectKey,\n fingerprint,\n fetchFn,\n });\n method = \"direct_ingest\";\n } catch (err2) {\n return {\n kind: \"failed\",\n reason: \"Could not deliver probe event\",\n hint: `child-process: ${probeError}; direct ingest: ${(err2 as Error).message}`,\n };\n }\n }\n }\n\n // Poll the API with the bearer secret for the probe fingerprint.\n const probeRow = await pollForFingerprint({\n ingestUrl: ingest,\n projectId: opts.projectId,\n projectSecret: opts.projectSecret,\n fingerprint,\n timeoutMs,\n fetchFn,\n });\n\n if (!probeRow) {\n return {\n kind: \"failed\",\n reason: `Probe sent (${method}) but didn't appear in /api/projects/${opts.projectId}/errors within ${timeoutMs}ms`,\n hint: probeError ?? undefined,\n };\n }\n\n // Best-effort cleanup so the probe doesn't clutter the user's overlay.\n try {\n await fetchFn(`${ingest}/api/errors/${probeRow.id}`, {\n method: \"DELETE\",\n headers: { authorization: `Bearer ${opts.projectSecret}` },\n });\n } catch {\n // Listings already filter probe fingerprints, so a leaked row is harmless.\n }\n\n return {\n kind: \"ok\",\n method,\n latencyMs: Date.now() - start,\n };\n}\n\n// ── helpers ──────────────────────────────────────────────────────────────\n\ninterface ChildProbeArgs {\n projectRoot: string;\n ingestUrl: string;\n projectKey: string;\n fingerprint: string;\n spawnFn: typeof nodeSpawn;\n}\n\nasync function runChildProbe(args: ChildProbeArgs): Promise<void> {\n const ggDir = join(args.projectRoot, \".gg\");\n if (!existsSync(ggDir)) mkdirSync(ggDir, { recursive: true });\n const probePath = join(ggDir, `pixel-probe-${randomBytes(4).toString(\"hex\")}.mjs`);\n\n // Probe script: import the SDK to confirm the package resolves from the\n // user's node_modules, then POST directly to /ingest so we can pin the\n // fingerprint we'll poll for. (`reportPixel` computes its own fingerprint\n // from the stack, so we couldn't otherwise correlate the probe.)\n const script = `import \"@iroaxel/gg-pixel\";\nconst body = ${JSON.stringify({\n project_key: args.projectKey,\n fingerprint: args.fingerprint,\n type: \"InstallProbe\",\n message: \"Install verification probe — auto-generated, safe to delete\",\n stack: [],\n code_context: null,\n runtime: \"\",\n manual_report: true,\n level: \"error\",\n })};\nbody.event_id = \"evt_probe_\" + crypto.randomUUID();\nbody.runtime = \"installer-node-\" + process.versions.node;\nbody.occurred_at = new Date().toISOString();\nconst res = await fetch(${JSON.stringify(args.ingestUrl + \"/ingest\")}, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n});\nif (!res.ok) {\n const txt = await res.text().catch(() => \"\");\n console.error(\"probe ingest failed: status=\" + res.status + \" body=\" + txt.slice(0, 200));\n process.exit(1);\n}\n`;\n writeFileSync(probePath, script, \"utf8\");\n\n try {\n await new Promise<void>((resolve, reject) => {\n const opts: SpawnOptions = { cwd: args.projectRoot, stdio: \"pipe\" };\n const child: ChildProcess = args.spawnFn(\"node\", [probePath], opts);\n let stderr = \"\";\n child.stderr?.on(\"data\", (b: Buffer) => {\n stderr += b.toString();\n });\n const timer = setTimeout(() => {\n child.kill(\"SIGKILL\");\n reject(new Error(\"Probe child timed out after 10s\"));\n }, 10_000);\n child.on(\"error\", (err: Error) => {\n clearTimeout(timer);\n reject(err);\n });\n child.on(\"exit\", (code: number | null) => {\n clearTimeout(timer);\n if (code === 0) resolve();\n else reject(new Error(`Probe exited code=${code}; stderr: ${stderr.trim().slice(0, 400)}`));\n });\n });\n } finally {\n try {\n unlinkSync(probePath);\n } catch {\n // best-effort\n }\n }\n}\n\ninterface DirectIngestArgs {\n ingestUrl: string;\n projectKey: string;\n fingerprint: string;\n fetchFn: typeof fetch;\n}\n\nasync function postDirectIngest(args: DirectIngestArgs): Promise<void> {\n const res = await args.fetchFn(`${args.ingestUrl}/ingest`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify({\n event_id: `evt_probe_${randomBytes(8).toString(\"hex\")}`,\n project_key: args.projectKey,\n fingerprint: args.fingerprint,\n type: \"InstallProbe\",\n message: \"Install verification probe\",\n stack: [],\n code_context: null,\n runtime: `installer-node-${process.versions.node}`,\n manual_report: true,\n level: \"error\",\n occurred_at: new Date().toISOString(),\n }),\n });\n if (!res.ok) {\n let body = \"\";\n try {\n body = await res.text();\n } catch {\n // ignore\n }\n throw new Error(`POST /ingest → ${res.status} ${body.slice(0, 200)}`);\n }\n}\n\ninterface PollArgs {\n ingestUrl: string;\n projectId: string;\n projectSecret: string;\n fingerprint: string;\n timeoutMs: number;\n fetchFn: typeof fetch;\n}\n\nasync function pollForFingerprint(args: PollArgs): Promise<{ id: string } | null> {\n const deadline = Date.now() + args.timeoutMs;\n while (Date.now() < deadline) {\n try {\n const res = await args.fetchFn(`${args.ingestUrl}/api/projects/${args.projectId}/errors`, {\n headers: { authorization: `Bearer ${args.projectSecret}` },\n });\n if (res.ok) {\n const body = (await res.json()) as { errors: Array<{ id: string; fingerprint: string }> };\n const match = body.errors.find((e) => e.fingerprint === args.fingerprint);\n if (match) return { id: match.id };\n }\n } catch {\n // Network blip — keep polling until deadline.\n }\n await new Promise((r) => setTimeout(r, 250));\n }\n return null;\n}\n","import { installNodeAdapter, type NodeAdapter } from \"./adapters/node.js\";\nimport { NodeHttpSink } from \"./core/sinks/node-http.js\";\nimport { LocalSqliteSink } from \"./core/sinks/local-sqlite.js\";\nimport type { PixelOptions, ReportInput, Sink, SinkConfig } from \"./core/types.js\";\n\nlet active: NodeAdapter | null = null;\n\nexport function initPixel(options: PixelOptions): NodeAdapter {\n if (active) {\n throw new Error(\"gg-pixel is already initialized; call closePixel() first\");\n }\n const sink = buildSink(options.sink);\n active = installNodeAdapter({\n projectKey: options.projectKey,\n runtime: options.runtime ?? defaultRuntime(),\n sink,\n captureConsoleErrors: options.captureConsoleErrors ?? true,\n captureConsoleWarnings: options.captureConsoleWarnings ?? false,\n captureUnhandledRejections: options.captureUnhandledRejections ?? true,\n captureUncaughtExceptions: options.captureUncaughtExceptions ?? true,\n });\n return active;\n}\n\nexport function reportPixel(input: ReportInput): void {\n if (!active) return;\n active.report(input);\n}\n\nexport async function flushPixel(): Promise<void> {\n if (!active) return;\n await active.flush();\n}\n\nexport async function closePixel(): Promise<void> {\n if (!active) return;\n await active.close();\n active = null;\n}\n\nfunction buildSink(config: SinkConfig): Sink {\n switch (config.kind) {\n case \"http\":\n return new NodeHttpSink(config.ingestUrl, config.fetchFn);\n case \"local\":\n return new LocalSqliteSink(config.path);\n case \"custom\":\n return config.sink;\n }\n}\n\nfunction defaultRuntime(): string {\n const v = process.versions.node;\n return `node-${v}`;\n}\n\nexport type {\n Level,\n PixelOptions,\n ReportInput,\n Sink,\n SinkConfig,\n StackFrame,\n CodeContext,\n WireEvent,\n} from \"./core/types.js\";\n\nexport { install, DEFAULT_INGEST_URL } from \"./install.js\";\nexport type { InstallOptions, InstallResult, PackageManager } from \"./install.js\";\nexport { verifyInstall, isInstallProbeFingerprint } from \"./verify.js\";\nexport type { VerifyOptions, VerifyOutcome } from \"./verify.js\";\n"],"mappings":";;;;;;AAAA;;;ACAA;AAAA,IAAM,yBAAyB;AAE/B,IAAM,aAAa,CAAC,SAAS,MAAM,UAAQ,QAAU,OAAO,MAAM;AAElE,IAAM,cAAc,CAAC,SAAS,MAAM,UAAQ,QAAU,KAAK,MAAM,MAAM,IAAI;AAE3E,IAAM,cAAc,CAAC,SAAS,MAAM,CAAC,KAAK,OAAO,SAAS,QAAU,KAAK,MAAM,MAAM,GAAG,IAAI,KAAK,IAAI,IAAI;AAEzG,IAAM,SAAS;AAAA,EACd,UAAU;AAAA,IACT,OAAO,CAAC,GAAG,CAAC;AAAA;AAAA,IAEZ,MAAM,CAAC,GAAG,EAAE;AAAA,IACZ,KAAK,CAAC,GAAG,EAAE;AAAA,IACX,QAAQ,CAAC,GAAG,EAAE;AAAA,IACd,WAAW,CAAC,GAAG,EAAE;AAAA,IACjB,UAAU,CAAC,IAAI,EAAE;AAAA,IACjB,SAAS,CAAC,GAAG,EAAE;AAAA,IACf,QAAQ,CAAC,GAAG,EAAE;AAAA,IACd,eAAe,CAAC,GAAG,EAAE;AAAA,EACtB;AAAA,EACA,OAAO;AAAA,IACN,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MAAM;MACN,SAAS;MACT,OAAO,CAAC;MACR,cAAc;MACd,SAAS,kBAAkB,QAAQ,SAAS,IAAI;MAChD,eAAe;MACf,OAAO;MACP,cAAa,oBAAI,KAAK,GAAE,YAAY;IACtC,CAAC;EACH,CAAC;AACD,MAAI,CAAC,IAAI,IAAI;AACX,QAAI,OAAO;AACX,QAAI;AACF,aAAO,MAAM,IAAI,KAAK;IACxB,QAAQ;IAER;AACA,UAAM,IAAI,MAAM,uBAAkB,IAAI,MAAM,IAAI,KAAK,MAAM,GAAG,GAAG,CAAC,EAAE;EACtE;AACF;AAWA,eAAe,mBAAmB,MAAgD;AAChF,QAAM,WAAW,KAAK,IAAI,IAAI,KAAK;AACnC,SAAO,KAAK,IAAI,IAAI,UAAU;AAC5B,QAAI;AACF,YAAM,MAAM,MAAM,KAAK,QAAQ,GAAG,KAAK,SAAS,iBAAiB,KAAK,SAAS,WAAW;QACxF,SAAS,EAAE,eAAe,UAAU,KAAK,aAAa,GAAG;MAC3D,CAAC;AACD,UAAI,IAAI,IAAI;AACV,cAAM,OAAQ,MAAM,IAAI,KAAK;AAC7B,cAAM,QAAQ,KAAK,OAAO,KAAK,CAAC,MAAM,EAAE,gBAAgB,KAAK,WAAW;AACxE,YAAI,MAAO,QAAO,EAAE,IAAI,MAAM,GAAG;MACnC;IACF,QAAQ;IAER;AACA,UAAM,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,GAAG,CAAC;EAC7C;AACA,SAAO;AACT;","names":["process","styles","chalk","styles","existsSync","readFileSync","mkdirSync","createRequire","homedir","dirname","join","spawnSync","writeFileSync","createRequire","homedir","join","readFileSync","existsSync","dirname","spawnSync","sep","mkdirSync","fingerprint","writeFileSync","resolve"]}