@orkestrel/scaffold 0.0.133 → 0.0.135

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 (92) hide show
  1. package/dist/agents/skills/orkestrel-dispatch/scripts/bench.js +61 -96
  2. package/dist/agents/skills/orkestrel-dispatch/scripts/brief.js +48 -76
  3. package/dist/agents/skills/orkestrel-dispatch/scripts/chain.js +27 -66
  4. package/dist/agents/skills/orkestrel-dispatch/scripts/cite.js +31 -64
  5. package/dist/agents/skills/orkestrel-dispatch/scripts/launch.js +43 -57
  6. package/dist/agents/skills/orkestrel-dispatch/scripts/login.js +43 -86
  7. package/dist/agents/skills/orkestrel-dispatch/scripts/patch.js +68 -104
  8. package/dist/agents/skills/orkestrel-dispatch/scripts/result.js +35 -69
  9. package/dist/agents/skills/orkestrel-dispatch/scripts/sweep.js +47 -84
  10. package/dist/agents/skills/orkestrel-falsify/scripts/mutate.js +134 -116
  11. package/dist/agents/skills/orkestrel-harden/scripts/discovery.js +38 -90
  12. package/dist/agents/skills/orkestrel-harden/scripts/interleave.js +39 -103
  13. package/dist/agents/skills/orkestrel-harden/scripts/measure.js +40 -89
  14. package/dist/agents/skills/orkestrel-harden/scripts/titles.js +41 -87
  15. package/dist/agents/skills/orkestrel-parallel/scripts/cases.js +43 -88
  16. package/dist/agents/skills/orkestrel-parallel/scripts/lane.js +1568 -213
  17. package/dist/agents/skills/orkestrel-publish/scripts/compare.js +40 -60
  18. package/dist/agents/skills/orkestrel-publish/scripts/pins.js +47 -81
  19. package/dist/agents/skills/orkestrel-publish/scripts/steps.js +66 -104
  20. package/dist/agents/skills/orkestrel-publish/scripts/swap.js +74 -88
  21. package/dist/agents/skills/orkestrel-publish/scripts/wave.js +387 -109
  22. package/dist/agents/skills/orkestrel-publish/scripts/window.js +55 -96
  23. package/dist/agents/skills/orkestrel-scout/scripts/map.js +54 -101
  24. package/dist/bin/main.js +275 -33
  25. package/dist/bin/main.js.map +1 -1
  26. package/dist/host/AGENTS.md +1 -1
  27. package/dist/host/agents/skills/orkestrel-dispatch/scripts/bench.ts +81 -97
  28. package/dist/host/agents/skills/orkestrel-dispatch/scripts/brief.ts +64 -72
  29. package/dist/host/agents/skills/orkestrel-dispatch/scripts/chain.ts +41 -63
  30. package/dist/host/agents/skills/orkestrel-dispatch/scripts/cite.ts +56 -79
  31. package/dist/host/agents/skills/orkestrel-dispatch/scripts/launch.ts +61 -74
  32. package/dist/host/agents/skills/orkestrel-dispatch/scripts/login.ts +59 -89
  33. package/dist/host/agents/skills/orkestrel-dispatch/scripts/patch.ts +87 -106
  34. package/dist/host/agents/skills/orkestrel-dispatch/scripts/result.ts +57 -76
  35. package/dist/host/agents/skills/orkestrel-dispatch/scripts/sweep.ts +73 -88
  36. package/dist/host/agents/skills/orkestrel-falsify/SKILL.md +2 -2
  37. package/dist/host/agents/skills/orkestrel-falsify/scripts/mutate.ts +167 -119
  38. package/dist/host/agents/skills/orkestrel-harden/references/methods.md +1 -1
  39. package/dist/host/agents/skills/orkestrel-harden/scripts/discovery.ts +58 -75
  40. package/dist/host/agents/skills/orkestrel-harden/scripts/interleave.ts +55 -99
  41. package/dist/host/agents/skills/orkestrel-harden/scripts/measure.ts +59 -90
  42. package/dist/host/agents/skills/orkestrel-harden/scripts/titles.ts +60 -80
  43. package/dist/host/agents/skills/orkestrel-parallel/SKILL.md +4 -4
  44. package/dist/host/agents/skills/orkestrel-parallel/scripts/cases.ts +71 -108
  45. package/dist/host/agents/skills/orkestrel-parallel/scripts/lane.ts +1990 -274
  46. package/dist/host/agents/skills/orkestrel-publish/references/release.md +1 -0
  47. package/dist/host/agents/skills/orkestrel-publish/references/wave.md +28 -7
  48. package/dist/host/agents/skills/orkestrel-publish/scripts/compare.ts +58 -79
  49. package/dist/host/agents/skills/orkestrel-publish/scripts/pins.ts +66 -87
  50. package/dist/host/agents/skills/orkestrel-publish/scripts/steps.ts +84 -102
  51. package/dist/host/agents/skills/orkestrel-publish/scripts/swap.ts +92 -99
  52. package/dist/host/agents/skills/orkestrel-publish/scripts/wave.ts +483 -127
  53. package/dist/host/agents/skills/orkestrel-publish/scripts/window.ts +82 -120
  54. package/dist/host/agents/skills/orkestrel-scout/SKILL.md +3 -3
  55. package/dist/host/agents/skills/orkestrel-scout/scripts/map.ts +85 -112
  56. package/dist/host/claude/agents/orkestrel.md +16 -16
  57. package/dist/host/claude/rules/architecture.md +1 -1
  58. package/dist/host/claude/rules/documentation.md +1 -1
  59. package/dist/host/claude/rules/patterns.md +7 -4
  60. package/dist/host/claude/rules/styles.md +1 -1
  61. package/dist/host/claude/rules/tests.md +3 -3
  62. package/dist/host/claude/rules/workspace.md +50 -37
  63. package/dist/host/configs/helpers.ts +117 -71
  64. package/dist/host/dotfiles/oxlintrc.json +6 -0
  65. package/dist/host/guides/agent.md +989 -395
  66. package/dist/host/guides/database.md +357 -342
  67. package/dist/host/guides/form.md +79 -4
  68. package/dist/host/guides/middleware.md +5 -5
  69. package/dist/host/guides/ollama.md +41 -42
  70. package/dist/host/guides/scaffold.md +170 -70
  71. package/dist/host/guides/study.md +12 -12
  72. package/dist/host/guides/table.md +20 -6
  73. package/dist/host/guides/test.md +166 -52
  74. package/dist/host/guides/toolbox.md +127 -81
  75. package/dist/host/guides/workspace.md +21 -14
  76. package/dist/host/manifest.json +54 -54
  77. package/dist/host/tests/config.test.ts +251 -7
  78. package/dist/host/tests/policy.test.ts +14 -21
  79. package/dist/host/tests/setupPolicy.ts +43 -36
  80. package/dist/src/core/index.cjs +533 -139
  81. package/dist/src/core/index.cjs.map +1 -1
  82. package/dist/src/core/index.d.cts +223 -16
  83. package/dist/src/core/index.d.ts +223 -16
  84. package/dist/src/core/index.js +524 -139
  85. package/dist/src/core/index.js.map +1 -1
  86. package/dist/src/server/index.cjs +23 -14
  87. package/dist/src/server/index.cjs.map +1 -1
  88. package/dist/src/server/index.d.cts +3 -2
  89. package/dist/src/server/index.d.ts +3 -2
  90. package/dist/src/server/index.js +24 -15
  91. package/dist/src/server/index.js.map +1 -1
  92. package/package.json +2 -2
