@kenkaiiii/gg-pixel 4.3.59

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 KenKai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/cli.js ADDED
@@ -0,0 +1,185 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/install.ts
4
+ import { existsSync, readFileSync, writeFileSync, appendFileSync, mkdirSync } from "fs";
5
+ import { homedir } from "os";
6
+ import { dirname, join, resolve } from "path";
7
+ import { spawnSync } from "child_process";
8
+ var DEFAULT_INGEST_URL = "https://gg-pixel-server.buzzbeamaustralia.workers.dev";
9
+ async function install(opts = {}) {
10
+ const cwd = resolve(opts.cwd ?? process.cwd());
11
+ const ingestUrl = (opts.ingestUrl ?? DEFAULT_INGEST_URL).replace(/\/+$/, "");
12
+ const fetchFn = opts.fetchFn ?? fetch;
13
+ const projectRoot = findProjectRoot(cwd);
14
+ if (!projectRoot) {
15
+ throw new Error(`No package.json found in ${cwd} or any parent directory.`);
16
+ }
17
+ const pkgPath = join(projectRoot, "package.json");
18
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
19
+ const projectName = opts.projectName ?? pkg.name ?? projectRoot.split("/").pop() ?? "unnamed";
20
+ const created = await createProject(fetchFn, ingestUrl, projectName);
21
+ const pm = detectPackageManager(projectRoot);
22
+ const packageInstalled = opts.skipPackageInstall ? false : runInstall(projectRoot, pm, "@kenkaiiii/gg-pixel");
23
+ const initFilePath = join(projectRoot, "gg-pixel.init.mjs");
24
+ writeFileSync(initFilePath, renderInitFile(ingestUrl), "utf8");
25
+ const envFilePath = join(projectRoot, ".env");
26
+ writeEnvKey(envFilePath, "GG_PIXEL_KEY", created.key);
27
+ const home = opts.homeDir ?? homedir();
28
+ const projectsJsonPath = join(home, ".gg", "projects.json");
29
+ writeProjectsMapping(projectsJsonPath, created.id, projectName, projectRoot);
30
+ return {
31
+ projectId: created.id,
32
+ projectKey: created.key,
33
+ projectName,
34
+ initFilePath,
35
+ envFilePath,
36
+ projectsJsonPath,
37
+ packageManager: pm,
38
+ packageInstalled
39
+ };
40
+ }
41
+ function findProjectRoot(start) {
42
+ let dir = start;
43
+ for (let i = 0; i < 20; i++) {
44
+ if (existsSync(join(dir, "package.json"))) return dir;
45
+ const parent = dirname(dir);
46
+ if (parent === dir) return null;
47
+ dir = parent;
48
+ }
49
+ return null;
50
+ }
51
+ async function createProject(fetchFn, ingestUrl, name) {
52
+ const res = await fetchFn(`${ingestUrl}/api/projects`, {
53
+ method: "POST",
54
+ headers: { "content-type": "application/json" },
55
+ body: JSON.stringify({ name })
56
+ });
57
+ if (!res.ok) {
58
+ throw new Error(`POST /api/projects failed: ${res.status} ${await safeText(res)}`);
59
+ }
60
+ const body = await res.json();
61
+ if (!body.id || !body.key) throw new Error("response missing id/key");
62
+ return { id: body.id, key: body.key };
63
+ }
64
+ async function safeText(r) {
65
+ try {
66
+ return await r.text();
67
+ } catch {
68
+ return "";
69
+ }
70
+ }
71
+ function detectPackageManager(projectRoot) {
72
+ if (existsSync(join(projectRoot, "pnpm-lock.yaml"))) return "pnpm";
73
+ if (existsSync(join(projectRoot, "bun.lockb"))) return "bun";
74
+ if (existsSync(join(projectRoot, "yarn.lock"))) return "yarn";
75
+ return "npm";
76
+ }
77
+ function runInstall(projectRoot, pm, pkg) {
78
+ const cmd = pm;
79
+ const args = pm === "npm" ? ["install", pkg] : ["add", pkg];
80
+ const result = spawnSync(cmd, args, { cwd: projectRoot, stdio: "inherit" });
81
+ return result.status === 0;
82
+ }
83
+ function renderInitFile(ingestUrl) {
84
+ return `import { initPixel } from "@kenkaiiii/gg-pixel";
85
+
86
+ const key = process.env.GG_PIXEL_KEY;
87
+ if (key) {
88
+ initPixel({
89
+ projectKey: key,
90
+ sink: { kind: "http", ingestUrl: ${JSON.stringify(`${ingestUrl}/ingest`)} },
91
+ });
92
+ }
93
+ `;
94
+ }
95
+ function writeEnvKey(envPath, key, value) {
96
+ if (existsSync(envPath)) {
97
+ const current = readFileSync(envPath, "utf8");
98
+ const lineRegex = new RegExp(`^${key}=.*$`, "m");
99
+ if (lineRegex.test(current)) {
100
+ writeFileSync(envPath, current.replace(lineRegex, `${key}=${value}`), "utf8");
101
+ return;
102
+ }
103
+ const sep = current.endsWith("\n") || current.length === 0 ? "" : "\n";
104
+ appendFileSync(envPath, `${sep}${key}=${value}
105
+ `, "utf8");
106
+ return;
107
+ }
108
+ writeFileSync(envPath, `${key}=${value}
109
+ `, "utf8");
110
+ }
111
+ function writeProjectsMapping(projectsJsonPath, projectId, name, path) {
112
+ mkdirSync(dirname(projectsJsonPath), { recursive: true });
113
+ let map = {};
114
+ if (existsSync(projectsJsonPath)) {
115
+ try {
116
+ map = JSON.parse(readFileSync(projectsJsonPath, "utf8"));
117
+ } catch {
118
+ }
119
+ }
120
+ map[projectId] = { name, path };
121
+ writeFileSync(projectsJsonPath, `${JSON.stringify(map, null, 2)}
122
+ `, "utf8");
123
+ }
124
+
125
+ // src/cli.ts
126
+ function parse(argv) {
127
+ const out = { command: argv[0] ?? "", skipPackageInstall: false, help: false };
128
+ for (let i = 1; i < argv.length; i++) {
129
+ const a = argv[i];
130
+ if (a === "--ingest-url") out.ingestUrl = argv[++i];
131
+ else if (a === "--name") out.name = argv[++i];
132
+ else if (a === "--skip-install") out.skipPackageInstall = true;
133
+ else if (a === "--help" || a === "-h") out.help = true;
134
+ }
135
+ return out;
136
+ }
137
+ function printUsage() {
138
+ console.log(`gg-pixel install \u2014 drop the pixel into the current project
139
+
140
+ Usage:
141
+ gg-pixel install [--name <project-name>] [--ingest-url <url>] [--skip-install]
142
+
143
+ Options:
144
+ --name Project name to register (defaults to package.json name)
145
+ --ingest-url Backend URL (defaults to ${DEFAULT_INGEST_URL})
146
+ --skip-install Skip the package-manager install step (useful for testing)
147
+ `);
148
+ }
149
+ async function main(argv) {
150
+ const args = parse(argv);
151
+ if (args.help || !args.command) {
152
+ printUsage();
153
+ return;
154
+ }
155
+ if (args.command !== "install") {
156
+ console.error(`Unknown command: ${args.command}`);
157
+ printUsage();
158
+ process.exitCode = 1;
159
+ return;
160
+ }
161
+ const result = await install({
162
+ ingestUrl: args.ingestUrl,
163
+ projectName: args.name,
164
+ skipPackageInstall: args.skipPackageInstall
165
+ });
166
+ console.log("");
167
+ console.log("Pixel installed.");
168
+ console.log(` Project: ${result.projectName} (${result.projectId})`);
169
+ console.log(` Wrote: ${result.initFilePath}`);
170
+ console.log(` Wrote env: ${result.envFilePath}`);
171
+ console.log(` Mapping saved: ${result.projectsJsonPath}`);
172
+ if (!result.packageInstalled && !args.skipPackageInstall) {
173
+ console.log(` \u26A0 Package install failed via ${result.packageManager}. Run it manually.`);
174
+ }
175
+ console.log("");
176
+ console.log("Last step: add this line to the TOP of your entry file:");
177
+ console.log("");
178
+ console.log(` import "./gg-pixel.init.mjs";`);
179
+ console.log("");
180
+ }
181
+ main(process.argv.slice(2)).catch((err) => {
182
+ console.error(err instanceof Error ? err.message : String(err));
183
+ process.exitCode = 1;
184
+ });
185
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/install.ts","../src/cli.ts"],"sourcesContent":["import { existsSync, readFileSync, writeFileSync, appendFileSync, mkdirSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { spawnSync } from \"node:child_process\";\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 projectName: string;\n initFilePath: string;\n envFilePath: string;\n projectsJsonPath: string;\n packageManager: PackageManager;\n packageInstalled: boolean;\n}\n\nexport type PackageManager = \"pnpm\" | \"yarn\" | \"bun\" | \"npm\";\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\n const projectRoot = findProjectRoot(cwd);\n if (!projectRoot) {\n throw new Error(`No package.json found in ${cwd} or any parent directory.`);\n }\n\n const pkgPath = join(projectRoot, \"package.json\");\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf8\")) as { name?: string };\n const projectName = opts.projectName ?? pkg.name ?? projectRoot.split(\"/\").pop() ?? \"unnamed\";\n\n const created = await createProject(fetchFn, ingestUrl, projectName);\n\n const pm = detectPackageManager(projectRoot);\n const packageInstalled = opts.skipPackageInstall\n ? false\n : runInstall(projectRoot, pm, \"@kenkaiiii/gg-pixel\");\n\n const initFilePath = join(projectRoot, \"gg-pixel.init.mjs\");\n writeFileSync(initFilePath, renderInitFile(ingestUrl), \"utf8\");\n\n const envFilePath = join(projectRoot, \".env\");\n writeEnvKey(envFilePath, \"GG_PIXEL_KEY\", created.key);\n\n const home = opts.homeDir ?? homedir();\n const projectsJsonPath = join(home, \".gg\", \"projects.json\");\n writeProjectsMapping(projectsJsonPath, created.id, projectName, projectRoot);\n\n return {\n projectId: created.id,\n projectKey: created.key,\n projectName,\n initFilePath,\n envFilePath,\n projectsJsonPath,\n packageManager: pm,\n packageInstalled,\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<{ id: string; key: string }> {\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 };\n if (!body.id || !body.key) throw new Error(\"response missing id/key\");\n return { id: body.id, key: body.key };\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 if (existsSync(join(projectRoot, \"bun.lockb\"))) return \"bun\";\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 const args = pm === \"npm\" ? [\"install\", pkg] : [\"add\", pkg];\n const result = spawnSync(cmd, args, { cwd: projectRoot, stdio: \"inherit\" });\n return result.status === 0;\n}\n\nexport function renderInitFile(ingestUrl: string): string {\n return `import { initPixel } from \"@kenkaiiii/gg-pixel\";\n\nconst key = process.env.GG_PIXEL_KEY;\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 writeProjectsMapping(\n projectsJsonPath: string,\n projectId: string,\n name: string,\n path: string,\n): void {\n mkdirSync(dirname(projectsJsonPath), { recursive: true });\n let map: Record<string, { name: string; path: 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 map[projectId] = { name, path };\n writeFileSync(projectsJsonPath, `${JSON.stringify(map, null, 2)}\\n`, \"utf8\");\n}\n","import { install, DEFAULT_INGEST_URL } from \"./install.js\";\n\ninterface ParsedArgs {\n command: string;\n ingestUrl?: string;\n name?: string;\n skipPackageInstall: boolean;\n help: boolean;\n}\n\nfunction parse(argv: string[]): ParsedArgs {\n const out: ParsedArgs = { command: argv[0] ?? \"\", skipPackageInstall: false, help: false };\n for (let i = 1; i < argv.length; i++) {\n const a = argv[i];\n if (a === \"--ingest-url\") out.ingestUrl = argv[++i];\n else if (a === \"--name\") out.name = argv[++i];\n else if (a === \"--skip-install\") out.skipPackageInstall = true;\n else if (a === \"--help\" || a === \"-h\") out.help = true;\n }\n return out;\n}\n\nfunction printUsage(): void {\n console.log(`gg-pixel install — drop the pixel into the current project\n\nUsage:\n gg-pixel install [--name <project-name>] [--ingest-url <url>] [--skip-install]\n\nOptions:\n --name Project name to register (defaults to package.json name)\n --ingest-url Backend URL (defaults to ${DEFAULT_INGEST_URL})\n --skip-install Skip the package-manager install step (useful for testing)\n`);\n}\n\nasync function main(argv: string[]): Promise<void> {\n const args = parse(argv);\n if (args.help || !args.command) {\n printUsage();\n return;\n }\n if (args.command !== \"install\") {\n console.error(`Unknown command: ${args.command}`);\n printUsage();\n process.exitCode = 1;\n return;\n }\n\n const result = await install({\n ingestUrl: args.ingestUrl,\n projectName: args.name,\n skipPackageInstall: args.skipPackageInstall,\n });\n\n console.log(\"\");\n console.log(\"Pixel installed.\");\n console.log(` Project: ${result.projectName} (${result.projectId})`);\n console.log(` Wrote: ${result.initFilePath}`);\n console.log(` Wrote env: ${result.envFilePath}`);\n console.log(` Mapping saved: ${result.projectsJsonPath}`);\n if (!result.packageInstalled && !args.skipPackageInstall) {\n console.log(` ⚠ Package install failed via ${result.packageManager}. Run it manually.`);\n }\n console.log(\"\");\n console.log(\"Last step: add this line to the TOP of your entry file:\");\n console.log(\"\");\n console.log(` import \"./gg-pixel.init.mjs\";`);\n console.log(\"\");\n}\n\nmain(process.argv.slice(2)).catch((err: unknown) => {\n console.error(err instanceof Error ? err.message : String(err));\n process.exitCode = 1;\n});\n"],"mappings":";;;AAAA,SAAS,YAAY,cAAc,eAAe,gBAAgB,iBAAiB;AACnF,SAAS,eAAe;AACxB,SAAS,SAAS,MAAM,eAAe;AACvC,SAAS,iBAAiB;AAEnB,IAAM,qBAAqB;AAwBlC,eAAsB,QAAQ,OAAuB,CAAC,GAA2B;AAC/E,QAAM,MAAM,QAAQ,KAAK,OAAO,QAAQ,IAAI,CAAC;AAC7C,QAAM,aAAa,KAAK,aAAa,oBAAoB,QAAQ,QAAQ,EAAE;AAC3E,QAAM,UAAU,KAAK,WAAW;AAEhC,QAAM,cAAc,gBAAgB,GAAG;AACvC,MA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A;AAAA,8CAOgC,kBAAkB;AAAA;AAAA,CAE/D;AACD;AAEA,eAAe,KAAK,MAA+B;AACjD,QAAM,OAAO,MAAM,IAAI;AACvB,MAAI,KAAK,QAAQ,CAAC,KAAK,SAAS;AAC9B,eAAW;AACX;AAAA,EACF;AACA,MAAI,KAAK,YAAY,WAAW;AAC9B,YAAQ,MAAM,oBAAoB,KAAK,OAAO,EAAE;AAChD,eAAW;AACX,YAAQ,WAAW;AACnB;AAAA,EACF;AAEA,QAAM,SAAS,MAAM,QAAQ;AAAA,IAC3B,WAAW,KAAK;AAAA,IAChB,aAAa,KAAK;AAAA,IAClB,oBAAoB,KAAK;AAAA,EAC3B,CAAC;AAED,UAAQ,IAAI,EAAE;AACd,UAAQ,IAAI,kBAAkB;AAC9B,UAAQ,IAAI,oBAAoB,OAAO,WAAW,KAAK,OAAO,SAAS,GAAG;AAC1E,UAAQ,IAAI,oBAAoB,OAAO,YAAY,EAAE;AACrD,UAAQ,IAAI,oBAAoB,OAAO,WAAW,EAAE;AACpD,UAAQ,IAAI,oBAAoB,OAAO,gBAAgB,EAAE;AACzD,MAAI,CAAC,OAAO,oBAAoB,CAAC,KAAK,oBAAoB;AACxD,YAAQ,IAAI,wCAAmC,OAAO,cAAc,oBAAoB;AAAA,EAC1F;AACA,UAAQ,IAAI,EAAE;AACd,UAAQ,IAAI,yDAAyD;AACrE,UAAQ,IAAI,EAAE;AACd,UAAQ,IAAI,iCAAiC;AAC7C,UAAQ,IAAI,EAAE;AAChB;AAEA,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE,MAAM,CAAC,QAAiB;AAClD,UAAQ,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAC9D,UAAQ,WAAW;AACrB,CAAC;","names":[]}
package/dist/index.cjs ADDED
@@ -0,0 +1,456 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ closePixel: () => closePixel,
34
+ flushPixel: () => flushPixel,
35
+ initPixel: () => initPixel,
36
+ reportPixel: () => reportPixel
37
+ });
38
+ module.exports = __toCommonJS(index_exports);
39
+
40
+ // src/adapters/node.ts
41
+ var import_node_crypto2 = require("crypto");
42
+
43
+ // src/core/stack.ts
44
+ var FRAME_WITH_FN = /^\s*at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)\s*$/;
45
+ var FRAME_NO_FN = /^\s*at\s+(.+?):(\d+):(\d+)\s*$/;
46
+ function parseStack(stack) {
47
+ if (!stack) return [];
48
+ const frames = [];
49
+ for (const line of stack.split("\n")) {
50
+ const withFn = FRAME_WITH_FN.exec(line);
51
+ if (withFn) {
52
+ const file = withFn[2];
53
+ frames.push({
54
+ fn: withFn[1],
55
+ file,
56
+ line: Number(withFn[3]),
57
+ col: Number(withFn[4]),
58
+ in_app: isInApp(file)
59
+ });
60
+ continue;
61
+ }
62
+ const noFn = FRAME_NO_FN.exec(line);
63
+ if (noFn) {
64
+ const file = noFn[1];
65
+ frames.push({
66
+ fn: "<anon>",
67
+ file,
68
+ line: Number(noFn[2]),
69
+ col: Number(noFn[3]),
70
+ in_app: isInApp(file)
71
+ });
72
+ }
73
+ }
74
+ return frames;
75
+ }
76
+ function isInApp(file) {
77
+ if (!file) return false;
78
+ if (file.startsWith("node:")) return false;
79
+ if (file.startsWith("internal/")) return false;
80
+ if (file.includes("/node_modules/")) return false;
81
+ return true;
82
+ }
83
+
84
+ // src/core/fingerprint.ts
85
+ var import_node_crypto = require("crypto");
86
+ function fingerprint(type, stack) {
87
+ const top = stack[0];
88
+ const normalized = top ? `${type}|${normalizeFile(top.file)}|${top.fn || "<anon>"}|${top.line}` : `${type}|<no-stack>`;
89
+ return (0, import_node_crypto.createHash)("sha256").update(normalized).digest("hex").slice(0, 16);
90
+ }
91
+ function normalizeFile(file) {
92
+ return file.replace(/^file:\/\//, "").replace(/^.*\/node_modules\//, "node_modules/").replace(/\?.*$/, "");
93
+ }
94
+
95
+ // src/code-context.ts
96
+ var import_node_fs = require("fs");
97
+ var WINDOW = 2;
98
+ var cache = /* @__PURE__ */ new Map();
99
+ function captureCodeContext(stack) {
100
+ const top = stack.find((f) => isReadable(f.file));
101
+ if (!top) return null;
102
+ const lines = loadLines(top.file);
103
+ if (!lines) return null;
104
+ const start = Math.max(0, top.line - 1 - WINDOW);
105
+ const end = Math.min(lines.length, top.line + WINDOW);
106
+ return {
107
+ file: top.file,
108
+ error_line: top.line,
109
+ lines: lines.slice(start, end)
110
+ };
111
+ }
112
+ function isReadable(file) {
113
+ if (!file || file.startsWith("node:")) return false;
114
+ if (file.includes("/node_modules/")) return false;
115
+ return file.startsWith("/") || file.startsWith("file://");
116
+ }
117
+ function loadLines(file) {
118
+ const path = file.replace(/^file:\/\//, "");
119
+ if (cache.has(path)) return cache.get(path) ?? null;
120
+ if (!(0, import_node_fs.existsSync)(path)) {
121
+ cache.set(path, null);
122
+ return null;
123
+ }
124
+ try {
125
+ const lines = (0, import_node_fs.readFileSync)(path, "utf8").split("\n");
126
+ cache.set(path, lines);
127
+ return lines;
128
+ } catch {
129
+ cache.set(path, null);
130
+ return null;
131
+ }
132
+ }
133
+
134
+ // src/core/queue.ts
135
+ var MAX_BUFFER = 100;
136
+ var BASE_DELAY_MS = 200;
137
+ var MAX_DELAY_MS = 5e3;
138
+ var EventQueue = class {
139
+ constructor(sink) {
140
+ this.sink = sink;
141
+ }
142
+ buffer = [];
143
+ draining = false;
144
+ closed = false;
145
+ enqueue(event) {
146
+ if (this.closed) return;
147
+ if (this.buffer.length >= MAX_BUFFER) {
148
+ this.buffer.shift();
149
+ }
150
+ this.buffer.push(event);
151
+ void this.drain();
152
+ }
153
+ enqueueSync(event) {
154
+ if (this.closed) return;
155
+ if (this.sink.emitSync) {
156
+ try {
157
+ this.sink.emitSync(event);
158
+ return;
159
+ } catch {
160
+ }
161
+ }
162
+ this.enqueue(event);
163
+ }
164
+ async flush() {
165
+ while (this.buffer.length > 0 || this.draining) {
166
+ await new Promise((r) => setTimeout(r, 10));
167
+ }
168
+ }
169
+ async close() {
170
+ await this.flush();
171
+ this.closed = true;
172
+ if (this.sink.close) await this.sink.close();
173
+ }
174
+ async drain() {
175
+ if (this.draining) return;
176
+ this.draining = true;
177
+ let attempt = 0;
178
+ while (this.buffer.length > 0) {
179
+ const event = this.buffer[0];
180
+ try {
181
+ await this.sink.emit(event);
182
+ this.buffer.shift();
183
+ attempt = 0;
184
+ } catch {
185
+ attempt++;
186
+ if (attempt >= 5) {
187
+ this.buffer.shift();
188
+ attempt = 0;
189
+ continue;
190
+ }
191
+ const delay = Math.min(BASE_DELAY_MS * 2 ** (attempt - 1), MAX_DELAY_MS);
192
+ await new Promise((r) => setTimeout(r, delay));
193
+ }
194
+ }
195
+ this.draining = false;
196
+ }
197
+ };
198
+
199
+ // src/adapters/node.ts
200
+ function installNodeAdapter(opts) {
201
+ const queue = new EventQueue(opts.sink);
202
+ const detach = [];
203
+ const enqueueError = (err, level, manual) => {
204
+ try {
205
+ const event = buildEvent(err, level, manual, opts.projectKey, opts.runtime);
206
+ queue.enqueue(event);
207
+ } catch {
208
+ }
209
+ };
210
+ const enqueueErrorSync = (err, level, manual) => {
211
+ try {
212
+ const event = buildEvent(err, level, manual, opts.projectKey, opts.runtime);
213
+ queue.enqueueSync(event);
214
+ } catch {
215
+ }
216
+ };
217
+ if (opts.captureUncaughtExceptions) {
218
+ const handler = (err) => enqueueErrorSync(err, "fatal", false);
219
+ process.on("uncaughtExceptionMonitor", handler);
220
+ detach.push(() => process.off("uncaughtExceptionMonitor", handler));
221
+ }
222
+ if (opts.captureUnhandledRejections) {
223
+ const handler = (reason) => enqueueErrorSync(reason, "error", false);
224
+ process.on("unhandledRejection", handler);
225
+ detach.push(() => process.off("unhandledRejection", handler));
226
+ }
227
+ if (opts.captureConsoleErrors) {
228
+ detach.push(patchConsole("error", (args) => enqueueError(consoleError(args), "error", false)));
229
+ }
230
+ if (opts.captureConsoleWarnings) {
231
+ detach.push(patchConsole("warn", (args) => enqueueError(consoleError(args), "warning", false)));
232
+ }
233
+ const onBeforeExit = () => {
234
+ void queue.flush();
235
+ };
236
+ process.on("beforeExit", onBeforeExit);
237
+ detach.push(() => process.off("beforeExit", onBeforeExit));
238
+ return {
239
+ report(input) {
240
+ const level = input.level ?? "error";
241
+ if (input.error !== void 0) {
242
+ try {
243
+ const event = buildEvent(input.error, level, true, opts.projectKey, opts.runtime);
244
+ if (input.message) event.message = input.message;
245
+ queue.enqueue(event);
246
+ } catch {
247
+ }
248
+ return;
249
+ }
250
+ const err = new Error(input.message);
251
+ err.name = "ManualReport";
252
+ enqueueError(err, level, true);
253
+ },
254
+ flush: () => queue.flush(),
255
+ close: async () => {
256
+ for (const fn of detach) fn();
257
+ await queue.close();
258
+ }
259
+ };
260
+ }
261
+ function buildEvent(err, level, manual, projectKey, runtime) {
262
+ const { type, message, stackString } = normalize(err);
263
+ const stack = parseStack(stackString);
264
+ return {
265
+ event_id: (0, import_node_crypto2.randomUUID)(),
266
+ project_key: projectKey,
267
+ fingerprint: fingerprint(type, stack),
268
+ type,
269
+ message,
270
+ stack,
271
+ code_context: captureCodeContext(stack),
272
+ runtime,
273
+ manual_report: manual,
274
+ level,
275
+ occurred_at: (/* @__PURE__ */ new Date()).toISOString()
276
+ };
277
+ }
278
+ function normalize(err) {
279
+ if (err instanceof Error) {
280
+ return { type: err.name || "Error", message: err.message, stackString: err.stack };
281
+ }
282
+ if (typeof err === "string") {
283
+ return { type: "StringError", message: err };
284
+ }
285
+ try {
286
+ return { type: "UnknownError", message: JSON.stringify(err) };
287
+ } catch {
288
+ return { type: "UnknownError", message: String(err) };
289
+ }
290
+ }
291
+ function consoleError(args) {
292
+ for (const a of args) if (a instanceof Error) return a;
293
+ return new Error(args.map(stringify).join(" "));
294
+ }
295
+ function stringify(x) {
296
+ if (typeof x === "string") return x;
297
+ try {
298
+ return JSON.stringify(x);
299
+ } catch {
300
+ return String(x);
301
+ }
302
+ }
303
+ function patchConsole(method, onCall) {
304
+ const original = console[method];
305
+ console[method] = (...args) => {
306
+ try {
307
+ onCall(args);
308
+ } catch {
309
+ }
310
+ original.apply(console, args);
311
+ };
312
+ return () => {
313
+ console[method] = original;
314
+ };
315
+ }
316
+
317
+ // src/core/sinks/http.ts
318
+ var HttpSink = class {
319
+ constructor(ingestUrl, fetchFn = fetch) {
320
+ this.ingestUrl = ingestUrl;
321
+ this.fetchFn = fetchFn;
322
+ }
323
+ async emit(event) {
324
+ const res = await this.fetchFn(this.ingestUrl, {
325
+ method: "POST",
326
+ headers: {
327
+ "content-type": "application/json",
328
+ "x-pixel-key": event.project_key
329
+ },
330
+ body: JSON.stringify(event)
331
+ });
332
+ if (!res.ok) {
333
+ throw new Error(`pixel ingest failed: ${res.status}`);
334
+ }
335
+ }
336
+ };
337
+
338
+ // src/core/sinks/local-sqlite.ts
339
+ var import_node_os = require("os");
340
+ var import_node_fs2 = require("fs");
341
+ var import_node_path = require("path");
342
+ var import_better_sqlite3 = __toESM(require("better-sqlite3"), 1);
343
+ var SCHEMA = `
344
+ CREATE TABLE IF NOT EXISTS events (
345
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
346
+ event_id TEXT NOT NULL UNIQUE,
347
+ project_key TEXT NOT NULL,
348
+ fingerprint TEXT NOT NULL,
349
+ type TEXT NOT NULL,
350
+ message TEXT NOT NULL,
351
+ stack TEXT NOT NULL,
352
+ code_context TEXT,
353
+ runtime TEXT NOT NULL,
354
+ manual_report INTEGER NOT NULL DEFAULT 0,
355
+ level TEXT NOT NULL,
356
+ occurred_at TEXT NOT NULL,
357
+ ingested_at TEXT NOT NULL DEFAULT (datetime('now'))
358
+ );
359
+ CREATE INDEX IF NOT EXISTS events_fingerprint ON events(project_key, fingerprint);
360
+ CREATE INDEX IF NOT EXISTS events_occurred ON events(occurred_at);
361
+ `;
362
+ var LocalSqliteSink = class {
363
+ db;
364
+ insert;
365
+ constructor(path) {
366
+ const resolved = path ?? (0, import_node_path.join)((0, import_node_os.homedir)(), ".gg", "errors.db");
367
+ (0, import_node_fs2.mkdirSync)((0, import_node_path.dirname)(resolved), { recursive: true });
368
+ this.db = new import_better_sqlite3.default(resolved);
369
+ this.db.pragma("journal_mode = WAL");
370
+ this.db.exec(SCHEMA);
371
+ this.insert = this.db.prepare(`
372
+ INSERT INTO events (
373
+ event_id, project_key, fingerprint, type, message, stack, code_context,
374
+ runtime, manual_report, level, occurred_at
375
+ ) VALUES (
376
+ @event_id, @project_key, @fingerprint, @type, @message, @stack, @code_context,
377
+ @runtime, @manual_report, @level, @occurred_at
378
+ )
379
+ `);
380
+ }
381
+ emitSync(event) {
382
+ this.insert.run({
383
+ event_id: event.event_id,
384
+ project_key: event.project_key,
385
+ fingerprint: event.fingerprint,
386
+ type: event.type,
387
+ message: event.message,
388
+ stack: JSON.stringify(event.stack),
389
+ code_context: event.code_context ? JSON.stringify(event.code_context) : null,
390
+ runtime: event.runtime,
391
+ manual_report: event.manual_report ? 1 : 0,
392
+ level: event.level,
393
+ occurred_at: event.occurred_at
394
+ });
395
+ }
396
+ async emit(event) {
397
+ this.emitSync(event);
398
+ }
399
+ async close() {
400
+ this.db.close();
401
+ }
402
+ };
403
+
404
+ // src/index.ts
405
+ var active = null;
406
+ function initPixel(options) {
407
+ if (active) {
408
+ throw new Error("gg-pixel is already initialized; call closePixel() first");
409
+ }
410
+ const sink = buildSink(options.sink);
411
+ active = installNodeAdapter({
412
+ projectKey: options.projectKey,
413
+ runtime: options.runtime ?? defaultRuntime(),
414
+ sink,
415
+ captureConsoleErrors: options.captureConsoleErrors ?? true,
416
+ captureConsoleWarnings: options.captureConsoleWarnings ?? false,
417
+ captureUnhandledRejections: options.captureUnhandledRejections ?? true,
418
+ captureUncaughtExceptions: options.captureUncaughtExceptions ?? true
419
+ });
420
+ return active;
421
+ }
422
+ function reportPixel(input) {
423
+ if (!active) return;
424
+ active.report(input);
425
+ }
426
+ async function flushPixel() {
427
+ if (!active) return;
428
+ await active.flush();
429
+ }
430
+ async function closePixel() {
431
+ if (!active) return;
432
+ await active.close();
433
+ active = null;
434
+ }
435
+ function buildSink(config) {
436
+ switch (config.kind) {
437
+ case "http":
438
+ return new HttpSink(config.ingestUrl, config.fetchFn);
439
+ case "local":
440
+ return new LocalSqliteSink(config.path);
441
+ case "custom":
442
+ return config.sink;
443
+ }
444
+ }
445
+ function defaultRuntime() {
446
+ const v = process.versions.node;
447
+ return `node-${v}`;
448
+ }
449
+ // Annotate the CommonJS export names for ESM import in node:
450
+ 0 && (module.exports = {
451
+ closePixel,
452
+ flushPixel,
453
+ initPixel,
454
+ reportPixel
455
+ });
456
+ //# sourceMappingURL=index.cjs.map