burrow-cli 0.0.0-stage → 0.1.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.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +594 -2
  3. package/bin/burrow.js +200 -0
  4. package/examples/acme-shop.tunnel.yml +18 -0
  5. package/package.json +45 -4
  6. package/src/access.js +163 -0
  7. package/src/add.js +106 -0
  8. package/src/cloudflare.js +118 -0
  9. package/src/commands.js +386 -0
  10. package/src/completion.js +127 -0
  11. package/src/config-file.js +31 -0
  12. package/src/config.js +82 -0
  13. package/src/dashboard/auth.js +79 -0
  14. package/src/dashboard/data.js +70 -0
  15. package/src/dashboard/logs.js +95 -0
  16. package/src/dashboard/manage.js +102 -0
  17. package/src/dashboard/panels/README.md +50 -0
  18. package/src/dashboard/panels/access.js +218 -0
  19. package/src/dashboard/panels/alerts.js +244 -0
  20. package/src/dashboard/panels/backup.js +193 -0
  21. package/src/dashboard/panels/bulk.js +246 -0
  22. package/src/dashboard/panels/cleanup.js +237 -0
  23. package/src/dashboard/panels/doctor.js +119 -0
  24. package/src/dashboard/panels/health.js +146 -0
  25. package/src/dashboard/panels/history.js +104 -0
  26. package/src/dashboard/panels/hooks.js +86 -0
  27. package/src/dashboard/panels/live.js +153 -0
  28. package/src/dashboard/panels/project-form.js +463 -0
  29. package/src/dashboard/panels/quick-actions.js +133 -0
  30. package/src/dashboard/panels/sessions.js +267 -0
  31. package/src/dashboard/panels/shares.js +280 -0
  32. package/src/dashboard/panels/stats.js +165 -0
  33. package/src/dashboard/panels/updates.js +156 -0
  34. package/src/dashboard/panels/uptime.js +115 -0
  35. package/src/dashboard/panels.js +53 -0
  36. package/src/dashboard/server.js +390 -0
  37. package/src/dashboard/session-store.js +47 -0
  38. package/src/dashboard/totp.js +103 -0
  39. package/src/dashboard/ui.js +454 -0
  40. package/src/doctor.js +342 -0
  41. package/src/edit.js +135 -0
  42. package/src/health-observer.js +81 -0
  43. package/src/history.js +145 -0
  44. package/src/hooks.js +256 -0
  45. package/src/naming.js +38 -0
  46. package/src/open.js +67 -0
  47. package/src/pending.js +72 -0
  48. package/src/process.js +95 -0
  49. package/src/project-form.js +134 -0
  50. package/src/project.js +114 -0
  51. package/src/prune.js +99 -0
  52. package/src/rename-state.js +39 -0
  53. package/src/restart.js +35 -0
  54. package/src/service.js +173 -0
  55. package/src/share-expiry.js +55 -0
  56. package/src/share.js +275 -0
  57. package/src/shell-words.js +284 -0
  58. package/src/stats.js +180 -0
  59. package/src/transfer.js +124 -0
  60. package/src/update.js +254 -0
  61. package/src/uptime.js +91 -0
  62. package/src/watch.js +263 -0
  63. package/src/zones.js +102 -0
