tina4-nodejs 3.13.151 → 3.13.152

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.
@@ -9,15 +9,15 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
9
9
  import { initProject } from "./commands/init.js";
10
10
  import { serveProject } from "./commands/serve.js";
11
11
  import { runMigrations } from "./commands/migrate.js";
12
- import { createMigration } from "./commands/migrateCreate.js";
12
+ import { createMigration, MIGRATE_CREATE_FLAGS } from "./commands/migrateCreate.js";
13
13
  import { migrateStatus } from "./commands/migrateStatus.js";
14
14
  import { migrateRollback } from "./commands/migrateRollback.js";
15
15
  import { listRoutes } from "./commands/routes.js";
16
16
  import { runTests } from "./commands/test.js";
17
17
  import { runLint } from "./commands/lint.js";
18
- import { generate, GENERATORS, RESOLUTION_ENVELOPE_VERSION } from "./commands/generate.js";
18
+ import { generate, GENERATORS, RESOLUTION_ENVELOPE_VERSION, RESOLUTION_FLAGS } from "./commands/generate.js";
19
19
  import { runSeeds } from "./commands/seed.js";
20
- import { queueCommand, QUEUE_SUBCOMMAND_NAMES } from "./commands/queue.js";
20
+ import { queueCommand, QUEUE_FLAGS, QUEUE_SUBCOMMAND_NAMES } from "./commands/queue.js";
21
21
  import { buildImage } from "./commands/build.js";
22
22
  import { spawnSync } from "node:child_process";
23
23
  import { existsSync, readFileSync } from "node:fs";
