@prisma-next/cli-telemetry 0.10.0 → 0.11.0

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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [2026] [Prisma Data, Inc]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,214 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "pathe";
3
+ //#region src/detect-agent.ts
4
+ const AGENT_MARKERS = [
5
+ {
6
+ envVar: "CLAUDECODE",
7
+ agent: "Claude Code"
8
+ },
9
+ {
10
+ envVar: "CURSOR_AGENT",
11
+ agent: "Cursor"
12
+ },
13
+ {
14
+ envVar: "CODEX_SANDBOX",
15
+ agent: "Codex CLI"
16
+ },
17
+ {
18
+ envVar: "GEMINI_CLI",
19
+ agent: "Gemini CLI"
20
+ },
21
+ {
22
+ envVar: "WINDSURF",
23
+ agent: "Windsurf"
24
+ },
25
+ {
26
+ envVar: "AIDER",
27
+ agent: "Aider"
28
+ },
29
+ {
30
+ envVar: "CODY",
31
+ agent: "Cody"
32
+ },
33
+ {
34
+ envVar: "CONTINUE",
35
+ agent: "Continue"
36
+ }
37
+ ];
38
+ function isTruthyMarker(raw) {
39
+ if (raw === void 0) return false;
40
+ const normalised = raw.trim().toLowerCase();
41
+ if (normalised === "") return false;
42
+ if (normalised === "0") return false;
43
+ if (normalised === "false") return false;
44
+ return true;
45
+ }
46
+ /**
47
+ * Resolve the agent label from an env snapshot, or `null` if no marker
48
+ * is set. Returns the **first** matching marker in `AGENT_MARKERS`
49
+ * order, so when multiple markers are set the agent label is
50
+ * deterministic and the allowlist's first entry wins.
51
+ *
52
+ * Pure: takes an env record, returns a string or null. No I/O.
53
+ */
54
+ function detectAgent(env) {
55
+ for (const marker of AGENT_MARKERS) if (isTruthyMarker(env[marker.envVar])) return marker.agent;
56
+ return null;
57
+ }
58
+ //#endregion
59
+ //#region src/enrich.ts
60
+ const EMPTY_PROJECT_CONFIG = {
61
+ databaseTarget: null,
62
+ extensions: []
63
+ };
64
+ /**
65
+ * Best-effort load of `prisma-next.config.*` from `projectRoot`,
66
+ * validated against the canonical `@prisma-next/config` schema.
67
+ * Returns `{ databaseTarget: null, extensions: [] }` on any failure
68
+ * mode — missing config file (e.g. before `prisma-next init`), c12
69
+ * throws while evaluating user TS, validator rejects a malformed
70
+ * shape, etc. Telemetry is non-blocking and best-effort; an empty
71
+ * result is the only downside of an unloadable or invalid config.
72
+ *
73
+ * Both `c12` and `@prisma-next/config/config-validation` are imported
74
+ * lazily so the detached sender's cold-start cost is paid only when
75
+ * telemetry actually fires, not on every fork even when gates
76
+ * short-circuit before reaching this code path.
77
+ */
78
+ async function loadProjectConfig(projectRoot) {
79
+ try {
80
+ const { loadConfig } = await import("c12");
81
+ const config = (await loadConfig({
82
+ name: "prisma-next",
83
+ cwd: projectRoot,
84
+ dotenv: false,
85
+ rcFile: false,
86
+ globalRc: false
87
+ })).config ?? null;
88
+ if (config === null || Object.keys(config).length === 0) return EMPTY_PROJECT_CONFIG;
89
+ const validate = (await import("@prisma-next/config/config-validation")).validateConfig;
90
+ validate(config);
91
+ return {
92
+ databaseTarget: config.target.targetId,
93
+ extensions: (config.extensionPacks ?? []).map((pack) => pack.id)
94
+ };
95
+ } catch {
96
+ return EMPTY_PROJECT_CONFIG;
97
+ }
98
+ }
99
+ /**
100
+ * Identify the runtime the sender is running in. Same-runtime as the
101
+ * parent is a correctness requirement: the parent forked us via
102
+ * `child_process.fork`, which inherits the parent's runtime. Detection
103
+ * keys on the runtime-specific version field rather than env vars so a
104
+ * spoofed env can't lie about the actual interpreter.
105
+ */
106
+ function resolveRuntime(versions) {
107
+ if (versions.bun !== void 0) return {
108
+ name: "bun",
109
+ version: versions.bun
110
+ };
111
+ if (versions.deno !== void 0) return {
112
+ name: "deno",
113
+ version: versions.deno
114
+ };
115
+ return {
116
+ name: "node",
117
+ version: versions.node
118
+ };
119
+ }
120
+ /**
121
+ * Parse `npm_config_user_agent` into a `<pm>/<version>` token. The
122
+ * value, when present, looks like
123
+ * `"pnpm/10.27.0 npm/? node/v24.13.0 darwin arm64"` — we take the first
124
+ * whitespace-separated token. Any failure → `null`.
125
+ */
126
+ function parsePackageManager(userAgent) {
127
+ if (userAgent === void 0) return null;
128
+ const first = userAgent.split(/\s+/)[0];
129
+ if (first === void 0 || first.length === 0) return null;
130
+ if (!first.includes("/")) return null;
131
+ return first;
132
+ }
133
+ /**
134
+ * Read the user's project `package.json` and resolve a TypeScript
135
+ * version from `devDependencies.typescript` (preferred) or
136
+ * `dependencies.typescript`. Strips a leading `^` or `~` semver
137
+ * prefix. Returns `null` on any failure mode — file missing,
138
+ * unreadable, malformed JSON, key absent, not a string.
139
+ */
140
+ function readTsVersionFromPackageJson(raw) {
141
+ if (raw === null) return null;
142
+ let parsed;
143
+ try {
144
+ parsed = JSON.parse(raw);
145
+ } catch {
146
+ return null;
147
+ }
148
+ const candidate = pickStringDep(parsed["devDependencies"]) ?? pickStringDep(parsed["dependencies"]);
149
+ if (candidate === null) return null;
150
+ return candidate.replace(/^[\^~]/, "");
151
+ }
152
+ function pickStringDep(deps) {
153
+ if (deps === null || typeof deps !== "object" || Array.isArray(deps)) return null;
154
+ const value = deps["typescript"];
155
+ return typeof value === "string" ? value : null;
156
+ }
157
+ /**
158
+ * Build the full backend event from the parent's payload, the
159
+ * c12-loaded project-config slice, and the child's per-process
160
+ * snapshot. Pure given a `projectConfig` + `EnrichEnvironment`.
161
+ */
162
+ function buildTelemetryEvent(payload, projectConfig, env) {
163
+ const runtime = resolveRuntime(env.versions);
164
+ return {
165
+ installationId: payload.installationId,
166
+ version: payload.version,
167
+ command: payload.command,
168
+ flags: payload.flags,
169
+ runtimeName: runtime.name,
170
+ runtimeVersion: runtime.version,
171
+ os: env.platform,
172
+ arch: env.arch,
173
+ packageManager: parsePackageManager(env.env["npm_config_user_agent"]),
174
+ databaseTarget: projectConfig.databaseTarget,
175
+ tsVersion: readTsVersionFromPackageJson(env.readProjectPackageJson()),
176
+ agent: detectAgent(env.env),
177
+ extensions: projectConfig.extensions
178
+ };
179
+ }
180
+ /**
181
+ * Convenience for the sender entry: build the event from the live
182
+ * `process` plus a c12 load of `prisma-next.config.*` from
183
+ * `payload.projectRoot` plus a real project-package.json reader,
184
+ * swallowing any I/O errors in the file read.
185
+ *
186
+ * The parent's `payload.databaseTarget` (when present) wins over the
187
+ * c12-derived value. The parent sets this for the first-`init` run,
188
+ * where the config file does not exist on disk yet but the user has
189
+ * just declared a target via the consent prompt; every other
190
+ * invocation leaves it unset and the c12 load supplies the value.
191
+ */
192
+ async function buildTelemetryEventFromProcess(payload) {
193
+ const loadedConfig = await loadProjectConfig(payload.projectRoot);
194
+ return buildTelemetryEvent(payload, {
195
+ databaseTarget: payload.databaseTarget ?? loadedConfig.databaseTarget,
196
+ extensions: loadedConfig.extensions
197
+ }, {
198
+ platform: process.platform,
199
+ arch: process.arch,
200
+ versions: process.versions,
201
+ env: process.env,
202
+ readProjectPackageJson: () => {
203
+ try {
204
+ return readFileSync(join(payload.projectRoot, "package.json"), "utf-8");
205
+ } catch {
206
+ return null;
207
+ }
208
+ }
209
+ });
210
+ }
211
+ //#endregion
212
+ export { loadProjectConfig as n, buildTelemetryEventFromProcess as t };
213
+
214
+ //# sourceMappingURL=enrich-CGZ8Za8Y.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enrich-CGZ8Za8Y.mjs","names":[],"sources":["../src/detect-agent.ts","../src/enrich.ts"],"sourcesContent":["/**\n * Best-effort identification of AI coding-agent sessions from an\n * env-var allowlist. Detector property: false positives are negligible\n * (a marker present ⇒ confidently an agent); false negatives are\n * expected and documented in the user-facing telemetry docs. New\n * entries should land here, not in per-CLI hand-rolls.\n *\n * Each entry is a `(envVar, agent)` pair with uniform comparison shape:\n * the marker counts as \"present\" when `process.env[envVar]` is set to a\n * truthy string. Truthy = anything other than the empty string, `'0'`,\n * or `'false'` (case-insensitive); see `gating.isTruthyOptOut` for the\n * same convention applied to opt-out env vars.\n *\n * The detector runs in the **child** sender process, never the parent;\n * the parent does not probe env at command start.\n *\n * Codex CLI note: `CODEX_SANDBOX` is the only clear marker available here.\n * Non-sandboxed Codex sessions may be false negatives.\n *\n * TODO: a ci-info-for-agents would be nice — this allowlist drifts the\n * moment a new agent ships its env marker, and consolidating with the\n * other ecosystems that need the same lookup (rate-limited LLM\n * gateways, agent-aware metrics, etc.) would let one library carry the\n * matrix instead of every consumer re-doing it.\n */\nexport interface AgentMarker {\n /** The env-var name to read. Exact-match; no prefix or fuzzy logic. */\n readonly envVar: string;\n /** The agent label written to the `agent` field of the telemetry event. */\n readonly agent: string;\n}\n\nexport const AGENT_MARKERS: readonly AgentMarker[] = [\n { envVar: 'CLAUDECODE', agent: 'Claude Code' },\n { envVar: 'CURSOR_AGENT', agent: 'Cursor' },\n { envVar: 'CODEX_SANDBOX', agent: 'Codex CLI' },\n { envVar: 'GEMINI_CLI', agent: 'Gemini CLI' },\n { envVar: 'WINDSURF', agent: 'Windsurf' },\n { envVar: 'AIDER', agent: 'Aider' },\n { envVar: 'CODY', agent: 'Cody' },\n { envVar: 'CONTINUE', agent: 'Continue' },\n];\n\nfunction isTruthyMarker(raw: string | undefined): boolean {\n if (raw === undefined) return false;\n const normalised = raw.trim().toLowerCase();\n if (normalised === '') return false;\n if (normalised === '0') return false;\n if (normalised === 'false') return false;\n return true;\n}\n\n/**\n * Resolve the agent label from an env snapshot, or `null` if no marker\n * is set. Returns the **first** matching marker in `AGENT_MARKERS`\n * order, so when multiple markers are set the agent label is\n * deterministic and the allowlist's first entry wins.\n *\n * Pure: takes an env record, returns a string or null. No I/O.\n */\nexport function detectAgent(env: Readonly<Record<string, string | undefined>>): string | null {\n for (const marker of AGENT_MARKERS) {\n if (isTruthyMarker(env[marker.envVar])) {\n return marker.agent;\n }\n }\n return null;\n}\n","import { readFileSync } from 'node:fs';\nimport type { PrismaNextConfig } from '@prisma-next/config/config-types';\nimport { join } from 'pathe';\nimport { detectAgent } from './detect-agent';\nimport type { ParentToSenderPayload, TelemetryEvent } from './payload';\n\n/**\n * Subset of the user's `prisma-next.config.*` the telemetry event\n * surfaces. Loaded inside the detached child via {@link loadProjectConfig}\n * — see the design rationale on {@link ParentToSenderPayload} for why\n * this side runs c12 instead of the parent CLI.\n */\nexport interface ProjectConfigFields {\n readonly databaseTarget: string | null;\n readonly extensions: readonly string[];\n}\n\nconst EMPTY_PROJECT_CONFIG: ProjectConfigFields = {\n databaseTarget: null,\n extensions: [],\n};\n\n/**\n * Best-effort load of `prisma-next.config.*` from `projectRoot`,\n * validated against the canonical `@prisma-next/config` schema.\n * Returns `{ databaseTarget: null, extensions: [] }` on any failure\n * mode — missing config file (e.g. before `prisma-next init`), c12\n * throws while evaluating user TS, validator rejects a malformed\n * shape, etc. Telemetry is non-blocking and best-effort; an empty\n * result is the only downside of an unloadable or invalid config.\n *\n * Both `c12` and `@prisma-next/config/config-validation` are imported\n * lazily so the detached sender's cold-start cost is paid only when\n * telemetry actually fires, not on every fork even when gates\n * short-circuit before reaching this code path.\n */\nexport async function loadProjectConfig(projectRoot: string): Promise<ProjectConfigFields> {\n try {\n const { loadConfig } = await import('c12');\n const result = await loadConfig<Record<string, unknown>>({\n name: 'prisma-next',\n cwd: projectRoot,\n dotenv: false,\n rcFile: false,\n globalRc: false,\n });\n const config = result.config ?? null;\n // c12 returns an empty object when no config file exists in the\n // search path — distinct from \"file existed but parsed to an empty\n // object\". Either way, the canonical validator below would reject\n // it on the first required field (`family`), so short-circuit\n // without paying the import cost.\n if (config === null || Object.keys(config).length === 0) {\n return EMPTY_PROJECT_CONFIG;\n }\n const validation = await import('@prisma-next/config/config-validation');\n // TS 4.7+ only flows `asserts cfg is X` narrowing when the\n // assertion function is called via a directly-declared name with\n // an explicit signature. The dynamic-import binding doesn't\n // satisfy that, so wrap the call in a local declaration that\n // re-asserts the signature.\n const validate: (cfg: unknown) => asserts cfg is PrismaNextConfig = validation.validateConfig;\n validate(config);\n return {\n databaseTarget: config.target.targetId,\n extensions: (config.extensionPacks ?? []).map((pack) => pack.id),\n };\n } catch {\n return EMPTY_PROJECT_CONFIG;\n }\n}\n\n/**\n * Versions surface the enrichment cares about. Modelled as a structural\n * record with a required `node` field so tests can pass a literal object\n * without faking every field of `NodeJS.ProcessVersions` (which adds\n * properties between Node versions and includes a long tail the\n * enrichment never touches). Both `bun` and `deno` are read on the\n * runtime-resolution path; everything else is ignored.\n */\nexport interface VersionsSnapshot {\n readonly node: string;\n readonly bun?: string;\n readonly deno?: string;\n}\n\n/**\n * Snapshot of process-level inputs the enrichment reads. Tests pass an\n * explicit snapshot so the enrichment is deterministic per case; the\n * sender entry point passes a fresh snapshot from `process`.\n */\nexport interface EnrichEnvironment {\n readonly platform: NodeJS.Platform;\n readonly arch: string;\n readonly versions: VersionsSnapshot;\n /**\n * Included because package-manager and agent detection intentionally read\n * environment variables from the same process snapshot as platform/versions.\n */\n readonly env: Readonly<Record<string, string | undefined>>;\n /**\n * Best-effort reader for the project's `package.json`, used only to derive\n * the optional `tsVersion` telemetry field. Returning `null` means unknown.\n */\n readonly readProjectPackageJson: () => string | null;\n}\n\n/**\n * Identify the runtime the sender is running in. Same-runtime as the\n * parent is a correctness requirement: the parent forked us via\n * `child_process.fork`, which inherits the parent's runtime. Detection\n * keys on the runtime-specific version field rather than env vars so a\n * spoofed env can't lie about the actual interpreter.\n */\nfunction resolveRuntime(versions: VersionsSnapshot): {\n readonly name: 'node' | 'bun' | 'deno';\n readonly version: string;\n} {\n if (versions.bun !== undefined) {\n return { name: 'bun', version: versions.bun };\n }\n if (versions.deno !== undefined) {\n return { name: 'deno', version: versions.deno };\n }\n return { name: 'node', version: versions.node };\n}\n\n/**\n * Parse `npm_config_user_agent` into a `<pm>/<version>` token. The\n * value, when present, looks like\n * `\"pnpm/10.27.0 npm/? node/v24.13.0 darwin arm64\"` — we take the first\n * whitespace-separated token. Any failure → `null`.\n */\nexport function parsePackageManager(userAgent: string | undefined): string | null {\n if (userAgent === undefined) return null;\n const first = userAgent.split(/\\s+/)[0];\n if (first === undefined || first.length === 0) return null;\n if (!first.includes('/')) return null;\n return first;\n}\n\n/**\n * Read the user's project `package.json` and resolve a TypeScript\n * version from `devDependencies.typescript` (preferred) or\n * `dependencies.typescript`. Strips a leading `^` or `~` semver\n * prefix. Returns `null` on any failure mode — file missing,\n * unreadable, malformed JSON, key absent, not a string.\n */\nexport function readTsVersionFromPackageJson(raw: string | null): string | null {\n if (raw === null) return null;\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(raw) as Record<string, unknown>;\n } catch {\n return null;\n }\n const candidate =\n pickStringDep(parsed['devDependencies']) ?? pickStringDep(parsed['dependencies']);\n if (candidate === null) return null;\n return candidate.replace(/^[\\^~]/, '');\n}\n\nfunction pickStringDep(deps: unknown): string | null {\n if (deps === null || typeof deps !== 'object' || Array.isArray(deps)) return null;\n const value = (deps as Record<string, unknown>)['typescript'];\n return typeof value === 'string' ? value : null;\n}\n\n/**\n * Build the full backend event from the parent's payload, the\n * c12-loaded project-config slice, and the child's per-process\n * snapshot. Pure given a `projectConfig` + `EnrichEnvironment`.\n */\nexport function buildTelemetryEvent(\n payload: ParentToSenderPayload,\n projectConfig: ProjectConfigFields,\n env: EnrichEnvironment,\n): TelemetryEvent {\n const runtime = resolveRuntime(env.versions);\n return {\n installationId: payload.installationId,\n version: payload.version,\n command: payload.command,\n flags: payload.flags,\n runtimeName: runtime.name,\n runtimeVersion: runtime.version,\n os: env.platform,\n arch: env.arch,\n packageManager: parsePackageManager(env.env['npm_config_user_agent']),\n databaseTarget: projectConfig.databaseTarget,\n tsVersion: readTsVersionFromPackageJson(env.readProjectPackageJson()),\n agent: detectAgent(env.env),\n extensions: projectConfig.extensions,\n };\n}\n\n/**\n * Convenience for the sender entry: build the event from the live\n * `process` plus a c12 load of `prisma-next.config.*` from\n * `payload.projectRoot` plus a real project-package.json reader,\n * swallowing any I/O errors in the file read.\n *\n * The parent's `payload.databaseTarget` (when present) wins over the\n * c12-derived value. The parent sets this for the first-`init` run,\n * where the config file does not exist on disk yet but the user has\n * just declared a target via the consent prompt; every other\n * invocation leaves it unset and the c12 load supplies the value.\n */\nexport async function buildTelemetryEventFromProcess(\n payload: ParentToSenderPayload,\n): Promise<TelemetryEvent> {\n const loadedConfig = await loadProjectConfig(payload.projectRoot);\n const projectConfig: ProjectConfigFields = {\n databaseTarget: payload.databaseTarget ?? loadedConfig.databaseTarget,\n extensions: loadedConfig.extensions,\n };\n return buildTelemetryEvent(payload, projectConfig, {\n platform: process.platform,\n arch: process.arch,\n versions: process.versions,\n env: process.env,\n readProjectPackageJson: () => {\n try {\n return readFileSync(join(payload.projectRoot, 'package.json'), 'utf-8');\n } catch {\n return null;\n }\n },\n });\n}\n"],"mappings":"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"}
@@ -21,6 +21,109 @@ declare const TELEMETRY_ENDPOINT_PATH = "/events";
21
21
  */