@@ -15,12 +15,16 @@
15
15
  // acceptance line, stops at the first refusal and names the package to resume from, then confirms
16
16
  // each accepted version against the registry. --confirm re-reads the registry for each name@version every 5
17
17
  // seconds until it serves the version or the wait (default 120 seconds) ends. Exit 0 when the mode
18
- // succeeded, 3 when it did not, 64 on usage, including a flag the script does not read and the
19
- // `--flag=value` form.
18
+ // succeeded, 3 when it did not, 64 on usage. The script reads its flags with `parseArgs` in strict
19
+ // mode, and takes the directories of --publish and the targets of --confirm as its positional
20
+ // arguments.
21
+ import type { ParseArgsOptionsConfig } from 'node:util'
20
22
  import type { SpawnSyncReturns } from 'node:child_process'
21
23
  import { spawnSync } from 'node:child_process'
22
24
  import { existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs'
25
+ import { setTimeout } from 'node:timers/promises'
23
26
  import { dirname, join, resolve } from 'node:path'
27
+ import { parseArgs } from 'node:util'
24
28
 
25
29
  /** Holds the milliseconds between two polls of the registry. */
26
30
  export const POLL_MS = 5_000
@@ -28,21 +32,54 @@ export const POLL_MS = 5_000
28
32
  /** Matches the acceptance line `npm publish` prints and captures the name and the version. */
29
33
  export const ACCEPTED = /^\+ (\S+)@(\S+)\s*$/mu
30
34
 
31
- /** Lists every flag the script reads, value flags and switches alike. */
32
- export const FLAGS: readonly string[] = [
33
- '--whoami',
34
- '--login',
35
- '--publish',
36
- '--confirm',
37
- '--wait',
38
- '--otp',
39
- '--json',
40
- ]
41
-
42
35
  /** Holds the usage line the script prints when no mode or two modes were given. */
43
36
  export const USAGE =
44
37
  'usage: window.ts --whoami [--wait SECONDS] | --login [--wait SECONDS] | --publish DIR... --otp CODE [--json] | --confirm NAME@VERSION... [--wait SECONDS]'
45
38
 
39
+ /** Declares every flag the script reads, for `parseArgs`. */
40
+ export const OPTIONS: ParseArgsOptionsConfig = Object.freeze({
41
+ whoami: Object.freeze({ type: 'boolean' }),
42
+ login: Object.freeze({ type: 'boolean' }),
43
+ publish: Object.freeze({ type: 'boolean' }),
44
+ confirm: Object.freeze({ type: 'boolean' }),
45
+ wait: Object.freeze({ type: 'string' }),
46
+ otp: Object.freeze({ type: 'string' }),
47
+ json: Object.freeze({ type: 'boolean' }),
48
+ })
49
+
50
+ /** Describes the arguments `parseArgs` read: each flag's value by name, and the positionals. */
51
+ export interface Arguments {
52
+ readonly values: Readonly<
53
+ Record<string, string | boolean | ReadonlyArray<string | boolean> | undefined>
54
+ >
55
+ readonly positionals: readonly string[]
56
+ }
57
+
58
+ /** Describes how `parseArgs` read the arguments: the arguments, or the message it refused them with. */
59
+ export type ArgumentsResult =
60
+ | { readonly success: true; readonly value: Arguments }
61
+ | { readonly success: false; readonly error: string }
62
+
63
+ /**
64
+ * Parses the arguments in strict mode against `OPTIONS`.
65
+ *
66
+ * @param argv - The arguments after the script path.
67
+ * @returns The values and positionals, or the message `parseArgs` refused the arguments with.
68
+ */
69
+ export function parseArguments(argv: readonly string[]): ArgumentsResult {
70
+ try {
71
+ const { values, positionals } = parseArgs({
72
+ args: [...argv],
73
+ options: OPTIONS,
74
+ strict: true,
75
+ allowPositionals: true,
76
+ })
77
+ return { success: true, value: { values, positionals } }
78
+ } catch (error) {
79
+ return { success: false, error: error instanceof Error ? error.message : String(error) }
80
+ }
81
+ }
82
+
46
83
  /** Describes how to spawn npm on this host without a shell where the CLI entry is present. */
47
84
  export interface NpmCommand {
48
85
  readonly file: string
@@ -74,74 +111,6 @@ export interface Published {
74
111
  readonly stopped: boolean
75
112
  }
76
113
 
77
- /**
78
- * Reads the value that follows a flag.
79
- *
80
- * @remarks
81
- * Reads `--flag value` pairs: the first occurrence of a flag wins, a following value that opens
82
- * with `--` is a missing value, and the `--flag=value` form is not read.
83
- *
84
- * @param argv - The arguments after the script path.
85
- * @param name - The flag, such as `--otp`.
86
- * @returns The value after the flag, or undefined when the flag is absent, last, or followed by
87
- * another flag.
88
- */
89
- export function readOption(argv: readonly string[], name: string): string | undefined {
90
- const index = argv.indexOf(name)
91
- const value = index === -1 ? undefined : argv[index + 1]
92
- return value === undefined || value.startsWith('--') ? undefined : value
93
- }
94
-
95
- /**
96
- * Names the value flags a caller gave with no value.
97
- *
98
- * @param argv - The arguments after the script path.
99
- * @param names - The flags that take a value.
100
- * @returns Each named flag that appears last or is followed by another flag, in argument order.
101
- */
102
- export function readMissingFlags(
103
- argv: readonly string[],
104
- names: readonly string[],
105
- ): readonly string[] {
106
- return names.filter((name) => argv.includes(name) && readOption(argv, name) === undefined)
107
- }
108
-
109
- /**
110
- * Names the flags a caller gave that the script does not read.
111
- *
112
- * @remarks
113
- * Reads the arguments before a bare `--`, which opens a command a script passes on. A `--flag=value`
114
- * argument is unknown, because the script reads no such form.
115
- *
116
- * @param argv - The arguments after the script path.
117
- * @param flags - Every flag the script reads, value flags and switches alike.
118
- * @returns Each argument that opens with `--` and is not a read flag, in argument order.
119
- */
120
- export function readUnknownFlags(
121
- argv: readonly string[],
122
- flags: readonly string[],
123
- ): readonly string[] {
124
- const end = argv.indexOf('--')
125
- return (end === -1 ? argv : argv.slice(0, end)).filter(
126
- (argument) => argument.startsWith('--') && !flags.includes(argument),
127
- )
128
- }
129
-
130
- /**
131
- * Reads the values that follow a flag up to the next flag.
132
- *
133
- * @param argv - The arguments after the script path.
134
- * @param name - The flag, such as `--publish`.
135
- * @returns The values between the flag and the next `--` argument, empty when the flag is absent.
136
- */
137
- export function readList(argv: readonly string[], name: string): readonly string[] {
138
- const index = argv.indexOf(name)
139
- if (index === -1) return []
140
- const rest = argv.slice(index + 1)
141
- const end = rest.findIndex((argument) => argument.startsWith('--'))
142
- return end === -1 ? rest : rest.slice(0, end)
143
- }
144
-
145
114
  /**
146
115
  * Parses a whole text as one JSON object.
147
116
  *
@@ -206,18 +175,6 @@ export function runNpm(args: readonly string[], cwd?: string): SpawnSyncReturns<
206
175
  })
207
176
  }
208
177
 
209
- /**
210
- * Waits for a number of milliseconds.
211
- *
212
- * @param ms - The delay.
213
- * @returns A promise that settles after the delay.
214
- */
215
- export function waitFor(ms: number): Promise<void> {
216
- return new Promise((settle) => {
217
- setTimeout(settle, ms)
218
- })
219
- }
220
-
221
178
  /**
222
179
  * Reads the account `npm whoami` names once.
223
180
  *
@@ -242,7 +199,7 @@ export async function pollWhoami(
242
199
  ): Promise<string | undefined> {
243
200
  const user = readWhoami()
244
201
  if (user !== undefined || Date.now() - started >= waitSeconds * 1000) return user
245
- await waitFor(POLL_MS)
202
+ await setTimeout(POLL_MS)
246
203
  return pollWhoami(waitSeconds, started)
247
204
  }
248
205
 
@@ -275,7 +232,7 @@ export async function confirmServed(
275
232
  ): Promise<boolean> {
276
233
  const served = readServed(name, version)
277
234
  if (served || Date.now() - started >= waitSeconds * 1000) return served
278
- await waitFor(POLL_MS)
235
+ await setTimeout(POLL_MS)
279
236
  return confirmServed(name, version, waitSeconds, started)
280
237
  }
281
238
 
@@ -404,34 +361,39 @@ export async function publishAll(
404
361
  * @returns The exit code: 0 when the mode succeeded, 3 when it did not, 64 on usage.
405
362
  */
406
363
  export async function main(argv: readonly string[]): Promise<number> {
407
- const unknown = readUnknownFlags(argv, FLAGS)
408
- if (unknown.length > 0) {
409
- console.error(
410
- `window: unknown flag ${unknown.join(', ')}; give each flag and its value as separate arguments\n${USAGE}`,
411
- )
364
+ const parsed = parseArguments(argv)
365
+ if (!parsed.success) {
366
+ console.error(`window: ${parsed.error}; ${USAGE}`)
412
367
  return 64
413
368
  }
414
- const missing = readMissingFlags(argv, ['--wait', '--otp'])
415
- if (missing.length > 0) {
416
- console.error(`window: ${missing.join(', ')} given with no value`)
369
+ const { values, positionals } = parsed.value
370
+ const modes = [values.whoami, values.login, values.publish, values.confirm].filter(
371
+ (value) => value === true,
372
+ )
373
+ if (modes.length > 1) {
374
+ console.error(USAGE)
417
375
  return 64
418
376
  }
419
- const wait = Number(readOption(argv, '--wait') ?? 120)
420
- const modes = ['--whoami', '--login', '--publish', '--confirm'].filter((flag) =>
421
- argv.includes(flag),
422
- )
423
- if (modes.length > 1 || (argv.includes('--wait') && (!Number.isFinite(wait) || wait < 0))) {
377
+ const given = typeof values.wait === 'string' ? values.wait : undefined
378
+ const wait = Number(given ?? 120)
379
+ if (given !== undefined && (given.trim() === '' || !Number.isFinite(wait) || wait < 0)) {
380
+ console.error(
381
+ `window: --wait takes a number of seconds from 0, not ${JSON.stringify(given)}; ${USAGE}`,
382
+ )
383
+ return 64
384
+ }
385
+ if (positionals.length > 0 && values.publish !== true && values.confirm !== true) {
424
386
  console.error(
425
- 'usage: window.ts names one mode (--whoami | --login | --publish | --confirm), and --wait takes a number of seconds',
387
+ `window: ${positionals.map((value) => JSON.stringify(value)).join(', ')} given without --publish or --confirm, the modes that take a list; ${USAGE}`,
426
388
  )
427
389
  return 64
428
390
  }
429
- if (argv.includes('--whoami')) {
430
- const user = await pollWhoami(argv.includes('--wait') ? wait : 0)
391
+ if (values.whoami === true) {
392
+ const user = await pollWhoami(given === undefined ? 0 : wait)
431
393
  console.log(JSON.stringify({ mode: 'whoami', user, live: user !== undefined }))
432
394
  return user === undefined ? 3 : 0
433
395
  }
434
- if (argv.includes('--login')) {
396
+ if (values.login === true) {
435
397
  const command =
436
398
  process.platform === 'win32'
437
399
  ? 'npm login --browser=false'
@@ -439,13 +401,13 @@ export async function main(argv: readonly string[]): Promise<number> {
439
401
  console.error(
440
402
  `window: run this in a real terminal, then approve the URL it prints on its first line: ${command}`,
441
403
  )
442
- const user = await pollWhoami(argv.includes('--wait') ? wait : 300)
404
+ const user = await pollWhoami(given === undefined ? 300 : wait)
443
405
  console.log(JSON.stringify({ mode: 'login', command, user, live: user !== undefined }))
444
406
  return user === undefined ? 3 : 0
445
407
  }
446
- if (argv.includes('--publish')) {
447
- const directories = readList(argv, '--publish')
448
- const otp = readOption(argv, '--otp')
408
+ if (values.publish === true) {
409
+ const directories = positionals
410
+ const otp = typeof values.otp === 'string' ? values.otp : undefined
449
411
  if (
450
412
  directories.length === 0 ||
451
413
  otp === undefined ||
@@ -460,7 +422,7 @@ export async function main(argv: readonly string[]): Promise<number> {
460
422
  for (const directory of directories) {
461
423
  const root = findGitRoot(resolve(directory))
462
424
  const entry = join(root, '.git')
463
- if (!existsSync(entry) || !statSync(entry).isFile()) continue
425
+ if (statSync(entry, { throwIfNoEntry: false })?.isFile() !== true) continue
464
426
  const line = readFileSync(entry, 'utf8')
465
427
  .split(/\r\n|\n/u)
466
428
  .find((value) => value.startsWith('gitdir:'))
@@ -491,7 +453,7 @@ export async function main(argv: readonly string[]): Promise<number> {
491
453
  return 3
492
454
  }
493
455
  const uploads = await publishAll(directories, otp, wait)
494
- if (argv.includes('--json')) console.log(JSON.stringify({ mode: 'publish', uploads }))
456
+ if (values.json === true) console.log(JSON.stringify({ mode: 'publish', uploads }))
495
457
  else {
496
458
  for (const upload of uploads) {
497
459
  console.log(
@@ -501,8 +463,8 @@ export async function main(argv: readonly string[]): Promise<number> {
501
463
  }
502
464
  return uploads.every((upload) => upload.accepted && upload.confirmed) ? 0 : 3
503
465
  }
504
- if (argv.includes('--confirm')) {
505
- const targets = readList(argv, '--confirm')
466
+ if (values.confirm === true) {
467
+ const targets = positionals
506
468
  if (targets.length === 0 || targets.some((target) => !/^@?[^@]+@\S+$/u.test(target))) {
507
469
  console.error('usage: window.ts --confirm NAME@VERSION... [--wait SECONDS]')
508
470
  return 64
@@ -10,9 +10,9 @@ A map is mechanical; reading is not. Run the map first, hand it to the reader, a
10
10
 
11
11
  ## Scripts
12
12
 
13
- | Script | Does |
14
- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
15
- | `scripts/map.ts` | `--tree PATH...` files with line counts and sizes; `--headings PATH...` Markdown headings with lines, outside fenced blocks of backticks or tildes; `--frontmatter PATH...` every key of a frontmatter block, a TOML file, or a YAML file with its whole value, nested keys dotted (`interface.default_prompt`); `--exports PATH...` `export` lines in TypeScript files (a text reading); `--census TERM...` every line carrying a term (a term that opens with `--` is refused as a missing value, so drop a custom property's leading dashes); `--refs PATH` every line naming a path or its basename; `--anchors PATH...` every `§ Heading` reference whose heading its target lacks. `--paths a,b` narrows a census or refs walk; `--ignore-case`; `--json`; `--out FILE` writes the map instead of printing it. Walks skip `node_modules`, `.git`, `dist`, `tmp`, `.orkestrel`, `.idea`, and `host.json`. |
13
+ | Script | Does |
14
+ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
15
+ | `scripts/map.ts` | `--tree PATH` files with line counts and sizes; `--headings PATH` Markdown headings with lines, outside fenced blocks of backticks or tildes; `--frontmatter PATH` every key of a frontmatter block, a TOML file, or a YAML file with its whole value, nested keys dotted (`interface.default_prompt`); `--exports PATH` `export` lines in TypeScript files (a text reading); `--census TERM` every line carrying a term (give a term that opens with `-` as `--census=--term`); `--refs PATH` every line naming a path or its basename; `--anchors PATH` every `§ Heading` reference whose heading its target lacks. Each of those flags but `--refs` repeats, one value per flag: `--tree src --tree tests`. `--paths a,b` narrows a census or refs walk; `--ignore-case`; `--json`; `--out FILE` writes the map instead of printing it. Walks skip `node_modules`, `.git`, `dist`, `tmp`, `.orkestrel`, `.idea`, and `host.json`. |
16
16
 
17
17
  ## Map
18
18
 
@@ -1,5 +1,7 @@
1
1
  // Map terrain before a brief, an absorption lane, or a rename. Run from the checkout root:
2
- // node .agents/skills/orkestrel-scout/scripts/map.ts --tree PATH... [--headings PATH...] [--frontmatter PATH...] [--exports PATH...] [--census TERM...] [--refs PATH] [--anchors PATH...] [--paths a,b] [--ignore-case] [--json] [--out FILE]
2
+ // node .agents/skills/orkestrel-scout/scripts/map.ts [--tree PATH ...] [--headings PATH ...]
3
+ // [--frontmatter PATH ...] [--exports PATH ...] [--census TERM ...] [--refs PATH]
4
+ // [--anchors PATH ...] [--paths a,b] [--ignore-case] [--json] [--out FILE]
3
5
  // --tree lists every file under each path with its line count and size. --headings lists every
4
6
  // Markdown heading with its line; a heading inside a fenced block is no heading, where a fence
5
7
  // opens with a run of three or more backticks or tildes indented up to three spaces and closes with
@@ -7,16 +9,15 @@
7
9
  // frontmatter block, a TOML file, or a YAML file with its whole value, a nested key dotted under its
8
10
  // parents (`interface.default_prompt`) and a TOML key under its table. --exports lists every
9
11
  // `export` declaration line in a TypeScript file (a text reading, not the compiler's). --census
10
- // lists every line carrying a term. --refs lists
11
- // every line naming a path or its basename. --anchors lists every `§ Heading` reference whose
12
- // heading the named file, or the same file, does not carry. Walks skip node_modules, .git, dist,
13
- // tmp, .orkestrel, .idea, and host.json; --paths narrows a census or refs walk. Modes combine, each
14
- // printing its section; --json prints one object; --out writes the output to FILE instead of the
15
- // terminal. Give each flag once; a later duplicate is not read. A value that opens with `--` is a
16
- // missing value, so census a custom property without its leading dashes. The script refuses a flag
17
- // it does not read, the `--flag=value` form included, and names every unknown flag and every flag
18
- // given with no value in one refusal. Exit 0, or 64 when no mode is given, a flag is given with no
19
- // value, or a flag is unknown.
12
+ // lists every line carrying a term. --refs lists every line naming a path or its basename.
13
+ // --anchors lists every `§ Heading` reference whose heading the named file, or the same file, does
14
+ // not carry. Walks skip node_modules, .git, dist, tmp, .orkestrel, .idea, and host.json; --paths
15
+ // narrows a census or refs walk. Modes combine, each printing its section; --json prints one
16
+ // object; --out writes the output to FILE instead of the terminal. Each mode flag but --refs
17
+ // repeats, one value per flag; give a value that opens with `-` in the `--census=--term` form. The
18
+ // script reads its flags with `parseArgs` in strict mode. Exit 0, or 64 on usage, including no mode
19
+ // given.
20
+ import type { ParseArgsOptionsConfig } from 'node:util'
20
21
  import {
21
22
  existsSync,
22
23
  mkdirSync,
@@ -27,6 +28,7 @@ import {
27
28
  writeFileSync,
28
29
  } from 'node:fs'
29
30
  import { basename, dirname, join } from 'node:path'
31
+ import { parseArgs } from 'node:util'
30
32
 
31
33
  /** Matches an `export` declaration line and captures its kind and name. */
32
34
  export const EXPORT =
@@ -55,25 +57,57 @@ export const SKIPPED_DIRECTORIES: ReadonlySet<string> = new Set([
55
57
  '.idea',
56
58
  ])
57
59
 
58
- /** Lists the flags that take a value. */
59
- export const VALUE_FLAGS: readonly string[] = [
60
- '--tree',
61
- '--headings',
62
- '--frontmatter',
63
- '--exports',
64
- '--census',
65
- '--refs',
66
- '--anchors',
67
- '--paths',
68
- '--out',
69
- ]
70
-
71
- /** Lists every flag the script reads, value flags and switches alike. */
72
- export const FLAGS: readonly string[] = [...VALUE_FLAGS, '--ignore-case', '--json']
73
-
74
60
  /** Holds the usage line printed when a call names no mode. */
75
61
  export const USAGE =
76
- 'usage: map.ts [--tree PATH...] [--headings PATH...] [--frontmatter PATH...] [--exports PATH...] [--census TERM...] [--refs PATH] [--anchors PATH...] [--paths a,b] [--ignore-case] [--json] [--out FILE]'
62
+ 'usage: map.ts [--tree PATH ...] [--headings PATH ...] [--frontmatter PATH ...] [--exports PATH ...] [--census TERM ...] [--refs PATH] [--anchors PATH ...] [--paths a,b] [--ignore-case] [--json] [--out FILE]; name one mode or more; each mode flag but --refs repeats, one value per flag'
63
+
64
+ /** Declares every flag the script reads, for `parseArgs`. */
65
+ export const OPTIONS: ParseArgsOptionsConfig = Object.freeze({
66
+ tree: Object.freeze({ type: 'string', multiple: true }),
67
+ headings: Object.freeze({ type: 'string', multiple: true }),
68
+ frontmatter: Object.freeze({ type: 'string', multiple: true }),
69
+ exports: Object.freeze({ type: 'string', multiple: true }),
70
+ census: Object.freeze({ type: 'string', multiple: true }),
71
+ refs: Object.freeze({ type: 'string' }),
72
+ anchors: Object.freeze({ type: 'string', multiple: true }),
73
+ paths: Object.freeze({ type: 'string' }),
74
+ 'ignore-case': Object.freeze({ type: 'boolean' }),
75
+ json: Object.freeze({ type: 'boolean' }),
76
+ out: Object.freeze({ type: 'string' }),
77
+ })
78
+
79
+ /** Describes the arguments `parseArgs` read: each flag's value by name, and the positionals. */
80
+ export interface Arguments {
81
+ readonly values: Readonly<
82
+ Record<string, string | boolean | ReadonlyArray<string | boolean> | undefined>
83
+ >
84
+ readonly positionals: readonly string[]
85
+ }
86
+
87
+ /** Describes how `parseArgs` read the arguments: the arguments, or the message it refused them with. */
88
+ export type ArgumentsResult =
89
+ | { readonly success: true; readonly value: Arguments }
90
+ | { readonly success: false; readonly error: string }
91
+
92
+ /**
93
+ * Parses the arguments in strict mode against `OPTIONS`.
94
+ *
95
+ * @param argv - The arguments after the script path.
96
+ * @returns The values and positionals, or the message `parseArgs` refused the arguments with.
97
+ */
98
+ export function parseArguments(argv: readonly string[]): ArgumentsResult {
99
+ try {
100
+ const { values, positionals } = parseArgs({
101
+ args: [...argv],
102
+ options: OPTIONS,
103
+ strict: true,
104
+ allowPositionals: false,
105
+ })
106
+ return { success: true, value: { values, positionals } }
107
+ } catch (error) {
108
+ return { success: false, error: error instanceof Error ? error.message : String(error) }
109
+ }
110
+ }
77
111
 
78
112
  /** Describes one file a tree walk found, with the modification time it carries. */
79
113
  export interface WalkedFile {
@@ -162,71 +196,15 @@ export interface Report {
162
196
  }
163
197
 
164
198
  /**
165
- * Reads the value that follows a flag.
166
- *
167
- * @remarks
168
- * The first occurrence of a flag wins, a following value that opens with `--` is a missing value,
169
- * and the `--flag=value` form is not read.
170
- *
171
- * @param argv - The arguments after the script path.
172
- * @param name - The flag, such as `--paths`.
173
- * @returns The value after the flag, or undefined when the flag is absent, last, or followed by
174
- * another flag.
175
- */
176
- export function readOption(argv: readonly string[], name: string): string | undefined {
177
- const index = argv.indexOf(name)
178
- const value = index === -1 ? undefined : argv[index + 1]
179
- return value === undefined || value.startsWith('--') ? undefined : value
180
- }
181
-
182
- /**
183
- * Names the value flags a caller gave with no value.
199
+ * Collects the strings a repeatable flag's value holds.
184
200
  *
185
- * @param argv - The arguments after the script path.
186
- * @param names - The flags that take a value.
187
- * @returns Each named flag that appears last or is followed by another flag, in argument order.
201
+ * @param value - The value `parseArgs` read for a flag declared with `multiple: true`.
202
+ * @returns Each string in order, empty when the flag never appears.
188
203
  */
189
- export function readMissingFlags(
190
- argv: readonly string[],
191
- names: readonly string[],
192
- ): readonly string[] {
193
- return names.filter((name) => argv.includes(name) && readOption(argv, name) === undefined)
194
- }
195
-
196
- /**
197
- * Names the flags a caller gave that the script does not read.
198
- *
199
- * @remarks
200
- * A `--flag=value` argument is unknown, because the script reads no such form. A bare `--` ends the
201
- * scan.
202
- *
203
- * @param argv - The arguments after the script path.
204
- * @param flags - Every flag the script reads, value flags and switches alike.
205
- * @returns Each argument that opens with `--` and is not a read flag, in argument order.
206
- */
207
- export function readUnknownFlags(
208
- argv: readonly string[],
209
- flags: readonly string[],
210
- ): readonly string[] {
211
- const end = argv.indexOf('--')
212
- return (end === -1 ? argv : argv.slice(0, end)).filter(
213
- (argument) => argument.startsWith('--') && !flags.includes(argument),
214
- )
215
- }
216
-
217
- /**
218
- * Reads the values that follow a flag up to the next flag.
219
- *
220
- * @param argv - The arguments after the script path.
221
- * @param name - The flag, such as `--tree`.
222
- * @returns The values between the flag and the next `--` argument, empty when the flag is absent.
223
- */
224
- export function readList(argv: readonly string[], name: string): readonly string[] {
225
- const index = argv.indexOf(name)
226
- if (index === -1) return []
227
- const rest = argv.slice(index + 1)
228
- const end = rest.findIndex((argument) => argument.startsWith('--'))
229
- return end === -1 ? rest : rest.slice(0, end)
204
+ export function collectStrings(value: unknown): readonly string[] {
205
+ return Array.isArray(value)
206
+ ? value.filter((member): member is string => typeof member === 'string')
207
+ : []
230
208
  }
231
209
 
232
210
  /**
@@ -236,7 +214,7 @@ export function readList(argv: readonly string[], name: string): readonly string
236
214
  * @returns The same path with every backslash replaced by a slash.
237
215
  */
238
216
  export function normalizeSlashes(path: string): string {
239
- return path.split('\\').join('/')
217
+ return path.replaceAll('\\', '/')
240
218
  }
241
219
 
242
220
  /**
@@ -723,26 +701,21 @@ export function renderReport(report: Report): string {
723
701
  * @returns The exit code: 0 on success, 64 on usage.
724
702
  */
725
703
  export function main(argv: readonly string[]): number {
726
- const unknown = readUnknownFlags(argv, FLAGS)
727
- const missing = readMissingFlags(argv, VALUE_FLAGS)
728
- if (unknown.length > 0 || missing.length > 0) {
729
- console.error(
730
- `map: ${[
731
- ...(unknown.length > 0 ? [`${unknown.join(', ')} is not a flag this script reads`] : []),
732
- ...(missing.length > 0 ? [`${missing.join(', ')} given with no value`] : []),
733
- ].join('; ')}; ${USAGE}`,
734
- )
704
+ const parsed = parseArguments(argv)
705
+ if (!parsed.success) {
706
+ console.error(`map: ${parsed.error}; ${USAGE}`)
735
707
  return 64
736
708
  }
737
- const roots = (readOption(argv, '--paths') ?? '.').split(',')
738
- const ignoreCase = argv.includes('--ignore-case')
739
- const tree = readList(argv, '--tree')
740
- const headings = readList(argv, '--headings')
741
- const frontmatter = readList(argv, '--frontmatter')
742
- const exports = readList(argv, '--exports')
743
- const census = readList(argv, '--census')
744
- const refs = readOption(argv, '--refs')
745
- const anchors = readList(argv, '--anchors')
709
+ const { values } = parsed.value
710
+ const roots = (typeof values.paths === 'string' ? values.paths : '.').split(',')
711
+ const ignoreCase = values['ignore-case'] === true
712
+ const tree = collectStrings(values.tree)
713
+ const headings = collectStrings(values.headings)
714
+ const frontmatter = collectStrings(values.frontmatter)
715
+ const exports = collectStrings(values.exports)
716
+ const census = collectStrings(values.census)
717
+ const refs = typeof values.refs === 'string' ? values.refs : undefined
718
+ const anchors = collectStrings(values.anchors)
746
719
  if (
747
720
  tree.length +
748
721
  headings.length +
@@ -765,8 +738,8 @@ export function main(argv: readonly string[]): number {
765
738
  ...(refs === undefined ? {} : { refs: mapRefs(refs, roots) }),
766
739
  ...(anchors.length > 0 ? { anchors: mapAnchors(anchors) } : {}),
767
740
  }
768
- const output = argv.includes('--json') ? `${JSON.stringify(report)}\n` : renderReport(report)
769
- const out = readOption(argv, '--out')
741
+ const output = values.json === true ? `${JSON.stringify(report)}\n` : renderReport(report)
742
+ const out = typeof values.out === 'string' ? values.out : undefined
770
743
  if (out === undefined) process.stdout.write(output)
771
744
  else {
772
745
  mkdirSync(dirname(out), { recursive: true })