@@ -246,8 +246,7 @@ function printHelp(): void {
246
246
  " --no-browser Don't open the browser on serve",
247
247
  " --no-reload Disable file watcher / live-reload on serve",
248
248
  " --all Install AI context for all tools (with ai command)",
249
- " --force Overwrite existing AI context files (with ai command)",
250
- " --help Show this help message",
249
+ " --help, -h Show this help, or one command's usage (tina4nodejs <command> --help)",
251
250
  "",
252
251
  " https://tina4.com",
253
252
  "",
@@ -291,7 +290,9 @@ async function openConsole(): Promise<void> {
291
290
 
292
291
  async function installAiContext(args: string[]): Promise<void> {
293
292
  const { showMenu, installSelected, installAll } = await import("../../core/src/ai.js");
294
- const root = args[0] || ".";
293
+ // The project root is the first positional; `--all` is a switch, never the
294
+ // root (it used to be taken as one, installing into a folder named `--all`).
295
+ const root = args.find((a) => !a.startsWith("-")) || ".";
295
296
 
296
297
  if (args.includes("--all")) {
297
298
  installAll(root);
@@ -314,6 +315,8 @@ async function installAiContext(args: string[]): Promise<void> {
314
315
  // COMMANDS[name] = {
315
316
  // handler: (cmdArgs) => …, // args AFTER the command name
316
317
  // summary: string,
318
+ // flags?: {name: boolean}, // options main() accepts; true = takes a value.
319
+ // // Absent = none. null = not checked.
317
320
  // usage?: string, // arg/flag hint for printHelp (human only)
318
321
  // args?: string[], // positional args for the manifest ("x?" = optional)
319
322
  // subcommands?: string[], // sub-names for the manifest (generate)
@@ -322,11 +325,23 @@ async function installAiContext(args: string[]): Promise<void> {
322
325
  export interface CommandSpec {
323
326
  handler: (cmdArgs: string[]) => void | Promise<void>;
324
327
  summary: string;
328
+ /** Options main() accepts (name -> takes a value). Absent = none; null = not checked. */
329
+ flags?: OptionMap | null;
325
330
  usage?: string;
326
331
  args?: string[];
327
332
  subcommands?: string[];
328
333
  }
329
334
 
335
+ /** Option name (without `--`) -> whether it takes a value. */
336
+ export type OptionMap = Record<string, boolean>;
337
+
338
+ const SERVE_FLAGS: OptionMap = {
339
+ port: true, "no-browser": false, "no-reload": false, "no-kill": false,
340
+ // Not read by serve, but the Dockerfile `init` scaffolds runs
341
+ // `tina4nodejs serve --production`, so refusing it would break every image.
342
+ production: false,
343
+ };
344
+
330
345
  export const COMMANDS: Record<string, CommandSpec> = {
331
346
  init: {
332
347
  handler: async (a) => { await initProject(a[0] || "."); },
@@ -347,6 +362,7 @@ export const COMMANDS: Record<string, CommandSpec> = {
347
362
  await killProcessOnPort(port);
348
363
  await serveProject({ port, noBrowser, noReload });
349
364
  },
365
+ flags: SERVE_FLAGS,
350
366
  usage: "[--port P] [--no-browser] [--no-reload]",
351
367
  summary: "Start the dev server with hot-reload (default: 0.0.0.0:7148)",
352
368
  },
@@ -359,6 +375,7 @@ export const COMMANDS: Record<string, CommandSpec> = {
359
375
  // reaches the same envelope machinery as `generate migration ...` (ADR-0063).
360
376
  // The delegation itself lives in commands/migrateCreate.ts.
361
377
  handler: async (a) => { await createMigration(a); },
378
+ flags: MIGRATE_CREATE_FLAGS,
362
379
  usage: "<desc>",
363
380
  args: ["description"],
364
381
  summary: "Create a new migration file (delegates to generate migration)",
@@ -382,6 +399,7 @@ export const COMMANDS: Record<string, CommandSpec> = {
382
399
  },
383
400
  lint: {
384
401
  handler: (a) => { runLint(a); },
402
+ flags: { fix: false, "no-install": false },
385
403
  usage: "[--fix] [--no-install]",
386
404
  summary: "Lint the project (eslint, installed dev-only on demand; else tsc/node --check baseline)",
387
405
  },
@@ -393,6 +411,7 @@ export const COMMANDS: Record<string, CommandSpec> = {
393
411
  },
394
412
  build: {
395
413
  handler: (a) => { buildImage(a); },
414
+ flags: { tag: true, file: true },
396
415
  usage: "[--tag NAME] [--file PATH]",
397
416
  summary: "Build the deployable Docker image",
398
417
  },
@@ -413,16 +432,20 @@ export const COMMANDS: Record<string, CommandSpec> = {
413
432
  },
414
433
  ai: {
415
434
  handler: async (a) => { await installAiContext(a); },
435
+ flags: { all: false },
416
436
  usage: "[--all]",
417
437
  summary: "Install AI coding assistant context files",
418
438
  },
419
439
  commands: {
420
440
  handler: (a) => { runCommands(a); },
441
+ flags: { json: false },
421
442
  usage: "[--json]",
422
443
  summary: "List available commands (add --json for the machine manifest)",
423
444
  },
424
445
  help: {
425
446
  handler: () => { printHelp(); },
447
+ // Not option-checked: `help --help` / `help -h` print the reference too.
448
+ flags: null,
426
449
  summary: "Show this help message",
427
450
  },
428
451
  };
@@ -540,8 +563,157 @@ export function delegateToClient(command: string, args: string[]): number {
540
563
  return result.status ?? EXIT_CLIENT_UNAVAILABLE;
541
564
  }
542
565
 
566
+ // ── Per-command help and option checking ────────────────────────────
567
+
568
+ const HELP_FLAGS = ["--help", "-h"];
569
+
570
+ /** Usage for one command (or one generator), from the same registries. */
571
+ function printCommandHelp(command: string, args: string[]): void {
572
+ if (command === "generate") {
573
+ const kind = args.find((a) => !a.startsWith("-"))?.toLowerCase();
574
+ const gen = kind ? GENERATORS[kind] : undefined;
575
+ if (gen) {
576
+ console.log(`Usage: tina4nodejs generate ${kind} ${gen.usage}`.trimEnd());
577
+ console.log(`\n ${gen.summary}`);
578
+ return;
579
+ }
580
+ console.log("Usage: tina4nodejs generate <what> <name> [options]\n\nGenerators:");
581
+ const pad = Math.max(...Object.keys(GENERATORS).map((n) => n.length));
582
+ for (const [name, g] of Object.entries(GENERATORS)) console.log(` ${name.padEnd(pad)} ${g.summary}`);
583
+ return;
584
+ }
585
+ const spec = COMMANDS[command];
586
+ console.log(`Usage: tina4nodejs ${command} ${spec.usage ?? ""}`.trimEnd());
587
+ console.log(`\n ${spec.summary}`);
588
+ if (spec.subcommands?.length) console.log(` Subcommands: ${spec.subcommands.join(", ")}`);
589
+ }
590
+
591
+ /**
592
+ * The options `command` accepts, or null when its arguments are not ours to
593
+ * check (an unknown generator or queue subcommand is reported by its own handler).
594
+ */
595
+ export function acceptedOptions(command: string, args: string[]): OptionMap | null {
596
+ const sub = (args[0] ?? "").toLowerCase();
597
+ if (command === "generate") {
598
+ const gen = GENERATORS[sub];
599
+ return gen ? { ...gen.flags, ...RESOLUTION_FLAGS } : null;
600
+ }
601
+ if (command === "queue") return QUEUE_FLAGS[sub] ?? null;
602
+ const flags = COMMANDS[command].flags;
603
+ return flags === undefined ? {} : flags;
604
+ }
605
+
606
+ /** Optimal-string-alignment distance: Levenshtein plus adjacent transposition. */
607
+ function editDistance(a: string, b: string): number {
608
+ const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
609
+ for (let j = 1; j <= b.length; j++) d[0][j] = j;
610
+ for (let i = 1; i <= a.length; i++) {
611
+ for (let j = 1; j <= b.length; j++) d[i][j] = distanceCell(d, a, b, i, j);
612
+ }
613
+ return d[a.length][b.length];
614
+ }
615
+
616
+ /** One cell of the editDistance table: delete, insert, substitute, or swap two neighbours. */
617
+ function distanceCell(d: number[][], a: string, b: string, i: number, j: number): number {
618
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
619
+ const best = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
620
+ const swapped = i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1];
621
+ return swapped ? Math.min(best, d[i - 2][j - 2] + 1) : best;
622
+ }
623
+
624
+ /** The accepted option closest to `name`, when it is close enough to be a typo. */
625
+ export function closestOption(name: string, accepted: string[]): string | null {
626
+ let best: string | null = null;
627
+ let bestDistance = Math.max(1, Math.floor(name.length / 3)) + 1;
628
+ for (const option of accepted) {
629
+ const distance = editDistance(name, option);
630
+ if (distance < bestDistance) {
631
+ best = option;
632
+ bestDistance = distance;
633
+ }
634
+ }
635
+ return best;
636
+ }
637
+
638
+ /** The did-you-mean text for an option `label` doesn't have. */
639
+ function unknownOptionMessage(option: string, name: string, accepted: OptionMap, label: string): string {
640
+ const close = closestOption(name, Object.keys(accepted));
641
+ return `Unknown option ${option} for "${label}".${close ? ` Did you mean --${close}?` : ""}\n`
642
+ + `Run "tina4nodejs ${label} --help" for its options.`;
643
+ }
644
+
645
+ /**
646
+ * Judge the argument at `i`: the refusal message (or null when it is fine) and
647
+ * how many arguments it used - 2 for a value option spelled `--name value`.
648
+ */
649
+ export function optionProblem(args: string[], i: number, accepted: OptionMap, label: string): [string | null, number] {
650
+ const arg = args[i];
651
+ if (!arg.startsWith("-") || arg === "-") return [null, 1];
652
+ const [option, inlineValue] = splitOption(arg);
653
+ const name = option.replace(/^-+/, "");
654
+ if (!isAccepted(option, name, accepted)) {
655
+ return [unknownOptionMessage(option, name, accepted, label), 1];
656
+ }
657
+ if (inlineValue || !accepted[name]) return [null, 1];
658
+ if (!hasValueAfter(args, i)) {
659
+ return [`Option --${name} for "${label}" needs a value: --${name} <value>`, 1];
660
+ }
661
+ return [null, 2];
662
+ }
663
+
664
+ /** A `--long` option the command declares (single-dash options never are, except -h). */
665
+ function isAccepted(option: string, name: string, accepted: OptionMap): boolean {
666
+ return option.startsWith("--") && Object.hasOwn(accepted, name);
667
+ }
668
+
669
+ /** `--name=value` -> ["--name", true]; `--name` -> ["--name", false]. */
670
+ function splitOption(arg: string): [string, boolean] {
671
+ const eq = arg.indexOf("=");
672
+ return eq === -1 ? [arg, false] : [arg.slice(0, eq), true];
673
+ }
674
+
675
+ /** True when the argument after `i` exists and is not itself an option. */
676
+ function hasValueAfter(args: string[], i: number): boolean {
677
+ return i + 1 < args.length && !args[i + 1].startsWith("-");
678
+ }
679
+
680
+ /**
681
+ * Refuse an option the command doesn't have, or a value option given no value.
682
+ * Both used to slip through: `--feilds` was silently dropped (the model came
683
+ * out without its fields) and a bare `--fields` became the value `true`.
684
+ */
685
+ function checkOptions(command: string, args: string[]): void {
686
+ const accepted = acceptedOptions(command, args);
687
+ if (accepted === null) return;
688
+ const label = command === "generate" || command === "queue" ? `${command} ${args[0].toLowerCase()}` : command;
689
+ for (let i = 0; i < args.length;) {
690
+ const [problem, consumed] = optionProblem(args, i, accepted, label);
691
+ if (problem) {
692
+ console.log(problem);
693
+ process.exit(1);
694
+ }
695
+ i += consumed;
696
+ }
697
+ }
698
+
543
699
  // ── Dispatch ────────────────────────────────────────────────────────
544
700
 
701
+ /**
702
+ * Run one registered command. `--help` / `-h` anywhere after it prints that
703
+ * command's usage and touches nothing. Handlers never looked for it, so it ran
704
+ * the command for real: `generate model --help` wrote a model named `--help`,
705
+ * `ai --help` installed into a folder named `--help`. Delegated commands never
706
+ * get here - the client answers --help itself.
707
+ */
708
+ async function runCommand(command: string, spec: CommandSpec, cmdArgs: string[]): Promise<void> {
709
+ if (command !== "help" && cmdArgs.some((a) => HELP_FLAGS.includes(a))) {
710
+ printCommandHelp(command, cmdArgs);
711
+ return;
712
+ }
713
+ checkOptions(command, cmdArgs);
714
+ await spec.handler(cmdArgs);
715
+ }
716
+
545
717
  async function main(): Promise<void> {
546
718
  const args = process.argv.slice(2);
547
719
  let command = args[0];
@@ -554,7 +726,7 @@ async function main(): Promise<void> {
554
726
 
555
727
  const spec = COMMANDS[command];
556
728
  if (spec) {
557
- await spec.handler(cmdArgs);
729
+ await runCommand(command, spec, cmdArgs);
558
730
  return;
559
731
  }
560
732
 
@@ -645,29 +645,41 @@ function isoNow(): string {
645
645
 
646
646
  export interface GeneratorSpec {
647
647
  handler: (name: string, flags: Record<string, string | boolean>) => void;
648
+ /**
649
+ * Options this generator reads (name -> takes a value), checked by bin.ts
650
+ * main() before the handler runs. RESOLUTION_FLAGS are added on top.
651
+ */
652
+ flags: Record<string, boolean>;
648
653
  /** Arg/flag hint shown in `tina4nodejs help` (human only). */
649
654
  usage: string;
650
655
  summary: string;
651
656
  }
652
657
 
653
658
  export const GENERATORS: Record<string, GeneratorSpec> = {
654
- model: { handler: generateModel, usage: '<Name> [--fields "name:string,price:float"] [--table-name <name>]', summary: "ORM model + matching migration" },
655
- route: { handler: generateRoute, usage: "<name> [--model Name] [--public]", summary: "CRUD route file, secure by default (--public opens writes)" },
656
- crud: { handler: generateCrud, usage: '<Name> [--fields "..."] [--public] [--no-templates]', summary: "Model + migration + AutoCrud-backed admin page (toCrud) + editable crud/ templates + gate test" },
657
- migration: { handler: (n, f) => generateMigration(n, f, undefined, undefined, !f["no-test"]), usage: "<description>", summary: "Timestamped migration file (UP/DOWN)" },
658
- middleware: { handler: generateMiddleware, usage: "<Name>", summary: "Middleware with before/after hooks" },
659
- test: { handler: generateTest, usage: "<name> [--model Name]", summary: "Test file" },
660
- form: { handler: generateForm, usage: '<Name> [--fields "..."]', summary: "Form template with inputs matching model fields" },
661
- view: { handler: generateView, usage: '<Name> [--fields "..."]', summary: "List + detail view templates" },
662
- auth: { handler: (_n, f) => generateAuth(f), usage: "", summary: "Login/register routes (public) + User model + templates" },
663
- service: { handler: generateService, usage: '<Name> [--every 5m | --cron "..."]', summary: "Scheduled ServiceRunner task (src/services/)" },
664
- queue: { handler: generateQueue, usage: "<topic>", summary: "Producer + consumer daemon worker (src/services/)" },
665
- validator: { handler: generateValidator, usage: "<Name>", summary: "Request-body Validator (src/validators/)" },
666
- seeder: { handler: generateSeeder, usage: "<Model>", summary: "FakeData + seedOrm seeder (src/seeds/)" },
667
- websocket: { handler: generateWebsocket, usage: "<path>", summary: "websocket() handler (src/routes/)" },
668
- listener: { handler: generateListener, usage: "<event>", summary: "Events.on(event) listener (src/listeners/)" },
659
+ model: { handler: generateModel, flags: { fields: true, "table-name": true, "no-migration": false }, usage: '<Name> [--fields "name:string,price:float"] [--table-name <name>]', summary: "ORM model + matching migration" },
660
+ route: { handler: generateRoute, flags: { model: true, public: false, "table-name": true }, usage: "<name> [--model Name] [--public]", summary: "CRUD route file, secure by default (--public opens writes)" },
661
+ crud: { handler: generateCrud, flags: { fields: true, "table-name": true, public: false, "no-templates": false, "no-migration": false, "skip-model": false }, usage: '<Name> [--fields "..."] [--public] [--no-templates] [--skip-model]', summary: "Model + migration + AutoCrud-backed admin page (toCrud) + editable crud/ templates + gate test" },
662
+ migration: { handler: (n, f) => generateMigration(n, f, undefined, undefined, !f["no-test"]), flags: { fields: true, "table-name": true, "no-test": false }, usage: "<description>", summary: "Timestamped migration file (UP/DOWN)" },
663
+ middleware: { handler: generateMiddleware, flags: {}, usage: "<Name>", summary: "Middleware with before/after hooks" },
664
+ test: { handler: generateTest, flags: { model: true, public: false, "secure-writes": false }, usage: "<name> [--model Name]", summary: "Test file" },
665
+ form: { handler: generateForm, flags: { fields: true, "table-name": true }, usage: '<Name> [--fields "..."]', summary: "Form template with inputs matching model fields" },
666
+ view: { handler: generateView, flags: { fields: true, "table-name": true }, usage: '<Name> [--fields "..."]', summary: "List + detail view templates" },
667
+ auth: { handler: (_n, f) => generateAuth(f), flags: {}, usage: "", summary: "Login/register routes (public) + User model + templates" },
668
+ service: { handler: generateService, flags: { every: true, cron: true }, usage: '<Name> [--every 5m | --cron "..."]', summary: "Scheduled ServiceRunner task (src/services/)" },
669
+ queue: { handler: generateQueue, flags: {}, usage: "<topic>", summary: "Producer + consumer daemon worker (src/services/)" },
670
+ validator: { handler: generateValidator, flags: {}, usage: "<Name>", summary: "Request-body Validator (src/validators/)" },
671
+ seeder: { handler: generateSeeder, flags: { "table-name": true }, usage: "<Model>", summary: "FakeData + seedOrm seeder (src/seeds/)" },
672
+ websocket: { handler: generateWebsocket, flags: {}, usage: "<path>", summary: "websocket() handler (src/routes/)" },
673
+ listener: { handler: generateListener, flags: {}, usage: "<event>", summary: "Events.on(event) listener (src/listeners/)" },
669
674
  };
670
675
 
676
+ /**
677
+ * Options every generator accepts on top of its own: the resolution envelope
678
+ * (`--json`) and the write-nothing preview (`--dry-run`) are honoured by every
679
+ * generator here, because writes go through the shared ensureDir/writeFileSafe.
680
+ */
681
+ export const RESOLUTION_FLAGS: Record<string, boolean> = { json: false, "dry-run": false };
682
+
671
683
  /** Comma-separated generator names for usage/error output — derived, never a hand-kept list. */
672
684
  const GENERATOR_LIST = Object.keys(GENERATORS).join(", ");
673
685
 
@@ -797,6 +809,12 @@ export async function generate(what: string, name: string, extraArgs: string[] =
797
809
  extraArgs = [name, ...extraArgs];
798
810
  name = "";
799
811
  }
812
+ // A name that is really a mistyped option (`generate model --fields x`, the
813
+ // name forgotten) would otherwise become a file called `--fields`.
814
+ if (GENERATORS[what] && !noNameGenerators.has(what) && name.startsWith("-")) {
815
+ console.log(`Invalid ${what} name: '${name}' - names can't start with '-'.`);
816
+ process.exit(1);
817
+ }
800
818
  if (!noNameGenerators.has(what) && !name) {
801
819
  console.error(` Usage: tina4nodejs generate ${what} <name> [options]`);
802
820
  process.exit(1);
@@ -1243,8 +1261,9 @@ function generateCrud(name: string, flags: Record<string, string | boolean>): vo
1243
1261
  if (!__resolution.jsonMode) console.log(`\n Generating CRUD for ${name}...\n`);
1244
1262
 
1245
1263
  // 1. Model + migration (its own model test is suppressed — the gate test
1246
- // below is CRUD's single, broader co-emitted test).
1247
- generateModel(name, flags, false);
1264
+ // below is CRUD's single, broader co-emitted test). --skip-model builds
1265
+ // the CRUD around a model that already exists.
1266
+ if (!flags["skip-model"]) generateModel(name, flags, false);
1248
1267
 
1249
1268
  // 2. Admin page route: registers AutoCrud (secure-by-default; --public opens
1250
1269
  // writes) and renders the toCrud admin UI at /admin/<table>.
@@ -28,15 +28,27 @@ file, You can obtain one at https://mozilla.org/MPL/2.0/.
28
28
  */
29
29
  import { generate } from "./generate.js";
30
30
 
31
+ /** Options migrate:create accepts (name -> takes a value), checked by bin.ts main(). */
32
+ export const MIGRATE_CREATE_FLAGS: Record<string, boolean> = {
33
+ fields: true, "table-name": true, json: false, "dry-run": false,
34
+ };
35
+
31
36
  export async function createMigration(args: string[] = []): Promise<void> {
32
37
  // Split flags from the description so `tina4 migrate:create "add users"
33
38
  // --json --dry-run` reaches the same envelope machinery as its
34
39
  // `tina4 generate migration` twin (see test/migrateCreateEnvelopeParity.test.ts).
40
+ // A value option keeps its value: `--fields name:string` must not fold
41
+ // `name:string` into the description.
35
42
  const positionals: string[] = [];
36
43
  const flags: string[] = [];
37
- for (const arg of args) {
38
- if (arg.startsWith("--")) flags.push(arg);
39
- else positionals.push(arg);
44
+ for (let i = 0; i < args.length; i++) {
45
+ const arg = args[i];
46
+ if (arg.startsWith("--")) {
47
+ flags.push(arg);
48
+ if (!arg.includes("=") && MIGRATE_CREATE_FLAGS[arg.slice(2)] && i + 1 < args.length) flags.push(args[++i]);
49
+ } else {
50
+ positionals.push(arg);
51
+ }
40
52
  }
41
53
  const description = positionals.join(" ").trim();
42
54
 
@@ -275,6 +275,14 @@ const QUEUE_SUBCOMMANDS: Record<string, (args: string[]) => Promise<void>> = {
275
275
  clear: queueClear,
276
276
  };
277
277
 
278
+ /** Options per queue subcommand (name -> takes a value), checked by bin.ts main(). */
279
+ export const QUEUE_FLAGS: Record<string, Record<string, boolean>> = {
280
+ work: { once: false, poll: true, services: true },
281
+ stats: { json: false },
282
+ retry: {},
283
+ clear: {},
284
+ };
285
+
278
286
  /** Subcommand names, in order — surfaced in `commands --json` for the tina4 client. */
279
287
  export const QUEUE_SUBCOMMAND_NAMES = Object.keys(QUEUE_SUBCOMMANDS);
280
288
 
@@ -20,7 +20,8 @@ export interface ParsedFlags {
20
20
  }
21
21
 
22
22
  /**
23
- * Parse `--key value` and bare `--flag` arguments into flags plus positionals.
23
+ * Parse `--key value`, `--key=value` and bare `--flag` arguments into flags
24
+ * plus positionals.
24
25
  *
25
26
  * A name listed in `booleanFlags` never consumes the next token; every other
26
27
  * `--key` takes the following token as its value unless that token is itself a
@@ -31,27 +32,36 @@ export function parseFlags(args: string[], booleanFlags?: ReadonlySet<string>):
31
32
  const positional: string[] = [];
32
33
  let i = 0;
33
34
  while (i < args.length) {
34
- const arg = args[i];
35
- if (arg.startsWith("--")) {
36
- const key = arg.slice(2);
37
- if (booleanFlags?.has(key)) {
38
- flags[key] = true;
39
- i += 1;
40
- } else if (i + 1 < args.length && !args[i + 1].startsWith("--")) {
41
- flags[key] = args[i + 1];
42
- i += 2;
43
- } else {
44
- flags[key] = true;
45
- i += 1;
46
- }
35
+ if (args[i].startsWith("--")) {
36
+ i += readFlag(args, i, flags, booleanFlags);
47
37
  } else {
48
- positional.push(arg);
38
+ positional.push(args[i]);
49
39
  i += 1;
50
40
  }
51
41
  }
52
42
  return { flags, positional };
53
43
  }
54
44
 
45
+ /** Store the `--flag` at `i` into `flags`; returns how many arguments it used. */
46
+ function readFlag(
47
+ args: string[], i: number, flags: Record<string, string | boolean>, booleanFlags?: ReadonlySet<string>,
48
+ ): number {
49
+ const arg = args[i];
50
+ const eq = arg.indexOf("=");
51
+ if (eq !== -1) {
52
+ flags[arg.slice(2, eq)] = arg.slice(eq + 1);
53
+ return 1;
54
+ }
55
+ const key = arg.slice(2);
56
+ const next = args[i + 1];
57
+ if (!booleanFlags?.has(key) && next !== undefined && !next.startsWith("--")) {
58
+ flags[key] = next;
59
+ return 2;
60
+ }
61
+ flags[key] = true;
62
+ return 1;
63
+ }
64
+
55
65
  /**
56
66
  * Absolute path of the first of `names` found on PATH, or null.
57
67
  *