22
22
  declare function resolveTelemetryEndpoint(env?: Readonly<Record<string, string | undefined>>): string;
23
23
  //#endregion
24
+ //#region src/payload.d.ts
25
+ /**
26
+ * Wire-shape payload the parent IPC-sends to the forked child sender.
27
+ * Mirrors only the fields the parent has naturally in hand at command
28
+ * start: installation id, sanitised command + flags, CLI version, and
29
+ * the project root the child uses to discover everything else. The
30
+ * child probes its own process (runtime/os/arch, package manager, ts
31
+ * version, agent) and reads the user's `prisma-next.config.*` via
32
+ * c12 to derive `databaseTarget` and `extensions`.
33
+ *
34
+ * Loading c12 on the parent side would put a `loadConfig()` await on
35
+ * the command's hot path between gate resolution and `fork()`,
36
+ * opening a race against any CLI command that throws synchronously
37
+ * before that await resolves (the parent exits before forking the
38
+ * sender, and the telemetry event is lost). Moving the load into the
39
+ * detached child eliminates that race; the trade is that the child
40
+ * now evaluates user TS config code, so it's gated behind the same
41
+ * privacy checks the parent already resolved before forking.
42
+ *
43
+ * `databaseTarget` is an optional parent-side override for the
44
+ * c12-derived value: the first-`init` invocation supplies the
45
+ * prompt-chosen target via this field because the config file does
46
+ * not yet exist on disk at that moment. Every other invocation
47
+ * leaves it unset (`undefined`) and the child's c12 load determines
48
+ * the value — there is no third state, so the field's type is
49
+ * `string | undefined`, not `string | null | undefined`.
50
+ *
51
+ * Both sides version-couple on this shape because the IPC carrier is
52
+ * structured-cloned by Node and there's no on-wire compat to maintain.
53
+ */
54
+ interface ParentToSenderPayload {
55
+ readonly installationId: string;
56
+ readonly version: string;
57
+ readonly command: string;
58
+ readonly flags: readonly string[];
59
+ /**
60
+ * Absolute path of the user's project. The child reads
61
+ * `<projectRoot>/package.json` for `tsVersion` and loads
62
+ * `<projectRoot>/prisma-next.config.*` via c12 for `databaseTarget`
63
+ * + `extensions`.
64
+ */
65
+ readonly projectRoot: string;
66
+ /** Resolved endpoint URL (already includes the `/events` path). */
67
+ readonly endpoint: string;
68
+ /**
69
+ * Optional parent-side override for the c12-derived database target.
70
+ * Set by `fireTelemetryAfterInitConsent` (the first-`init` path,
71
+ * where the config file is about to be written but doesn't exist
72
+ * yet); left undefined by `fireTelemetryFromPreAction` (steady
73
+ * state, child resolves the value via c12). The wire-format
74
+ * `TelemetryEvent.databaseTarget: string | null` keeps `null` as
75
+ * the on-the-wire "no target known" marker, but the IPC override
76
+ * channel only needs two states so it's `string | undefined`.
77
+ */
78
+ readonly databaseTarget?: string;
79
+ }
80
+ /**
81
+ * The full event the child POSTs to the backend. Shape matches the
82
+ * backend's arktype schema (`apps/telemetry-backend/src/schema.ts`).
83
+ */
84
+ interface TelemetryEvent {
85
+ readonly installationId: string;
86
+ readonly version: string;
87
+ readonly command: string;
88
+ readonly flags: readonly string[];
89
+ readonly runtimeName: string;
90
+ readonly runtimeVersion: string;
91
+ readonly os: string;
92
+ readonly arch: string;
93
+ readonly packageManager: string | null;
94
+ readonly databaseTarget: string | null;
95
+ readonly tsVersion: string | null;
96
+ readonly agent: string | null;
97
+ readonly extensions: readonly string[];
98
+ }
99
+ //#endregion
100
+ //#region src/enrich.d.ts
101
+ /**
102
+ * Subset of the user's `prisma-next.config.*` the telemetry event
103
+ * surfaces. Loaded inside the detached child via {@link loadProjectConfig}
104
+ * — see the design rationale on {@link ParentToSenderPayload} for why
105
+ * this side runs c12 instead of the parent CLI.
106
+ */
107
+ interface ProjectConfigFields {
108
+ readonly databaseTarget: string | null;
109
+ readonly extensions: readonly string[];
110
+ }
111
+ /**
112
+ * Best-effort load of `prisma-next.config.*` from `projectRoot`,
113
+ * validated against the canonical `@prisma-next/config` schema.
114
+ * Returns `{ databaseTarget: null, extensions: [] }` on any failure
115
+ * mode — missing config file (e.g. before `prisma-next init`), c12
116
+ * throws while evaluating user TS, validator rejects a malformed
117
+ * shape, etc. Telemetry is non-blocking and best-effort; an empty
118
+ * result is the only downside of an unloadable or invalid config.
119
+ *
120
+ * Both `c12` and `@prisma-next/config/config-validation` are imported
121
+ * lazily so the detached sender's cold-start cost is paid only when
122
+ * telemetry actually fires, not on every fork even when gates
123
+ * short-circuit before reaching this code path.
124
+ */
125
+ declare function loadProjectConfig(projectRoot: string): Promise<ProjectConfigFields>;
126
+ //#endregion
24
127
  //#region src/user-config.d.ts
