splithub 0.1.8 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-3DUWIEHB.js +561 -0
- package/dist/chunk-3DUWIEHB.js.map +1 -0
- package/dist/chunk-3VACHXWE.js +319 -0
- package/dist/chunk-3VACHXWE.js.map +1 -0
- package/dist/chunk-3VY5CP3E.js +383 -0
- package/dist/chunk-3VY5CP3E.js.map +1 -0
- package/dist/chunk-74NI7BED.js +58 -0
- package/dist/chunk-74NI7BED.js.map +1 -0
- package/dist/chunk-A2RCSPG6.js +184 -0
- package/dist/chunk-A2RCSPG6.js.map +1 -0
- package/dist/chunk-AJO3C4BS.js +97 -0
- package/dist/chunk-AJO3C4BS.js.map +1 -0
- package/dist/chunk-C5S7RPYM.js +54 -0
- package/dist/chunk-C5S7RPYM.js.map +1 -0
- package/dist/chunk-EUF75FUC.js +160 -0
- package/dist/chunk-EUF75FUC.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-HSH4ZI2V.js +72 -0
- package/dist/chunk-HSH4ZI2V.js.map +1 -0
- package/dist/chunk-PLXDG4B5.js +134 -0
- package/dist/chunk-PLXDG4B5.js.map +1 -0
- package/dist/chunk-PWSRKABE.js +113 -0
- package/dist/chunk-PWSRKABE.js.map +1 -0
- package/dist/chunk-QOXGIB3R.js +393 -0
- package/dist/chunk-QOXGIB3R.js.map +1 -0
- package/dist/chunk-UUTLLC54.js +158 -0
- package/dist/chunk-UUTLLC54.js.map +1 -0
- package/dist/chunk-V3DLUVOE.js +112 -0
- package/dist/chunk-V3DLUVOE.js.map +1 -0
- package/dist/chunk-YSXW2HN6.js +104 -0
- package/dist/chunk-YSXW2HN6.js.map +1 -0
- package/dist/ci-ZQZ6RBUJ.js +16 -0
- package/dist/ci-ZQZ6RBUJ.js.map +1 -0
- package/dist/create-K75OY6XK.js +18 -0
- package/dist/create-K75OY6XK.js.map +1 -0
- package/dist/dev-WQWFEA6I.js +11 -0
- package/dist/dev-WQWFEA6I.js.map +1 -0
- package/dist/doctor-MFYBZUKO.js +13 -0
- package/dist/doctor-MFYBZUKO.js.map +1 -0
- package/dist/holdout-PECSNGAD.js +44 -0
- package/dist/holdout-PECSNGAD.js.map +1 -0
- package/dist/index.js +84 -2238
- package/dist/index.js.map +1 -1
- package/dist/init-QAAM2GQ7.js +15 -0
- package/dist/init-QAAM2GQ7.js.map +1 -0
- package/dist/lifecycle-56HM7ITG.js +12 -0
- package/dist/lifecycle-56HM7ITG.js.map +1 -0
- package/dist/login-TTWSQ7XS.js +18 -0
- package/dist/login-TTWSQ7XS.js.map +1 -0
- package/dist/menu-UQX3K5QR.js +162 -0
- package/dist/menu-UQX3K5QR.js.map +1 -0
- package/dist/plan-BSFSMKTU.js +135 -0
- package/dist/plan-BSFSMKTU.js.map +1 -0
- package/dist/push-YVS25VVD.js +16 -0
- package/dist/push-YVS25VVD.js.map +1 -0
- package/dist/refs-ZDNH6NRK.js +44 -0
- package/dist/refs-ZDNH6NRK.js.map +1 -0
- package/dist/remove-KFQUK367.js +54 -0
- package/dist/remove-KFQUK367.js.map +1 -0
- package/dist/report-TF2BLJMC.js +64 -0
- package/dist/report-TF2BLJMC.js.map +1 -0
- package/dist/results-TLV5KJWO.js +17 -0
- package/dist/results-TLV5KJWO.js.map +1 -0
- package/dist/review-EIZDOGDC.js +34 -0
- package/dist/review-EIZDOGDC.js.map +1 -0
- package/dist/ship-4YX2WCBP.js +450 -0
- package/dist/ship-4YX2WCBP.js.map +1 -0
- package/dist/skills-HWQT3DTJ.js +13 -0
- package/dist/skills-HWQT3DTJ.js.map +1 -0
- package/dist/status-CWI7ZCYJ.js +11 -0
- package/dist/status-CWI7ZCYJ.js.map +1 -0
- package/package.json +22 -5
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
detectProject
|
|
4
|
+
} from "./chunk-PLXDG4B5.js";
|
|
5
|
+
import {
|
|
6
|
+
c,
|
|
7
|
+
printJson
|
|
8
|
+
} from "./chunk-V3DLUVOE.js";
|
|
9
|
+
|
|
10
|
+
// src/commands/ci.ts
|
|
11
|
+
import { existsSync, mkdirSync, writeFileSync } from "fs";
|
|
12
|
+
import { dirname, join, relative } from "path";
|
|
13
|
+
var CLI = "npx -y splithub@latest";
|
|
14
|
+
function gitRoot(from) {
|
|
15
|
+
let dir = from;
|
|
16
|
+
for (; ; ) {
|
|
17
|
+
if (existsSync(join(dir, ".git"))) return dir;
|
|
18
|
+
const up = dirname(dir);
|
|
19
|
+
if (up === dir) return from;
|
|
20
|
+
dir = up;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function workflowTemplate(workingDirectory) {
|
|
24
|
+
const wd = workingDirectory === "" ? "." : workingDirectory;
|
|
25
|
+
const configGlob = wd === "." ? "splithub.config.*" : `${wd}/splithub.config.*`;
|
|
26
|
+
return `# SplitHub: checks experiments on pull requests that touch the config, and keeps
|
|
27
|
+
# a results comment up to date on weekday mornings. Needs the SPLITHUB_API_KEY
|
|
28
|
+
# secret (dashboard, Settings, API keys) for results and cloud comparisons.
|
|
29
|
+
name: SplitHub
|
|
30
|
+
|
|
31
|
+
on:
|
|
32
|
+
pull_request:
|
|
33
|
+
paths:
|
|
34
|
+
- '${configGlob}'
|
|
35
|
+
schedule:
|
|
36
|
+
- cron: '0 8 * * 1-5'
|
|
37
|
+
workflow_dispatch:
|
|
38
|
+
|
|
39
|
+
permissions:
|
|
40
|
+
contents: read
|
|
41
|
+
pull-requests: write
|
|
42
|
+
issues: write
|
|
43
|
+
|
|
44
|
+
jobs:
|
|
45
|
+
splithub:
|
|
46
|
+
runs-on: ubuntu-latest
|
|
47
|
+
defaults:
|
|
48
|
+
run:
|
|
49
|
+
shell: bash
|
|
50
|
+
working-directory: ${wd}
|
|
51
|
+
env:
|
|
52
|
+
SPLITHUB_API_KEY: \${{ secrets.SPLITHUB_API_KEY }}
|
|
53
|
+
GH_TOKEN: \${{ github.token }}
|
|
54
|
+
NO_COLOR: '1'
|
|
55
|
+
# check on a pull request (doctor + push --dry-run), report otherwise (results tables)
|
|
56
|
+
MODE: \${{ github.event_name == 'pull_request' && 'check' || 'report' }}
|
|
57
|
+
PR_NUMBER: \${{ github.event.pull_request.number }}
|
|
58
|
+
ISSUE_TITLE: SplitHub results
|
|
59
|
+
OUT: \${{ runner.temp }}/splithub
|
|
60
|
+
steps:
|
|
61
|
+
- uses: actions/checkout@v4
|
|
62
|
+
- uses: actions/setup-node@v4
|
|
63
|
+
with:
|
|
64
|
+
node-version: 20
|
|
65
|
+
|
|
66
|
+
- name: Install dependencies
|
|
67
|
+
run: |
|
|
68
|
+
# The config imports @splithub/core; the lockfile may live at the repository root.
|
|
69
|
+
dir="$PWD"
|
|
70
|
+
while [ "$dir" != "/" ] && [ ! -f "$dir/pnpm-lock.yaml" ] && [ ! -f "$dir/yarn.lock" ] && [ ! -f "$dir/package-lock.json" ] && [ ! -f "$dir/bun.lockb" ] && [ ! -f "$dir/bun.lock" ]; do dir="$(dirname "$dir")"; done
|
|
71
|
+
cd "$dir"
|
|
72
|
+
if [ -f pnpm-lock.yaml ]; then corepack enable && pnpm install --frozen-lockfile
|
|
73
|
+
elif [ -f yarn.lock ]; then corepack enable && (yarn install --frozen-lockfile || yarn install --immutable)
|
|
74
|
+
elif [ -f bun.lockb ] || [ -f bun.lock ]; then npm i -g bun && bun install --frozen-lockfile
|
|
75
|
+
elif [ -f package-lock.json ]; then npm ci
|
|
76
|
+
else npm install; fi
|
|
77
|
+
|
|
78
|
+
- name: Run SplitHub
|
|
79
|
+
id: run
|
|
80
|
+
run: |
|
|
81
|
+
mkdir -p "$OUT"
|
|
82
|
+
ok=true
|
|
83
|
+
if [ "$MODE" = "check" ]; then
|
|
84
|
+
${CLI} doctor --json > "$OUT/doctor.json" || ok=false
|
|
85
|
+
${CLI} push --dry-run --json > "$OUT/push.json" || ok=false
|
|
86
|
+
elif [ -z "$SPLITHUB_API_KEY" ]; then
|
|
87
|
+
echo '{"error":"Add the SPLITHUB_API_KEY secret (dashboard, Settings, API keys) to post results."}' > "$OUT/report.json"
|
|
88
|
+
else
|
|
89
|
+
${CLI} report --json > "$OUT/report.json" || ok=false
|
|
90
|
+
fi
|
|
91
|
+
echo "ok=$ok" >> "$GITHUB_OUTPUT"
|
|
92
|
+
|
|
93
|
+
- name: Write the comment
|
|
94
|
+
run: |
|
|
95
|
+
node - <<'JS'
|
|
96
|
+
const fs = require('fs');
|
|
97
|
+
const path = require('path');
|
|
98
|
+
const out = process.env.OUT;
|
|
99
|
+
const read = (name) => {
|
|
100
|
+
try {
|
|
101
|
+
const lines = fs.readFileSync(path.join(out, name), 'utf8').trim().split('\\n');
|
|
102
|
+
return JSON.parse(lines[lines.length - 1]);
|
|
103
|
+
} catch {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
const hint = (r) => (r.hint ? ' ' + r.hint : '');
|
|
108
|
+
const lines = [];
|
|
109
|
+
if (process.env.MODE === 'check') {
|
|
110
|
+
const doctor = read('doctor.json');
|
|
111
|
+
const push = read('push.json');
|
|
112
|
+
lines.push('### SplitHub check', '');
|
|
113
|
+
if (!doctor) lines.push('Doctor did not run.');
|
|
114
|
+
else if (doctor.error) lines.push('\u2716 ' + doctor.error + hint(doctor));
|
|
115
|
+
else {
|
|
116
|
+
lines.push(doctor.ok ? '\u2714 No problems found.' : '\u2716 ' + doctor.errors + ' problem(s) to fix.', '');
|
|
117
|
+
for (const c of doctor.checks.filter((c) => c.level !== 'ok')) lines.push('- ' + (c.level === 'error' ? '\u2716' : '!') + ' ' + c.message);
|
|
118
|
+
}
|
|
119
|
+
lines.push('');
|
|
120
|
+
if (!push) lines.push('The config check did not run.');
|
|
121
|
+
else if (push.error) lines.push('\u2716 Config: ' + push.error + hint(push));
|
|
122
|
+
else if (!push.diff) lines.push('Config loads: ' + push.experiments.length + ' experiment(s). ' + (push.cloud === 'self mode' ? 'Self-hosted, nothing to push.' : 'Add the SPLITHUB_API_KEY secret to compare it with the cloud.'));
|
|
123
|
+
else {
|
|
124
|
+
const d = push.diff;
|
|
125
|
+
if (!d.added.length && !d.removed.length && !d.changed.length) lines.push('The cloud already has this config.');
|
|
126
|
+
else {
|
|
127
|
+
lines.push('After merge, \`npx splithub push\` changes:', '');
|
|
128
|
+
for (const k of d.added) lines.push('- added \`' + k + '\`');
|
|
129
|
+
for (const k of d.removed) lines.push('- removed \`' + k + '\`');
|
|
130
|
+
for (const c of d.changed) lines.push('- \`' + c.experiment + '\`: ' + c.fields.join(', '));
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
} else {
|
|
134
|
+
const report = read('report.json');
|
|
135
|
+
lines.push(!report ? 'SplitHub report did not run.' : report.error ? '### SplitHub\\n\\n' + report.error : report.markdown);
|
|
136
|
+
lines.push('', '<sub>Updated ' + new Date().toISOString().slice(0, 16).replace('T', ' ') + ' UTC</sub>');
|
|
137
|
+
}
|
|
138
|
+
fs.writeFileSync(path.join(out, 'body.md'), '<!-- splithub:' + process.env.MODE + ' -->\\n' + lines.join('\\n') + '\\n');
|
|
139
|
+
JS
|
|
140
|
+
|
|
141
|
+
- name: Post the sticky comment
|
|
142
|
+
run: |
|
|
143
|
+
marker="<!-- splithub:$MODE -->"
|
|
144
|
+
number="$PR_NUMBER"
|
|
145
|
+
if [ -z "$number" ]; then
|
|
146
|
+
number="$(gh issue list --repo "$GITHUB_REPOSITORY" --state open --search "$ISSUE_TITLE in:title" --json number,title --jq '.[] | [.number, .title] | @tsv' | awk -F '\\t' -v t="$ISSUE_TITLE" '$2 == t { print $1; exit }')"
|
|
147
|
+
fi
|
|
148
|
+
if [ -z "$number" ]; then
|
|
149
|
+
url="$(gh issue create --repo "$GITHUB_REPOSITORY" --title "$ISSUE_TITLE" --body 'A/B test results from SplitHub, refreshed by the SplitHub workflow.')"
|
|
150
|
+
number="\${url##*/}"
|
|
151
|
+
fi
|
|
152
|
+
id="$(gh api --paginate "repos/$GITHUB_REPOSITORY/issues/$number/comments" --jq '.[] | [.id, (.body | split("\\n") | .[0])] | @tsv' | awk -F '\\t' -v m="$marker" '$2 == m { print $1; exit }')"
|
|
153
|
+
if [ -n "$id" ]; then
|
|
154
|
+
gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$id" -F body=@"$OUT/body.md" > /dev/null
|
|
155
|
+
else
|
|
156
|
+
gh api "repos/$GITHUB_REPOSITORY/issues/$number/comments" -F body=@"$OUT/body.md" > /dev/null
|
|
157
|
+
fi
|
|
158
|
+
|
|
159
|
+
- name: Fail on problems
|
|
160
|
+
if: steps.run.outputs.ok != 'true' && env.MODE == 'check'
|
|
161
|
+
run: |
|
|
162
|
+
echo "SplitHub found problems: see the comment on the pull request."
|
|
163
|
+
exit 1
|
|
164
|
+
`;
|
|
165
|
+
}
|
|
166
|
+
function writeWorkflow(root, force = false) {
|
|
167
|
+
const repo = gitRoot(root);
|
|
168
|
+
const file = join(repo, ".github", "workflows", "splithub.yml");
|
|
169
|
+
const workingDirectory = relative(repo, root).replace(/\\/g, "/") || ".";
|
|
170
|
+
const written = force || !existsSync(file);
|
|
171
|
+
if (written) {
|
|
172
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
173
|
+
writeFileSync(file, workflowTemplate(workingDirectory), "utf8");
|
|
174
|
+
}
|
|
175
|
+
return { file: relative(root, file).replace(/\\/g, "/"), written, workingDirectory, secret: "SPLITHUB_API_KEY" };
|
|
176
|
+
}
|
|
177
|
+
async function ciInit(flags) {
|
|
178
|
+
const project = detectProject();
|
|
179
|
+
const result = writeWorkflow(project.root, Boolean(flags.force));
|
|
180
|
+
const next = "Add the SPLITHUB_API_KEY secret in GitHub (Settings, Secrets and variables, Actions), then commit the workflow.";
|
|
181
|
+
if (flags.json) {
|
|
182
|
+
printJson({ ...result, next });
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
console.log(result.written ? `${c.green("\u2714")} wrote ${result.file}` : c.dim(`${result.file} is already there; --force replaces it`));
|
|
186
|
+
console.log(c.dim(next));
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export {
|
|
190
|
+
CLI,
|
|
191
|
+
workflowTemplate,
|
|
192
|
+
writeWorkflow,
|
|
193
|
+
ciInit
|
|
194
|
+
};
|
|
195
|
+
//# sourceMappingURL=chunk-EYYLDI5J.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/ci.ts"],"sourcesContent":["// `splithub ci init` (also `init --github-action`): write a GitHub workflow that\n// checks experiments on pull requests and posts results on a schedule.\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\nimport { printJson } from '../errors';\nimport { detectProject } from '../project';\nimport { c } from '../ui';\nimport type { Flags } from './init';\n\n/** The CLI as the workflow runs it: always the published package, never a private action. */\nexport const CLI = 'npx -y splithub@latest';\n\n/** The repository root: the closest folder with .git, else the project itself. */\nfunction gitRoot(from: string): string {\n let dir = from;\n for (;;) {\n if (existsSync(join(dir, '.git'))) return dir;\n const up = dirname(dir);\n if (up === dir) return from;\n dir = up;\n }\n}\n\n/**\n * A self-contained workflow: plain `run:` steps with the published CLI and the `gh`\n * that every GitHub runner has, plus actions/checkout and actions/setup-node only.\n * One sticky comment per mode, found again by its hidden marker and edited in place.\n */\nexport function workflowTemplate(workingDirectory: string): string {\n const wd = workingDirectory === '' ? '.' : workingDirectory;\n const configGlob = wd === '.' ? 'splithub.config.*' : `${wd}/splithub.config.*`;\n return `# SplitHub: checks experiments on pull requests that touch the config, and keeps\n# a results comment up to date on weekday mornings. Needs the SPLITHUB_API_KEY\n# secret (dashboard, Settings, API keys) for results and cloud comparisons.\nname: SplitHub\n\non:\n pull_request:\n paths:\n - '${configGlob}'\n schedule:\n - cron: '0 8 * * 1-5'\n workflow_dispatch:\n\npermissions:\n contents: read\n pull-requests: write\n issues: write\n\njobs:\n splithub:\n runs-on: ubuntu-latest\n defaults:\n run:\n shell: bash\n working-directory: ${wd}\n env:\n SPLITHUB_API_KEY: \\${{ secrets.SPLITHUB_API_KEY }}\n GH_TOKEN: \\${{ github.token }}\n NO_COLOR: '1'\n # check on a pull request (doctor + push --dry-run), report otherwise (results tables)\n MODE: \\${{ github.event_name == 'pull_request' && 'check' || 'report' }}\n PR_NUMBER: \\${{ github.event.pull_request.number }}\n ISSUE_TITLE: SplitHub results\n OUT: \\${{ runner.temp }}/splithub\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-node@v4\n with:\n node-version: 20\n\n - name: Install dependencies\n run: |\n # The config imports @splithub/core; the lockfile may live at the repository root.\n dir=\"$PWD\"\n while [ \"$dir\" != \"/\" ] && [ ! -f \"$dir/pnpm-lock.yaml\" ] && [ ! -f \"$dir/yarn.lock\" ] && [ ! -f \"$dir/package-lock.json\" ] && [ ! -f \"$dir/bun.lockb\" ] && [ ! -f \"$dir/bun.lock\" ]; do dir=\"$(dirname \"$dir\")\"; done\n cd \"$dir\"\n if [ -f pnpm-lock.yaml ]; then corepack enable && pnpm install --frozen-lockfile\n elif [ -f yarn.lock ]; then corepack enable && (yarn install --frozen-lockfile || yarn install --immutable)\n elif [ -f bun.lockb ] || [ -f bun.lock ]; then npm i -g bun && bun install --frozen-lockfile\n elif [ -f package-lock.json ]; then npm ci\n else npm install; fi\n\n - name: Run SplitHub\n id: run\n run: |\n mkdir -p \"$OUT\"\n ok=true\n if [ \"$MODE\" = \"check\" ]; then\n ${CLI} doctor --json > \"$OUT/doctor.json\" || ok=false\n ${CLI} push --dry-run --json > \"$OUT/push.json\" || ok=false\n elif [ -z \"$SPLITHUB_API_KEY\" ]; then\n echo '{\"error\":\"Add the SPLITHUB_API_KEY secret (dashboard, Settings, API keys) to post results.\"}' > \"$OUT/report.json\"\n else\n ${CLI} report --json > \"$OUT/report.json\" || ok=false\n fi\n echo \"ok=$ok\" >> \"$GITHUB_OUTPUT\"\n\n - name: Write the comment\n run: |\n node - <<'JS'\n const fs = require('fs');\n const path = require('path');\n const out = process.env.OUT;\n const read = (name) => {\n try {\n const lines = fs.readFileSync(path.join(out, name), 'utf8').trim().split('\\\\n');\n return JSON.parse(lines[lines.length - 1]);\n } catch {\n return null;\n }\n };\n const hint = (r) => (r.hint ? ' ' + r.hint : '');\n const lines = [];\n if (process.env.MODE === 'check') {\n const doctor = read('doctor.json');\n const push = read('push.json');\n lines.push('### SplitHub check', '');\n if (!doctor) lines.push('Doctor did not run.');\n else if (doctor.error) lines.push('✖ ' + doctor.error + hint(doctor));\n else {\n lines.push(doctor.ok ? '✔ No problems found.' : '✖ ' + doctor.errors + ' problem(s) to fix.', '');\n for (const c of doctor.checks.filter((c) => c.level !== 'ok')) lines.push('- ' + (c.level === 'error' ? '✖' : '!') + ' ' + c.message);\n }\n lines.push('');\n if (!push) lines.push('The config check did not run.');\n else if (push.error) lines.push('✖ Config: ' + push.error + hint(push));\n else if (!push.diff) lines.push('Config loads: ' + push.experiments.length + ' experiment(s). ' + (push.cloud === 'self mode' ? 'Self-hosted, nothing to push.' : 'Add the SPLITHUB_API_KEY secret to compare it with the cloud.'));\n else {\n const d = push.diff;\n if (!d.added.length && !d.removed.length && !d.changed.length) lines.push('The cloud already has this config.');\n else {\n lines.push('After merge, \\`npx splithub push\\` changes:', '');\n for (const k of d.added) lines.push('- added \\`' + k + '\\`');\n for (const k of d.removed) lines.push('- removed \\`' + k + '\\`');\n for (const c of d.changed) lines.push('- \\`' + c.experiment + '\\`: ' + c.fields.join(', '));\n }\n }\n } else {\n const report = read('report.json');\n lines.push(!report ? 'SplitHub report did not run.' : report.error ? '### SplitHub\\\\n\\\\n' + report.error : report.markdown);\n lines.push('', '<sub>Updated ' + new Date().toISOString().slice(0, 16).replace('T', ' ') + ' UTC</sub>');\n }\n fs.writeFileSync(path.join(out, 'body.md'), '<!-- splithub:' + process.env.MODE + ' -->\\\\n' + lines.join('\\\\n') + '\\\\n');\n JS\n\n - name: Post the sticky comment\n run: |\n marker=\"<!-- splithub:$MODE -->\"\n number=\"$PR_NUMBER\"\n if [ -z \"$number\" ]; then\n number=\"$(gh issue list --repo \"$GITHUB_REPOSITORY\" --state open --search \"$ISSUE_TITLE in:title\" --json number,title --jq '.[] | [.number, .title] | @tsv' | awk -F '\\\\t' -v t=\"$ISSUE_TITLE\" '$2 == t { print $1; exit }')\"\n fi\n if [ -z \"$number\" ]; then\n url=\"$(gh issue create --repo \"$GITHUB_REPOSITORY\" --title \"$ISSUE_TITLE\" --body 'A/B test results from SplitHub, refreshed by the SplitHub workflow.')\"\n number=\"\\${url##*/}\"\n fi\n id=\"$(gh api --paginate \"repos/$GITHUB_REPOSITORY/issues/$number/comments\" --jq '.[] | [.id, (.body | split(\"\\\\n\") | .[0])] | @tsv' | awk -F '\\\\t' -v m=\"$marker\" '$2 == m { print $1; exit }')\"\n if [ -n \"$id\" ]; then\n gh api -X PATCH \"repos/$GITHUB_REPOSITORY/issues/comments/$id\" -F body=@\"$OUT/body.md\" > /dev/null\n else\n gh api \"repos/$GITHUB_REPOSITORY/issues/$number/comments\" -F body=@\"$OUT/body.md\" > /dev/null\n fi\n\n - name: Fail on problems\n if: steps.run.outputs.ok != 'true' && env.MODE == 'check'\n run: |\n echo \"SplitHub found problems: see the comment on the pull request.\"\n exit 1\n`;\n}\n\nexport interface CiResult {\n file: string;\n written: boolean;\n workingDirectory: string;\n secret: string;\n}\n\nexport function writeWorkflow(root: string, force = false): CiResult {\n const repo = gitRoot(root);\n const file = join(repo, '.github', 'workflows', 'splithub.yml');\n const workingDirectory = relative(repo, root).replace(/\\\\/g, '/') || '.';\n const written = force || !existsSync(file);\n if (written) {\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, workflowTemplate(workingDirectory), 'utf8');\n }\n return { file: relative(root, file).replace(/\\\\/g, '/'), written, workingDirectory, secret: 'SPLITHUB_API_KEY' };\n}\n\nexport async function ciInit(flags: Flags): Promise<void> {\n const project = detectProject();\n const result = writeWorkflow(project.root, Boolean(flags.force));\n const next = 'Add the SPLITHUB_API_KEY secret in GitHub (Settings, Secrets and variables, Actions), then commit the workflow.';\n if (flags.json) {\n printJson({ ...result, next });\n return;\n }\n console.log(result.written ? `${c.green('✔')} wrote ${result.file}` : c.dim(`${result.file} is already there; --force replaces it`));\n console.log(c.dim(next));\n}\n"],"mappings":";;;;;;;;;;AAEA,SAAS,YAAY,WAAW,qBAAqB;AACrD,SAAS,SAAS,MAAM,gBAAgB;AAOjC,IAAM,MAAM;AAGnB,SAAS,QAAQ,MAAsB;AACrC,MAAI,MAAM;AACV,aAAS;AACP,QAAI,WAAW,KAAK,KAAK,MAAM,CAAC,EAAG,QAAO;AAC1C,UAAM,KAAK,QAAQ,GAAG;AACtB,QAAI,OAAO,IAAK,QAAO;AACvB,UAAM;AAAA,EACR;AACF;AAOO,SAAS,iBAAiB,kBAAkC;AACjE,QAAM,KAAK,qBAAqB,KAAK,MAAM;AAC3C,QAAM,aAAa,OAAO,MAAM,sBAAsB,GAAG,EAAE;AAC3D,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,WAQE,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,6BAgBQ,EAAE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,cAkCjB,GAAG;AAAA,cACH,GAAG;AAAA;AAAA;AAAA;AAAA,cAIH,GAAG;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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B;","names":[]}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
grepLines,
|
|
4
|
+
listSourceFiles,
|
|
5
|
+
quoted
|
|
6
|
+
} from "./chunk-PLXDG4B5.js";
|
|
7
|
+
|
|
8
|
+
// src/refs.ts
|
|
9
|
+
var CONFIG_FILE = /(^|\/)splithub\.config\.[mc]?[jt]s$/;
|
|
10
|
+
function findRefs(root, config, id, files = listSourceFiles(root)) {
|
|
11
|
+
const exp = config?.experiments.find((e) => e.key === id);
|
|
12
|
+
const goal = exp?.goal ?? null;
|
|
13
|
+
const goalShared = Boolean(goal && config?.experiments.some((e) => e.key !== id && e.goal === goal));
|
|
14
|
+
const code = files.filter((f) => !CONFIG_FILE.test(f.replace(/\\/g, "/")));
|
|
15
|
+
const refs = grepLines(root, code, quoted(id)).map(({ needle: _n, ...hit }) => ({ ...hit, match: "experiment" }));
|
|
16
|
+
if (goal) {
|
|
17
|
+
for (const { needle: _n, ...hit } of grepLines(root, code, quoted(goal))) {
|
|
18
|
+
if (!refs.some((r) => r.file === hit.file && r.line === hit.line)) refs.push({ ...hit, match: "goal" });
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
refs.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
|
|
22
|
+
return { experiment: id, goal, goalShared, refs };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export {
|
|
26
|
+
findRefs
|
|
27
|
+
};
|
|
28
|
+
//# sourceMappingURL=chunk-GVARYUL3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/refs.ts"],"sourcesContent":["// Where an experiment and its goal appear in the project's code. Shared by\n// `doctor` (is it wired?), `refs` (what to touch) and `ship` (what is left).\nimport type { SplitHubConfig } from '@splithub/core';\nimport { grepLines, listSourceFiles, quoted, type LineHit } from './project';\n\nexport interface Ref extends Omit<LineHit, 'needle'> {\n /** experiment: the id in quotes · goal: the goal key in quotes. */\n match: 'experiment' | 'goal';\n}\n\nexport interface RefsResult {\n experiment: string;\n goal: string | null;\n /** True when another experiment measures the same goal: keep its track() calls. */\n goalShared: boolean;\n refs: Ref[];\n}\n\nconst CONFIG_FILE = /(^|\\/)splithub\\.config\\.[mc]?[jt]s$/;\n\nexport function findRefs(root: string, config: SplitHubConfig | null, id: string, files = listSourceFiles(root)): RefsResult {\n const exp = config?.experiments.find((e) => e.key === id);\n const goal = exp?.goal ?? null;\n const goalShared = Boolean(goal && config?.experiments.some((e) => e.key !== id && e.goal === goal));\n const code = files.filter((f) => !CONFIG_FILE.test(f.replace(/\\\\/g, '/')));\n const refs: Ref[] = grepLines(root, code, quoted(id)).map(({ needle: _n, ...hit }) => ({ ...hit, match: 'experiment' as const }));\n if (goal) {\n for (const { needle: _n, ...hit } of grepLines(root, code, quoted(goal))) {\n if (!refs.some((r) => r.file === hit.file && r.line === hit.line)) refs.push({ ...hit, match: 'goal' });\n }\n }\n refs.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);\n return { experiment: id, goal, goalShared, refs };\n}\n"],"mappings":";;;;;;;;AAkBA,IAAM,cAAc;AAEb,SAAS,SAAS,MAAc,QAA+B,IAAY,QAAQ,gBAAgB,IAAI,GAAe;AAC3H,QAAM,MAAM,QAAQ,YAAY,KAAK,CAAC,MAAM,EAAE,QAAQ,EAAE;AACxD,QAAM,OAAO,KAAK,QAAQ;AAC1B,QAAM,aAAa,QAAQ,QAAQ,QAAQ,YAAY,KAAK,CAAC,MAAM,EAAE,QAAQ,MAAM,EAAE,SAAS,IAAI,CAAC;AACnG,QAAM,OAAO,MAAM,OAAO,CAAC,MAAM,CAAC,YAAY,KAAK,EAAE,QAAQ,OAAO,GAAG,CAAC,CAAC;AACzE,QAAM,OAAc,UAAU,MAAM,MAAM,OAAO,EAAE,CAAC,EAAE,IAAI,CAAC,EAAE,QAAQ,IAAI,GAAG,IAAI,OAAO,EAAE,GAAG,KAAK,OAAO,aAAsB,EAAE;AAChI,MAAI,MAAM;AACR,eAAW,EAAE,QAAQ,IAAI,GAAG,IAAI,KAAK,UAAU,MAAM,MAAM,OAAO,IAAI,CAAC,GAAG;AACxE,UAAI,CAAC,KAAK,KAAK,CAAC,MAAM,EAAE,SAAS,IAAI,QAAQ,EAAE,SAAS,IAAI,IAAI,EAAG,MAAK,KAAK,EAAE,GAAG,KAAK,OAAO,OAAO,CAAC;AAAA,IACxG;AAAA,EACF;AACA,OAAK,KAAK,CAAC,GAAG,MAAM,EAAE,KAAK,cAAc,EAAE,IAAI,KAAK,EAAE,OAAO,EAAE,IAAI;AACnE,SAAO,EAAE,YAAY,IAAI,MAAM,YAAY,KAAK;AAClD;","names":[]}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
fetchStatus,
|
|
4
|
+
resolveTarget
|
|
5
|
+
} from "./chunk-EUF75FUC.js";
|
|
6
|
+
import {
|
|
7
|
+
detectProject
|
|
8
|
+
} from "./chunk-PLXDG4B5.js";
|
|
9
|
+
import {
|
|
10
|
+
c
|
|
11
|
+
} from "./chunk-V3DLUVOE.js";
|
|
12
|
+
|
|
13
|
+
// src/commands/dev.ts
|
|
14
|
+
import { spawn } from "child_process";
|
|
15
|
+
function openBrowser(url) {
|
|
16
|
+
const [cmd, args] = process.platform === "win32" ? ["cmd", ["/c", "start", "", url]] : process.platform === "darwin" ? ["open", [url]] : ["xdg-open", [url]];
|
|
17
|
+
try {
|
|
18
|
+
spawn(cmd, args, { stdio: "ignore", detached: true }).unref();
|
|
19
|
+
} catch {
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
async function dev(flags) {
|
|
23
|
+
const project = detectProject();
|
|
24
|
+
const port = project?.framework === "next" ? 3e3 : 5173;
|
|
25
|
+
const page = typeof flags.url === "string" && flags.url || `http://localhost:${port}/`;
|
|
26
|
+
const u = new URL(page);
|
|
27
|
+
u.searchParams.set("sh_debug", flags.hold ? "hold" : "1");
|
|
28
|
+
const link = u.toString();
|
|
29
|
+
console.log(`${c.bold("SplitHub dev mode")}
|
|
30
|
+
`);
|
|
31
|
+
console.log(` ${c.cyan(link)}
|
|
32
|
+
`);
|
|
33
|
+
console.log(c.dim(" In the browser: the console shows every assignment (variant + reason), exposure and goal; the panel"));
|
|
34
|
+
console.log(c.dim(" in the corner forces variants, starts a new visitor and can hold redirects. Add ?sh_debug=0 to stop.\n"));
|
|
35
|
+
if (!flags["no-open"]) openBrowser(link);
|
|
36
|
+
const target = resolveTarget(flags, project);
|
|
37
|
+
console.log(c.dim(` Watching ${target.url} every 5 s. Ctrl+C to stop.
|
|
38
|
+
`));
|
|
39
|
+
const seen = /* @__PURE__ */ new Map();
|
|
40
|
+
let first = true;
|
|
41
|
+
const poll = async () => {
|
|
42
|
+
let data;
|
|
43
|
+
try {
|
|
44
|
+
data = await fetchStatus(target);
|
|
45
|
+
} catch (e) {
|
|
46
|
+
if (first) console.log(c.yellow(` results endpoint not reachable yet (${e instanceof Error ? e.message : String(e)}); is the dev server running?`));
|
|
47
|
+
first = false;
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
const now = (/* @__PURE__ */ new Date()).toLocaleTimeString();
|
|
51
|
+
for (const e of data.experiments) {
|
|
52
|
+
const prev = seen.get(e.experiment);
|
|
53
|
+
if (!prev) console.log(` ${c.dim(now)} ${c.bold(e.experiment)} ${c.dim(e.status)} \xB7 ${e.visitors} visitors${e.headline ? ` \xB7 ${e.headline}` : ""}`);
|
|
54
|
+
else if (prev.visitors !== e.visitors || prev.headline !== (e.headline ?? null)) console.log(` ${c.dim(now)} ${c.bold(e.experiment)} ${c.green(`+${e.visitors - prev.visitors}`)} \u2192 ${e.visitors} visitors${e.headline ? ` \xB7 ${e.headline}` : ""}`);
|
|
55
|
+
seen.set(e.experiment, { visitors: e.visitors, headline: e.headline ?? null });
|
|
56
|
+
}
|
|
57
|
+
first = false;
|
|
58
|
+
};
|
|
59
|
+
await poll();
|
|
60
|
+
await new Promise((resolve) => {
|
|
61
|
+
const t = setInterval(() => void poll(), 5e3);
|
|
62
|
+
process.on("SIGINT", () => {
|
|
63
|
+
clearInterval(t);
|
|
64
|
+
resolve();
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export {
|
|
70
|
+
dev
|
|
71
|
+
};
|
|
72
|
+
//# sourceMappingURL=chunk-HSH4ZI2V.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/dev.ts"],"sourcesContent":["// splithub dev — test experiments locally with full visibility.\n//\n// splithub dev opens the app (localhost:3000 for Next.js, 5173 for Vite) with ?sh_debug=1\n// splithub dev --url http://… a different page\n// splithub dev --hold redirect experiments log the target instead of navigating\n// splithub dev --no-open only print the link and watch\n//\n// With ?sh_debug the SDK and the drop-in script log every decision (which\n// variant and why), every exposure and goal with its payload, and the remote\n// overrides they applied, in the browser console and in a floating panel that\n// can force a variant, start a new visitor or hold redirects. Meanwhile this\n// command polls `status` and prints new visitors / conversions as they land.\n\nimport { spawn } from 'node:child_process';\nimport { fetchStatus, resolveTarget } from '../api';\nimport { detectProject } from '../project';\nimport { c } from '../ui';\n\nfunction openBrowser(url: string): void {\n const [cmd, args] = process.platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : process.platform === 'darwin' ? ['open', [url]] : ['xdg-open', [url]];\n try {\n spawn(cmd, args, { stdio: 'ignore', detached: true }).unref();\n } catch {\n // no browser available: the link is printed anyway\n }\n}\n\nexport async function dev(flags: Record<string, unknown>): Promise<void> {\n const project = detectProject();\n const port = project?.framework === 'next' ? 3000 : 5173;\n const page = (typeof flags.url === 'string' && flags.url) || `http://localhost:${port}/`;\n const u = new URL(page);\n u.searchParams.set('sh_debug', flags.hold ? 'hold' : '1');\n const link = u.toString();\n\n console.log(`${c.bold('SplitHub dev mode')}\\n`);\n console.log(` ${c.cyan(link)}\\n`);\n console.log(c.dim(' In the browser: the console shows every assignment (variant + reason), exposure and goal; the panel'));\n console.log(c.dim(' in the corner forces variants, starts a new visitor and can hold redirects. Add ?sh_debug=0 to stop.\\n'));\n if (!flags['no-open']) openBrowser(link);\n\n const target = resolveTarget(flags, project);\n console.log(c.dim(` Watching ${target.url} every 5 s. Ctrl+C to stop.\\n`));\n const seen = new Map<string, { visitors: number; headline: string | null }>();\n let first = true;\n const poll = async () => {\n let data: Awaited<ReturnType<typeof fetchStatus>>;\n try {\n data = await fetchStatus(target);\n } catch (e) {\n if (first) console.log(c.yellow(` results endpoint not reachable yet (${e instanceof Error ? e.message : String(e)}); is the dev server running?`));\n first = false;\n return;\n }\n const now = new Date().toLocaleTimeString();\n for (const e of data.experiments) {\n const prev = seen.get(e.experiment);\n if (!prev) console.log(` ${c.dim(now)} ${c.bold(e.experiment)} ${c.dim(e.status)} · ${e.visitors} visitors${e.headline ? ` · ${e.headline}` : ''}`);\n else if (prev.visitors !== e.visitors || prev.headline !== (e.headline ?? null)) console.log(` ${c.dim(now)} ${c.bold(e.experiment)} ${c.green(`+${e.visitors - prev.visitors}`)} → ${e.visitors} visitors${e.headline ? ` · ${e.headline}` : ''}`);\n seen.set(e.experiment, { visitors: e.visitors, headline: e.headline ?? null });\n }\n first = false;\n };\n await poll();\n await new Promise<void>((resolve) => {\n const t = setInterval(() => void poll(), 5000);\n process.on('SIGINT', () => {\n clearInterval(t);\n resolve();\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,SAAS,aAAa;AAKtB,SAAS,YAAY,KAAmB;AACtC,QAAM,CAAC,KAAK,IAAI,IAAI,QAAQ,aAAa,UAAU,CAAC,OAAO,CAAC,MAAM,SAAS,IAAI,GAAG,CAAC,IAAI,QAAQ,aAAa,WAAW,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC;AAC3J,MAAI;AACF,UAAM,KAAK,MAAM,EAAE,OAAO,UAAU,UAAU,KAAK,CAAC,EAAE,MAAM;AAAA,E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AM,CAAC,SAAM,EAAE,QAAQ,YAAY,EAAE,WAAW,SAAM,EAAE,QAAQ,KAAK,EAAE,EAAE;AAAA,eAC1I,KAAK,aAAa,EAAE,YAAY,KAAK,cAAc,EAAE,YAAY,MAAO,SAAQ,IAAI,KAAK,EAAE,IAAI,GAAG,CAAC,IAAI,EAAE,KAAK,EAAE,UAAU,CAAC,IAAI,EAAE,MAAM,IAAI,EAAE,WAAW,KAAK,QAAQ,EAAE,CAAC,WAAM,EAAE,QAAQ,YAAY,EAAE,WAAW,SAAM,EAAE,QAAQ,KAAK,EAAE,EAAE;AACnP,WAAK,IAAI,EAAE,YAAY,EAAE,UAAU,EAAE,UAAU,UAAU,EAAE,YAAY,KAAK,CAAC;AAAA,IAC/E;AACA,YAAQ;AAAA,EACV;AACA,QAAM,KAAK;AACX,QAAM,IAAI,QAAc,CAAC,YAAY;AACnC,UAAM,IAAI,YAAY,MAAM,KAAK,KAAK,GAAG,GAAI;AAC7C,YAAQ,GAAG,UAAU,MAAM;AACzB,oBAAc,CAAC;AACf,cAAQ;AAAA,IACV,CAAC;AAAA,EACH,CAAC;AACH;","names":[]}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
fail
|
|
4
|
+
} from "./chunk-V3DLUVOE.js";
|
|
5
|
+
|
|
6
|
+
// src/project.ts
|
|
7
|
+
import { existsSync, readFileSync, readdirSync, statSync } from "fs";
|
|
8
|
+
import { join, relative, resolve } from "path";
|
|
9
|
+
var CONFIG_NAMES = ["splithub.config.ts", "splithub.config.mts", "splithub.config.js", "splithub.config.mjs"];
|
|
10
|
+
function findConfigFile(root) {
|
|
11
|
+
for (const name of CONFIG_NAMES) {
|
|
12
|
+
const p = join(root, name);
|
|
13
|
+
if (existsSync(p)) return p;
|
|
14
|
+
}
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
function detectProject(cwd = process.cwd()) {
|
|
18
|
+
const root = resolve(cwd);
|
|
19
|
+
let name = "my-app";
|
|
20
|
+
let deps = {};
|
|
21
|
+
try {
|
|
22
|
+
const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
|
23
|
+
name = pkg.name ?? name;
|
|
24
|
+
deps = { ...pkg.dependencies ?? {}, ...pkg.devDependencies ?? {} };
|
|
25
|
+
} catch {
|
|
26
|
+
}
|
|
27
|
+
const has = (file) => existsSync(join(root, file));
|
|
28
|
+
const framework = deps.next || has("next.config.js") || has("next.config.mjs") || has("next.config.ts") ? "next" : deps.vite || has("vite.config.ts") || has("vite.config.js") || has("vite.config.mjs") ? "vite" : "unknown";
|
|
29
|
+
const packageManager = has("pnpm-lock.yaml") ? "pnpm" : has("yarn.lock") ? "yarn" : has("bun.lockb") || has("bun.lock") ? "bun" : "npm";
|
|
30
|
+
const appDir = has("src/app") ? "src/app" : has("app") ? "app" : null;
|
|
31
|
+
return {
|
|
32
|
+
root,
|
|
33
|
+
name: name.replace(/^@[^/]+\//, ""),
|
|
34
|
+
framework,
|
|
35
|
+
packageManager,
|
|
36
|
+
appDir,
|
|
37
|
+
hasSrc: has("src"),
|
|
38
|
+
configFile: findConfigFile(root),
|
|
39
|
+
typescript: has("tsconfig.json")
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function requireConfig(cwd = process.cwd()) {
|
|
43
|
+
const project = detectProject(cwd);
|
|
44
|
+
if (!project.configFile) fail("NO_CONFIG", "There's no splithub.config.ts here.", "Run npx splithub init first, or run the command in your app folder.");
|
|
45
|
+
return project;
|
|
46
|
+
}
|
|
47
|
+
function installCommand(pm, packages, dev = false) {
|
|
48
|
+
const flag = dev ? pm === "npm" ? " -D" : " -D" : "";
|
|
49
|
+
switch (pm) {
|
|
50
|
+
case "pnpm":
|
|
51
|
+
return `pnpm add${flag} ${packages.join(" ")}`;
|
|
52
|
+
case "yarn":
|
|
53
|
+
return `yarn add${flag} ${packages.join(" ")}`;
|
|
54
|
+
case "bun":
|
|
55
|
+
return `bun add${dev ? " -d" : ""} ${packages.join(" ")}`;
|
|
56
|
+
default:
|
|
57
|
+
return `npm install${flag} ${packages.join(" ")}`;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".next", "dist", "build", ".git", "coverage", "out", ".turbo"]);
|
|
61
|
+
var CODE_EXT = /\.(tsx?|jsx?|mjs|cjs|mts|cts)$/;
|
|
62
|
+
function listSourceFiles(root, maxFiles = 5e3) {
|
|
63
|
+
const out = [];
|
|
64
|
+
const walk = (dir, depth) => {
|
|
65
|
+
if (out.length >= maxFiles || depth > 8) return;
|
|
66
|
+
let entries;
|
|
67
|
+
try {
|
|
68
|
+
entries = readdirSync(dir);
|
|
69
|
+
} catch {
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
for (const entry of entries) {
|
|
73
|
+
if (SKIP_DIRS.has(entry)) continue;
|
|
74
|
+
const full = join(dir, entry);
|
|
75
|
+
let st;
|
|
76
|
+
try {
|
|
77
|
+
st = statSync(full);
|
|
78
|
+
} catch {
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (st.isDirectory()) walk(full, depth + 1);
|
|
82
|
+
else if (CODE_EXT.test(entry)) out.push(full);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
walk(root, 0);
|
|
86
|
+
return out;
|
|
87
|
+
}
|
|
88
|
+
function quoted(key) {
|
|
89
|
+
return [`'${key}'`, `"${key}"`, `\`${key}\``];
|
|
90
|
+
}
|
|
91
|
+
function grepLines(root, files, needles) {
|
|
92
|
+
const hits = [];
|
|
93
|
+
for (const f of files) {
|
|
94
|
+
let src;
|
|
95
|
+
try {
|
|
96
|
+
src = readFileSync(f, "utf8");
|
|
97
|
+
} catch {
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (!needles.some((n) => src.includes(n))) continue;
|
|
101
|
+
const lines = src.split(/\r?\n/);
|
|
102
|
+
lines.forEach((text, i) => {
|
|
103
|
+
for (const needle of needles) {
|
|
104
|
+
const col = text.indexOf(needle);
|
|
105
|
+
if (col >= 0) {
|
|
106
|
+
hits.push({ file: relative(root, f).replace(/\\/g, "/"), line: i + 1, column: col + 1, text: text.trim().slice(0, 200), needle });
|
|
107
|
+
break;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
return hits;
|
|
113
|
+
}
|
|
114
|
+
function grepFiles(files, needle) {
|
|
115
|
+
const hits = [];
|
|
116
|
+
for (const f of files) {
|
|
117
|
+
try {
|
|
118
|
+
if (readFileSync(f, "utf8").includes(needle)) hits.push(f);
|
|
119
|
+
} catch {
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return hits;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export {
|
|
126
|
+
detectProject,
|
|
127
|
+
requireConfig,
|
|
128
|
+
installCommand,
|
|
129
|
+
listSourceFiles,
|
|
130
|
+
quoted,
|
|
131
|
+
grepLines,
|
|
132
|
+
grepFiles
|
|
133
|
+
};
|
|
134
|
+
//# sourceMappingURL=chunk-PLXDG4B5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/project.ts"],"sourcesContent":["import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';\nimport { join, relative, resolve } from 'node:path';\nimport { fail } from './errors';\n\nexport type Framework = 'next' | 'vite' | 'unknown';\nexport type PackageManager = 'pnpm' | 'yarn' | 'bun' | 'npm';\n\nexport interface ProjectInfo {\n root: string;\n name: string;\n framework: Framework;\n packageManager: PackageManager;\n /** Next.js app directory (`app` or `src/app`), when present. */\n appDir: string | null;\n /** Whether sources live under `src/`. */\n hasSrc: boolean;\n configFile: string | null;\n typescript: boolean;\n}\n\nconst CONFIG_NAMES = ['splithub.config.ts', 'splithub.config.mts', 'splithub.config.js', 'splithub.config.mjs'];\n\nexport function findConfigFile(root: string): string | null {\n for (const name of CONFIG_NAMES) {\n const p = join(root, name);\n if (existsSync(p)) return p;\n }\n return null;\n}\n\nexport function detectProject(cwd = process.cwd()): ProjectInfo {\n const root = resolve(cwd);\n let name = 'my-app';\n let deps: Record<string, string> = {};\n try {\n const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { name?: string; dependencies?: Record<string, string>; devDependencies?: Record<string, string> };\n name = pkg.name ?? name;\n deps = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };\n } catch {\n // no package.json: still usable\n }\n const has = (file: string) => existsSync(join(root, file));\n const framework: Framework = deps.next || has('next.config.js') || has('next.config.mjs') || has('next.config.ts')\n ? 'next'\n : deps.vite || has('vite.config.ts') || has('vite.config.js') || has('vite.config.mjs')\n ? 'vite'\n : 'unknown';\n const packageManager: PackageManager = has('pnpm-lock.yaml') ? 'pnpm' : has('yarn.lock') ? 'yarn' : has('bun.lockb') || has('bun.lock') ? 'bun' : 'npm';\n const appDir = has('src/app') ? 'src/app' : has('app') ? 'app' : null;\n return {\n root,\n name: name.replace(/^@[^/]+\\//, ''),\n framework,\n packageManager,\n appDir,\n hasSrc: has('src'),\n configFile: findConfigFile(root),\n typescript: has('tsconfig.json'),\n };\n}\n\n/** The project and its config file; NO_CONFIG when there is none. */\nexport function requireConfig(cwd = process.cwd()): ProjectInfo & { configFile: string } {\n const project = detectProject(cwd);\n if (!project.configFile) fail('NO_CONFIG', \"There's no splithub.config.ts here.\", 'Run npx splithub init first, or run the command in your app folder.');\n return project as ProjectInfo & { configFile: string };\n}\n\nexport function installCommand(pm: PackageManager, packages: string[], dev = false): string {\n const flag = dev ? (pm === 'npm' ? ' -D' : ' -D') : '';\n switch (pm) {\n case 'pnpm':\n return `pnpm add${flag} ${packages.join(' ')}`;\n case 'yarn':\n return `yarn add${flag} ${packages.join(' ')}`;\n case 'bun':\n return `bun add${dev ? ' -d' : ''} ${packages.join(' ')}`;\n default:\n return `npm install${flag} ${packages.join(' ')}`;\n }\n}\n\nconst SKIP_DIRS = new Set(['node_modules', '.next', 'dist', 'build', '.git', 'coverage', 'out', '.turbo']);\nconst CODE_EXT = /\\.(tsx?|jsx?|mjs|cjs|mts|cts)$/;\n\n/** Source files of the project (shallow enough for a doctor run). */\nexport function listSourceFiles(root: string, maxFiles = 5000): string[] {\n const out: string[] = [];\n const walk = (dir: string, depth: number) => {\n if (out.length >= maxFiles || depth > 8) return;\n let entries: string[];\n try {\n entries = readdirSync(dir);\n } catch {\n return;\n }\n for (const entry of entries) {\n if (SKIP_DIRS.has(entry)) continue;\n const full = join(dir, entry);\n let st;\n try {\n st = statSync(full);\n } catch {\n continue;\n }\n if (st.isDirectory()) walk(full, depth + 1);\n else if (CODE_EXT.test(entry)) out.push(full);\n }\n };\n walk(root, 0);\n return out;\n}\n\nexport interface LineHit {\n /** Path relative to the project root, forward slashes. */\n file: string;\n line: number;\n column: number;\n text: string;\n /** Which needle matched. */\n needle: string;\n}\n\n/** Quoted forms of a key as it appears in code: 'k', \"k\", `k`. */\nexport function quoted(key: string): string[] {\n return [`'${key}'`, `\"${key}\"`, `\\`${key}\\``];\n}\n\n/** Every line of `files` that contains one of `needles`, with its position. */\nexport function grepLines(root: string, files: string[], needles: string[]): LineHit[] {\n const hits: LineHit[] = [];\n for (const f of files) {\n let src: string;\n try {\n src = readFileSync(f, 'utf8');\n } catch {\n continue;\n }\n if (!needles.some((n) => src.includes(n))) continue;\n const lines = src.split(/\\r?\\n/);\n lines.forEach((text, i) => {\n for (const needle of needles) {\n const col = text.indexOf(needle);\n if (col >= 0) {\n hits.push({ file: relative(root, f).replace(/\\\\/g, '/'), line: i + 1, column: col + 1, text: text.trim().slice(0, 200), needle });\n break;\n }\n }\n });\n }\n return hits;\n}\n\nexport function grepFiles(files: string[], needle: string): string[] {\n const hits: string[] = [];\n for (const f of files) {\n try {\n if (readFileSync(f, 'utf8').includes(needle)) hits.push(f);\n } catch {\n // unreadable file\n }\n }\n return hits;\n}\n"],"mappings":";;;;;;AAAA,SAAS,YAAY,cAAc,aAA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
9
|
+
requireCloudToken,
|
|
10
|
+
saveCredential
|
|
11
|
+
} from "./chunk-EUF75FUC.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-PWSRKABE.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,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