package/src/share.js ADDED
@@ -0,0 +1,275 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { existsSync, readdirSync } from 'node:fs';
3
+ import { resolve } from 'node:path';
4
+ import { loadConfig, requireConfig, stateDir } from './config.js';
5
+ import { Cloudflare } from './cloudflare.js';
6
+ import { tunnelName, recordComment, tunnelTarget, assertLabel, assertDomain } from './naming.js';
7
+ import { ensureExpiryWatcher } from './share-expiry.js';
8
+ import { startConnector, stopConnector, runningPid, saveMeta, readMeta, removeMeta, logFile } from './process.js';
9
+ import { loadProjectFile } from './project.js';
10
+ import { zoneIdFor, inZone } from './zones.js';
11
+ import { runHook, beforeDown, afterDown, stopBackground } from './hooks.js';
12
+
13
+ // A share is a throwaway project: tunnel burrow-share-<label>, hostname
14
+ // <label>.<domain>, DNS comment burrow:share-<label>, state share-<label>.*
15
+ export const SHARE_PREFIX = 'share-';
16
+ const log = (...a) => console.log(...a);
17
+
18
+ // --expires: 30m, 2h, 1d, 7d (at least 1 minute, at most 30 days). Returns milliseconds.
19
+ const EXPIRY_UNITS = { m: 60e3, min: 60e3, h: 3600e3, d: 24 * 3600e3 };
20
+ export function parseExpires(value) {
21
+ const m = String(value ?? '').trim().match(/^(\d+)\s*(m|min|h|d)$/i);
22
+ const ms = m ? Number(m[1]) * EXPIRY_UNITS[m[2].toLowerCase()] : NaN;
23
+ if (!(ms >= 60e3 && ms <= 30 * 24 * 3600e3)) throw new Error(`Invalid --expires "${value}". Use e.g. 30m, 2h, 1d (1 minute to 30 days).`);
24
+ return ms;
25
+ }
26
+
27
+ // The dashboard (or anything else) asks a foreground `burrow share` to stop by setting
28
+ // stopRequestedAt in the share's state file; that process checks it every 2 seconds.
29
+ export function requestStop(project) {
30
+ const meta = readMeta(project);
31
+ if (!meta?.share) return false;
32
+ saveMeta(project, { ...meta, stopRequestedAt: new Date().toISOString() });
33
+ return true;
34
+ }
35
+
36
+ // Why a foreground share should stop now, or null.
37
+ export function stopReason(meta, now = Date.now()) {
38
+ if (!meta) return 'its state was removed';
39
+ if (meta.stopRequestedAt) return 'stop requested from the dashboard';
40
+ if (meta.expiresAt && Date.parse(meta.expiresAt) <= now) return `it expired at ${meta.expiresAt}`;
41
+ return null;
42
+ }
43
+
44
+ export function isShare(project) {
45
+ return project.startsWith(SHARE_PREFIX) && readMeta(project)?.share === true;
46
+ }
47
+
48
+ export function randomLabel(length = 10) {
49
+ const letters = 'abcdefghijklmnopqrstuvwxyz';
50
+ const chars = letters + '0123456789';
51
+ const bytes = randomBytes(length);
52
+ let s = letters[bytes[0] % letters.length];
53
+ for (let i = 1; i < length; i++) s += chars[bytes[i] % chars.length];
54
+ return s;
55
+ }
56
+
57
+ export function targetUrl(target) {
58
+ const t = String(target ?? '').trim();
59
+ if (/^\d+$/.test(t)) {
60
+ const port = Number(t);
61
+ if (port < 1 || port > 65535) throw new Error(`Invalid port ${t}`);
62
+ return `http://localhost:${port}`;
63
+ }
64
+ let u;
65
+ try { u = new URL(t); } catch { throw new Error(`Expected a port or an http(s) URL, got "${t}"`); }
66
+ if (!['http:', 'https:'].includes(u.protocol)) throw new Error(`Expected an http(s) URL, got "${t}"`);
67
+ return t;
68
+ }
69
+
70
+ async function client(cfg) {
71
+ const cf = new Cloudflare({ token: cfg.token, accountId: cfg.accountId, zoneId: cfg.zoneId });
72
+ await cf.resolveZoneId(cfg.domain);
73
+ return cf;
74
+ }
75
+
76
+ // The client for a share's zone: the one remembered in its state (--domain or the project's
77
+ // domain:), else BURROW_DOMAIN's.
78
+ async function shareClient(cfg, meta) {
79
+ if (meta?.zoneId) return inZone(new Cloudflare({ token: cfg.token, accountId: cfg.accountId }), meta.zoneId);
80
+ requireConfig(cfg, ['domain']);
81
+ return client(cfg);
82
+ }
83
+
84
+ // Which tunnel.yml a share is for: -f <path>, or --project <name> (the file its last
85
+ // `burrow up` remembered). Gives its domain: and hooks to the share.
86
+ function shareProject(opts) {
87
+ let file = null;
88
+ if (opts.file) file = resolve(opts.file);
89
+ else if (opts.project) {
90
+ file = readMeta(opts.project)?.file || null;
91
+ if (!file) throw new Error(`No tunnel.yml known for "${opts.project}". Run burrow up for it once, or pass -f.`);
92
+ }
93
+ if (!file) return null;
94
+ if (!existsSync(file)) throw new Error(`${file} not found.`);
95
+ return { file, proj: loadProjectFile(file) };
96
+ }
97
+
98
+ // Hook context for a share: its own project name (so a background pre_up gets its own pid
99
+ // file), the project's tunnel.yml for the commands and their directory.
100
+ const shareHookContext = (project, file, hostname, of) => ({
101
+ project, file, hostnames: [hostname], url: `https://${hostname}`, extra: { BURROW_SHARE: '1', BURROW_SHARE_OF: of },
102
+ });
103
+
104
+ // Stop the connector and delete the share's DNS records, tunnel and state.
105
+ export async function removeShare(project, cf) {
106
+ const meta = readMeta(project);
107
+ if (!cf) {
108
+ const cfg = loadConfig();
109
+ requireConfig(cfg, ['token', 'accountId']);
110
+ cf = await shareClient(cfg, meta);
111
+ }
112
+ await stopConnector(project);
113
+ for (const r of await cf.recordsByComment(recordComment(project))) await cf.deleteRecord(r.id);
114
+ const id = meta?.tunnelId || (await cf.findTunnel(tunnelName(project)))?.id;
115
+ if (id) {
116
+ await cf.deleteTunnelConnections(id);
117
+ await cf.deleteTunnel(id);
118
+ }
119
+ removeMeta(project);
120
+ }
121
+
122
+ const alive = (pid) => {
123
+ try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
124
+ };
125
+ // Is the foreground `burrow share` that owns this share still running?
126
+ export const ownerAlive = (meta) => !!meta?.ownerPid && meta.ownerPid !== process.pid && alive(meta.ownerPid);
127
+
128
+ // All shares this machine knows about (state files with share: true).
129
+ export function shareNames() {
130
+ let names = [];
131
+ try { names = readdirSync(stateDir()).filter((f) => f.endsWith('.json')).map((f) => f.slice(0, -5)); } catch {}
132
+ return names.filter((n) => isShare(n)).sort();
133
+ }
134
+
135
+ // `burrow restart` for a share: re-apply its ingress, make sure its CNAME is there and
136
+ // restart cloudflared on the same tunnel and hostname. A share whose `burrow share`
137
+ // process is still in the foreground is skipped (that process owns it), and a share whose
138
+ // tunnel is gone on Cloudflare is cleaned up locally instead of being recreated.
139
+ export async function restartShare(project, opts = {}) {
140
+ const meta = readMeta(project);
141
+ if (!meta?.share) throw new Error(`${project} is not a share.`);
142
+ const label = project.slice(SHARE_PREFIX.length);
143
+ if (meta.ownerPid && meta.ownerPid !== process.pid && alive(meta.ownerPid)) {
144
+ log(`${project}: skipped; it belongs to a running "burrow share" (pid ${meta.ownerPid}). Stop that with Ctrl+C and share again to change it.`);
145
+ return 'skipped';
146
+ }
147
+ const ingress = [{ hostname: meta.hostname, service: meta.target }, { service: 'http_status:404' }];
148
+ if (opts.dryRun) {
149
+ log(`[dry-run] ${project}: would re-apply ${meta.hostname} -> ${meta.target}, check its DNS record and restart cloudflared`);
150
+ return 'planned';
151
+ }
152
+ const cfg = loadConfig();
153
+ requireConfig(cfg, ['token', 'accountId']);
154
+ const cf = await shareClient(cfg, meta);
155
+ const tunnel = await cf.findTunnel(tunnelName(project));
156
+ if (!tunnel) {
157
+ await stopConnector(project);
158
+ removeMeta(project);
159
+ log(`${project}: its tunnel is gone on Cloudflare; removed the local share. Share again with: burrow share ${meta.target} --name ${label}`);
160
+ return 'removed';
161
+ }
162
+ await cf.putTunnelConfig(tunnel.id, ingress);
163
+ const comment = recordComment(project);
164
+ const target = tunnelTarget(tunnel.id);
165
+ const records = await cf.recordsByComment(comment);
166
+ if (!records.some((r) => r.name === meta.hostname && r.type === 'CNAME' && r.content === target)) {
167
+ for (const r of records) await cf.deleteRecord(r.id);
168
+ await cf.createRecord({ type: 'CNAME', name: meta.hostname, content: target, proxied: true, ttl: 1, comment });
169
+ log(`${project}: recreated DNS ${meta.hostname}`);
170
+ }
171
+ await stopConnector(project);
172
+ const pid = startConnector(project, await cf.getTunnelToken(tunnel.id), cfg.cloudflared);
173
+ saveMeta(project, { ...meta, tunnelId: tunnel.id, ownerPid: null });
174
+ ensureExpiryWatcher(project); // e.g. after a reboot: the expiry still applies
175
+ log(`${project}: restarted cloudflared (pid ${pid}) for https://${meta.hostname} -> ${meta.target}`);
176
+ return 'restarted';
177
+ }
178
+
179
+ export async function share(target, opts = {}) {
180
+ const dry = !!opts.dryRun;
181
+ const cfg = loadConfig();
182
+ const url = targetUrl(target);
183
+ const of = shareProject(opts);
184
+ // --domain, else the project's domain:, else BURROW_DOMAIN.
185
+ const domain = opts.domain || of?.proj.domain || cfg.domain;
186
+ if (opts.domain) assertDomain(opts.domain);
187
+ requireConfig(cfg, (dry ? [] : ['token', 'accountId']).concat(domain ? [] : ['domain']));
188
+ const label = opts.name || randomLabel();
189
+ assertLabel(label, 'share name');
190
+ const project = SHARE_PREFIX + label;
191
+ const hostname = `${label}.${domain}`;
192
+ const ingress = [{ hostname, service: url }, { service: 'http_status:404' }];
193
+ const hooks = { enabled: opts.hooks !== false };
194
+ const hookCtx = of && shareHookContext(project, of.file, hostname, of.proj.project);
195
+ const expiresMs = opts.expires === undefined ? null : parseExpires(opts.expires);
196
+ const expiresAt = expiresMs ? new Date(Date.now() + expiresMs).toISOString() : null;
197
+
198
+ if (dry) {
199
+ if (domain !== cfg.domain) log(`[dry-run] would use domain ${domain}${opts.domain ? '' : ` from ${of.file}`} (checking its zone is on the account)`);
200
+ if (hookCtx) await runHook('pre_up', hookCtx, { dry: true, ...hooks });
201
+ log(`[dry-run] would create tunnel ${tunnelName(project)} with ingress ${JSON.stringify(ingress)}`);
202
+ log(`[dry-run] would create DNS CNAME ${hostname} (comment "${recordComment(project)}")`);
203
+ log(`[dry-run] would start cloudflared and share ${url} at https://${hostname}${expiresAt ? ` until ${expiresAt}` : ''}`);
204
+ if (hookCtx) await runHook('post_up', hookCtx, { dry: true, ...hooks });
205
+ return;
206
+ }
207
+ if (readMeta(project)) throw new Error(`Share "${label}" already exists. Remove it with "burrow down ${project}".`);
208
+
209
+ let cf;
210
+ let zoneId = null;
211
+ if (domain === cfg.domain) cf = await client(cfg);
212
+ else {
213
+ const base = new Cloudflare({ token: cfg.token, accountId: cfg.accountId });
214
+ zoneId = await zoneIdFor(base, cfg, domain);
215
+ cf = inZone(base, zoneId);
216
+ }
217
+ if ((await cf.recordsByName(hostname)).length) throw new Error(`${hostname} already has DNS records; pick another --name.`);
218
+ if (hookCtx) await runHook('pre_up', hookCtx, hooks);
219
+ let tunnel;
220
+ try { tunnel = await cf.createTunnel(tunnelName(project), randomBytes(32).toString('base64')); } catch (e) {
221
+ await stopBackground(project);
222
+ throw e;
223
+ }
224
+ saveMeta(project, {
225
+ project, share: true, hostname, target: url, tunnelId: tunnel.id, tunnelName: tunnelName(project),
226
+ hostnames: [hostname], createdAt: new Date().toISOString(), expiresAt,
227
+ // Not `file`: a share is never `burrow up`-able. projectFile gives down its hooks.
228
+ ...(zoneId ? { domain, zoneId } : {}),
229
+ ...(of ? { projectFile: of.file, shareOf: of.proj.project, hooks: hooks.enabled } : {}),
230
+ // A share in the foreground belongs to this process; restart leaves it alone.
231
+ ownerPid: opts.detach ? null : process.pid,
232
+ });
233
+ let pid;
234
+ try {
235
+ await cf.putTunnelConfig(tunnel.id, ingress);
236
+ await cf.createRecord({
237
+ type: 'CNAME', name: hostname, content: tunnelTarget(tunnel.id), proxied: true, ttl: 1, comment: recordComment(project),
238
+ });
239
+ pid = startConnector(project, await cf.getTunnelToken(tunnel.id), cfg.cloudflared);
240
+ } catch (e) {
241
+ await removeShare(project, cf).catch(() => {});
242
+ await stopBackground(project);
243
+ throw e;
244
+ }
245
+ log(`Sharing ${url} at https://${hostname} (cloudflared pid ${pid}, log ${logFile(project)})`);
246
+ if (hookCtx) await runHook('post_up', { ...hookCtx, extra: { ...hookCtx.extra, BURROW_TUNNEL_ID: tunnel.id } }, { ...hooks, soft: true });
247
+ if (expiresAt) log(`Expires at ${expiresAt}${opts.detach ? ' (a background watcher removes it then)' : ''}.`);
248
+ if (opts.detach && expiresAt) ensureExpiryWatcher(project);
249
+ if (opts.detach) {
250
+ log(`Running in the background. Remove it with "burrow down ${project}" (or "burrow down").`);
251
+ return;
252
+ }
253
+ // Register the signal handlers before telling the user to press Ctrl+C. The state file is
254
+ // re-read every 2 s: the dashboard can extend the expiry or ask this process to stop.
255
+ const stopped = new Promise((resolve) => {
256
+ const done = () => { clearInterval(watch); process.off('SIGINT', done); process.off('SIGTERM', done); resolve(); };
257
+ const watch = setInterval(() => {
258
+ if (!runningPid(project)) { log('cloudflared exited.'); done(); return; }
259
+ const why = stopReason(readMeta(project));
260
+ if (why) { log(`Stopping: ${why}.`); done(); }
261
+ }, Number(process.env.BURROW_SHARE_POLL_MS) || 2000);
262
+ process.on('SIGINT', done);
263
+ process.on('SIGTERM', done);
264
+ });
265
+ log('Press Ctrl+C to stop sharing and remove the hostname.');
266
+ await stopped;
267
+ log('Removing share…');
268
+ if (of) {
269
+ const ctx = await beforeDown(project, opts);
270
+ await stopConnector(project);
271
+ await afterDown(project, ctx, opts);
272
+ }
273
+ await removeShare(project, cf);
274
+ log(`Removed https://${hostname}`);
275
+ }
@@ -0,0 +1,284 @@
1
+ // A small, safe reader for POSIX sh command lines, for checks such as `burrow doctor`. It
2
+ // never runs anything: it splits a script into simple commands (at ;, &, &&, ||, | and
3
+ // newlines) and each command into words, honouring '…', "…" and backslash escapes, and
4
+ // skipping redirections. Compound commands are read too:
5
+ // - $(…) and `…` (also inside "…"): the inner commands are returned before the command
6
+ // that uses them, in their own scope (a cd inside doesn't leak out);
7
+ // - ( … ) subshells: their commands, in their own scope; { …; } groups: their commands;
8
+ // - if/then/elif/else/fi, while/until/do/done and for … in …; do … done: the reserved words
9
+ // are dropped and the conditions and bodies returned with depth > 0 (they may not run);
10
+ // - case … in pattern) …;; esac: each arm's commands, with depth > 0.
11
+ // What it doesn't model is reported in `unsupported` so the caller can leave it unchecked:
12
+ // function definitions, unterminated quotes or brackets, redirections without a target.
13
+ // Here-document bodies are skipped (the command itself is still read).
14
+
15
+ const OPERATORS = ['&&', '||', ';;', ';', '&', '|', '\n'];
16
+ const OPENERS = new Set(['if', 'while', 'until']);
17
+ const CLOSERS = new Set(['fi', 'done']);
18
+ const PREFIX_WORDS = new Set(['then', 'else', 'elif', 'do', '!']);
19
+ const SEP = /[\s;&|<>()]/;
20
+
21
+ // Index just past the `)` that closes the `(` before `i`, skipping quotes and escapes; -1 if
22
+ // it never closes.
23
+ function closeParen(src, i) {
24
+ let depth = 1;
25
+ while (i < src.length) {
26
+ const c = src[i];
27
+ if (c === '\\') { i += 2; continue; }
28
+ if (c === "'") { const j = src.indexOf("'", i + 1); if (j < 0) return -1; i = j + 1; continue; }
29
+ if (c === '"') { const j = closeDouble(src, i + 1); if (j < 0) return -1; i = j + 1; continue; }
30
+ if (c === '`') { const j = closeBacktick(src, i + 1); if (j < 0) return -1; i = j + 1; continue; }
31
+ if (c === '#' && (i === 0 || /\s/.test(src[i - 1]))) { while (i < src.length && src[i] !== '\n') i++; continue; }
32
+ if (c === '(') depth++;
33
+ else if (c === ')' && --depth === 0) return i + 1;
34
+ i++;
35
+ }
36
+ return -1;
37
+ }
38
+ // Index of the closing " (from just after the opening one), or -1.
39
+ function closeDouble(src, i) {
40
+ while (i < src.length && src[i] !== '"') {
41
+ if (src[i] === '\\') { i += 2; continue; }
42
+ if (src[i] === '$' && src[i + 1] === '(') { const j = closeParen(src, i + 2); if (j < 0) return -1; i = j; continue; }
43
+ if (src[i] === '`') { const j = closeBacktick(src, i + 1); if (j < 0) return -1; i = j + 1; continue; }
44
+ i++;
45
+ }
46
+ return i < src.length ? i : -1;
47
+ }
48
+ const closeBacktick = (src, i) => { while (i < src.length && src[i] !== '`') i += src[i] === '\\' ? 2 : 1; return i < src.length ? i : -1; };
49
+ const unBacktick = (s) => s.replace(/\\([\\`$])/g, '$1');
50
+ const wordAt = (src, i, w) => src.startsWith(w, i) && (i === 0 || /[\s;&|(]/.test(src[i - 1])) && (i + w.length >= src.length || SEP.test(src[i + w.length]));
51
+
52
+ // Index of the `}` closing a { group whose body starts at i (standalone braces are counted).
53
+ function closeBrace(src, i) {
54
+ let depth = 1;
55
+ while (i < src.length) {
56
+ const c = src[i];
57
+ if (c === '\\') { i += 2; continue; }
58
+ if (c === "'") { const j = src.indexOf("'", i + 1); if (j < 0) return -1; i = j + 1; continue; }
59
+ if (c === '"') { const j = closeDouble(src, i + 1); if (j < 0) return -1; i = j + 1; continue; }
60
+ if (c === '`') { const j = closeBacktick(src, i + 1); if (j < 0) return -1; i = j + 1; continue; }
61
+ if (c === '$' && src[i + 1] === '(') { const j = closeParen(src, i + 2); if (j < 0) return -1; i = j; continue; }
62
+ if (wordAt(src, i, '{')) depth++;
63
+ else if (wordAt(src, i, '}') && --depth === 0) return i;
64
+ i++;
65
+ }
66
+ return -1;
67
+ }
68
+
69
+ // case WORD in [(]pat[|pat]) body ;; … esac, starting just after `case`. -> { arms: [body], end } or null
70
+ function readCase(src, i) {
71
+ const m = /^\s+(?:"[^"]*"|'[^']*'|[^\s;&|<>()]+)\s+in(?=[\s;])/.exec(src.slice(i));
72
+ if (!m) return null;
73
+ i += m[0].length;
74
+ const arms = [];
75
+ for (;;) {
76
+ while (i < src.length && /[\s;]/.test(src[i])) i++;
77
+ if (wordAt(src, i, 'esac')) return { arms, end: i + 4 };
78
+ if (i >= src.length) return null;
79
+ if (src[i] === '(') i++;
80
+ const close = closeParen(src, i);
81
+ if (close < 0) return null;
82
+ i = close;
83
+ // The body runs to ;; or esac at this level (nested case … esac is skipped over).
84
+ const start = i;
85
+ let nest = 0;
86
+ while (i < src.length) {
87
+ const c = src[i];
88
+ if (c === '\\') { i += 2; continue; }
89
+ if (c === "'") { const j = src.indexOf("'", i + 1); if (j < 0) return null; i = j + 1; continue; }
90
+ if (c === '"') { const j = closeDouble(src, i + 1); if (j < 0) return null; i = j + 1; continue; }
91
+ if (c === '$' && src[i + 1] === '(') { const j = closeParen(src, i + 2); if (j < 0) return null; i = j; continue; }
92
+ if (wordAt(src, i, 'case')) nest++;
93
+ if (wordAt(src, i, 'esac')) { if (nest === 0) break; nest--; }
94
+ if (nest === 0 && src.startsWith(';;', i)) break;
95
+ i++;
96
+ }
97
+ arms.push(src.slice(start, i));
98
+ if (src.startsWith(';;', i)) i += 2;
99
+ }
100
+ }
101
+
102
+ // -> [{ words: [{ text, plain, quoted, expands }], unsupported: '<reason>' | null, depth, scope }]
103
+ // (plain: the word's unquoted leading part, used to spot NAME=value; depth: how many
104
+ // if/while/for/case bodies it is inside; scope: '' at the top, another string inside each
105
+ // subshell or command substitution; branchStart: the first command of a then/elif/else/do
106
+ // body or case arm, which starts from the directory the block was entered in; branchKind:
107
+ // 'then' / 'elif' / 'else' / 'do' for it; cond: 'start' for the first command of an
108
+ // if/elif/while/until condition and 'cont' for the rest of it; op: the operator before the
109
+ // command)
110
+ export function parseCommands(script, ctx = { scope: '', depth: 0, ids: { n: 0 } }) {
111
+ const src = String(script ?? '');
112
+ const commands = [];
113
+ let depth = ctx.depth;
114
+ let words = [];
115
+ let unsupported = null;
116
+ let before = []; // commands of $(…) in this command, which run first
117
+ let word = null; // { text, plain, quoted, expands }
118
+ let heredocs = []; // delimiters waiting for the next newline
119
+ let pendingBranch = false; // `then` / `do` / `else` alone: the next command starts the branch
120
+ let pendingKind = null; // which word that was
121
+ let condMode = null; // 'start' / 'cont' while reading the condition of an if / elif / while / until
122
+ let curOp = ''; // the operator (&&, ||, ;, |, &, newline) just before the command being read
123
+ const nested = (text, extra = {}) => parseCommands(text, { ...ctx, depth, ...extra });
124
+ const isolated = (text) => nested(text, { scope: `${ctx.scope}/${++ctx.ids.n}` });
125
+ const flush = () => { if (word) { words.push(word); word = null; } };
126
+ const end = () => {
127
+ flush();
128
+ commands.push(...before); before = [];
129
+ // Reserved words: drop then/do/else/…, and track how deep in blocks we are.
130
+ let opened = false;
131
+ let branch = false;
132
+ let kind = null;
133
+ while (words.length && !words[0].quoted) {
134
+ const t = words[0].text;
135
+ if (PREFIX_WORDS.has(t)) {
136
+ words.shift();
137
+ if (t !== '!') { branch = true; kind = t; }
138
+ if (t === 'elif') condMode = 'start';
139
+ else if (t === 'then' || t === 'do') condMode = null;
140
+ continue;
141
+ }
142
+ if (OPENERS.has(t)) { words.shift(); if (!opened) { depth++; opened = true; } condMode = 'start'; continue; }
143
+ break;
144
+ }
145
+ const head = words[0] && !words[0].quoted ? words[0].text : '';
146
+ if (CLOSERS.has(head)) { words.shift(); depth = Math.max(ctx.depth, depth - 1); }
147
+ else if (head === 'for' || head === 'select') { words = []; depth++; } // the loop header: for NAME [in WORDS]
148
+ if (words.length || unsupported) {
149
+ commands.push({
150
+ words, unsupported, depth, scope: ctx.scope, op: curOp,
151
+ ...(condMode ? { cond: condMode } : {}),
152
+ ...(branch || pendingBranch ? { branchStart: true, branchKind: branch ? kind : pendingKind } : {}),
153
+ });
154
+ if (condMode === 'start') condMode = 'cont';
155
+ curOp = '';
156
+ }
157
+ if (words.length || unsupported) pendingBranch = false; else if (branch) { pendingBranch = true; pendingKind = kind; }
158
+ words = []; unsupported = null;
159
+ };
160
+ const cur = () => (word ||= { text: '', plain: '', quoted: false, expands: false });
161
+ // At the start of a command, possibly after then/do/else/if/while/…
162
+ const atStart = () => !word && words.every((w) => !w.quoted && (PREFIX_WORDS.has(w.text) || OPENERS.has(w.text)));
163
+ let i = 0;
164
+ while (i < src.length) {
165
+ const c = src[i];
166
+ if (c === '\n' && heredocs.length) {
167
+ end(); i++;
168
+ // Skip each here-document body up to its delimiter line.
169
+ for (const { delim, strip } of heredocs) {
170
+ while (i < src.length) {
171
+ let nl = src.indexOf('\n', i); if (nl < 0) nl = src.length;
172
+ const line = src.slice(i, nl); i = nl + 1;
173
+ if ((strip ? line.replace(/^\t+/, '') : line) === delim) break;
174
+ }
175
+ }
176
+ heredocs = [];
177
+ continue;
178
+ }
179
+ if (c === '#' && !word) { while (i < src.length && src[i] !== '\n') i++; continue; }
180
+ if (c === ' ' || c === '\t') { flush(); i++; continue; }
181
+ if (c === '\\') {
182
+ if (src[i + 1] === '\n') { i += 2; continue; }
183
+ cur().text += src[i + 1] ?? ''; word.quoted = true; i += 2; continue;
184
+ }
185
+ if (c === "'") {
186
+ const j = src.indexOf("'", i + 1);
187
+ if (j < 0) { unsupported ||= 'unterminated quote'; i = src.length; continue; }
188
+ cur().text += src.slice(i + 1, j); word.quoted = true; i = j + 1; continue;
189
+ }
190
+ if (c === '"') {
191
+ const close = closeDouble(src, i + 1);
192
+ if (close < 0) { unsupported ||= 'unterminated quote'; i = src.length; continue; }
193
+ let j = i + 1; let text = '';
194
+ while (j < close) {
195
+ if (src[j] === '\\' && '"\\$`\n'.includes(src[j + 1])) { text += src[j + 1]; j += 2; continue; }
196
+ if (src[j] === '$' && src[j + 1] === '(' && src[j + 2] !== '(') {
197
+ const k = closeParen(src, j + 2);
198
+ before.push(...isolated(src.slice(j + 2, k - 1))); cur().expands = true; text += src.slice(j, k); j = k; continue;
199
+ }
200
+ if (src[j] === '`') {
201
+ const k = closeBacktick(src, j + 1);
202
+ before.push(...isolated(unBacktick(src.slice(j + 1, k)))); cur().expands = true; text += src.slice(j, k + 1); j = k + 1; continue;
203
+ }
204
+ if (src[j] === '$') cur().expands = true;
205
+ text += src[j++];
206
+ }
207
+ cur().text += text; word.quoted = true; i = close + 1; continue;
208
+ }
209
+ if (c === '$') {
210
+ if (src[i + 1] === '(') {
211
+ const arith = src[i + 2] === '(';
212
+ const k = closeParen(src, i + 2);
213
+ if (k < 0) { unsupported ||= 'unterminated $('; i = src.length; continue; }
214
+ if (!arith) before.push(...isolated(src.slice(i + 2, k - 1)));
215
+ cur().expands = true; word.text += src.slice(i, k); if (!word.quoted) word.plain += src.slice(i, k); i = k; continue;
216
+ }
217
+ cur().expands = true; cur().text += c; if (!word.quoted) word.plain += c; i++; continue;
218
+ }
219
+ if (c === '`') {
220
+ const k = closeBacktick(src, i + 1);
221
+ if (k < 0) { unsupported ||= 'unterminated `'; i = src.length; continue; }
222
+ before.push(...isolated(unBacktick(src.slice(i + 1, k))));
223
+ cur().expands = true; word.text += src.slice(i, k + 1); i = k + 1; continue;
224
+ }
225
+ if (atStart() && wordAt(src, i, 'case')) {
226
+ const r = readCase(src, i + 4);
227
+ if (!r) { unsupported ||= 'case block it could not read'; i = src.length; continue; }
228
+ for (const arm of r.arms) {
229
+ const cmds = nested(arm, { depth: depth + 1 });
230
+ if (cmds[0]) cmds[0].branchStart = true; // arms are alternatives
231
+ commands.push(...cmds);
232
+ }
233
+ i = r.end; continue;
234
+ }
235
+ const op = OPERATORS.find((o) => src.startsWith(o, i));
236
+ if (op && !(op === '&' && /[<>]$/.test(word?.text || ''))) {
237
+ end();
238
+ // "a &&\n b": the newline continues the list, it doesn't end it.
239
+ if (!(op === '\n' && !words.length && !word && ['&&', '||', '|'].includes(curOp))) curOp = op;
240
+ i += op.length; continue;
241
+ }
242
+ if (c === '(') {
243
+ if (atStart()) {
244
+ const k = closeParen(src, i + 1);
245
+ if (k < 0) { unsupported ||= 'unterminated ('; i = src.length; continue; }
246
+ commands.push(...isolated(src.slice(i + 1, k - 1)));
247
+ i = k; continue;
248
+ }
249
+ // NAME() { …; }: a function definition; its body isn't checked.
250
+ unsupported ||= /^\s*\)/.test(src.slice(i + 1)) ? 'function definition' : 'unexpected (';
251
+ end(); i = src.length; continue;
252
+ }
253
+ if (c === ')') { unsupported ||= 'unexpected )'; i++; continue; }
254
+ if (c === '<' || c === '>') {
255
+ // A redirection: optional fd digits already in `word`, the operator, then its target.
256
+ if (word && /^\d+$/.test(word.text) && !word.quoted) word = null; else flush();
257
+ const heredoc = src.startsWith('<<', i) && src[i + 2] !== '<';
258
+ const strip = heredoc && src[i + 2] === '-';
259
+ while (src[i] === '<' || src[i] === '>' || src[i] === '&' || src[i] === '|' || (heredoc && src[i] === '-')) i++;
260
+ while (src[i] === ' ' || src[i] === '\t') i++;
261
+ // skip the target word (simple form)
262
+ if (/^\d|-/.test(src[i] || '') && src[i - 1] === '&') { while (i < src.length && /[\d-]/.test(src[i])) i++; continue; }
263
+ const start = i;
264
+ while (i < src.length && !SEP.test(src[i])) {
265
+ if (src[i] === "'" || src[i] === '"') { const q = src[i]; const j = src.indexOf(q, i + 1); i = j < 0 ? src.length : j + 1; } else i++;
266
+ }
267
+ if (i === start) unsupported ||= 'redirection without a target';
268
+ else if (heredoc) heredocs.push({ delim: src.slice(start, i).replace(/['"\\]/g, ''), strip });
269
+ continue;
270
+ }
271
+ if (c === '{' && atStart() && /[\s;]|$/.test(src[i + 1] ?? '')) {
272
+ const k = closeBrace(src, i + 1);
273
+ if (k < 0) { unsupported ||= 'unterminated {'; i = src.length; continue; }
274
+ commands.push(...nested(src.slice(i + 1, k)));
275
+ i = k + 1; continue;
276
+ }
277
+ cur().text += c; if (!word.quoted) word.plain += c; i++;
278
+ }
279
+ end();
280
+ return commands;
281
+ }
282
+
283
+ // NAME=value, where NAME= is unquoted (the value may be quoted: FOO="a b").
284
+ export const isAssignment = (w) => /^[A-Za-z_][A-Za-z0-9_]*=/.test(w.plain ?? w.text);