25
128
  /**
26
129
  * The user-level config file. Persists the consent flag and the
@@ -103,50 +206,6 @@ interface GatingInputs {
103
206
  */
104
207
  declare function resolveGating(inputs: GatingInputs): GatingResolution;
105
208
  //#endregion
106
- //#region src/payload.d.ts
107
- /**
108
- * Wire-shape payload the parent IPC-sends to the forked child sender.
109
- * Mirrors the fields the parent has naturally in hand at command start
110
- * (installation id, sanitised command + flags, CLI version, db target,
111
- * extension-pack ids, project root for TS-version lookup). The child
112
- * fills in the rest (runtime/os/arch, package manager, ts version,
113
- * agent) on its side.
114
- *
115
- * Both sides version-couple on this shape because the IPC carrier is
116
- * structured-cloned by Node and there's no on-wire compat to maintain.
117
- */
118
- interface ParentToSenderPayload {
119
- readonly installationId: string;
120
- readonly version: string;
121
- readonly command: string;
122
- readonly flags: readonly string[];
123
- readonly databaseTarget: string | null;
124
- readonly extensions: readonly string[];
125
- /** Absolute path of the user's project. The child reads `<projectRoot>/package.json` for `tsVersion`. */
126
- readonly projectRoot: string;
127
- /** Resolved endpoint URL (already includes the `/events` path). */
128
- readonly endpoint: string;
129
- }
130
- /**
131
- * The full event the child POSTs to the backend. Shape matches the
132
- * backend's arktype schema (`apps/telemetry-backend/src/schema.ts`).
133
- */
134
- interface TelemetryEvent {
135
- readonly installationId: string;
136
- readonly version: string;
137
- readonly command: string;
138
- readonly flags: readonly string[];
139
- readonly runtimeName: string;
140
- readonly runtimeVersion: string;
141
- readonly os: string;
142
- readonly arch: string;
143
- readonly packageManager: string | null;
144
- readonly databaseTarget: string | null;
145
- readonly tsVersion: string | null;
146
- readonly agent: string | null;
147
- readonly extensions: readonly string[];
148
- }
149
- //#endregion
150
209
  //#region src/sanitize.d.ts
