@rebasepro/cli 0.24.0 → 0.24.1-canary.g19596ef
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/bin/rebase.js +3 -0
- package/dist/agent-setup-B31F00DC.js +324 -0
- package/dist/agent-setup-B31F00DC.js.map +1 -0
- package/dist/api-keys-Bl1I9q7M.js +525 -0
- package/dist/api-keys-Bl1I9q7M.js.map +1 -0
- package/dist/apps-CNgQJjg5.js +340 -0
- package/dist/apps-CNgQJjg5.js.map +1 -0
- package/dist/args-BnmsEXvu.js +109 -0
- package/dist/args-BnmsEXvu.js.map +1 -0
- package/dist/atlas-dev-database-D_LP_Woq.js +62 -0
- package/dist/atlas-dev-database-D_LP_Woq.js.map +1 -0
- package/dist/auth-aySHEF45.js +414 -0
- package/dist/auth-aySHEF45.js.map +1 -0
- package/dist/branch-pointer-DvSHBjjz.js +2 -0
- package/dist/build-DIHWIqO4.js +336 -0
- package/dist/build-DIHWIqO4.js.map +1 -0
- package/dist/bundle-CqURVN-K.js +1621 -0
- package/dist/bundle-CqURVN-K.js.map +1 -0
- package/dist/bundle.d.ts +6 -1
- package/dist/cli.d.ts +2 -2
- package/dist/cloud-DjByQlkW.js +9667 -0
- package/dist/cloud-DjByQlkW.js.map +1 -0
- package/dist/collection-drift-BKj_BoMq.js +106 -0
- package/dist/collection-drift-BKj_BoMq.js.map +1 -0
- package/dist/commands/api-keys.d.ts +2 -0
- package/dist/commands/console.d.ts +12 -0
- package/dist/commands/db.d.ts +64 -24
- package/dist/commands/dev.d.ts +103 -6
- package/dist/commands/generate_sdk.d.ts +26 -0
- package/dist/commands/init.d.ts +58 -0
- package/dist/commands/skills.d.ts +22 -7
- package/dist/commands/start.d.ts +15 -0
- package/dist/commands/storage.d.ts +46 -0
- package/dist/commands/upgrade.d.ts +1 -0
- package/dist/consent-ClRHmcxf.js +76 -0
- package/dist/consent-ClRHmcxf.js.map +1 -0
- package/dist/console-D6SJf8k_.js +102 -0
- package/dist/console-D6SJf8k_.js.map +1 -0
- package/dist/context-BqhRydBg.js +1234 -0
- package/dist/context-BqhRydBg.js.map +1 -0
- package/dist/{daemon-entry-LTFKtpHy.js → daemon-entry-Da-D3rmH.js} +3 -4
- package/dist/daemon-entry-Da-D3rmH.js.map +1 -0
- package/dist/daemon-pzsQwDHa.js +2 -0
- package/dist/db-B7RuNuaQ.js +1312 -0
- package/dist/db-B7RuNuaQ.js.map +1 -0
- package/dist/derive-Dl0z2OWi.js +484 -0
- package/dist/derive-Dl0z2OWi.js.map +1 -0
- package/dist/dev-CYr_WXan.js +1599 -0
- package/dist/dev-CYr_WXan.js.map +1 -0
- package/dist/dev-db/atlas-dev-database.d.ts +32 -0
- package/dist/dev-db/daemon-entry.d.ts +13 -0
- package/dist/dev-db/last-dev-database.d.ts +41 -0
- package/dist/dev-db/prepare.d.ts +19 -3
- package/dist/dev-db/pull.d.ts +90 -5
- package/dist/dev-db/resolve.d.ts +26 -2
- package/dist/dev-preflight-B-LYyBf1.js +2 -0
- package/dist/dev-server-DG8Tt-uf.js +96 -0
- package/dist/dev-server-DG8Tt-uf.js.map +1 -0
- package/dist/doctor-BP8cZ-7F.js +771 -0
- package/dist/doctor-BP8cZ-7F.js.map +1 -0
- package/dist/eject-DizdoecV.js +335 -0
- package/dist/eject-DizdoecV.js.map +1 -0
- package/dist/fold-static-BC9CYicw.js +201 -0
- package/dist/fold-static-BC9CYicw.js.map +1 -0
- package/dist/function-portability-BIvlvR9q.js +265 -0
- package/dist/function-portability-BIvlvR9q.js.map +1 -0
- package/dist/generate_sdk-BPqdJc3Q.js +489 -0
- package/dist/generate_sdk-BPqdJc3Q.js.map +1 -0
- package/dist/index.es.js +151 -24674
- package/dist/index.es.js.map +1 -1
- package/dist/init-Utstvh2Q.js +1149 -0
- package/dist/init-Utstvh2Q.js.map +1 -0
- package/dist/last-dev-database-B58g89uA.js +2 -0
- package/dist/manifest-DRp0UVTj.js +880 -0
- package/dist/manifest-DRp0UVTj.js.map +1 -0
- package/dist/manifest.d.ts +15 -3
- package/dist/normalize-imports-X0Tgze9y.js +107 -0
- package/dist/normalize-imports-X0Tgze9y.js.map +1 -0
- package/dist/{package-manager-CXQevsE1.js → package-manager-DSEOwTqM.js} +2 -2
- package/dist/{package-manager-CXQevsE1.js.map → package-manager-DSEOwTqM.js.map} +1 -1
- package/dist/path-flags-BFgG9V6y.js +91 -0
- package/dist/path-flags-BFgG9V6y.js.map +1 -0
- package/dist/precompress.d.ts +17 -0
- package/dist/prepare-CDN6lSpz.js +1236 -0
- package/dist/prepare-CDN6lSpz.js.map +1 -0
- package/dist/{project-DmaGLmH2.js → project-Wp2zoyeN.js} +33 -4
- package/dist/project-Wp2zoyeN.js.map +1 -0
- package/dist/pull-CrGYMEsy.js +458 -0
- package/dist/pull-CrGYMEsy.js.map +1 -0
- package/dist/resolve-B2O-wKKk.js +2 -0
- package/dist/resources-FD7AfZx8.js +183 -0
- package/dist/resources-FD7AfZx8.js.map +1 -0
- package/dist/schema-DMdr431S.js +125 -0
- package/dist/schema-DMdr431S.js.map +1 -0
- package/dist/skills-DTFibT1m.js +642 -0
- package/dist/skills-DTFibT1m.js.map +1 -0
- package/dist/start-DEa-hOBh.js +267 -0
- package/dist/start-DEa-hOBh.js.map +1 -0
- package/dist/{state-C59Elrnt.js → state-Do7ZJYkF.js} +49 -4
- package/dist/state-Do7ZJYkF.js.map +1 -0
- package/dist/status-DxnJTekv.js +352 -0
- package/dist/status-DxnJTekv.js.map +1 -0
- package/dist/storage-DyVq-f_F.js +303 -0
- package/dist/storage-DyVq-f_F.js.map +1 -0
- package/dist/telemetry/identity.d.ts +10 -1
- package/dist/telemetry-C8Uq8phb.js +129 -0
- package/dist/telemetry-C8Uq8phb.js.map +1 -0
- package/dist/telemetry-EMFRVRQi.js +351 -0
- package/dist/telemetry-EMFRVRQi.js.map +1 -0
- package/dist/unknown-command-DNwDcX3w.js +98 -0
- package/dist/unknown-command-DNwDcX3w.js.map +1 -0
- package/dist/upgrade-CtZtRkTE.js +1332 -0
- package/dist/upgrade-CtZtRkTE.js.map +1 -0
- package/dist/upgrade.d.ts +24 -3
- package/dist/utils/dev-preflight.d.ts +47 -5
- package/dist/utils/dev-server.d.ts +30 -0
- package/dist/utils/path-flags.d.ts +15 -2
- package/dist/utils/project.d.ts +16 -0
- package/dist/utils/temp-archive.d.ts +9 -0
- package/dist/{version-DsgBmP22.js → version-Buyyo1ut.js} +2 -2
- package/dist/{version-DsgBmP22.js.map → version-Buyyo1ut.js.map} +1 -1
- package/package.json +7 -7
- package/templates/eject/Dockerfile +4 -2
- package/templates/eject/backend/src/env.ts +1 -1
- package/templates/eject/backend/src/index.ts +29 -4
- package/templates/eject/docker-compose.custom.yml +8 -4
- package/templates/generated-schemas/blank.ts +40 -0
- package/templates/generated-schemas/blog.ts +127 -0
- package/templates/generated-schemas/ecommerce.ts +93 -0
- package/templates/overlays/baas/config/package.json +1 -0
- package/templates/overlays/baas/package.json +1 -0
- package/templates/template/.env.example +10 -4
- package/templates/template/README.md +11 -4
- package/templates/template/ai-instructions.md +3 -2
- package/templates/template/config/resources.ts +7 -6
- package/templates/template/docker-compose.yml +9 -3
- package/templates/template/frontend/vite.config.ts +13 -3
- package/templates/template/package.json +1 -0
- package/templates/template/scripts/example.ts +2 -1
- package/templates/template/tsconfig.json +25 -0
- package/dist/branch-pointer-kk9F5FBO.js +0 -111
- package/dist/branch-pointer-kk9F5FBO.js.map +0 -1
- package/dist/constraints-DKGbNfUW.js +0 -48
- package/dist/constraints-DKGbNfUW.js.map +0 -1
- package/dist/daemon-C8p32i-n.js +0 -357
- package/dist/daemon-C8p32i-n.js.map +0 -1
- package/dist/daemon-entry-LTFKtpHy.js.map +0 -1
- package/dist/dev-preflight-CNLl4rdo.js +0 -367
- package/dist/dev-preflight-CNLl4rdo.js.map +0 -1
- package/dist/project-DmaGLmH2.js.map +0 -1
- package/dist/pull-Dywm5FWP.js +0 -232
- package/dist/pull-Dywm5FWP.js.map +0 -1
- package/dist/resolve-BAeRUBhg.js +0 -74
- package/dist/resolve-BAeRUBhg.js.map +0 -1
- package/dist/state-C59Elrnt.js.map +0 -1
- package/templates/template/backend/src/schema.generated.ts +0 -13
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
import { c as findProjectRoot, t as MANIFEST_FILENAME } from "./project-Wp2zoyeN.js";
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import os from "os";
|
|
4
|
+
import path from "path";
|
|
5
|
+
import crypto from "crypto";
|
|
6
|
+
import { fileURLToPath } from "url";
|
|
7
|
+
import { parseEnvBoolean } from "@rebasepro/types";
|
|
8
|
+
function configPath() {
|
|
9
|
+
return path.join(os.homedir(), ".rebase", "telemetry.json");
|
|
10
|
+
}
|
|
11
|
+
function readConfig() {
|
|
12
|
+
try {
|
|
13
|
+
const raw = JSON.parse(fs.readFileSync(configPath(), "utf-8"));
|
|
14
|
+
if (raw && typeof raw === "object") return {
|
|
15
|
+
version: typeof raw.version === "number" ? raw.version : 1,
|
|
16
|
+
enabled: typeof raw.enabled === "boolean" ? raw.enabled : void 0,
|
|
17
|
+
machineId: typeof raw.machineId === "string" ? raw.machineId : void 0,
|
|
18
|
+
decidedAt: typeof raw.decidedAt === "string" ? raw.decidedAt : void 0
|
|
19
|
+
};
|
|
20
|
+
} catch {}
|
|
21
|
+
return { version: 1 };
|
|
22
|
+
}
|
|
23
|
+
function writeConfig(config) {
|
|
24
|
+
const file = configPath();
|
|
25
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
26
|
+
fs.writeFileSync(file, JSON.stringify({
|
|
27
|
+
...config,
|
|
28
|
+
version: 1
|
|
29
|
+
}, null, 2), {
|
|
30
|
+
encoding: "utf-8",
|
|
31
|
+
mode: 384
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The machine's id, generating and persisting one on first use.
|
|
36
|
+
*
|
|
37
|
+
* Only called once consent exists — an id written before the user agreed would
|
|
38
|
+
* be a record we had no right to create, even unsent.
|
|
39
|
+
*/
|
|
40
|
+
function ensureMachineId() {
|
|
41
|
+
const config = readConfig();
|
|
42
|
+
if (config.machineId) return config.machineId;
|
|
43
|
+
const machineId = crypto.randomUUID();
|
|
44
|
+
writeConfig({
|
|
45
|
+
...config,
|
|
46
|
+
machineId
|
|
47
|
+
});
|
|
48
|
+
return machineId;
|
|
49
|
+
}
|
|
50
|
+
/** Where a checkout keeps its id, under the project's gitignored `.rebase/`. */
|
|
51
|
+
var PROJECT_ID_FILE = "telemetry-project.json";
|
|
52
|
+
/**
|
|
53
|
+
* The checkout's id, generating one if this project has none.
|
|
54
|
+
*
|
|
55
|
+
* The directory is created when it is missing, but **only** where a
|
|
56
|
+
* `rebase.json` proves this really is a project root. An earlier version
|
|
57
|
+
* required `.rebase/` to already exist, on the assumption that `rebase init`
|
|
58
|
+
* created it — it does not. It is written only when a scaffold is linked to
|
|
59
|
+
* Rebase Cloud, so every self-hosted project reported no `projectId` at all,
|
|
60
|
+
* for ever. That silently broke the funnel this id exists for, on exactly the
|
|
61
|
+
* population the telemetry is meant to learn about.
|
|
62
|
+
*
|
|
63
|
+
* The `rebase.json` check is what keeps the fix from being "scatter `.rebase/`
|
|
64
|
+
* wherever a command happens to run": no manifest, no project, no directory,
|
|
65
|
+
* and the event simply reports no project.
|
|
66
|
+
*
|
|
67
|
+
* A file of its own, written by nothing else. The id used to be a key in
|
|
68
|
+
* `.rebase/state.json`, which is the dev server's runtime file: rewritten
|
|
69
|
+
* from scratch on every start and deleted on every shutdown. So every
|
|
70
|
+
* restart of `rebase dev` minted a new id, and one checkout read as a new
|
|
71
|
+
* project each time — the error this split exists to prevent, by another way.
|
|
72
|
+
*/
|
|
73
|
+
function ensureProjectId(projectRoot) {
|
|
74
|
+
if (!fs.existsSync(path.join(projectRoot, "rebase.json"))) return void 0;
|
|
75
|
+
const dir = path.join(projectRoot, ".rebase");
|
|
76
|
+
try {
|
|
77
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
78
|
+
} catch {
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
const file = path.join(dir, PROJECT_ID_FILE);
|
|
82
|
+
if (fs.existsSync(file)) return readProjectId(file);
|
|
83
|
+
const projectId = crypto.randomUUID();
|
|
84
|
+
try {
|
|
85
|
+
fs.writeFileSync(file, `${JSON.stringify({ projectId }, null, 2)}\n`, {
|
|
86
|
+
encoding: "utf-8",
|
|
87
|
+
flag: "wx",
|
|
88
|
+
mode: 384
|
|
89
|
+
});
|
|
90
|
+
} catch {
|
|
91
|
+
return fs.existsSync(file) ? readProjectId(file) : void 0;
|
|
92
|
+
}
|
|
93
|
+
return projectId;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* The id a checkout's file holds. A file that does not parse is not ours to
|
|
97
|
+
* repair — overwriting it would quietly start a second id for the same
|
|
98
|
+
* checkout — so the event reports no project instead.
|
|
99
|
+
*/
|
|
100
|
+
function readProjectId(file) {
|
|
101
|
+
try {
|
|
102
|
+
const raw = JSON.parse(fs.readFileSync(file, "utf-8"));
|
|
103
|
+
if (raw && typeof raw === "object" && typeof raw.projectId === "string") return raw.projectId;
|
|
104
|
+
} catch {}
|
|
105
|
+
}
|
|
106
|
+
/** Duration in coarse bands — enough to see "slow", not enough to fingerprint. */
|
|
107
|
+
function durationBucket(ms) {
|
|
108
|
+
if (!Number.isFinite(ms) || ms < 0) return "unknown";
|
|
109
|
+
if (ms < 5e3) return "<5s";
|
|
110
|
+
if (ms < 3e4) return "5-30s";
|
|
111
|
+
if (ms < 12e4) return "30-120s";
|
|
112
|
+
return "120s+";
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* An error reduced to something safe to transmit.
|
|
116
|
+
*
|
|
117
|
+
* The message and the stack are discarded, always. What survives is the
|
|
118
|
+
* constructor name and, for the errors that carry one, a `code` — both of which
|
|
119
|
+
* come from the program rather than from anything the user typed or named.
|
|
120
|
+
* `EACCES` is useful and safe; "cannot write /Users/francesco/clients/acme" is
|
|
121
|
+
* neither.
|
|
122
|
+
*/
|
|
123
|
+
function errorClass(error) {
|
|
124
|
+
if (error && typeof error === "object") {
|
|
125
|
+
const code = error.code;
|
|
126
|
+
if (typeof code === "string" && /^[A-Z][A-Z0-9_]{1,31}$/.test(code)) return code;
|
|
127
|
+
const name = error.name;
|
|
128
|
+
if (typeof name === "string" && /^[A-Za-z][A-Za-z0-9]{0,31}$/.test(name)) return name;
|
|
129
|
+
}
|
|
130
|
+
return "Unknown";
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Drop anything that is not a permitted value type, and clamp strings.
|
|
134
|
+
*
|
|
135
|
+
* The last line of defence rather than the first. Every call site is supposed
|
|
136
|
+
* to pass enumerated values; this is what stops a future one that forgets from
|
|
137
|
+
* turning into an incident. Strings are capped at 64 characters because no
|
|
138
|
+
* legitimate enumerated value is longer, and a path or a message always is.
|
|
139
|
+
*/
|
|
140
|
+
/**
|
|
141
|
+
* Key names that shadow an `Object.prototype` member.
|
|
142
|
+
*
|
|
143
|
+
* `__proto__` is already excluded by the pattern (it starts with an
|
|
144
|
+
* underscore), and assigning any of these to an object literal shadows rather
|
|
145
|
+
* than pollutes — so nothing is exploitable here. They are refused because a
|
|
146
|
+
* stored property called `constructor` is a trap for every consumer downstream
|
|
147
|
+
* that reaches for `properties.constructor` and gets a string.
|
|
148
|
+
*/
|
|
149
|
+
var RESERVED_KEYS = /* @__PURE__ */ new Set([
|
|
150
|
+
"constructor",
|
|
151
|
+
"prototype",
|
|
152
|
+
"hasownproperty",
|
|
153
|
+
"tostring",
|
|
154
|
+
"valueof"
|
|
155
|
+
]);
|
|
156
|
+
function sanitize(properties) {
|
|
157
|
+
const out = {};
|
|
158
|
+
for (const [key, value] of Object.entries(properties)) {
|
|
159
|
+
if (!/^[a-z][a-z0-9_]{0,31}$/.test(key) || RESERVED_KEYS.has(key.toLowerCase())) continue;
|
|
160
|
+
if (typeof value === "boolean" || typeof value === "number" && Number.isFinite(value)) out[key] = value;
|
|
161
|
+
else if (typeof value === "string" && value.length > 0 && value.length <= 64) {
|
|
162
|
+
if (!/[/\\@:\s]/.test(value)) out[key] = value;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return out;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* The CLI's own version, read by walking up to this package's manifest.
|
|
169
|
+
*
|
|
170
|
+
* The obvious `require("../../package.json")` was wrong everywhere, not only on
|
|
171
|
+
* one install path: `vite build` bundles this module into `dist/index.es.js`, so
|
|
172
|
+
* the specifier resolves relative to `<pkg>/dist/` and lands on
|
|
173
|
+
* `<parent-of-pkg>/package.json` — a file that does not exist under npm, pnpm or
|
|
174
|
+
* the monorepo. Every event ever sent carried `cliVersion: "unknown"`, which is
|
|
175
|
+
* the one field that makes the rest of a payload interpretable.
|
|
176
|
+
*
|
|
177
|
+
* So walk up and check the manifest's `name` rather than counting directory
|
|
178
|
+
* levels: the count differs between `src/telemetry/` and the bundled `dist/`,
|
|
179
|
+
* and a wrong count fails silently by finding *some* package.json — the nearest
|
|
180
|
+
* dependency's, under a hoisted layout. Matching the name cannot do that.
|
|
181
|
+
*/
|
|
182
|
+
function cliVersion() {
|
|
183
|
+
try {
|
|
184
|
+
let dir = path.dirname(fileURLToPath(import.meta.url));
|
|
185
|
+
const root = path.parse(dir).root;
|
|
186
|
+
while (dir && dir !== root) {
|
|
187
|
+
const manifest = path.join(dir, "package.json");
|
|
188
|
+
if (fs.existsSync(manifest)) {
|
|
189
|
+
const pkg = JSON.parse(fs.readFileSync(manifest, "utf-8"));
|
|
190
|
+
if (pkg?.name === "@rebasepro/cli" && typeof pkg.version === "string" && pkg.version) return pkg.version;
|
|
191
|
+
}
|
|
192
|
+
dir = path.dirname(dir);
|
|
193
|
+
}
|
|
194
|
+
} catch {}
|
|
195
|
+
return "unknown";
|
|
196
|
+
}
|
|
197
|
+
function buildEvent(event, properties, identity) {
|
|
198
|
+
return {
|
|
199
|
+
schema: 1,
|
|
200
|
+
event,
|
|
201
|
+
machineId: identity.machineId,
|
|
202
|
+
projectId: identity.projectId,
|
|
203
|
+
cliVersion: cliVersion(),
|
|
204
|
+
nodeMajor: Number(process.versions.node.split(".")[0]) || 0,
|
|
205
|
+
platform: os.platform(),
|
|
206
|
+
arch: os.arch(),
|
|
207
|
+
at: (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "Z"),
|
|
208
|
+
properties: sanitize(properties)
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
//#endregion
|
|
212
|
+
//#region src/telemetry/project.ts
|
|
213
|
+
function readProjectPolicy(startDir = process.cwd()) {
|
|
214
|
+
try {
|
|
215
|
+
const root = findProjectRoot(startDir);
|
|
216
|
+
if (!root) return "unset";
|
|
217
|
+
const file = path.join(root, MANIFEST_FILENAME);
|
|
218
|
+
if (!fs.existsSync(file)) return "unset";
|
|
219
|
+
const raw = fs.readFileSync(file, "utf-8");
|
|
220
|
+
const match = /"telemetry"\s*:\s*(true|false)/.exec(raw);
|
|
221
|
+
if (!match) return "unset";
|
|
222
|
+
return match[1] === "false" ? "opt_out" : "ignored_opt_in";
|
|
223
|
+
} catch {
|
|
224
|
+
return "unset";
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
function endpoint() {
|
|
228
|
+
return process.env.REBASE_TELEMETRY_ENDPOINT?.trim() || "https://app.rebase.pro/api/functions/telemetry";
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Set to anything but a spelled no.
|
|
232
|
+
*
|
|
233
|
+
* The conventions behind these variables make presence the signal —
|
|
234
|
+
* `CI=woodpecker` is a CI run, `DO_NOT_TRACK=please` is an answer — so a value
|
|
235
|
+
* the parser does not recognise still counts, and the refusal holds. Only the
|
|
236
|
+
* platform's spellings of no turn one off. It was `!== "0"` for two of them and
|
|
237
|
+
* `!== "false"` for `CI`, so `CI=0` read as a runner.
|
|
238
|
+
*/
|
|
239
|
+
function setAndNotNo(value) {
|
|
240
|
+
return value !== void 0 && value.trim() !== "" && parseEnvBoolean(value) !== false;
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* The one function that decides whether anything leaves the machine.
|
|
244
|
+
*
|
|
245
|
+
* Every path is a refusal except the last, which is the point: consent is
|
|
246
|
+
* opt-in, so the default answer at every branch — never asked, unreadable
|
|
247
|
+
* config, a set env var, a CI runner — is no.
|
|
248
|
+
*
|
|
249
|
+
* `DO_NOT_TRACK` is honoured because it is the cross-tool convention
|
|
250
|
+
* (consoledonottrack.com); a user who has set it globally has already answered
|
|
251
|
+
* this question and should not be asked again by us.
|
|
252
|
+
*
|
|
253
|
+
* `CI` is refused for a different reason: a build runner is not a person, and
|
|
254
|
+
* counting one is both useless and misleading. A single pipeline re-running on
|
|
255
|
+
* every push would otherwise outweigh every real developer in the data.
|
|
256
|
+
*
|
|
257
|
+
* A project's own `"telemetry": false` is checked *before* the machine setting,
|
|
258
|
+
* because it has to beat an individual opt-in to be worth anything — see
|
|
259
|
+
* project.ts on why the reverse is refused.
|
|
260
|
+
*/
|
|
261
|
+
function suppressionReason(env = process.env, cwd = process.cwd()) {
|
|
262
|
+
if (setAndNotNo(env.DO_NOT_TRACK)) return "do_not_track";
|
|
263
|
+
if (setAndNotNo(env.REBASE_TELEMETRY_DISABLED)) return "rebase_telemetry_disabled";
|
|
264
|
+
if (setAndNotNo(env.CI)) return "ci";
|
|
265
|
+
if (readProjectPolicy(cwd) === "opt_out") return "project_opt_out";
|
|
266
|
+
const config = readConfig();
|
|
267
|
+
if (config.enabled === void 0) return "not_asked";
|
|
268
|
+
if (!config.enabled) return "declined";
|
|
269
|
+
return null;
|
|
270
|
+
}
|
|
271
|
+
function isEnabled(env = process.env, cwd = process.cwd()) {
|
|
272
|
+
return suppressionReason(env, cwd) === null;
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Record the user's answer. `false` is final — nothing prompts again.
|
|
276
|
+
*
|
|
277
|
+
* Returns whether the choice could actually be persisted. A read-only or full
|
|
278
|
+
* home directory makes `writeConfig` throw, and the direction of that failure
|
|
279
|
+
* matters enormously: someone turning sharing **off** who sees a stack trace,
|
|
280
|
+
* or worse sees nothing, is left sharing. The caller is expected to say so and
|
|
281
|
+
* point at `REBASE_TELEMETRY_DISABLED`, which needs no disk.
|
|
282
|
+
*/
|
|
283
|
+
function setConsent(enabled) {
|
|
284
|
+
const config = readConfig();
|
|
285
|
+
try {
|
|
286
|
+
writeConfig({
|
|
287
|
+
...config,
|
|
288
|
+
enabled,
|
|
289
|
+
decidedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
290
|
+
machineId: enabled ? config.machineId ?? void 0 : void 0
|
|
291
|
+
});
|
|
292
|
+
if (enabled) ensureMachineId();
|
|
293
|
+
return true;
|
|
294
|
+
} catch {
|
|
295
|
+
return false;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Build the event that *would* be sent, without sending it.
|
|
300
|
+
*
|
|
301
|
+
* This is what `rebase telemetry show` prints, and it is deliberately the same
|
|
302
|
+
* function the sender uses — a preview assembled by separate code is a promise
|
|
303
|
+
* that drifts. Returns `null` when nothing would be sent, so the command can
|
|
304
|
+
* say why instead of showing a payload that is never going anywhere.
|
|
305
|
+
*/
|
|
306
|
+
function previewEvent(event, properties = {}, projectRoot) {
|
|
307
|
+
const config = readConfig();
|
|
308
|
+
if (!config.machineId) return null;
|
|
309
|
+
return buildEvent(event, properties, {
|
|
310
|
+
machineId: config.machineId,
|
|
311
|
+
projectId: projectRoot ? ensureProjectId(projectRoot) : void 0
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* Send one event, or quietly do nothing.
|
|
316
|
+
*
|
|
317
|
+
* Three properties this must hold, in order of importance:
|
|
318
|
+
*
|
|
319
|
+
* 1. **It never throws.** Telemetry failing is not a reason for `rebase dev`
|
|
320
|
+
* to fail. Every error is swallowed.
|
|
321
|
+
* 2. **It never blocks meaningfully.** A two-second ceiling, after which the
|
|
322
|
+
* command carries on regardless — a collector having a bad day must not
|
|
323
|
+
* become the CLI hanging.
|
|
324
|
+
* 3. **It never sends without consent.** Enforced here rather than at the call
|
|
325
|
+
* sites, so a new call site cannot get it wrong.
|
|
326
|
+
*/
|
|
327
|
+
async function recordEvent(event, properties = {}, options = {}) {
|
|
328
|
+
try {
|
|
329
|
+
if (!isEnabled(process.env, options.projectRoot ?? process.cwd())) return;
|
|
330
|
+
const payload = buildEvent(event, properties, {
|
|
331
|
+
machineId: ensureMachineId(),
|
|
332
|
+
projectId: options.projectRoot ? ensureProjectId(options.projectRoot) : void 0
|
|
333
|
+
});
|
|
334
|
+
const abort = new AbortController();
|
|
335
|
+
const timer = setTimeout(() => abort.abort(), options.timeoutMs ?? 2e3);
|
|
336
|
+
try {
|
|
337
|
+
await fetch(endpoint(), {
|
|
338
|
+
method: "POST",
|
|
339
|
+
headers: { "Content-Type": "application/json" },
|
|
340
|
+
body: JSON.stringify(payload),
|
|
341
|
+
signal: abort.signal
|
|
342
|
+
});
|
|
343
|
+
} finally {
|
|
344
|
+
clearTimeout(timer);
|
|
345
|
+
}
|
|
346
|
+
} catch {}
|
|
347
|
+
}
|
|
348
|
+
//#endregion
|
|
349
|
+
export { setConsent as a, buildEvent as c, configPath as d, readConfig as f, recordEvent as i, durationBucket as l, isEnabled as n, suppressionReason as o, previewEvent as r, readProjectPolicy as s, endpoint as t, errorClass as u };
|
|
350
|
+
|
|
351
|
+
//# sourceMappingURL=telemetry-EMFRVRQi.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"telemetry-EMFRVRQi.js","names":[],"sources":["../src/telemetry/identity.ts","../src/telemetry/payload.ts","../src/telemetry/project.ts","../src/telemetry/index.ts"],"sourcesContent":["import fs from \"fs\";\nimport os from \"os\";\nimport path from \"path\";\nimport crypto from \"crypto\";\n\n/**\n * Who is reporting, and where that is remembered.\n *\n * Two identifiers, because they answer two different questions and conflating\n * them would make the answers wrong:\n *\n * - `machineId` — one developer's machine. Lives beside the cloud credentials\n * in `~/.rebase/`, so it survives across every project they scaffold.\n * - `projectId` — one *checkout*. Lives in the project's gitignored\n * `.rebase/`, in a file of its own, `telemetry-project.json`, so it lasts\n * as long as the checkout does.\n *\n * Without the split, a developer trying five templates in an afternoon reads as\n * five installations. With it, that is one machine and five projects, which is\n * the shape the funnel actually needs.\n *\n * ## Why `projectId` is not committed\n *\n * `rebase.json` is checked in, and a stable identifier sitting in a public\n * repository is a correlation handle for anyone who finds it — it ties a named\n * organisation to whatever that id did. `.rebase/` is gitignored, so the id\n * stays on the machine that generated it. It also makes the unit honest: what\n * is being counted is a developer working on a project, not the project.\n *\n * ## Why both are random\n *\n * Neither is derived from a hostname, a database name, an email or a machine\n * fingerprint. Hashing any of those only *looks* anonymous — the space of real\n * hostnames is small enough to brute-force a salted hash back to the original\n * in minutes. A random UUID carries no information at all and does the same job.\n */\n\n/** Bumped when the stored shape changes in a way old CLIs cannot read. */\nexport const TELEMETRY_CONFIG_VERSION = 1;\n\nexport type TelemetryConfig = {\n version: number;\n /**\n * `undefined` means never asked — which is *not* the same as declining, and\n * is the only state in which anything may prompt.\n */\n enabled?: boolean;\n machineId?: string;\n /** When the choice was made, so a later release can tell stale consent from fresh. */\n decidedAt?: string;\n};\n\nexport function configPath(): string {\n return path.join(os.homedir(), \".rebase\", \"telemetry.json\");\n}\n\nexport function readConfig(): TelemetryConfig {\n try {\n const raw = JSON.parse(fs.readFileSync(configPath(), \"utf-8\"));\n if (raw && typeof raw === \"object\") {\n return {\n version: typeof raw.version === \"number\" ? raw.version : TELEMETRY_CONFIG_VERSION,\n enabled: typeof raw.enabled === \"boolean\" ? raw.enabled : undefined,\n machineId: typeof raw.machineId === \"string\" ? raw.machineId : undefined,\n decidedAt: typeof raw.decidedAt === \"string\" ? raw.decidedAt : undefined\n };\n }\n } catch {\n // Missing, unreadable or corrupt all mean the same thing: we have no\n // record of a decision, so nothing may be sent.\n }\n return { version: TELEMETRY_CONFIG_VERSION };\n}\n\nexport function writeConfig(config: TelemetryConfig): void {\n const file = configPath();\n fs.mkdirSync(path.dirname(file), { recursive: true });\n // 0600: it sits beside `credentials.json`, and a world-readable identifier\n // on a shared machine is a way to link one developer's activity to another's.\n fs.writeFileSync(file, JSON.stringify({ ...config,\nversion: TELEMETRY_CONFIG_VERSION }, null, 2), {\n encoding: \"utf-8\",\n mode: 0o600\n });\n}\n\n/**\n * The machine's id, generating and persisting one on first use.\n *\n * Only called once consent exists — an id written before the user agreed would\n * be a record we had no right to create, even unsent.\n */\nexport function ensureMachineId(): string {\n const config = readConfig();\n if (config.machineId) return config.machineId;\n const machineId = crypto.randomUUID();\n writeConfig({ ...config,\nmachineId });\n return machineId;\n}\n\n/** Where a checkout keeps its id, under the project's gitignored `.rebase/`. */\nexport const PROJECT_ID_FILE = \"telemetry-project.json\";\n\n/**\n * The checkout's id, generating one if this project has none.\n *\n * The directory is created when it is missing, but **only** where a\n * `rebase.json` proves this really is a project root. An earlier version\n * required `.rebase/` to already exist, on the assumption that `rebase init`\n * created it — it does not. It is written only when a scaffold is linked to\n * Rebase Cloud, so every self-hosted project reported no `projectId` at all,\n * for ever. That silently broke the funnel this id exists for, on exactly the\n * population the telemetry is meant to learn about.\n *\n * The `rebase.json` check is what keeps the fix from being \"scatter `.rebase/`\n * wherever a command happens to run\": no manifest, no project, no directory,\n * and the event simply reports no project.\n *\n * A file of its own, written by nothing else. The id used to be a key in\n * `.rebase/state.json`, which is the dev server's runtime file: rewritten\n * from scratch on every start and deleted on every shutdown. So every\n * restart of `rebase dev` minted a new id, and one checkout read as a new\n * project each time — the error this split exists to prevent, by another way.\n */\nexport function ensureProjectId(projectRoot: string): string | undefined {\n if (!fs.existsSync(path.join(projectRoot, \"rebase.json\"))) return undefined;\n\n const dir = path.join(projectRoot, \".rebase\");\n try {\n fs.mkdirSync(dir, { recursive: true });\n } catch {\n return undefined;\n }\n\n const file = path.join(dir, PROJECT_ID_FILE);\n if (fs.existsSync(file)) return readProjectId(file);\n\n const projectId = crypto.randomUUID();\n try {\n // `wx`: of two commands minting the first id at once, one writes and\n // the other reads what it wrote.\n fs.writeFileSync(file, `${JSON.stringify({ projectId }, null, 2)}\\n`, { encoding: \"utf-8\", flag: \"wx\", mode: 0o600 });\n } catch {\n return fs.existsSync(file) ? readProjectId(file) : undefined;\n }\n return projectId;\n}\n\n/**\n * The id a checkout's file holds. A file that does not parse is not ours to\n * repair — overwriting it would quietly start a second id for the same\n * checkout — so the event reports no project instead.\n */\nfunction readProjectId(file: string): string | undefined {\n try {\n const raw = JSON.parse(fs.readFileSync(file, \"utf-8\"));\n if (raw && typeof raw === \"object\" && typeof raw.projectId === \"string\") return raw.projectId;\n } catch {\n // Unreadable or corrupt: see above.\n }\n return undefined;\n}\n","import os from \"os\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\n\n/**\n * Every field that may ever leave the machine, and nothing else.\n *\n * ## The rule this file exists to enforce\n *\n * **No value here may be free text.** Every property is either a number, a\n * boolean, or a string drawn from a set enumerated in this file. That is not\n * fussiness — free text is the mechanism by which telemetry leaks. An error\n * message carries `/Users/francesco/rebase/...`, which is a real person's name.\n * A collection name carries a customer's product vocabulary. A database URL\n * carries a password. None of those are things anyone intends to send; they\n * arrive by being interpolated into a string that a well-meaning field was\n * happy to accept.\n *\n * So the payload is closed by construction. Adding a field means adding it\n * here, where the review question — \"can this ever contain something the user\n * typed?\" — is unavoidable.\n *\n * ## What is deliberately absent\n *\n * Project names, directory paths, collection or table names, hostnames,\n * database URLs, error messages, stack traces, email addresses, exact row or\n * user counts. Anything that would let a payload be traced to an organisation\n * rather than to an anonymous id.\n */\n\n/**\n * Bumped whenever a field is added, removed or changes meaning.\n *\n * Sent with every event so the receiving end can reject or migrate old shapes,\n * and so `rebase telemetry show` can state which contract the user agreed to.\n */\nexport const TELEMETRY_SCHEMA_VERSION = 1;\n\n/** The events the CLI reports. Closed set — a name not listed cannot be sent. */\nexport type TelemetryEventName =\n | \"cli.init\"\n | \"cli.dev\"\n | \"cli.deploy\"\n // Named for the command group, not for one of its subcommands. These were\n // `cli.schema_generate` and `cli.db_push` and were sent for *every*\n // subcommand of their group — so `rebase db restore` was recorded as a\n // push, and anything counting pushes counted every database command. The\n // subcommand travels as a property, where it can be read.\n | \"cli.schema\"\n | \"cli.db\"\n | \"cli.error\";\n\n/** A single non-free-text value. */\nexport type TelemetryValue = string | number | boolean;\n\nexport type TelemetryEvent = {\n schema: number;\n event: TelemetryEventName;\n /** Random per machine — see identity.ts on why it is not derived. */\n machineId: string;\n /** Random per checkout. Absent when the command ran outside a project. */\n projectId?: string;\n /** The CLI's own version, so old releases can be told apart. */\n cliVersion: string;\n /** Coarse platform facts, for the support matrix. */\n nodeMajor: number;\n platform: NodeJS.Platform;\n arch: string;\n /** UTC, second precision. Not a device clock reading anyone can fingerprint. */\n at: string;\n properties: Record<string, TelemetryValue>;\n};\n\n/**\n * Buckets rather than exact counts.\n *\n * An exact figure is a surprisingly good fingerprint — \"this install has 37\n * collections\" narrows the field a great deal when combined with a version and\n * a driver. A bucket answers \"roughly how big\" without doing that.\n */\nexport function bucket(value: number): string {\n if (!Number.isFinite(value) || value < 0) return \"unknown\";\n if (value === 0) return \"0\";\n if (value <= 5) return \"1-5\";\n if (value <= 20) return \"6-20\";\n if (value <= 50) return \"21-50\";\n if (value <= 200) return \"51-200\";\n return \"200+\";\n}\n\n/** Duration in coarse bands — enough to see \"slow\", not enough to fingerprint. */\nexport function durationBucket(ms: number): string {\n if (!Number.isFinite(ms) || ms < 0) return \"unknown\";\n if (ms < 5_000) return \"<5s\";\n if (ms < 30_000) return \"5-30s\";\n if (ms < 120_000) return \"30-120s\";\n return \"120s+\";\n}\n\n/**\n * An error reduced to something safe to transmit.\n *\n * The message and the stack are discarded, always. What survives is the\n * constructor name and, for the errors that carry one, a `code` — both of which\n * come from the program rather than from anything the user typed or named.\n * `EACCES` is useful and safe; \"cannot write /Users/francesco/clients/acme\" is\n * neither.\n */\nexport function errorClass(error: unknown): string {\n if (error && typeof error === \"object\") {\n const code = (error as { code?: unknown }).code;\n if (typeof code === \"string\" && /^[A-Z][A-Z0-9_]{1,31}$/.test(code)) return code;\n const name = (error as { name?: unknown }).name;\n if (typeof name === \"string\" && /^[A-Za-z][A-Za-z0-9]{0,31}$/.test(name)) return name;\n }\n return \"Unknown\";\n}\n\n/**\n * Drop anything that is not a permitted value type, and clamp strings.\n *\n * The last line of defence rather than the first. Every call site is supposed\n * to pass enumerated values; this is what stops a future one that forgets from\n * turning into an incident. Strings are capped at 64 characters because no\n * legitimate enumerated value is longer, and a path or a message always is.\n */\n/**\n * Key names that shadow an `Object.prototype` member.\n *\n * `__proto__` is already excluded by the pattern (it starts with an\n * underscore), and assigning any of these to an object literal shadows rather\n * than pollutes — so nothing is exploitable here. They are refused because a\n * stored property called `constructor` is a trap for every consumer downstream\n * that reaches for `properties.constructor` and gets a string.\n */\nconst RESERVED_KEYS = new Set([\"constructor\", \"prototype\", \"hasownproperty\", \"tostring\", \"valueof\"]);\n\nexport function sanitize(properties: Record<string, unknown>): Record<string, TelemetryValue> {\n const out: Record<string, TelemetryValue> = {};\n for (const [key, value] of Object.entries(properties)) {\n if (!/^[a-z][a-z0-9_]{0,31}$/.test(key) || RESERVED_KEYS.has(key.toLowerCase())) continue;\n if (typeof value === \"boolean\" || (typeof value === \"number\" && Number.isFinite(value))) {\n out[key] = value;\n } else if (typeof value === \"string\" && value.length > 0 && value.length <= 64) {\n // Anything with a separator in it is a path, a URL or a sentence —\n // never one of our enumerated tokens.\n if (!/[/\\\\@:\\s]/.test(value)) out[key] = value;\n }\n }\n return out;\n}\n\n/**\n * The CLI's own version, read by walking up to this package's manifest.\n *\n * The obvious `require(\"../../package.json\")` was wrong everywhere, not only on\n * one install path: `vite build` bundles this module into `dist/index.es.js`, so\n * the specifier resolves relative to `<pkg>/dist/` and lands on\n * `<parent-of-pkg>/package.json` — a file that does not exist under npm, pnpm or\n * the monorepo. Every event ever sent carried `cliVersion: \"unknown\"`, which is\n * the one field that makes the rest of a payload interpretable.\n *\n * So walk up and check the manifest's `name` rather than counting directory\n * levels: the count differs between `src/telemetry/` and the bundled `dist/`,\n * and a wrong count fails silently by finding *some* package.json — the nearest\n * dependency's, under a hoisted layout. Matching the name cannot do that.\n */\nfunction cliVersion(): string {\n try {\n let dir = path.dirname(fileURLToPath(import.meta.url));\n const root = path.parse(dir).root;\n while (dir && dir !== root) {\n const manifest = path.join(dir, \"package.json\");\n if (fs.existsSync(manifest)) {\n const pkg = JSON.parse(fs.readFileSync(manifest, \"utf-8\"));\n if (pkg?.name === \"@rebasepro/cli\" && typeof pkg.version === \"string\" && pkg.version) {\n return pkg.version;\n }\n }\n dir = path.dirname(dir);\n }\n } catch {\n // Fall through — a version we cannot read is reported as such.\n }\n return \"unknown\";\n}\n\nexport function buildEvent(\n event: TelemetryEventName,\n properties: Record<string, unknown>,\n identity: { machineId: string; projectId?: string }\n): TelemetryEvent {\n return {\n schema: TELEMETRY_SCHEMA_VERSION,\n event,\n machineId: identity.machineId,\n projectId: identity.projectId,\n cliVersion: cliVersion(),\n nodeMajor: Number(process.versions.node.split(\".\")[0]) || 0,\n platform: os.platform(),\n arch: os.arch(),\n at: new Date().toISOString().replace(/\\.\\d{3}Z$/, \"Z\"),\n properties: sanitize(properties)\n };\n}\n","import fs from \"fs\";\nimport path from \"path\";\n\nimport { findProjectRoot, MANIFEST_FILENAME } from \"../utils/project\";\n\n/**\n * A repository's own policy on usage sharing.\n *\n * ## Why this is deliberately one-directional\n *\n * `rebase.json` is committed, so whatever it says applies to everyone who\n * clones the repository — including people who have never seen our prompt. That\n * makes it the right place for exactly one of the two answers:\n *\n * - **`false` is honoured**, and beats an individual's opt-in. An organisation\n * restricting its own repository is setting policy for work done on its\n * behalf, which is theirs to set. It is the same shape as a committed\n * `.npmrc`.\n * - **`true` is ignored**, and says so. It would be one developer answering a\n * privacy question for every colleague who later clones the repo — consent\n * by proxy, which is the precise thing opt-in exists to prevent.\n *\n * The asymmetry is the whole feature. A symmetric flag would be a worse version\n * of the machine-level setting, and a quietly-obeyed `true` would be a way to\n * enrol people without asking them.\n *\n * Read straight from the file rather than through `parseManifest`, for two\n * reasons: the parser builds a typed object and drops keys it does not model,\n * and a manifest too malformed to parse must still be able to switch telemetry\n * off. A repository that says no should be obeyed even when it is broken.\n */\nexport type ProjectTelemetryPolicy =\n /** `\"telemetry\": false` — suppress, regardless of the machine setting. */\n | \"opt_out\"\n /** `\"telemetry\": true` — refused; the machine setting still decides. */\n | \"ignored_opt_in\"\n /** No manifest, no key, or an unreadable one. */\n | \"unset\";\n\nexport function readProjectPolicy(startDir: string = process.cwd()): ProjectTelemetryPolicy {\n try {\n const root = findProjectRoot(startDir);\n if (!root) return \"unset\";\n\n const file = path.join(root, MANIFEST_FILENAME);\n if (!fs.existsSync(file)) return \"unset\";\n\n // A regex rather than JSON.parse: a manifest with a trailing comma or a\n // half-finished edit still parses badly but reads clearly, and \"your\n // JSON is malformed\" is not a reason to start sending data the file\n // plainly asks us not to send.\n const raw = fs.readFileSync(file, \"utf-8\");\n const match = /\"telemetry\"\\s*:\\s*(true|false)/.exec(raw);\n if (!match) return \"unset\";\n return match[1] === \"false\" ? \"opt_out\" : \"ignored_opt_in\";\n } catch {\n return \"unset\";\n }\n}\n","import { ensureMachineId, ensureProjectId, readConfig, writeConfig } from \"./identity\";\nimport { buildEvent, TelemetryEvent, TelemetryEventName } from \"./payload\";\nimport { readProjectPolicy } from \"./project\";\nimport { parseEnvBoolean } from \"@rebasepro/types\";\n\nexport { TELEMETRY_SCHEMA_VERSION, bucket, durationBucket, errorClass, buildEvent, sanitize } from \"./payload\";\nexport type { TelemetryEvent, TelemetryEventName, TelemetryValue } from \"./payload\";\nexport { configPath, readConfig, writeConfig } from \"./identity\";\nexport type { TelemetryConfig } from \"./identity\";\nexport { readProjectPolicy } from \"./project\";\nexport type { ProjectTelemetryPolicy } from \"./project\";\n\n/**\n * Where events go. Overridable so a fork can point at its own collector, and so\n * the tests never touch the network.\n */\nexport const DEFAULT_TELEMETRY_ENDPOINT = \"https://app.rebase.pro/api/functions/telemetry\";\n\nexport function endpoint(): string {\n return process.env.REBASE_TELEMETRY_ENDPOINT?.trim() || DEFAULT_TELEMETRY_ENDPOINT;\n}\n\n/**\n * Set to anything but a spelled no.\n *\n * The conventions behind these variables make presence the signal —\n * `CI=woodpecker` is a CI run, `DO_NOT_TRACK=please` is an answer — so a value\n * the parser does not recognise still counts, and the refusal holds. Only the\n * platform's spellings of no turn one off. It was `!== \"0\"` for two of them and\n * `!== \"false\"` for `CI`, so `CI=0` read as a runner.\n */\nfunction setAndNotNo(value: string | undefined): boolean {\n return value !== undefined && value.trim() !== \"\" && parseEnvBoolean(value) !== false;\n}\n\n/** Why nothing would be sent right now, or `null` when it would. */\nexport type SuppressionReason =\n | \"not_asked\"\n | \"declined\"\n | \"do_not_track\"\n | \"rebase_telemetry_disabled\"\n | \"ci\"\n | \"project_opt_out\";\n\n/**\n * The one function that decides whether anything leaves the machine.\n *\n * Every path is a refusal except the last, which is the point: consent is\n * opt-in, so the default answer at every branch — never asked, unreadable\n * config, a set env var, a CI runner — is no.\n *\n * `DO_NOT_TRACK` is honoured because it is the cross-tool convention\n * (consoledonottrack.com); a user who has set it globally has already answered\n * this question and should not be asked again by us.\n *\n * `CI` is refused for a different reason: a build runner is not a person, and\n * counting one is both useless and misleading. A single pipeline re-running on\n * every push would otherwise outweigh every real developer in the data.\n *\n * A project's own `\"telemetry\": false` is checked *before* the machine setting,\n * because it has to beat an individual opt-in to be worth anything — see\n * project.ts on why the reverse is refused.\n */\nexport function suppressionReason(\n env: NodeJS.ProcessEnv = process.env,\n cwd: string = process.cwd()\n): SuppressionReason | null {\n if (setAndNotNo(env.DO_NOT_TRACK)) return \"do_not_track\";\n if (setAndNotNo(env.REBASE_TELEMETRY_DISABLED)) return \"rebase_telemetry_disabled\";\n if (setAndNotNo(env.CI)) return \"ci\";\n if (readProjectPolicy(cwd) === \"opt_out\") return \"project_opt_out\";\n\n const config = readConfig();\n if (config.enabled === undefined) return \"not_asked\";\n if (!config.enabled) return \"declined\";\n return null;\n}\n\nexport function isEnabled(env: NodeJS.ProcessEnv = process.env, cwd: string = process.cwd()): boolean {\n return suppressionReason(env, cwd) === null;\n}\n\n/**\n * Record the user's answer. `false` is final — nothing prompts again.\n *\n * Returns whether the choice could actually be persisted. A read-only or full\n * home directory makes `writeConfig` throw, and the direction of that failure\n * matters enormously: someone turning sharing **off** who sees a stack trace,\n * or worse sees nothing, is left sharing. The caller is expected to say so and\n * point at `REBASE_TELEMETRY_DISABLED`, which needs no disk.\n */\nexport function setConsent(enabled: boolean): boolean {\n const config = readConfig();\n try {\n writeConfig({\n ...config,\n enabled,\n decidedAt: new Date().toISOString(),\n // An id is minted only on acceptance. Generating one at decline\n // time would create the very record the user just refused.\n machineId: enabled ? (config.machineId ?? undefined) : undefined\n });\n if (enabled) ensureMachineId();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Build the event that *would* be sent, without sending it.\n *\n * This is what `rebase telemetry show` prints, and it is deliberately the same\n * function the sender uses — a preview assembled by separate code is a promise\n * that drifts. Returns `null` when nothing would be sent, so the command can\n * say why instead of showing a payload that is never going anywhere.\n */\nexport function previewEvent(\n event: TelemetryEventName,\n properties: Record<string, unknown> = {},\n projectRoot?: string\n): TelemetryEvent | null {\n const config = readConfig();\n if (!config.machineId) return null;\n return buildEvent(event, properties, {\n machineId: config.machineId,\n projectId: projectRoot ? ensureProjectId(projectRoot) : undefined\n });\n}\n\n/**\n * Send one event, or quietly do nothing.\n *\n * Three properties this must hold, in order of importance:\n *\n * 1. **It never throws.** Telemetry failing is not a reason for `rebase dev`\n * to fail. Every error is swallowed.\n * 2. **It never blocks meaningfully.** A two-second ceiling, after which the\n * command carries on regardless — a collector having a bad day must not\n * become the CLI hanging.\n * 3. **It never sends without consent.** Enforced here rather than at the call\n * sites, so a new call site cannot get it wrong.\n */\nexport async function recordEvent(\n event: TelemetryEventName,\n properties: Record<string, unknown> = {},\n options: { projectRoot?: string; timeoutMs?: number } = {}\n): Promise<void> {\n try {\n // The project's own policy is read relative to the project being acted\n // on, not the shell's cwd — `rebase dev` run from a subdirectory must\n // still see its own repository's opt-out.\n if (!isEnabled(process.env, options.projectRoot ?? process.cwd())) return;\n\n const machineId = ensureMachineId();\n const projectId = options.projectRoot ? ensureProjectId(options.projectRoot) : undefined;\n const payload = buildEvent(event, properties, { machineId,\nprojectId });\n\n const abort = new AbortController();\n const timer = setTimeout(() => abort.abort(), options.timeoutMs ?? 2000);\n try {\n await fetch(endpoint(), {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(payload),\n signal: abort.signal\n });\n } finally {\n clearTimeout(timer);\n }\n } catch {\n // Deliberately silent. A warning here would be worse than useless: it\n // draws attention to a subsystem the user opted into and cannot act on,\n // in the middle of output they were actually reading.\n }\n}\n"],"mappings":";;;;;;;AAoDA,SAAgB,aAAqB;CACjC,OAAO,KAAK,KAAK,GAAG,QAAQ,GAAG,WAAW,gBAAgB;AAC9D;AAEA,SAAgB,aAA8B;CAC1C,IAAI;EACA,MAAM,MAAM,KAAK,MAAM,GAAG,aAAa,WAAW,GAAG,OAAO,CAAC;EAC7D,IAAI,OAAO,OAAO,QAAQ,UACtB,OAAO;GACH,SAAS,OAAO,IAAI,YAAY,WAAW,IAAI,UAAA;GAC/C,SAAS,OAAO,IAAI,YAAY,YAAY,IAAI,UAAU,KAAA;GAC1D,WAAW,OAAO,IAAI,cAAc,WAAW,IAAI,YAAY,KAAA;GAC/D,WAAW,OAAO,IAAI,cAAc,WAAW,IAAI,YAAY,KAAA;EACnE;CAER,QAAQ,CAGR;CACA,OAAO,EAAE,SAAA,EAAkC;AAC/C;AAEA,SAAgB,YAAY,QAA+B;CACvD,MAAM,OAAO,WAAW;CACxB,GAAG,UAAU,KAAK,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAGpD,GAAG,cAAc,MAAM,KAAK,UAAU;EAAE,GAAG;EAC/C,SAAA;CA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AI;EACvE,IAAI;GACA,MAAM,MAAM,SAAS,GAAG;IACpB,QAAQ;IACR,SAAS,EAAE,gBAAgB,mBAAmB;IAC9C,MAAM,KAAK,UAAU,OAAO;IAC5B,QAAQ,MAAM;GAClB,CAAC;EACL,UAAU;GACN,aAAa,KAAK;EACtB;CACJ,QAAQ,CAIR;AACJ"}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import chalk from "chalk";
|
|
2
|
+
//#region src/utils/unknown-command.ts
|
|
3
|
+
/**
|
|
4
|
+
* What every command family says when it does not recognise a subcommand.
|
|
5
|
+
*
|
|
6
|
+
* Six families each did it differently, and the differences were not stylistic:
|
|
7
|
+
*
|
|
8
|
+
* rebase statsu "Unknown command: statsu" + the whole top-level help
|
|
9
|
+
* rebase auth foo "Unknown auth command: foo" + the whole auth help
|
|
10
|
+
* rebase apps foo "Unknown subcommand: foo" — which command's?
|
|
11
|
+
* rebase skills foo "Unknown skills subcommand: foo" + the whole help
|
|
12
|
+
* rebase telemetry x the help, silently, with exit code 1 and no error line
|
|
13
|
+
* rebase cloud debug x both a JSON error *and* the human one, in JSON mode
|
|
14
|
+
*
|
|
15
|
+
* Dumping a screen of help after an error is the wrong shape: the one line that
|
|
16
|
+
* says what happened scrolls off the top, and in a CI log it is buried in
|
|
17
|
+
* forty. None of them offered the correction, which for a typo is the entire
|
|
18
|
+
* answer — `statsu` is one transposition from `status`.
|
|
19
|
+
*
|
|
20
|
+
* So: one line, the near-miss when there is one, and where to read the rest.
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* Damerau–Levenshtein distance, capped by the caller.
|
|
24
|
+
*
|
|
25
|
+
* The transposition is the reason this is not plain Levenshtein: `statsu` for
|
|
26
|
+
* `status` and `craete` for `create` are the two most common typing errors
|
|
27
|
+
* there are, and both are distance 2 without it — the same as two unrelated
|
|
28
|
+
* edits, which is too far to suggest anything at all.
|
|
29
|
+
*/
|
|
30
|
+
function editDistance(a, b) {
|
|
31
|
+
const rows = a.length + 1;
|
|
32
|
+
const cols = b.length + 1;
|
|
33
|
+
const d = Array.from({ length: rows }, () => new Array(cols).fill(0));
|
|
34
|
+
for (let i = 0; i < rows; i++) d[i][0] = i;
|
|
35
|
+
for (let j = 0; j < cols; j++) d[0][j] = j;
|
|
36
|
+
for (let i = 1; i < rows; i++) for (let j = 1; j < cols; j++) {
|
|
37
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
38
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
|
|
39
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
40
|
+
}
|
|
41
|
+
return d[a.length][b.length];
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The one command the user probably meant, or nothing.
|
|
45
|
+
*
|
|
46
|
+
* Tight on purpose. A suggestion that is wrong is worse than none: it sends
|
|
47
|
+
* someone to read the help for a command that was never the answer, and on a
|
|
48
|
+
* family like `db` — where `push` and `pull` are one edit apart — a loose
|
|
49
|
+
* threshold would confidently propose the destructive neighbour of what they
|
|
50
|
+
* typed. So: one edit for a short word, two for a long one, and a prefix match
|
|
51
|
+
* always counts (`rebase cloud dep` for `deploy`).
|
|
52
|
+
*/
|
|
53
|
+
function suggestCommand(typed, known) {
|
|
54
|
+
const word = typed.toLowerCase();
|
|
55
|
+
if (!word) return void 0;
|
|
56
|
+
if (word.length >= 3) {
|
|
57
|
+
const prefixed = known.filter((name) => name.toLowerCase().startsWith(word));
|
|
58
|
+
if (prefixed.length === 1) return prefixed[0];
|
|
59
|
+
}
|
|
60
|
+
const budget = word.length <= 4 ? 1 : 2;
|
|
61
|
+
let best;
|
|
62
|
+
for (const candidate of known) {
|
|
63
|
+
const distance = editDistance(word, candidate.toLowerCase());
|
|
64
|
+
if (distance > budget) continue;
|
|
65
|
+
if (!best || distance < best.distance) best = {
|
|
66
|
+
name: candidate,
|
|
67
|
+
distance
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
return best?.name;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* The line itself, without printing it — so callers that must answer in JSON
|
|
74
|
+
* (the cloud family, whose `fail()` writes a machine-readable envelope) use the
|
|
75
|
+
* same words as the ones that print.
|
|
76
|
+
*
|
|
77
|
+
* `family` is empty for the top level: `rebase --help`, not `rebase --help`.
|
|
78
|
+
*/
|
|
79
|
+
function unknownCommandMessage(typed, known, family = "") {
|
|
80
|
+
const what = family ? `${family} command` : "command";
|
|
81
|
+
const suggestion = typed ? suggestCommand(typed, known) : void 0;
|
|
82
|
+
const help = family ? `rebase ${family} --help` : "rebase --help";
|
|
83
|
+
return suggestion ? `Unknown ${what} "${typed}" — did you mean \`${suggestion}\`? Run \`${help}\` for the rest.` : `Unknown ${what} "${typed ?? ""}". Run \`${help}\` for the ones there are.`;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Print the line to stderr and exit 1.
|
|
87
|
+
*
|
|
88
|
+
* stderr, not stdout: a mistyped command is a failure, and the families with a
|
|
89
|
+
* `--json` mode guarantee that stdout holds only their envelope.
|
|
90
|
+
*/
|
|
91
|
+
function unknownCommand(typed, known, family = "") {
|
|
92
|
+
console.error(chalk.red(`✗ ${unknownCommandMessage(typed, known, family)}`));
|
|
93
|
+
process.exit(1);
|
|
94
|
+
}
|
|
95
|
+
//#endregion
|
|
96
|
+
export { unknownCommandMessage as n, unknownCommand as t };
|
|
97
|
+
|
|
98
|
+
//# sourceMappingURL=unknown-command-DNwDcX3w.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"unknown-command-DNwDcX3w.js","names":[],"sources":["../src/utils/unknown-command.ts"],"sourcesContent":["/**\n * What every command family says when it does not recognise a subcommand.\n *\n * Six families each did it differently, and the differences were not stylistic:\n *\n * rebase statsu \"Unknown command: statsu\" + the whole top-level help\n * rebase auth foo \"Unknown auth command: foo\" + the whole auth help\n * rebase apps foo \"Unknown subcommand: foo\" — which command's?\n * rebase skills foo \"Unknown skills subcommand: foo\" + the whole help\n * rebase telemetry x the help, silently, with exit code 1 and no error line\n * rebase cloud debug x both a JSON error *and* the human one, in JSON mode\n *\n * Dumping a screen of help after an error is the wrong shape: the one line that\n * says what happened scrolls off the top, and in a CI log it is buried in\n * forty. None of them offered the correction, which for a typo is the entire\n * answer — `statsu` is one transposition from `status`.\n *\n * So: one line, the near-miss when there is one, and where to read the rest.\n */\nimport chalk from \"chalk\";\n\n/**\n * Damerau–Levenshtein distance, capped by the caller.\n *\n * The transposition is the reason this is not plain Levenshtein: `statsu` for\n * `status` and `craete` for `create` are the two most common typing errors\n * there are, and both are distance 2 without it — the same as two unrelated\n * edits, which is too far to suggest anything at all.\n */\nfunction editDistance(a: string, b: string): number {\n const rows = a.length + 1;\n const cols = b.length + 1;\n const d: number[][] = Array.from({ length: rows }, () => new Array<number>(cols).fill(0));\n\n for (let i = 0; i < rows; i++) d[i][0] = i;\n for (let j = 0; j < cols; j++) d[0][j] = j;\n\n for (let i = 1; i < rows; i++) {\n for (let j = 1; j < cols; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n d[i][j] = Math.min(\n d[i - 1][j] + 1,\n d[i][j - 1] + 1,\n d[i - 1][j - 1] + cost\n );\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);\n }\n }\n }\n return d[a.length][b.length];\n}\n\n/**\n * The one command the user probably meant, or nothing.\n *\n * Tight on purpose. A suggestion that is wrong is worse than none: it sends\n * someone to read the help for a command that was never the answer, and on a\n * family like `db` — where `push` and `pull` are one edit apart — a loose\n * threshold would confidently propose the destructive neighbour of what they\n * typed. So: one edit for a short word, two for a long one, and a prefix match\n * always counts (`rebase cloud dep` for `deploy`).\n */\nexport function suggestCommand(typed: string, known: readonly string[]): string | undefined {\n const word = typed.toLowerCase();\n if (!word) return undefined;\n\n // An abbreviation, but only when it names exactly one command. \"res\" is a\n // prefix of both `reset` and `restore`, and picking whichever comes first\n // in the list would be a coin toss dressed up as an answer.\n if (word.length >= 3) {\n const prefixed = known.filter(name => name.toLowerCase().startsWith(word));\n if (prefixed.length === 1) return prefixed[0];\n }\n\n const budget = word.length <= 4 ? 1 : 2;\n let best: { name: string; distance: number } | undefined;\n\n for (const candidate of known) {\n const distance = editDistance(word, candidate.toLowerCase());\n if (distance > budget) continue;\n if (!best || distance < best.distance) best = { name: candidate, distance };\n }\n\n return best?.name;\n}\n\n/**\n * The line itself, without printing it — so callers that must answer in JSON\n * (the cloud family, whose `fail()` writes a machine-readable envelope) use the\n * same words as the ones that print.\n *\n * `family` is empty for the top level: `rebase --help`, not `rebase --help`.\n */\nexport function unknownCommandMessage(\n typed: string | undefined,\n known: readonly string[],\n family = \"\"\n): string {\n const what = family ? `${family} command` : \"command\";\n const suggestion = typed ? suggestCommand(typed, known) : undefined;\n const help = family ? `rebase ${family} --help` : \"rebase --help\";\n\n return suggestion\n ? `Unknown ${what} \"${typed}\" — did you mean \\`${suggestion}\\`? Run \\`${help}\\` for the rest.`\n : `Unknown ${what} \"${typed ?? \"\"}\". Run \\`${help}\\` for the ones there are.`;\n}\n\n/**\n * Print the line to stderr and exit 1.\n *\n * stderr, not stdout: a mistyped command is a failure, and the families with a\n * `--json` mode guarantee that stdout holds only their envelope.\n */\nexport function unknownCommand(\n typed: string | undefined,\n known: readonly string[],\n family = \"\"\n): never {\n console.error(chalk.red(`✗ ${unknownCommandMessage(typed, known, family)}`));\n process.exit(1);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAS,aAAa,GAAW,GAAmB;CAChD,MAAM,OAAO,EAAE,SAAS;CACxB,MAAM,OAAO,EAAE,SAAS;CACxB,MAAM,IAAgB,MAAM,KAAK,EAAE,QAAQ,KAAK,SAAS,IAAI,MAAc,IAA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