splithub 0.1.9 → 0.2.1
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/README.md +11 -0
- package/dist/chunk-3RVNT2HA.js +54 -0
- package/dist/chunk-3RVNT2HA.js.map +1 -0
- package/dist/chunk-5C24F2ZN.js +113 -0
- package/dist/chunk-5C24F2ZN.js.map +1 -0
- package/dist/chunk-B6FITBWN.js +384 -0
- package/dist/chunk-B6FITBWN.js.map +1 -0
- package/dist/chunk-BJQJGLOB.js +160 -0
- package/dist/chunk-BJQJGLOB.js.map +1 -0
- package/dist/chunk-DDWYTOX4.js +565 -0
- package/dist/chunk-DDWYTOX4.js.map +1 -0
- package/dist/chunk-DUIJ5DTV.js +170 -0
- package/dist/chunk-DUIJ5DTV.js.map +1 -0
- package/dist/chunk-E5VH4BQX.js +326 -0
- package/dist/chunk-E5VH4BQX.js.map +1 -0
- package/dist/chunk-EYYLDI5J.js +195 -0
- package/dist/chunk-EYYLDI5J.js.map +1 -0
- package/dist/chunk-GVARYUL3.js +28 -0
- package/dist/chunk-GVARYUL3.js.map +1 -0
- package/dist/chunk-KMO5GGGC.js +185 -0
- package/dist/chunk-KMO5GGGC.js.map +1 -0
- package/dist/chunk-LT4JP3IF.js +119 -0
- package/dist/chunk-LT4JP3IF.js.map +1 -0
- package/dist/chunk-NMN5YGNP.js +72 -0
- package/dist/chunk-NMN5YGNP.js.map +1 -0
- package/dist/chunk-OHA2M7QR.js +264 -0
- package/dist/chunk-OHA2M7QR.js.map +1 -0
- package/dist/chunk-OYM64FMD.js +63 -0
- package/dist/chunk-OYM64FMD.js.map +1 -0
- package/dist/chunk-PLXDG4B5.js +134 -0
- package/dist/chunk-PLXDG4B5.js.map +1 -0
- package/dist/chunk-PNPOOAHF.js +393 -0
- package/dist/chunk-PNPOOAHF.js.map +1 -0
- package/dist/chunk-RYDA7PQF.js +97 -0
- package/dist/chunk-RYDA7PQF.js.map +1 -0
- package/dist/chunk-V3DLUVOE.js +112 -0
- package/dist/chunk-V3DLUVOE.js.map +1 -0
- package/dist/ci-ZQZ6RBUJ.js +16 -0
- package/dist/ci-ZQZ6RBUJ.js.map +1 -0
- package/dist/create-AEJVXN25.js +18 -0
- package/dist/create-AEJVXN25.js.map +1 -0
- package/dist/dev-W2JGUV2A.js +11 -0
- package/dist/dev-W2JGUV2A.js.map +1 -0
- package/dist/doctor-D3KOGOX6.js +14 -0
- package/dist/doctor-D3KOGOX6.js.map +1 -0
- package/dist/holdout-BWVTTLEY.js +44 -0
- package/dist/holdout-BWVTTLEY.js.map +1 -0
- package/dist/index.js +94 -2240
- package/dist/index.js.map +1 -1
- package/dist/init-UBUDSJBD.js +15 -0
- package/dist/init-UBUDSJBD.js.map +1 -0
- package/dist/lifecycle-ZLZUTASA.js +12 -0
- package/dist/lifecycle-ZLZUTASA.js.map +1 -0
- package/dist/login-TIIX5V4O.js +18 -0
- package/dist/login-TIIX5V4O.js.map +1 -0
- package/dist/menu-S3WDS4JY.js +163 -0
- package/dist/menu-S3WDS4JY.js.map +1 -0
- package/dist/plan-G2A55FR7.js +135 -0
- package/dist/plan-G2A55FR7.js.map +1 -0
- package/dist/push-OJX4F2BH.js +16 -0
- package/dist/push-OJX4F2BH.js.map +1 -0
- package/dist/refs-RY7H3J7L.js +44 -0
- package/dist/refs-RY7H3J7L.js.map +1 -0
- package/dist/remove-EQQCDJRU.js +54 -0
- package/dist/remove-EQQCDJRU.js.map +1 -0
- package/dist/report-6WNO576N.js +69 -0
- package/dist/report-6WNO576N.js.map +1 -0
- package/dist/results-ZDOCWN6U.js +21 -0
- package/dist/results-ZDOCWN6U.js.map +1 -0
- package/dist/review-7E7JVMMV.js +34 -0
- package/dist/review-7E7JVMMV.js.map +1 -0
- package/dist/ship-MRBHWFZR.js +450 -0
- package/dist/ship-MRBHWFZR.js.map +1 -0
- package/dist/skills-JJOKGNO5.js +13 -0
- package/dist/skills-JJOKGNO5.js.map +1 -0
- package/dist/status-SATP23WK.js +12 -0
- package/dist/status-SATP23WK.js.map +1 -0
- package/dist/update-67QDJ6GF.js +37 -0
- package/dist/update-67QDJ6GF.js.map +1 -0
- package/package.json +22 -5
package/README.md
CHANGED
|
@@ -44,4 +44,15 @@ saved key.
|
|
|
44
44
|
The public key (`pk_...`) is safe in the browser: it only allows sending
|
|
45
45
|
events. The API key (`sk_...`) reads results and pushes config; keep it out of git.
|
|
46
46
|
|
|
47
|
+
## Updates
|
|
48
|
+
|
|
49
|
+
When you run a command in a terminal, the CLI asks npm once whether a newer `splithub` is out and offers to update after the command finishes. It updates the way you installed it: your project's `splithub` and `@splithub/*` packages with your package manager, or the global install with `npm i -g`; with `npx`, run `npx splithub@latest`.
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
npx splithub update # check now and update (--yes skips the question)
|
|
53
|
+
npx splithub update --json # { current, latest, outdated, command }, installs nothing
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
The check never runs with `--json`, in CI, under the MCP server or outside a terminal. Turn it off with `SPLITHUB_NO_UPDATE_CHECK=1`. `splithub doctor` also lists your installed versions against npm.
|
|
57
|
+
|
|
47
58
|
Planned: `watch` (live verdicts).
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
loadConfig,
|
|
4
|
+
readSource,
|
|
5
|
+
setExperimentStatus,
|
|
6
|
+
writeConfigChecked
|
|
7
|
+
} from "./chunk-B6FITBWN.js";
|
|
8
|
+
import {
|
|
9
|
+
applyLiveStatus
|
|
10
|
+
} from "./chunk-BJQJGLOB.js";
|
|
11
|
+
import {
|
|
12
|
+
requireConfig
|
|
13
|
+
} from "./chunk-PLXDG4B5.js";
|
|
14
|
+
import {
|
|
15
|
+
c,
|
|
16
|
+
fail,
|
|
17
|
+
printJson
|
|
18
|
+
} from "./chunk-V3DLUVOE.js";
|
|
19
|
+
|
|
20
|
+
// src/commands/lifecycle.ts
|
|
21
|
+
import { relative } from "path";
|
|
22
|
+
var MAP = { start: "running", pause: "paused", finish: "finished" };
|
|
23
|
+
async function lifecycle(command, id, flags) {
|
|
24
|
+
const status = MAP[command];
|
|
25
|
+
if (!status) fail("USAGE", `Unknown command "${command}".`);
|
|
26
|
+
if (!id) fail("USAGE", `Which experiment? npx splithub ${command} <id>`);
|
|
27
|
+
const project = requireConfig();
|
|
28
|
+
const file = relative(project.root, project.configFile);
|
|
29
|
+
const before = await loadConfig(project.configFile);
|
|
30
|
+
const current = before.experiments.find((e) => e.key === id);
|
|
31
|
+
if (!current) fail("EXPERIMENT_NOT_FOUND", `There's no experiment "${id}" in ${file}.`, "See the ids with npx splithub status.");
|
|
32
|
+
if (current.status !== status) {
|
|
33
|
+
const original = readSource(project.configFile);
|
|
34
|
+
const updated = setExperimentStatus(original, id, status);
|
|
35
|
+
await writeConfigChecked(project.configFile, original, updated, (config) => {
|
|
36
|
+
const e = config.experiments.find((x) => x.key === id);
|
|
37
|
+
return !e ? `"${id}" disappeared` : e.status !== status ? `"${id}" is still ${e.status}` : null;
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
const live = before.storage.mode === "cloud" ? await applyLiveStatus(flags, id, status) : "skipped";
|
|
41
|
+
const next = status === "finished" ? `Read the verdict (npx splithub results ${id}), decide which variant to keep, then run npx splithub ship ${id} --keep <variant> to remove the test from the code and the config.` : null;
|
|
42
|
+
if (flags.json) printJson({ experiment: id, status, previous: current.status, configFile: file, live, ...next ? { next } : {} });
|
|
43
|
+
else {
|
|
44
|
+
console.log(`${c.green("\u2714")} ${c.bold(id)} \u2192 ${status} ${c.dim(`(${file})`)}`);
|
|
45
|
+
if (live === "applied") console.log(`${c.green("\u2714")} live in the cloud within 60s, no deploy needed (the config change ships with your next deploy)`);
|
|
46
|
+
else if (live !== "skipped") console.log(c.yellow(`! ${live}`));
|
|
47
|
+
if (next) console.log(c.dim(`Next: ${next}`));
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export {
|
|
52
|
+
lifecycle
|
|
53
|
+
};
|
|
54
|
+
//# sourceMappingURL=chunk-3RVNT2HA.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/lifecycle.ts"],"sourcesContent":["import type { ExperimentStatus } from '@splithub/core';\nimport { relative } from 'node:path';\nimport { applyLiveStatus } from '../api';\nimport { loadConfig, readSource, setExperimentStatus, writeConfigChecked } from '../config-file';\nimport { fail, printJson } from '../errors';\nimport { requireConfig } from '../project';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\nconst MAP: Record<string, ExperimentStatus> = { start: 'running', pause: 'paused', finish: 'finished' };\n\nexport async function lifecycle(command: string, id: string | undefined, flags: Flags): Promise<void> {\n const status = MAP[command];\n if (!status) fail('USAGE', `Unknown command \"${command}\".`);\n if (!id) fail('USAGE', `Which experiment? npx splithub ${command} <id>`);\n const project = requireConfig();\n const file = relative(project.root, project.configFile);\n\n // Validate before touching the file: the config must load and know the experiment.\n const before = await loadConfig(project.configFile);\n const current = before.experiments.find((e) => e.key === id);\n if (!current) fail('EXPERIMENT_NOT_FOUND', `There's no experiment \"${id}\" in ${file}.`, 'See the ids with npx splithub status.');\n\n if (current.status !== status) {\n const original = readSource(project.configFile);\n const updated = setExperimentStatus(original, id, status);\n await writeConfigChecked(project.configFile, original, updated, (config) => {\n const e = config.experiments.find((x) => x.key === id);\n return !e ? `\"${id}\" disappeared` : e.status !== status ? `\"${id}\" is still ${e.status}` : null;\n });\n }\n\n // Cloud mode: also apply it live through a remote override, so no deploy is needed.\n const live = before.storage.mode === 'cloud' ? await applyLiveStatus(flags, id, status) : 'skipped';\n\n // A finished test keeps its numbers, but every variant is still in the code until someone decides.\n const next = status === 'finished' ? `Read the verdict (npx splithub results ${id}), decide which variant to keep, then run npx splithub ship ${id} --keep <variant> to remove the test from the code and the config.` : null;\n if (flags.json) printJson({ experiment: id, status, previous: current.status, configFile: file, live, ...(next ? { next } : {}) });\n else {\n console.log(`${c.green('✔')} ${c.bold(id)} → ${status} ${c.dim(`(${file})`)}`);\n if (live === 'applied') console.log(`${c.green('✔')} live in the cloud within 60s, no deploy needed (the config change ships with your next deploy)`);\n else if (live !== 'skipped') console.log(c.yellow(`! ${live}`));\n if (next) console.log(c.dim(`Next: ${next}`));\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AACA,SAAS,gBAAgB;AAQzB,IAAM,MAAwC,EAAE,OAAO,WAAW,OAAO,UAAU,QAAQ,WAAW;AAEtG,eAAsB,UAAU,SAAiB,IAAwB,OAA6B;AACpG,QAAM,SAAS,IAAI,OAAO;AAC1B,MAAI,CAAC,OAAQ,MAAK,SAAS,oBAAoB,OAAO,IAAI;AAC1D,MAAI,CAAC,GAAI,MAAK,SAAS,kCAAkC,OAAO,OAAO;AACvE,QAAM,UAAU,cAAc;AAC9B,QAAM,OAAO,SAAS,QAAQ,MAAM,QAAQ,UAAU;AAGtD,QAAM,SAAS,MAAM,WAAW,QAAQ,UAAU;AAClD,QAAM,UAAU,OAAO,YAAY,KAAK,CAAC,MAAM,EAAE,QAAQ,EAAE;AAC3D,MAAI,CAAC,QAAS,MAAK,wBAAwB,0BAA0B,EAAE,QAAQ,IAAI,KAAK,uCAAuC;AAE/H,MAAI,QAAQ,WAAW,QAAQ;AAC7B,UAAM,WAAW,WAAW,QAAQ,UAAU;AAC9C,UAAM,UAAU,oBAAoB,UAAU,IAAI,MAAM;AACxD,UAAM,mBAAmB,QAAQ,YAAY,UAAU,SAAS,CAAC,WAAW;AAC1E,YAAM,IAAI,OAAO,YAAY,KAAK,CAAC,MAAM,EAAE,QAAQ,EAAE;AACrD,aAAO,CAAC,IAAI,IAAI,EAAE,kBAAkB,EAAE,WAAW,SAAS,IAAI,EAAE,cAAc,EAAE,MAAM,KAAK;AAAA,IAC7F,CAAC;AAAA,EACH;AAGA,QAAM,OAAO,OAAO,QAAQ,SAAS,UAAU,MAAM,gBAAgB,OAAO,IAAI,MAAM,IAAI;AAG1F,QAAM,OAAO,WAAW,aAAa,0CAA0C,EAAE,+DAA+D,EAAE,uEAAuE;AACzN,MAAI,MAAM,KAAM,WAAU,EAAE,YAAY,IAAI,QAAQ,UAAU,QAAQ,QAAQ,YAAY,MAAM,MAAM,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC,EAAG,CAAC;AAAA,OAC5H;AACH,YAAQ,IAAI,GAAG,EAAE,MAAM,QAAG,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,WAAM,MAAM,IAAI,EAAE,IAAI,IAAI,IAAI,GAAG,CAAC,EAAE;AAC7E,QAAI,SAAS,UAAW,SAAQ,IAAI,GAAG,EAAE,MAAM,QAAG,CAAC,iGAAiG;AAAA,aAC3I,SAAS,UAAW,SAAQ,IAAI,EAAE,OAAO,KAAK,IAAI,EAAE,CAAC;AAC9D,QAAI,KAAM,SAAQ,IAAI,EAAE,IAAI,SAAS,IAAI,EAAE,CAAC;AAAA,EAC9C;AACF;","names":[]}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
apiError,
|
|
4
|
+
cloudTarget,
|
|
5
|
+
credentialsFile,
|
|
6
|
+
listCredentials,
|
|
7
|
+
loadCredential,
|
|
8
|
+
removeCredential,
|
|
9
|
+
requireCloudToken,
|
|
10
|
+
saveCredential
|
|
11
|
+
} from "./chunk-BJQJGLOB.js";
|
|
12
|
+
import {
|
|
13
|
+
CliError,
|
|
14
|
+
c,
|
|
15
|
+
fail
|
|
16
|
+
} from "./chunk-V3DLUVOE.js";
|
|
17
|
+
|
|
18
|
+
// src/commands/login.ts
|
|
19
|
+
import { hostname } from "os";
|
|
20
|
+
import { basename } from "path";
|
|
21
|
+
var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
22
|
+
async function deviceLogin(options) {
|
|
23
|
+
const { api } = options;
|
|
24
|
+
const root = options.root ?? process.cwd();
|
|
25
|
+
const label = `cli \xB7 ${basename(root)} @ ${hostname()}`.slice(0, 80);
|
|
26
|
+
const startRes = await fetch(`${api}/auth/device`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ label }) });
|
|
27
|
+
if (!startRes.ok) fail("API_ERROR", `${api}/auth/device responded ${startRes.status}.`);
|
|
28
|
+
const start = await startRes.json();
|
|
29
|
+
if (options.project) start.verifyUrl += `${start.verifyUrl.includes("?") ? "&" : "?"}project=${encodeURIComponent(options.project)}`;
|
|
30
|
+
if (options.onCode) options.onCode(start);
|
|
31
|
+
else if (options.json) console.log(JSON.stringify({ step: "approve", userCode: start.userCode, verifyUrl: start.verifyUrl, expiresIn: start.expiresIn }));
|
|
32
|
+
else {
|
|
33
|
+
console.log(`
|
|
34
|
+
${c.bold("Open this link to connect:")} ${c.cyan(start.verifyUrl)}`);
|
|
35
|
+
console.log(`${c.dim("Code")} ${c.green(start.userCode)} ${c.dim(`(expires in ${Math.round(start.expiresIn / 60)} min)`)}`);
|
|
36
|
+
console.log(c.dim("Sign in, pick or create the project, approve. Waiting\u2026"));
|
|
37
|
+
}
|
|
38
|
+
const deadline = Date.now() + start.expiresIn * 1e3;
|
|
39
|
+
while (Date.now() < deadline) {
|
|
40
|
+
await sleep(Math.max(2, start.interval) * 1e3);
|
|
41
|
+
const res = await fetch(`${api}/auth/device/${start.deviceCode}`);
|
|
42
|
+
if (!res.ok) fail("API_ERROR", `${api}/auth/device responded ${res.status}.`);
|
|
43
|
+
const poll = await res.json();
|
|
44
|
+
if (poll.status === "pending") continue;
|
|
45
|
+
if (poll.status === "denied") fail("NOT_LOGGED_IN", "The sign-in was denied in the dashboard.", "Run npx splithub login again.");
|
|
46
|
+
if (poll.status === "expired") fail("NOT_LOGGED_IN", "The sign-in code expired.", "Run npx splithub login again.");
|
|
47
|
+
if (poll.status === "consumed" || !poll.apiKey) fail("NOT_LOGGED_IN", "The key for this code was already collected.", "Run npx splithub login again.");
|
|
48
|
+
const cred = { apiKey: poll.apiKey, projectId: poll.projectId ?? null, projectName: poll.projectName ?? null, publicKey: poll.publicKey ?? null, savedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
49
|
+
saveCredential(api, root, cred);
|
|
50
|
+
return cred;
|
|
51
|
+
}
|
|
52
|
+
throw new CliError("NOT_LOGGED_IN", "The sign-in code expired.", "Run npx splithub login again.");
|
|
53
|
+
}
|
|
54
|
+
async function login(flags) {
|
|
55
|
+
const api = cloudTarget({ api: flags.api }).url;
|
|
56
|
+
const root = process.cwd();
|
|
57
|
+
const existing = loadCredential(api, root);
|
|
58
|
+
if (existing && !flags.yes) {
|
|
59
|
+
const msg = `already logged in for ${c.cyan(existing.projectName ?? existing.projectId ?? "a project")} (${credentialsFile()}). Use --yes to replace.`;
|
|
60
|
+
if (flags.json) console.log(JSON.stringify({ ok: true, alreadyLoggedIn: true, projectId: existing.projectId, projectName: existing.projectName, publicKey: existing.publicKey ?? null }));
|
|
61
|
+
else console.log(msg);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
const cred = await deviceLogin({ api, root, json: Boolean(flags.json), ...typeof flags.project === "string" ? { project: flags.project } : {} });
|
|
65
|
+
if (flags.json) console.log(JSON.stringify({ ok: true, projectId: cred.projectId, projectName: cred.projectName, publicKey: cred.publicKey, credentials: credentialsFile() }));
|
|
66
|
+
else {
|
|
67
|
+
console.log(`${c.green("\u2714")} logged in to ${c.cyan(cred.projectName ?? cred.projectId ?? "project")}`);
|
|
68
|
+
console.log(c.dim(`key saved for ${root} in ${credentialsFile()}`));
|
|
69
|
+
console.log(c.dim("next: npx splithub push"));
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async function logout(flags) {
|
|
73
|
+
const api = cloudTarget({ api: flags.api }).url;
|
|
74
|
+
const removed = removeCredential(api, process.cwd());
|
|
75
|
+
if (flags.json) console.log(JSON.stringify({ ok: true, removed }));
|
|
76
|
+
else console.log(removed ? `${c.green("\u2714")} removed the saved key for this directory` : c.dim("nothing saved for this directory"));
|
|
77
|
+
}
|
|
78
|
+
async function whoami(flags) {
|
|
79
|
+
const target = requireCloudToken(flags);
|
|
80
|
+
const res = await fetch(`${target.url}/status`, { headers: { authorization: `Bearer ${target.token}` } });
|
|
81
|
+
const data = await res.json().catch(() => ({}));
|
|
82
|
+
if (!res.ok) throw apiError(res.status, data, `${target.url}/status responded ${res.status}`);
|
|
83
|
+
const saved = loadCredential(target.url);
|
|
84
|
+
if (flags.json) console.log(JSON.stringify({ ok: true, api: target.url, project: data.project, projectId: saved?.projectId ?? null, publicKey: saved?.publicKey ?? null }));
|
|
85
|
+
else console.log(`${c.bold("api")} ${target.url}
|
|
86
|
+
${c.bold("project")} ${c.cyan(data.project ?? "?")}
|
|
87
|
+
${c.bold("public key")} ${saved?.publicKey ?? c.dim("unknown (log in again to fetch it)")}
|
|
88
|
+
${c.bold("api key")} ${target.token.slice(0, 11)}\u2026`);
|
|
89
|
+
}
|
|
90
|
+
async function projects(flags) {
|
|
91
|
+
const api = cloudTarget({ api: flags.api }).url;
|
|
92
|
+
const here = process.cwd();
|
|
93
|
+
const rows = listCredentials(api).map((r) => ({ root: r.root, current: r.root === here, projectId: r.cred.projectId, projectName: r.cred.projectName, publicKey: r.cred.publicKey ?? null, savedAt: r.cred.savedAt }));
|
|
94
|
+
if (flags.json) {
|
|
95
|
+
console.log(JSON.stringify({ api, credentials: credentialsFile(), current: rows.find((r) => r.current) ?? null, projects: rows }));
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
if (rows.length === 0) {
|
|
99
|
+
console.log(c.dim("no directory on this machine is connected yet. Run `splithub login` in your app."));
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
for (const r of rows) console.log(`${r.current ? c.green("\u25B8") : " "} ${c.cyan(r.projectName ?? r.projectId ?? "?")} ${c.dim(`\xB7 ${r.root}`)}`);
|
|
103
|
+
console.log(c.dim("\nswitch: run `splithub login --yes --project <name>` in that directory \xB7 disconnect: `splithub logout`"));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export {
|
|
107
|
+
deviceLogin,
|
|
108
|
+
login,
|
|
109
|
+
logout,
|
|
110
|
+
whoami,
|
|
111
|
+
projects
|
|
112
|
+
};
|
|
113
|
+
//# sourceMappingURL=chunk-5C24F2ZN.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/login.ts"],"sourcesContent":["// `splithub login`: device-code sign-in. The CLI prints a short code and a\n// URL; the user opens it, picks (or creates) a project and approves; the CLI\n// receives a project API key and saves it for this directory. No browser\n// automation, no secrets typed into the terminal — works over SSH and when a\n// coding agent runs it: the agent shows the link, the human clicks it.\nimport { hostname } from 'node:os';\nimport { basename } from 'node:path';\nimport { apiError, requireCloudToken, cloudTarget } from '../api';\nimport { CliError, fail } from '../errors';\nimport { credentialsFile, listCredentials, loadCredential, removeCredential, saveCredential, type SavedCredential } from '../credentials';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\ninterface Start {\n deviceCode: string;\n userCode: string;\n verifyUrl: string;\n interval: number;\n expiresIn: number;\n}\ninterface Poll {\n status: 'pending' | 'approved' | 'denied' | 'expired' | 'consumed';\n apiKey?: string;\n projectId?: string | null;\n projectName?: string | null;\n publicKey?: string | null;\n}\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nexport interface DeviceLoginOptions {\n api: string;\n root?: string;\n json?: boolean;\n /** Project name or id to preselect on the approval page. */\n project?: string;\n /** Called with the link and code as soon as they exist (default: print them). */\n onCode?: (start: { verifyUrl: string; userCode: string; expiresIn: number }) => void;\n}\n\n/** Run the device flow and save the credential. Resolves with what was saved. */\nexport async function deviceLogin(options: DeviceLoginOptions): Promise<SavedCredential> {\n const { api } = options;\n const root = options.root ?? process.cwd();\n const label = `cli · ${basename(root)} @ ${hostname()}`.slice(0, 80);\n const startRes = await fetch(`${api}/auth/device`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ label }) });\n if (!startRes.ok) fail('API_ERROR', `${api}/auth/device responded ${startRes.status}.`);\n const start = (await startRes.json()) as Start;\n if (options.project) start.verifyUrl += `${start.verifyUrl.includes('?') ? '&' : '?'}project=${encodeURIComponent(options.project)}`;\n\n if (options.onCode) options.onCode(start);\n else if (options.json) console.log(JSON.stringify({ step: 'approve', userCode: start.userCode, verifyUrl: start.verifyUrl, expiresIn: start.expiresIn }));\n else {\n console.log(`\\n${c.bold('Open this link to connect:')} ${c.cyan(start.verifyUrl)}`);\n console.log(`${c.dim('Code')} ${c.green(start.userCode)} ${c.dim(`(expires in ${Math.round(start.expiresIn / 60)} min)`)}`);\n console.log(c.dim('Sign in, pick or create the project, approve. Waiting…'));\n }\n\n const deadline = Date.now() + start.expiresIn * 1000;\n while (Date.now() < deadline) {\n await sleep(Math.max(2, start.interval) * 1000);\n const res = await fetch(`${api}/auth/device/${start.deviceCode}`);\n if (!res.ok) fail('API_ERROR', `${api}/auth/device responded ${res.status}.`);\n const poll = (await res.json()) as Poll;\n if (poll.status === 'pending') continue;\n if (poll.status === 'denied') fail('NOT_LOGGED_IN', 'The sign-in was denied in the dashboard.', 'Run npx splithub login again.');\n if (poll.status === 'expired') fail('NOT_LOGGED_IN', 'The sign-in code expired.', 'Run npx splithub login again.');\n if (poll.status === 'consumed' || !poll.apiKey) fail('NOT_LOGGED_IN', 'The key for this code was already collected.', 'Run npx splithub login again.');\n const cred: SavedCredential = { apiKey: poll.apiKey, projectId: poll.projectId ?? null, projectName: poll.projectName ?? null, publicKey: poll.publicKey ?? null, savedAt: new Date().toISOString() };\n saveCredential(api, root, cred);\n return cred;\n }\n throw new CliError('NOT_LOGGED_IN', 'The sign-in code expired.', 'Run npx splithub login again.');\n}\n\nexport async function login(flags: Flags): Promise<void> {\n const api = cloudTarget({ api: flags.api }).url;\n const root = process.cwd();\n const existing = loadCredential(api, root);\n if (existing && !flags.yes) {\n const msg = `already logged in for ${c.cyan(existing.projectName ?? existing.projectId ?? 'a project')} (${credentialsFile()}). Use --yes to replace.`;\n if (flags.json) console.log(JSON.stringify({ ok: true, alreadyLoggedIn: true, projectId: existing.projectId, projectName: existing.projectName, publicKey: existing.publicKey ?? null }));\n else console.log(msg);\n return;\n }\n const cred = await deviceLogin({ api, root, json: Boolean(flags.json), ...(typeof flags.project === 'string' ? { project: flags.project } : {}) });\n if (flags.json) console.log(JSON.stringify({ ok: true, projectId: cred.projectId, projectName: cred.projectName, publicKey: cred.publicKey, credentials: credentialsFile() }));\n else {\n console.log(`${c.green('✔')} logged in to ${c.cyan(cred.projectName ?? cred.projectId ?? 'project')}`);\n console.log(c.dim(`key saved for ${root} in ${credentialsFile()}`));\n console.log(c.dim('next: npx splithub push'));\n }\n}\n\nexport async function logout(flags: Flags): Promise<void> {\n const api = cloudTarget({ api: flags.api }).url;\n const removed = removeCredential(api, process.cwd());\n if (flags.json) console.log(JSON.stringify({ ok: true, removed }));\n else console.log(removed ? `${c.green('✔')} removed the saved key for this directory` : c.dim('nothing saved for this directory'));\n}\n\nexport async function whoami(flags: Flags): Promise<void> {\n const target = requireCloudToken(flags);\n const res = await fetch(`${target.url}/status`, { headers: { authorization: `Bearer ${target.token}` } });\n const data = (await res.json().catch(() => ({}))) as { project?: string };\n if (!res.ok) throw apiError(res.status, data, `${target.url}/status responded ${res.status}`);\n const saved = loadCredential(target.url);\n if (flags.json) console.log(JSON.stringify({ ok: true, api: target.url, project: data.project, projectId: saved?.projectId ?? null, publicKey: saved?.publicKey ?? null }));\n else console.log(`${c.bold('api')} ${target.url}\\n${c.bold('project')} ${c.cyan(data.project ?? '?')}\\n${c.bold('public key')} ${saved?.publicKey ?? c.dim('unknown (log in again to fetch it)')}\\n${c.bold('api key')} ${target.token.slice(0, 11)}…`);\n}\n\n/** `splithub projects`: what this machine is connected to, the current directory first. */\nexport async function projects(flags: Flags): Promise<void> {\n const api = cloudTarget({ api: flags.api }).url;\n const here = process.cwd();\n const rows = listCredentials(api).map((r) => ({ root: r.root, current: r.root === here, projectId: r.cred.projectId, projectName: r.cred.projectName, publicKey: r.cred.publicKey ?? null, savedAt: r.cred.savedAt }));\n if (flags.json) {\n console.log(JSON.stringify({ api, credentials: credentialsFile(), current: rows.find((r) => r.current) ?? null, projects: rows }));\n return;\n }\n if (rows.length === 0) {\n console.log(c.dim('no directory on this machine is connected yet. Run `splithub login` in your app.'));\n return;\n }\n for (const r of rows) console.log(`${r.current ? c.green('▸') : ' '} ${c.cyan(r.projectName ?? r.projectId ?? '?')} ${c.dim(`· ${r.root}`)}`);\n console.log(c.dim('\\nswitch: run `splithub login --yes --project <name>` in that directory · disconnect: `splithub logout`'));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAKA,SAAS,gBAAgB;AACzB,SAAS,gBAAgB;AAsBzB,IAAM,QAAQ,CAAC,OAAe,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,EAAE,CAAC;AAalE,eAAsB,YAAY,SAAuD;AACvF,QAAM,EAAE,IAAI,IAAI;AAChB,QAAM,OAAO,QAAQ,QAAQ,QAAQ,IAAI;AACzC,QAAM,QAAQ,YAAS,SAAS,IAAI,CAAC,MAAM,SAAS,CAAC,GAAG,MAAM,GAAG,EAAE;AACnE,QAAM,WAAW,MAAM,MAAM,GAAG,GAAG,gBAAgB,EAAE,QAAQ,QAAQ,SAAS,EAAE,gBAAgB,mBAAmB,GAAG,MAAM,KAAK,UAAU,EAAE,MAAM,CAAC,EAAE,CAAC;AACvJ,MAAI,CAAC,SAAS,GAAI,MAAK,aAAa,GAAG,GAAG,0BAA0B,SAAS,MAAM,GAAG;AACtF,QAAM,QAAS,MAAM,SAAS,KAAK;AACnC,MAAI,QAAQ,QAAS,OAAM,aAAa,GAAG,MAAM,UAAU,SAAS,GAAG,IAAI,MAAM,GAAG,WAAW,mBAAmB,QAAQ,OAAO,CAAC;AAElI,MAAI,QAAQ,OAAQ,SAAQ,OAAO,KAAK;AAAA,WAC/B,QAAQ,KAAM,SAAQ,IAAI,KAAK,UAAU,EAAE,MAAM,WAAW,UAAU,MAAM,UAAU,WAAW,MAAM,WAAW,WAAW,MAAM,UAAU,CAAC,CAA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,aAAa,EAAE,KAAK,aAAa,WAAW,EAAE,KAAK,aAAa,MAAM,SAAS,EAAE,KAAK,QAAQ,EAAE;AACrN,MAAI,MAAM,MAAM;AACd,YAAQ,IAAI,KAAK,UAAU,EAAE,KAAK,aAAa,gBAAgB,GAAG,SAAS,KAAK,KAAK,CAAC,MAAM,EAAE,OAAO,KAAK,MAAM,UAAU,KAAK,CAAC,CAAC;AACjI;AAAA,EACF;AACA,MAAI,KAAK,WAAW,GAAG;AACrB,YAAQ,IAAI,EAAE,IAAI,kFAAkF,CAAC;AACrG;AAAA,EACF;AACA,aAAW,KAAK,KAAM,SAAQ,IAAI,GAAG,EAAE,UAAU,EAAE,MAAM,QAAG,IAAI,GAAG,IAAI,EAAE,KAAK,EAAE,eAAe,EAAE,aAAa,GAAG,CAAC,IAAI,EAAE,IAAI,QAAK,EAAE,IAAI,EAAE,CAAC,EAAE;AAC5I,UAAQ,IAAI,EAAE,IAAI,4GAAyG,CAAC;AAC9H;","names":[]}
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
CliError,
|
|
4
|
+
fail
|
|
5
|
+
} from "./chunk-V3DLUVOE.js";
|
|
6
|
+
|
|
7
|
+
// src/config-file.ts
|
|
8
|
+
import { isSplitHubConfig } from "@splithub/core";
|
|
9
|
+
import { readFileSync, writeFileSync } from "fs";
|
|
10
|
+
import { basename } from "path";
|
|
11
|
+
import { pathToFileURL } from "url";
|
|
12
|
+
async function loadConfig(file) {
|
|
13
|
+
let mod;
|
|
14
|
+
try {
|
|
15
|
+
const { createJiti } = await import("jiti");
|
|
16
|
+
const jiti = createJiti(pathToFileURL(file).href, { fsCache: false, moduleCache: false });
|
|
17
|
+
mod = await jiti.import(file, { default: true });
|
|
18
|
+
} catch (error) {
|
|
19
|
+
fail("CONFIG_PARSE", `${basename(file)} doesn't load: ${error instanceof Error ? error.message.split("\n")[0] : String(error)}`, "Fix the error in the file, then run npx splithub doctor.");
|
|
20
|
+
}
|
|
21
|
+
if (!isSplitHubConfig(mod)) {
|
|
22
|
+
fail("CONFIG_PARSE", `${basename(file)} must \`export default defineConfig({...})\` from @splithub/core.`);
|
|
23
|
+
}
|
|
24
|
+
return mod;
|
|
25
|
+
}
|
|
26
|
+
var REGEX_BEFORE = /* @__PURE__ */ new Set(["", "(", ",", "=", ":", "[", "!", "&", "|", "?", "{", "}", ";", "+", "-", "*", "%", "<", ">", "~", "^"]);
|
|
27
|
+
function maskSource(source) {
|
|
28
|
+
const out = source.split("");
|
|
29
|
+
const blank = (from, to) => {
|
|
30
|
+
for (let j = from; j < to && j < out.length; j++) if (out[j] !== "\n" && out[j] !== "\r") out[j] = " ";
|
|
31
|
+
};
|
|
32
|
+
let lastCode = "";
|
|
33
|
+
let i = 0;
|
|
34
|
+
while (i < source.length) {
|
|
35
|
+
const ch = source[i];
|
|
36
|
+
const next = source[i + 1];
|
|
37
|
+
if (ch === "/" && next === "/") {
|
|
38
|
+
const end = source.indexOf("\n", i);
|
|
39
|
+
const stop = end < 0 ? source.length : end;
|
|
40
|
+
blank(i, stop);
|
|
41
|
+
i = stop;
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (ch === "/" && next === "*") {
|
|
45
|
+
const end = source.indexOf("*/", i + 2);
|
|
46
|
+
const stop = end < 0 ? source.length : end + 2;
|
|
47
|
+
blank(i, stop);
|
|
48
|
+
i = stop;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (ch === "'" || ch === '"') {
|
|
52
|
+
let j = i + 1;
|
|
53
|
+
while (j < source.length && source[j] !== ch && source[j] !== "\n") j += source[j] === "\\" ? 2 : 1;
|
|
54
|
+
blank(i + 1, j);
|
|
55
|
+
i = j + 1;
|
|
56
|
+
lastCode = ch;
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
if (ch === "`") {
|
|
60
|
+
let j = i + 1;
|
|
61
|
+
let depth = 0;
|
|
62
|
+
while (j < source.length) {
|
|
63
|
+
const c = source[j];
|
|
64
|
+
if (c === "\\") {
|
|
65
|
+
j += 2;
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (depth === 0 && c === "`") break;
|
|
69
|
+
if (c === "$" && source[j + 1] === "{") {
|
|
70
|
+
depth++;
|
|
71
|
+
j += 2;
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
if (depth > 0 && c === "{") depth++;
|
|
75
|
+
else if (depth > 0 && c === "}") depth--;
|
|
76
|
+
j++;
|
|
77
|
+
}
|
|
78
|
+
blank(i + 1, j);
|
|
79
|
+
i = j + 1;
|
|
80
|
+
lastCode = "`";
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (ch === "/" && REGEX_BEFORE.has(lastCode)) {
|
|
84
|
+
let j = i + 1;
|
|
85
|
+
let inClass = false;
|
|
86
|
+
while (j < source.length && source[j] !== "\n") {
|
|
87
|
+
const c = source[j];
|
|
88
|
+
if (c === "\\") {
|
|
89
|
+
j += 2;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (c === "[") inClass = true;
|
|
93
|
+
else if (c === "]") inClass = false;
|
|
94
|
+
else if (c === "/" && !inClass) break;
|
|
95
|
+
j++;
|
|
96
|
+
}
|
|
97
|
+
blank(i + 1, j);
|
|
98
|
+
i = j + 1;
|
|
99
|
+
lastCode = "/";
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (!/\s/.test(ch)) lastCode = /[\w$)\]]/.test(ch) ? "x" : ch;
|
|
103
|
+
i++;
|
|
104
|
+
}
|
|
105
|
+
return out.join("");
|
|
106
|
+
}
|
|
107
|
+
function matchingClose(masked, open) {
|
|
108
|
+
let depth = 0;
|
|
109
|
+
for (let i = open; i < masked.length; i++) {
|
|
110
|
+
const ch = masked[i];
|
|
111
|
+
if (ch === "{" || ch === "(" || ch === "[") depth++;
|
|
112
|
+
else if (ch === "}" || ch === ")" || ch === "]") {
|
|
113
|
+
depth--;
|
|
114
|
+
if (depth === 0) return i;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
function objectEntries(source, masked, open, close) {
|
|
120
|
+
const entries = [];
|
|
121
|
+
let i = open + 1;
|
|
122
|
+
const ws = () => {
|
|
123
|
+
while (i < close && /[\s,]/.test(masked[i])) i++;
|
|
124
|
+
};
|
|
125
|
+
const valueTo = (from) => {
|
|
126
|
+
let j = from;
|
|
127
|
+
while (j < close) {
|
|
128
|
+
const ch = masked[j];
|
|
129
|
+
if (ch === ",") break;
|
|
130
|
+
if (ch === "{" || ch === "(" || ch === "[") {
|
|
131
|
+
const m = matchingClose(masked, j);
|
|
132
|
+
j = m === null ? close : m + 1;
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
j++;
|
|
136
|
+
}
|
|
137
|
+
return j;
|
|
138
|
+
};
|
|
139
|
+
for (; ; ) {
|
|
140
|
+
ws();
|
|
141
|
+
if (i >= close) break;
|
|
142
|
+
const start = i;
|
|
143
|
+
let key = null;
|
|
144
|
+
let kind = "expr";
|
|
145
|
+
if (masked.startsWith("...", i)) {
|
|
146
|
+
kind = "spread";
|
|
147
|
+
i += 3;
|
|
148
|
+
} else {
|
|
149
|
+
const ch = masked[i];
|
|
150
|
+
if (ch === "'" || ch === '"') {
|
|
151
|
+
const end2 = masked.indexOf(ch, i + 1);
|
|
152
|
+
key = source.slice(i + 1, end2).replace(/\\(.)/g, "$1");
|
|
153
|
+
i = end2 + 1;
|
|
154
|
+
} else if (ch === "[") {
|
|
155
|
+
kind = "computed";
|
|
156
|
+
const m = matchingClose(masked, i);
|
|
157
|
+
i = m === null ? close : m + 1;
|
|
158
|
+
} else {
|
|
159
|
+
const m = /^[\w$-]+/.exec(masked.slice(i, close));
|
|
160
|
+
if (!m) break;
|
|
161
|
+
key = m[0];
|
|
162
|
+
i += m[0].length;
|
|
163
|
+
}
|
|
164
|
+
while (i < close && /\s/.test(masked[i])) i++;
|
|
165
|
+
if (masked[i] === ":") i++;
|
|
166
|
+
}
|
|
167
|
+
while (i < close && /\s/.test(masked[i])) i++;
|
|
168
|
+
const valueStart = i;
|
|
169
|
+
const stop = valueTo(i);
|
|
170
|
+
let valueEnd = stop;
|
|
171
|
+
while (valueEnd > valueStart && /\s/.test(masked[valueEnd - 1])) valueEnd--;
|
|
172
|
+
if (kind === "expr" && masked[valueStart] === "{" && matchingClose(masked, valueStart) === valueEnd - 1) kind = "object";
|
|
173
|
+
const end = masked[stop] === "," ? stop + 1 : valueEnd;
|
|
174
|
+
entries.push({ key, kind, start, valueStart, valueEnd, end });
|
|
175
|
+
i = stop;
|
|
176
|
+
}
|
|
177
|
+
return entries;
|
|
178
|
+
}
|
|
179
|
+
function locateExperiments(source) {
|
|
180
|
+
const masked = maskSource(source);
|
|
181
|
+
let open = -1;
|
|
182
|
+
const root = /defineConfig\s*\(\s*\{|export\s+default\s+\{/.exec(masked);
|
|
183
|
+
if (root) {
|
|
184
|
+
const rootOpen = root.index + root[0].length - 1;
|
|
185
|
+
const rootClose = matchingClose(masked, rootOpen);
|
|
186
|
+
if (rootClose !== null) {
|
|
187
|
+
const exp = objectEntries(source, masked, rootOpen, rootClose).find((e) => e.key === "experiments");
|
|
188
|
+
if (exp && exp.kind !== "object") {
|
|
189
|
+
fail("CONFIG_UNSAFE", "`experiments` in the config is not written inline, so the CLI cannot edit it safely.", "Edit the experiments where they are defined, or write them inline as experiments: { ... }.");
|
|
190
|
+
}
|
|
191
|
+
if (exp) open = exp.valueStart;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (open < 0) {
|
|
195
|
+
const m = /\bexperiments\s*:\s*\{/.exec(masked);
|
|
196
|
+
if (!m) fail("CONFIG_UNSAFE", "Couldn't find `experiments: {` in the config file.", "Add experiments: {} to defineConfig({...}) and retry.");
|
|
197
|
+
open = m.index + m[0].length - 1;
|
|
198
|
+
}
|
|
199
|
+
const close = matchingClose(masked, open);
|
|
200
|
+
if (close === null) fail("CONFIG_PARSE", "The braces after `experiments: {` are not balanced.");
|
|
201
|
+
return { masked, open, close, entries: objectEntries(source, masked, open, close) };
|
|
202
|
+
}
|
|
203
|
+
function unsafeHint(key) {
|
|
204
|
+
return `Edit "${key}" where it is defined (it comes from a spread or an imported constant), then run npx splithub doctor.`;
|
|
205
|
+
}
|
|
206
|
+
function experimentEntry(source, key) {
|
|
207
|
+
const loc = locateExperiments(source);
|
|
208
|
+
const entry = loc.entries.find((e) => e.key === key);
|
|
209
|
+
if (!entry) {
|
|
210
|
+
if (loc.entries.some((e) => e.kind === "spread" || e.kind === "computed")) {
|
|
211
|
+
fail("CONFIG_UNSAFE", `"${key}" isn't written inline in the config (the experiments use a spread), so the CLI can't edit it safely.`, unsafeHint(key));
|
|
212
|
+
}
|
|
213
|
+
fail("EXPERIMENT_NOT_FOUND", `There's no experiment "${key}" in the config.`, "See the ids with npx splithub status.");
|
|
214
|
+
}
|
|
215
|
+
return { ...loc, entry };
|
|
216
|
+
}
|
|
217
|
+
function hasExperiment(source, key) {
|
|
218
|
+
try {
|
|
219
|
+
return locateExperiments(source).entries.some((e) => e.key === key);
|
|
220
|
+
} catch {
|
|
221
|
+
return false;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
function indentAt(source, index) {
|
|
225
|
+
const lineStart = source.lastIndexOf("\n", index - 1) + 1;
|
|
226
|
+
return /^[ \t]*/.exec(source.slice(lineStart))?.[0] ?? "";
|
|
227
|
+
}
|
|
228
|
+
function appendProperty(source, masked, open, close, render) {
|
|
229
|
+
const outerIndent = indentAt(source, open);
|
|
230
|
+
const indent = outerIndent + " ";
|
|
231
|
+
let last = close - 1;
|
|
232
|
+
while (last > open && /\s/.test(masked[last])) last--;
|
|
233
|
+
const needsComma = last > open && masked[last] !== ",";
|
|
234
|
+
const lineStart = source.lastIndexOf("\n", close - 1) + 1;
|
|
235
|
+
const closeOnOwnLine = source.slice(lineStart, close).trim() === "";
|
|
236
|
+
const block = `${indent}${render(indent)},
|
|
237
|
+
`;
|
|
238
|
+
const at = closeOnOwnLine && lineStart > last ? lineStart : close;
|
|
239
|
+
const text = at === close ? `
|
|
240
|
+
${block}${outerIndent}` : block;
|
|
241
|
+
const comma = needsComma ? "," : "";
|
|
242
|
+
const head = at === close ? source.slice(0, last + 1) + comma : source.slice(0, last + 1) + comma + source.slice(last + 1, at);
|
|
243
|
+
return head + text + source.slice(at);
|
|
244
|
+
}
|
|
245
|
+
function q(s) {
|
|
246
|
+
return `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n")}'`;
|
|
247
|
+
}
|
|
248
|
+
function k(s) {
|
|
249
|
+
return /^[a-z_$][\w$]*$/i.test(s) ? s : q(s);
|
|
250
|
+
}
|
|
251
|
+
function renderExperiment(e, indent = " ") {
|
|
252
|
+
const i2 = indent + " ";
|
|
253
|
+
const i3 = i2 + " ";
|
|
254
|
+
const lines = [`${k(e.key)}: {`];
|
|
255
|
+
lines.push(`${i2}kind: ${q(e.kind)},`);
|
|
256
|
+
lines.push(`${i2}status: ${q(e.status)},`);
|
|
257
|
+
if (e.match) lines.push(`${i2}match: ${q(e.match)},`);
|
|
258
|
+
if (e.kind === "mvt") {
|
|
259
|
+
lines.push(`${i2}factors: {`);
|
|
260
|
+
for (const [factor, levels] of Object.entries(e.factors ?? {})) {
|
|
261
|
+
lines.push(`${i3}${k(factor)}: { ${Object.entries(levels).map(([l, v]) => `${k(l)}: ${q(v)}`).join(", ")} },`);
|
|
262
|
+
}
|
|
263
|
+
lines.push(`${i2}},`);
|
|
264
|
+
} else if (e.kind === "component") {
|
|
265
|
+
lines.push(`${i2}variants: { ${e.variants.map((v) => `${k(v.key)}: ${v.weight}`).join(", ")} },`);
|
|
266
|
+
} else {
|
|
267
|
+
lines.push(`${i2}variants: {`);
|
|
268
|
+
for (const v of e.variants) {
|
|
269
|
+
const extra = e.kind === "value" ? `value: ${q(v.value ?? "")}` : `to: ${q(v.to ?? "/")}`;
|
|
270
|
+
lines.push(`${i3}${k(v.key)}: { weight: ${v.weight}, ${extra} },`);
|
|
271
|
+
}
|
|
272
|
+
lines.push(`${i2}},`);
|
|
273
|
+
}
|
|
274
|
+
if (e.goal) lines.push(`${i2}goal: ${q(e.goal)},`);
|
|
275
|
+
if (e.traffic !== void 0 && e.traffic !== 1) lines.push(`${i2}traffic: ${e.traffic},`);
|
|
276
|
+
if (e.maxExposures) lines.push(`${i2}maxExposures: ${e.maxExposures},`);
|
|
277
|
+
if (e.minDays !== void 0) lines.push(`${i2}minDays: ${e.minDays},`);
|
|
278
|
+
if (e.goodSample !== void 0) lines.push(`${i2}goodSample: ${e.goodSample},`);
|
|
279
|
+
if (e.schedule && (e.schedule.startAt || e.schedule.endAt)) lines.push(`${i2}schedule: { ${[e.schedule.startAt ? `startAt: ${q(e.schedule.startAt)}` : null, e.schedule.endAt ? `endAt: ${q(e.schedule.endAt)}` : null].filter(Boolean).join(", ")} },`);
|
|
280
|
+
if (e.metrics && (e.metrics.secondary?.length || e.metrics.guardrails?.length)) {
|
|
281
|
+
const parts = [];
|
|
282
|
+
if (e.metrics.secondary?.length) parts.push(`secondary: [${e.metrics.secondary.map(q).join(", ")}]`);
|
|
283
|
+
if (e.metrics.guardrails?.length) parts.push(`guardrails: [${e.metrics.guardrails.map((g) => typeof g === "string" ? q(g) : `{ goal: ${q(g.goal)}, worse: ${q(g.worse)} }`).join(", ")}]`);
|
|
284
|
+
lines.push(`${i2}metrics: { ${parts.join(", ")} },`);
|
|
285
|
+
}
|
|
286
|
+
if (e.layer) lines.push(`${i2}layer: { key: ${q(e.layer.key)}, range: [${e.layer.range[0]}, ${e.layer.range[1]}] },`);
|
|
287
|
+
if (e.description) lines.push(`${i2}description: ${q(e.description)},`);
|
|
288
|
+
if (e.flow) {
|
|
289
|
+
const json = JSON.stringify(e.flow, null, 2).split("\n");
|
|
290
|
+
lines.push(`${i2}// targeting graph from the dashboard; edit it there or by hand
|
|
291
|
+
${i2}flow: ${json.map((l, n) => n === 0 ? l : i2 + l).join("\n")},`);
|
|
292
|
+
}
|
|
293
|
+
lines.push(`${indent}}`);
|
|
294
|
+
return lines.join("\n");
|
|
295
|
+
}
|
|
296
|
+
function insertExperiment(source, e) {
|
|
297
|
+
const { masked, open, close, entries } = locateExperiments(source);
|
|
298
|
+
if (entries.some((x) => x.key === e.key)) fail("EXPERIMENT_EXISTS", `There's already an experiment "${e.key}".`, "Pick another id: an old id keeps its history.");
|
|
299
|
+
return appendProperty(source, masked, open, close, (indent) => renderExperiment(e, indent));
|
|
300
|
+
}
|
|
301
|
+
function setExperimentStatus(source, key, status) {
|
|
302
|
+
const { masked, entry } = experimentEntry(source, key);
|
|
303
|
+
if (entry.kind !== "object") fail("CONFIG_UNSAFE", `"${key}" points to a value defined elsewhere, so the CLI can't edit it safely.`, unsafeHint(key));
|
|
304
|
+
const inner = objectEntries(source, masked, entry.valueStart, entry.valueEnd - 1);
|
|
305
|
+
const field = inner.filter((x) => x.key === "status").pop();
|
|
306
|
+
if (field) {
|
|
307
|
+
const raw = masked.slice(field.valueStart, field.valueEnd);
|
|
308
|
+
if (!/^(['"])\s*\1$/.test(raw)) fail("CONFIG_UNSAFE", `The status of "${key}" isn't a plain string, so the CLI can't change it safely.`, `Set status: '${status}' by hand.`);
|
|
309
|
+
const quote = raw[0];
|
|
310
|
+
return source.slice(0, field.valueStart) + `${quote}${status}${quote}` + source.slice(field.valueEnd);
|
|
311
|
+
}
|
|
312
|
+
return appendProperty(source, masked, entry.valueStart, entry.valueEnd - 1, () => `status: ${q(status)}`);
|
|
313
|
+
}
|
|
314
|
+
function removeExperiment(source, key) {
|
|
315
|
+
return removeEntry(source, experimentEntry(source, key).entry);
|
|
316
|
+
}
|
|
317
|
+
function removeEntry(source, entry) {
|
|
318
|
+
const lineStart = source.lastIndexOf("\n", entry.start - 1) + 1;
|
|
319
|
+
const from = source.slice(lineStart, entry.start).trim() === "" ? lineStart : entry.start;
|
|
320
|
+
let to = entry.end;
|
|
321
|
+
const lineEnd = source.indexOf("\n", to);
|
|
322
|
+
const rest = source.slice(to, lineEnd < 0 ? source.length : lineEnd);
|
|
323
|
+
if (rest.trim() === "" && from === lineStart) to = lineEnd < 0 ? source.length : lineEnd + 1;
|
|
324
|
+
return source.slice(0, from) + source.slice(to);
|
|
325
|
+
}
|
|
326
|
+
function locateRoot(source) {
|
|
327
|
+
const masked = maskSource(source);
|
|
328
|
+
const root = /defineConfig\s*\(\s*\{|export\s+default\s+\{/.exec(masked);
|
|
329
|
+
if (!root) fail("CONFIG_UNSAFE", "Couldn't find defineConfig({ ... }) in the config file.", "Make the change by hand in splithub.config.ts.");
|
|
330
|
+
const open = root.index + root[0].length - 1;
|
|
331
|
+
const close = matchingClose(masked, open);
|
|
332
|
+
if (close === null) fail("CONFIG_PARSE", "The braces of defineConfig({ ... }) are not balanced.");
|
|
333
|
+
return { masked, open, close, entries: objectEntries(source, masked, open, close) };
|
|
334
|
+
}
|
|
335
|
+
function setTopLevel(source, name, valueText) {
|
|
336
|
+
const { masked, open, close, entries } = locateRoot(source);
|
|
337
|
+
const entry = entries.find((e) => e.key === name);
|
|
338
|
+
if (valueText === null) return entry ? removeEntry(source, entry) : source;
|
|
339
|
+
if (entry) return source.slice(0, entry.valueStart) + valueText + source.slice(entry.valueEnd);
|
|
340
|
+
return appendProperty(source, masked, open, close, () => `${k(name)}: ${valueText}`);
|
|
341
|
+
}
|
|
342
|
+
function ensureLayer(source, key) {
|
|
343
|
+
const { masked, open, close, entries } = locateRoot(source);
|
|
344
|
+
const layers = entries.find((e) => e.key === "layers");
|
|
345
|
+
if (!layers) return appendProperty(source, masked, open, close, () => `layers: { ${k(key)}: {} }`);
|
|
346
|
+
if (layers.kind !== "object") fail("CONFIG_UNSAFE", "`layers` in the config is not written inline.", `Add ${key}: {} to layers by hand.`);
|
|
347
|
+
if (objectEntries(source, masked, layers.valueStart, layers.valueEnd - 1).some((e) => e.key === key)) return source;
|
|
348
|
+
return appendProperty(source, masked, layers.valueStart, layers.valueEnd - 1, () => `${k(key)}: {}`);
|
|
349
|
+
}
|
|
350
|
+
function readSource(file) {
|
|
351
|
+
return readFileSync(file, "utf8");
|
|
352
|
+
}
|
|
353
|
+
function writeSource(file, source) {
|
|
354
|
+
writeFileSync(file, source, "utf8");
|
|
355
|
+
}
|
|
356
|
+
async function writeConfigChecked(file, original, updated, verify) {
|
|
357
|
+
writeSource(file, updated);
|
|
358
|
+
let problem = null;
|
|
359
|
+
let config = null;
|
|
360
|
+
try {
|
|
361
|
+
config = await loadConfig(file);
|
|
362
|
+
problem = verify(config);
|
|
363
|
+
} catch (error) {
|
|
364
|
+
problem = error instanceof CliError || error instanceof Error ? error.message : String(error);
|
|
365
|
+
}
|
|
366
|
+
if (problem || !config) {
|
|
367
|
+
writeSource(file, original);
|
|
368
|
+
fail("CONFIG_WRITE", `Couldn't update ${basename(file)}: ${problem ?? "it did not load"}. The file is back as it was.`, "Make the change by hand in the config, then run npx splithub doctor.");
|
|
369
|
+
}
|
|
370
|
+
return config;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
export {
|
|
374
|
+
loadConfig,
|
|
375
|
+
hasExperiment,
|
|
376
|
+
insertExperiment,
|
|
377
|
+
setExperimentStatus,
|
|
378
|
+
removeExperiment,
|
|
379
|
+
setTopLevel,
|
|
380
|
+
ensureLayer,
|
|
381
|
+
readSource,
|
|
382
|
+
writeConfigChecked
|
|
383
|
+
};
|
|
384
|
+
//# sourceMappingURL=chunk-B6FITBWN.js.map
|