151
210
  interface CommanderOptionShape {
152
211
  /** Commander's option attribute name, e.g. `dryRun` for `--dry-run`. */
@@ -213,22 +272,33 @@ declare function sanitizeCommanderResult(input: CommanderResultShape): Sanitised
213
272
  //#region src/spawn.d.ts
214
273
  /**
215
274
  * Inputs the CLI entry point hands the telemetry layer at command
216
- * start. The CLI is responsible for stitching commander's result, the
217
- * loaded config, and the project root together; the telemetry module
218
- * does no I/O of its own except for the user-config read (skipped when
219
- * `userConfig` is provided).
275
+ * start. The CLI is responsible for stitching commander's result and
276
+ * the project root together; the telemetry module does no I/O of its
277
+ * own except for the user-config read (skipped when `userConfig` is
278
+ * provided). `extensions` is deliberately absent: the detached child
279
+ * loads `prisma-next.config.*` via c12 itself and derives the
280
+ * extension-pack ids from the validated config — see the rationale
281
+ * on `ParentToSenderPayload` for why c12 lives in the child rather
282
+ * than on the parent's hot path.
283
+ *
284
+ * `databaseTarget` is an optional parent-side override forwarded to
285
+ * the child. Set by `fireTelemetryAfterInitConsent` (where the
286
+ * config file does not yet exist on disk); left unset by the
287
+ * preAction-hook path so the child's c12 load supplies the value.
220
288
  */
221
289
  interface RunTelemetryInputs {
222
290
  /** Sanitised commander snapshot — see `CommanderResultShape`. */
223
291
  readonly command: CommanderResultShape;
224
292
  /** This CLI's own version (from its `package.json`). */
225
293
  readonly version: string;
226
- /** Resolved `config.target.targetId`, or `null` when the config could not be loaded. */
227
- readonly databaseTarget: string | null;
228
- /** Declared extension-pack IDs, in any deterministic order. */
229
- readonly extensions: readonly string[];
230
294
  /** Absolute path of the project root (typically `process.cwd()`). */
231
295
  readonly projectRoot: string;
296
+ /**
297
+ * Optional parent-side override for the c12-derived database target,
298
+ * forwarded verbatim to the child sender. Wins over the child's
299
+ * c12-derived value when present; `undefined` means "no override".
300
+ */
301
+ readonly databaseTarget?: string;
232
302
  /**
233
303
  * Path to the sender entry compiled into this package's `dist/`.
234
304
  * Resolved by the caller because the compiled sender lives at
@@ -274,5 +344,5 @@ declare function runTelemetry(inputs: RunTelemetryInputs): TelemetryRunOutcome;
274
344
  */
275
345
  declare function senderModuleUrl(importMetaUrl: string): string;
276
346
  //#endregion
277
- export { type CommanderOptionShape, type CommanderResultShape, type GatingDisabledReason, type GatingInputs, type GatingResolution, type ParentToSenderPayload, type RunTelemetryInputs, type SanitisedCommand, TELEMETRY_BACKEND_URL, TELEMETRY_ENDPOINT_PATH, type TelemetryEvent, type TelemetryRunOutcome, type UserConfig, readUserConfig, resolveGating, resolveTelemetryEndpoint, runTelemetry, sanitizeCommanderResult, senderModuleUrl, userConfigPath, writeUserConfig };
347
+ export { type CommanderOptionShape, type CommanderResultShape, type GatingDisabledReason, type GatingInputs, type GatingResolution, type ParentToSenderPayload, type ProjectConfigFields, type RunTelemetryInputs, type SanitisedCommand, TELEMETRY_BACKEND_URL, TELEMETRY_ENDPOINT_PATH, type TelemetryEvent, type TelemetryRunOutcome, type UserConfig, loadProjectConfig, readUserConfig, resolveGating, resolveTelemetryEndpoint, runTelemetry, sanitizeCommanderResult, senderModuleUrl, userConfigPath, writeUserConfig };
278
348
  //# sourceMappingURL=index.d.mts.map