@kinloom/cli 0.1.1 → 0.3.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 (111) hide show
  1. package/dist/assets/cached-ocr.py +786 -0
  2. package/dist/assets/ocr.md +76 -0
  3. package/dist/assets/prep-scan.md +97 -0
  4. package/dist/assets/prep-scan.py +1313 -0
  5. package/dist/bundled-skills/acpl-persi/SKILL.md +103 -0
  6. package/dist/bundled-skills/acpl-persi/scripts/persi +539 -0
  7. package/dist/bundled-skills/archive-org/SKILL.md +162 -0
  8. package/dist/bundled-skills/archive-org/scripts/archive-org +1576 -0
  9. package/dist/bundled-skills/blm-glo/SKILL.md +54 -0
  10. package/dist/bundled-skills/california-archives/SKILL.md +130 -0
  11. package/dist/bundled-skills/california-archives/scripts/ca-archives +614 -0
  12. package/dist/bundled-skills/chronicling-america/SKILL.md +120 -0
  13. package/dist/bundled-skills/chronicling-america/scripts/chronam +553 -0
  14. package/dist/bundled-skills/cyndis-list/SKILL.md +53 -0
  15. package/dist/bundled-skills/findagrave/SKILL.md +129 -0
  16. package/dist/bundled-skills/findagrave/scripts/findagrave +965 -0
  17. package/dist/bundled-skills/hathitrust/SKILL.md +117 -0
  18. package/dist/bundled-skills/hathitrust/scripts/hathi +379 -0
  19. package/dist/bundled-skills/kentucky-archives/SKILL.md +124 -0
  20. package/dist/bundled-skills/kentucky-archives/scripts/ky-archives +646 -0
  21. package/dist/bundled-skills/library-of-michigan/SKILL.md +118 -0
  22. package/dist/bundled-skills/library-of-michigan/scripts/michiganology +515 -0
  23. package/dist/bundled-skills/missouri-archives/SKILL.md +109 -0
  24. package/dist/bundled-skills/missouri-archives/scripts/mo-archives +751 -0
  25. package/dist/bundled-skills/nara-catalog-search/SKILL.md +130 -0
  26. package/dist/bundled-skills/nara-catalog-search/scripts/nara +1387 -0
  27. package/dist/bundled-skills/narrative-audio/SKILL.md +103 -0
  28. package/dist/bundled-skills/narrative-audio/references/script-rules.md +109 -0
  29. package/dist/bundled-skills/narrative-audio/scripts/narrative-audio +290 -0
  30. package/dist/bundled-skills/new-jersey-archives/SKILL.md +135 -0
  31. package/dist/bundled-skills/new-jersey-archives/scripts/nj-archives +869 -0
  32. package/dist/bundled-skills/openarchieven/SKILL.md +97 -0
  33. package/dist/bundled-skills/openarchieven/scripts/openarchieven +624 -0
  34. package/dist/bundled-skills/texas-archives/SKILL.md +102 -0
  35. package/dist/bundled-skills/texas-archives/scripts/texas-archives +666 -0
  36. package/dist/bundled-skills/uk-archives/SKILL.md +110 -0
  37. package/dist/bundled-skills/uk-archives/scripts/uk-archives +631 -0
  38. package/dist/bundled-skills/usgs-gnis/SKILL.md +99 -0
  39. package/dist/bundled-skills/usgs-gnis/scripts/gnis +418 -0
  40. package/dist/bundled-skills/virginia-archives/SKILL.md +144 -0
  41. package/dist/bundled-skills/virginia-archives/scripts/va-archives +1039 -0
  42. package/dist/bundled-skills/wikitree/SKILL.md +154 -0
  43. package/dist/bundled-skills/wikitree/scripts/wikitree +455 -0
  44. package/dist/cli.d.ts +1 -1
  45. package/dist/cli.d.ts.map +1 -1
  46. package/dist/cli.js +488 -26
  47. package/dist/cli.js.map +1 -1
  48. package/dist/client.d.ts.map +1 -1
  49. package/dist/client.js +30 -5
  50. package/dist/client.js.map +1 -1
  51. package/dist/commands/ops/audit.d.ts +138 -0
  52. package/dist/commands/ops/audit.d.ts.map +1 -0
  53. package/dist/commands/ops/audit.js +872 -0
  54. package/dist/commands/ops/audit.js.map +1 -0
  55. package/dist/commands/ops/context.d.ts +100 -0
  56. package/dist/commands/ops/context.d.ts.map +1 -0
  57. package/dist/commands/ops/context.js +917 -0
  58. package/dist/commands/ops/context.js.map +1 -0
  59. package/dist/commands/ops/dates.d.ts +87 -0
  60. package/dist/commands/ops/dates.d.ts.map +1 -0
  61. package/dist/commands/ops/dates.js +228 -0
  62. package/dist/commands/ops/dates.js.map +1 -0
  63. package/dist/commands/ops/help.d.ts +8 -0
  64. package/dist/commands/ops/help.d.ts.map +1 -0
  65. package/dist/commands/ops/help.js +107 -0
  66. package/dist/commands/ops/help.js.map +1 -0
  67. package/dist/commands/ops/index.d.ts +8 -0
  68. package/dist/commands/ops/index.d.ts.map +1 -0
  69. package/dist/commands/ops/index.js +8 -0
  70. package/dist/commands/ops/index.js.map +1 -0
  71. package/dist/commands/ops/integrate.d.ts +61 -0
  72. package/dist/commands/ops/integrate.d.ts.map +1 -0
  73. package/dist/commands/ops/integrate.js +1063 -0
  74. package/dist/commands/ops/integrate.js.map +1 -0
  75. package/dist/commands/ops/sync.d.ts +194 -0
  76. package/dist/commands/ops/sync.d.ts.map +1 -0
  77. package/dist/commands/ops/sync.js +1251 -0
  78. package/dist/commands/ops/sync.js.map +1 -0
  79. package/dist/commands/ops/telemetry.d.ts +79 -0
  80. package/dist/commands/ops/telemetry.d.ts.map +1 -0
  81. package/dist/commands/ops/telemetry.js +249 -0
  82. package/dist/commands/ops/telemetry.js.map +1 -0
  83. package/dist/commands/ops/verify.d.ts +76 -0
  84. package/dist/commands/ops/verify.d.ts.map +1 -0
  85. package/dist/commands/ops/verify.js +325 -0
  86. package/dist/commands/ops/verify.js.map +1 -0
  87. package/dist/commands/records/help.d.ts +18 -0
  88. package/dist/commands/records/help.d.ts.map +1 -0
  89. package/dist/commands/records/help.js +174 -0
  90. package/dist/commands/records/help.js.map +1 -0
  91. package/dist/commands/records/index.d.ts +5 -0
  92. package/dist/commands/records/index.d.ts.map +1 -0
  93. package/dist/commands/records/index.js +5 -0
  94. package/dist/commands/records/index.js.map +1 -0
  95. package/dist/commands/records/registry.d.ts +32 -0
  96. package/dist/commands/records/registry.d.ts.map +1 -0
  97. package/dist/commands/records/registry.js +227 -0
  98. package/dist/commands/records/registry.js.map +1 -0
  99. package/dist/commands/records/resolve.d.ts +14 -0
  100. package/dist/commands/records/resolve.d.ts.map +1 -0
  101. package/dist/commands/records/resolve.js +61 -0
  102. package/dist/commands/records/resolve.js.map +1 -0
  103. package/dist/commands/records/runner.d.ts +27 -0
  104. package/dist/commands/records/runner.d.ts.map +1 -0
  105. package/dist/commands/records/runner.js +255 -0
  106. package/dist/commands/records/runner.js.map +1 -0
  107. package/dist/index.d.ts +2 -0
  108. package/dist/index.d.ts.map +1 -1
  109. package/dist/index.js +2 -0
  110. package/dist/index.js.map +1 -1
  111. package/package.json +3 -3
package/dist/cli.js CHANGED
@@ -2,14 +2,9 @@
2
2
  import { realpathSync } from 'node:fs';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { parseArgs } from 'node:util';
5
- import { BuildModeSchema } from '@kinloom/core';
6
- import { runExportYamlCommand } from './commands/exportYaml.js';
7
- import { runInitCommand } from './commands/init.js';
8
- import { runReconcileCommand } from './commands/reconcile.js';
9
- import { runSeedCommand } from './commands/seed.js';
10
- import { runSliceGedcomCommand } from './commands/sliceGedcom.js';
11
- import { runSubmitBatchCommand } from './commands/submitBatch.js';
12
- import { runUploadMediaCommand } from './commands/uploadMedia.js';
5
+ import { AUDIT_HELP, CONTEXT_HELP, DATES_HELP, INTEGRATE_HELP, SYNC_HELP, TELEMETRY_HELP, VERIFY_HELP, } from './commands/ops/help.js';
6
+ import { formatRecordCommandsHelp, renderRecordCommandHelp } from './commands/records/help.js';
7
+ import { resolveRecordCommand } from './commands/records/registry.js';
13
8
  import { CliValidationError, EXIT_ERROR, EXIT_OK, EXIT_USAGE, KinloomApiError, formatConflictDetails, } from './errors.js';
14
9
  const DEFAULT_IO = {
15
10
  stdout: (line) => {
@@ -21,24 +16,38 @@ const DEFAULT_IO = {
21
16
  };
22
17
  export const ROOT_HELP = `Usage: kinloom <command> [options]
23
18
 
24
- Commands:
25
- init Scaffold a thin private family archive repository
26
- slice-gedcom Slice a combined GEDCOM export into deterministic YAML files
27
- seed Load local YAML + config and submit an idempotent seed batch
28
- submit-batch Validate and submit a typed BatchSubmission JSON/YAML file
29
- export-yaml Export deterministic YAML snapshot with ETag/304 support
30
- upload-media Validate and upload a media scan or recording via multipart POST
31
- reconcile Compare cached GET /api/bundle against full compileArchive
19
+ Archive lifecycle:
20
+ init Scaffold a thin private family archive repository
21
+ slice-gedcom Slice a combined GEDCOM export into deterministic YAML files
22
+ seed Load local YAML + config and submit an idempotent seed batch
23
+ submit-batch Validate and submit a typed BatchSubmission JSON/YAML file
24
+ export-yaml Export deterministic YAML snapshot with ETag/304 support
25
+ upload-media Validate and upload a media scan or recording via multipart POST
26
+ reconcile Compare cached GET /api/bundle against full compileArchive
27
+
28
+ Research & archive ops:
29
+ context Dump privacy-fenced YAML context, relatives, and leads for a person
30
+ integrate Validate and merge a person research package into local YAML
31
+ audit Run 5-check deterministic audit on a person research package
32
+ verify Run full-archive invariant checks over local data/*.yaml files
33
+ sync Diff and sync local YAML + R2 media to a live Cloudflare archive
34
+ dates Compute exact Gregorian weekdays, date diffs, and ages
35
+ telemetry Report local CLI latency, cache hit rate, and failure summary
36
+
37
+ ${formatRecordCommandsHelp()}
32
38
 
33
39
  Global options:
34
- -h, --help Show help for kinloom or a specific command
40
+ -h, --help Show help for kinloom or a specific command
41
+ help <command> Show full help or research guide for any command
35
42
 
36
43
  Environment variables:
37
- KINLOOM_TOKEN Bearer token used when --token is omitted
44
+ KINLOOM_TOKEN Bearer token used when --token is omitted
45
+ KINLOOM_ANCESTRY_FACTS_DIR Optional external facts JSON directory for \`kinloom context\`
46
+ KINLOOM_TELEMETRY_FILE Override JSONL telemetry path (~/.cache/kinloom-telemetry/calls.jsonl)
38
47
 
39
48
  Exit codes:
40
49
  0 Success
41
- 1 Runtime, HTTP, or reconciliation drift error
50
+ 1 Runtime, HTTP, audit, or reconciliation drift error
42
51
  2 CLI usage or boundary validation error
43
52
  3 Optimistic concurrency conflict (HTTP 409)`;
44
53
  const COMMAND_HELP = {
@@ -112,6 +121,13 @@ Options:
112
121
  --token <secret> Bearer token (defaults to KINLOOM_TOKEN)
113
122
  --mode <mode> Override build mode ('private' or 'public')
114
123
  -h, --help Show this help message`,
124
+ context: CONTEXT_HELP,
125
+ integrate: INTEGRATE_HELP,
126
+ audit: AUDIT_HELP,
127
+ verify: VERIFY_HELP,
128
+ sync: SYNC_HELP,
129
+ dates: DATES_HELP,
130
+ telemetry: TELEMETRY_HELP,
115
131
  };
116
132
  function requireStringFlag(value, flagName) {
117
133
  if (!value || !value.trim()) {
@@ -129,6 +145,16 @@ function parseOptionalPositiveInt(value, flagName) {
129
145
  }
130
146
  return parsed;
131
147
  }
148
+ function parseOptionalPositiveNumber(value, flagName) {
149
+ if (value === undefined) {
150
+ return undefined;
151
+ }
152
+ const parsed = Number(value);
153
+ if (!Number.isFinite(parsed) || parsed <= 0) {
154
+ throw new CliValidationError(`Option \`${flagName}\` must be a positive number.`);
155
+ }
156
+ return parsed;
157
+ }
132
158
  function safeParseArgs(config) {
133
159
  try {
134
160
  return parseArgs(config);
@@ -138,20 +164,181 @@ function safeParseArgs(config) {
138
164
  throw new CliValidationError(message);
139
165
  }
140
166
  }
167
+ function writeRenderedOutput(io, rendered) {
168
+ const trimmed = rendered.replace(/\r?\n$/, '');
169
+ if (trimmed.length > 0) {
170
+ io.stdout(trimmed);
171
+ }
172
+ }
173
+ function parseSyncArgs(argv) {
174
+ const parsed = {
175
+ syncMissingMedia: false,
176
+ uploadMediaPaths: [],
177
+ allowDeletes: false,
178
+ deleteTokens: [],
179
+ includeLiving: false,
180
+ verifyLive: false,
181
+ dryRun: false,
182
+ json: false,
183
+ };
184
+ const readFlagValue = (arg, index, name) => {
185
+ if (arg.includes('=')) {
186
+ const val = arg.slice(arg.indexOf('=') + 1).trim();
187
+ if (!val) {
188
+ throw new CliValidationError(`Option \`${name}\` requires a value.`);
189
+ }
190
+ return [val, index];
191
+ }
192
+ const next = argv[index + 1];
193
+ if (!next || next.startsWith('-')) {
194
+ throw new CliValidationError(`Option \`${name}\` requires a value.`);
195
+ }
196
+ return [next.trim(), index + 1];
197
+ };
198
+ for (let i = 0; i < argv.length; i += 1) {
199
+ const arg = argv[i];
200
+ if (arg === '--sync-missing-media') {
201
+ parsed.syncMissingMedia = true;
202
+ continue;
203
+ }
204
+ if (arg === '--allow-deletes') {
205
+ parsed.allowDeletes = true;
206
+ continue;
207
+ }
208
+ if (arg === '--include-living') {
209
+ parsed.includeLiving = true;
210
+ continue;
211
+ }
212
+ if (arg === '--verify-live') {
213
+ parsed.verifyLive = true;
214
+ continue;
215
+ }
216
+ if (arg === '--dry-run') {
217
+ parsed.dryRun = true;
218
+ continue;
219
+ }
220
+ if (arg === '--json') {
221
+ parsed.json = true;
222
+ continue;
223
+ }
224
+ if (arg === '--repo' || arg.startsWith('--repo=')) {
225
+ const [val, nextIdx] = readFlagValue(arg, i, '--repo');
226
+ parsed.repoDir = val;
227
+ i = nextIdx;
228
+ continue;
229
+ }
230
+ if (arg === '--site-url' || arg.startsWith('--site-url=')) {
231
+ const [val, nextIdx] = readFlagValue(arg, i, '--site-url');
232
+ parsed.siteUrl = val;
233
+ i = nextIdx;
234
+ continue;
235
+ }
236
+ if (arg === '--types' || arg.startsWith('--types=')) {
237
+ const [val, nextIdx] = readFlagValue(arg, i, '--types');
238
+ parsed.typesRaw = parsed.typesRaw ? `${parsed.typesRaw},${val}` : val;
239
+ i = nextIdx;
240
+ continue;
241
+ }
242
+ if (arg === '--summary' || arg.startsWith('--summary=')) {
243
+ const [val, nextIdx] = readFlagValue(arg, i, '--summary');
244
+ parsed.summary = val;
245
+ i = nextIdx;
246
+ continue;
247
+ }
248
+ if (arg === '--concurrency' || arg.startsWith('--concurrency=')) {
249
+ const [val, nextIdx] = readFlagValue(arg, i, '--concurrency');
250
+ parsed.concurrency = parseOptionalPositiveInt(val, '--concurrency');
251
+ i = nextIdx;
252
+ continue;
253
+ }
254
+ if (arg === '--chunk-size' || arg.startsWith('--chunk-size=')) {
255
+ const [val, nextIdx] = readFlagValue(arg, i, '--chunk-size');
256
+ parsed.chunkSize = parseOptionalPositiveInt(val, '--chunk-size');
257
+ i = nextIdx;
258
+ continue;
259
+ }
260
+ if (arg === '--delete' || arg.startsWith('--delete=')) {
261
+ const [val, nextIdx] = readFlagValue(arg, i, '--delete');
262
+ parsed.deleteTokens.push(val);
263
+ i = nextIdx;
264
+ continue;
265
+ }
266
+ if (arg === '--upload-media' || arg.startsWith('--upload-media=')) {
267
+ if (arg.startsWith('--upload-media=')) {
268
+ const raw = arg.slice('--upload-media='.length);
269
+ const items = raw
270
+ .split(',')
271
+ .map((item) => item.trim())
272
+ .filter(Boolean);
273
+ if (items.length === 0) {
274
+ throw new CliValidationError('Option `--upload-media` requires at least one file path.');
275
+ }
276
+ parsed.uploadMediaPaths.push(...items);
277
+ }
278
+ else {
279
+ let consumed = 0;
280
+ while (i + 1 < argv.length && !argv[i + 1].startsWith('-')) {
281
+ i += 1;
282
+ for (const item of argv[i].split(',').map((part) => part.trim()).filter(Boolean)) {
283
+ parsed.uploadMediaPaths.push(item);
284
+ consumed += 1;
285
+ }
286
+ }
287
+ if (consumed === 0) {
288
+ throw new CliValidationError('Option `--upload-media` requires at least one file path.');
289
+ }
290
+ }
291
+ continue;
292
+ }
293
+ throw new CliValidationError(`Unknown argument '${arg}' for \`kinloom sync\`.`);
294
+ }
295
+ return parsed;
296
+ }
297
+ function normalizeExitCode(code) {
298
+ if (code === 0 || code === 1 || code === 2 || code === 3) {
299
+ return code;
300
+ }
301
+ return EXIT_ERROR;
302
+ }
141
303
  export async function runCli(argv, options) {
142
304
  const io = options?.io ?? DEFAULT_IO;
143
305
  const fetchImpl = options?.fetchImpl;
144
306
  if (argv.length === 0 || argv[0] === '-h' || argv[0] === '--help' || argv[0] === 'help') {
145
307
  const sub = argv[0] === 'help' ? argv[1] : undefined;
146
- if (sub && COMMAND_HELP[sub]) {
308
+ if (!sub) {
309
+ io.stdout(ROOT_HELP);
310
+ return EXIT_OK;
311
+ }
312
+ if (COMMAND_HELP[sub]) {
147
313
  io.stdout(COMMAND_HELP[sub]);
314
+ return EXIT_OK;
148
315
  }
149
- else {
150
- io.stdout(ROOT_HELP);
316
+ const recordSpec = resolveRecordCommand(sub);
317
+ if (recordSpec) {
318
+ io.stdout(renderRecordCommandHelp(recordSpec));
319
+ return EXIT_OK;
151
320
  }
152
- return EXIT_OK;
321
+ io.stderr(`Unknown command '${sub}'. Run \`kinloom --help\` for available commands.`);
322
+ return EXIT_USAGE;
153
323
  }
154
324
  const [command, ...rest] = argv;
325
+ // Dispatch record, archive-search, guide, and scan/OCR commands before generic --help parsing
326
+ // so subcommand --help (e.g. `kinloom ia grep --help`) and `--script-help` pass through intact.
327
+ const recordSpec = resolveRecordCommand(command);
328
+ if (recordSpec) {
329
+ try {
330
+ const { runRecordCommand } = await import('./commands/records/runner.js');
331
+ const result = await runRecordCommand(recordSpec.command, rest, {
332
+ io: options?.io,
333
+ });
334
+ return normalizeExitCode(result.exitCode);
335
+ }
336
+ catch (err) {
337
+ const message = err instanceof Error ? err.message : String(err);
338
+ io.stderr(`Error: ${message}`);
339
+ return EXIT_ERROR;
340
+ }
341
+ }
155
342
  if (rest.includes('-h') || rest.includes('--help')) {
156
343
  const help = COMMAND_HELP[command];
157
344
  if (!help) {
@@ -178,6 +365,7 @@ export async function runCli(argv, options) {
178
365
  if (!targetDir) {
179
366
  throw new CliValidationError('Missing required positional argument `<dir>`.');
180
367
  }
368
+ const { runInitCommand } = await import('./commands/init.js');
181
369
  const result = await runInitCommand({
182
370
  targetDir,
183
371
  family: requireStringFlag(values.family, '--family'),
@@ -205,6 +393,7 @@ export async function runCli(argv, options) {
205
393
  'reference-year': { type: 'string' },
206
394
  },
207
395
  });
396
+ const { runSliceGedcomCommand } = await import('./commands/sliceGedcom.js');
208
397
  const result = await runSliceGedcomCommand({
209
398
  inputPath: requireStringFlag(values.input, '--input'),
210
399
  outDir: requireStringFlag(values.out, '--out'),
@@ -242,6 +431,7 @@ export async function runCli(argv, options) {
242
431
  const siteUrl = dryRun
243
432
  ? values.site?.trim() || 'http://localhost'
244
433
  : requireStringFlag(values.site, '--site');
434
+ const { runSeedCommand } = await import('./commands/seed.js');
245
435
  const result = await runSeedCommand({
246
436
  dataDir: requireStringFlag(values.data, '--data'),
247
437
  configPath: requireStringFlag(values.config, '--config'),
@@ -280,6 +470,7 @@ export async function runCli(argv, options) {
280
470
  const siteUrl = dryRun
281
471
  ? values.site?.trim() || 'http://localhost'
282
472
  : requireStringFlag(values.site, '--site');
473
+ const { runSubmitBatchCommand } = await import('./commands/submitBatch.js');
283
474
  const result = await runSubmitBatchCommand({
284
475
  filePath: requireStringFlag(filePath, '--file'),
285
476
  siteUrl,
@@ -311,6 +502,7 @@ export async function runCli(argv, options) {
311
502
  'state-file': { type: 'string' },
312
503
  },
313
504
  });
505
+ const { runExportYamlCommand } = await import('./commands/exportYaml.js');
314
506
  const result = await runExportYamlCommand({
315
507
  siteUrl: requireStringFlag(values.site, '--site'),
316
508
  outDir: requireStringFlag(values.out, '--out'),
@@ -345,6 +537,7 @@ export async function runCli(argv, options) {
345
537
  const siteUrl = dryRun
346
538
  ? values.site?.trim() || 'http://localhost'
347
539
  : requireStringFlag(values.site, '--site');
540
+ const { runUploadMediaCommand } = await import('./commands/uploadMedia.js');
348
541
  const result = await runUploadMediaCommand({
349
542
  filePath: requireStringFlag(values.file, '--file'),
350
543
  metadataInput: requireStringFlag(values.metadata, '--metadata'),
@@ -377,12 +570,12 @@ export async function runCli(argv, options) {
377
570
  });
378
571
  let mode;
379
572
  if (values.mode !== undefined) {
380
- const parsedMode = BuildModeSchema.safeParse(values.mode);
381
- if (!parsedMode.success) {
573
+ if (values.mode !== 'private' && values.mode !== 'public') {
382
574
  throw new CliValidationError(`Invalid \`--mode\` '${values.mode}'. Expected 'private' or 'public'.`);
383
575
  }
384
- mode = parsedMode.data;
576
+ mode = values.mode;
385
577
  }
578
+ const { runReconcileCommand } = await import('./commands/reconcile.js');
386
579
  const result = await runReconcileCommand({
387
580
  siteUrl: requireStringFlag(values.site, '--site'),
388
581
  configPath: requireStringFlag(values.config, '--config'),
@@ -400,6 +593,269 @@ export async function runCli(argv, options) {
400
593
  }
401
594
  return EXIT_ERROR;
402
595
  }
596
+ case 'context': {
597
+ const { values, positionals } = safeParseArgs({
598
+ args: rest,
599
+ allowPositionals: true,
600
+ options: {
601
+ person: { type: 'string' },
602
+ repo: { type: 'string' },
603
+ 'ancestry-dir': { type: 'string' },
604
+ json: { type: 'boolean', default: false },
605
+ },
606
+ });
607
+ const personId = requireStringFlag(values.person ?? positionals[0], '--person');
608
+ const [{ runContextCommand }, { measureCommand }] = await Promise.all([
609
+ import('./commands/ops/context.js'),
610
+ import('./commands/ops/telemetry.js'),
611
+ ]);
612
+ const result = await measureCommand({
613
+ subcmd: 'context',
614
+ personId,
615
+ extractResultMeta: (res) => ({
616
+ personId,
617
+ exitCode: EXIT_OK,
618
+ bytesOut: res.bytesOut,
619
+ }),
620
+ }, () => runContextCommand({
621
+ repoDir: values.repo,
622
+ personId,
623
+ ancestryDir: values['ancestry-dir'],
624
+ json: values.json,
625
+ }));
626
+ writeRenderedOutput(io, result.rendered);
627
+ return EXIT_OK;
628
+ }
629
+ case 'integrate': {
630
+ const { values, positionals } = safeParseArgs({
631
+ args: rest,
632
+ allowPositionals: true,
633
+ options: {
634
+ person: { type: 'string' },
635
+ repo: { type: 'string' },
636
+ 'package-dir': { type: 'string' },
637
+ 'dry-run': { type: 'boolean', default: false },
638
+ json: { type: 'boolean', default: false },
639
+ },
640
+ });
641
+ const personId = requireStringFlag(values.person ?? positionals[0], '--person');
642
+ const [{ runIntegrateCommand }, { measureCommand }] = await Promise.all([
643
+ import('./commands/ops/integrate.js'),
644
+ import('./commands/ops/telemetry.js'),
645
+ ]);
646
+ const result = await measureCommand({
647
+ subcmd: values['dry-run'] ? 'integrate --dry-run' : 'integrate',
648
+ personId,
649
+ extractResultMeta: (res) => ({
650
+ personId,
651
+ exitCode: EXIT_OK,
652
+ bytesOut: Buffer.byteLength(res.rendered, 'utf8'),
653
+ }),
654
+ }, () => runIntegrateCommand({
655
+ repoDir: values.repo,
656
+ personId,
657
+ packageDir: values['package-dir'],
658
+ dryRun: values['dry-run'],
659
+ json: values.json,
660
+ }));
661
+ writeRenderedOutput(io, result.rendered);
662
+ return EXIT_OK;
663
+ }
664
+ case 'audit': {
665
+ const { values, positionals } = safeParseArgs({
666
+ args: rest,
667
+ allowPositionals: true,
668
+ options: {
669
+ person: { type: 'string' },
670
+ repo: { type: 'string' },
671
+ 'package-dir': { type: 'string' },
672
+ json: { type: 'boolean', default: false },
673
+ },
674
+ });
675
+ const personId = requireStringFlag(values.person ?? positionals[0], '--person');
676
+ const [{ runAuditCommand }, { measureCommand }] = await Promise.all([
677
+ import('./commands/ops/audit.js'),
678
+ import('./commands/ops/telemetry.js'),
679
+ ]);
680
+ const result = await measureCommand({
681
+ subcmd: 'audit',
682
+ personId,
683
+ extractResultMeta: (res) => ({
684
+ personId,
685
+ exitCode: res.ok ? EXIT_OK : EXIT_ERROR,
686
+ bytesOut: Buffer.byteLength(res.rendered, 'utf8'),
687
+ }),
688
+ }, () => runAuditCommand({
689
+ repoDir: values.repo,
690
+ personId,
691
+ packageDir: values['package-dir'],
692
+ json: values.json,
693
+ }));
694
+ writeRenderedOutput(io, result.rendered);
695
+ return result.ok ? EXIT_OK : EXIT_ERROR;
696
+ }
697
+ case 'verify': {
698
+ const { values } = safeParseArgs({
699
+ args: rest,
700
+ allowPositionals: false,
701
+ options: {
702
+ repo: { type: 'string' },
703
+ json: { type: 'boolean', default: false },
704
+ },
705
+ });
706
+ const [{ runVerifyCommand }, { measureCommand }] = await Promise.all([
707
+ import('./commands/ops/verify.js'),
708
+ import('./commands/ops/telemetry.js'),
709
+ ]);
710
+ const result = await measureCommand({
711
+ subcmd: 'verify',
712
+ extractResultMeta: (res) => ({
713
+ exitCode: res.ok ? EXIT_OK : EXIT_ERROR,
714
+ bytesOut: Buffer.byteLength(res.rendered, 'utf8'),
715
+ }),
716
+ }, () => runVerifyCommand({
717
+ repoDir: values.repo,
718
+ json: values.json,
719
+ }));
720
+ writeRenderedOutput(io, result.rendered);
721
+ return result.ok ? EXIT_OK : EXIT_ERROR;
722
+ }
723
+ case 'sync': {
724
+ const parsed = parseSyncArgs(rest);
725
+ const [{ parseDeleteTargets, parseEntityTypeList, runSyncCommand }, { measureCommand }] = await Promise.all([
726
+ import('./commands/ops/sync.js'),
727
+ import('./commands/ops/telemetry.js'),
728
+ ]);
729
+ const types = parsed.typesRaw ? parseEntityTypeList(parsed.typesRaw) : undefined;
730
+ const explicitDeletes = parsed.deleteTokens.length > 0
731
+ ? parseDeleteTargets(parsed.deleteTokens.join(','))
732
+ : undefined;
733
+ const result = await measureCommand({
734
+ subcmd: parsed.dryRun ? 'sync --dry-run' : 'sync',
735
+ extractResultMeta: (res) => ({
736
+ exitCode: res.liveVerification && !res.liveVerification.ok ? EXIT_ERROR : EXIT_OK,
737
+ bytesOut: Buffer.byteLength(res.rendered, 'utf8'),
738
+ }),
739
+ }, () => runSyncCommand({
740
+ repoDir: parsed.repoDir,
741
+ siteUrl: parsed.siteUrl,
742
+ types,
743
+ syncMissingMedia: parsed.syncMissingMedia,
744
+ uploadMediaPaths: parsed.uploadMediaPaths,
745
+ concurrency: parsed.concurrency,
746
+ chunkSize: parsed.chunkSize,
747
+ summary: parsed.summary,
748
+ allowDeletes: parsed.allowDeletes,
749
+ explicitDeletes,
750
+ includeLiving: parsed.includeLiving,
751
+ verifyLive: parsed.verifyLive,
752
+ dryRun: parsed.dryRun,
753
+ json: parsed.json,
754
+ fetchImpl,
755
+ }));
756
+ writeRenderedOutput(io, result.rendered);
757
+ return result.liveVerification && !result.liveVerification.ok ? EXIT_ERROR : EXIT_OK;
758
+ }
759
+ case 'dates': {
760
+ const sub = rest[0];
761
+ if (sub !== 'weekday' && sub !== 'diff' && sub !== 'age') {
762
+ throw new CliValidationError(sub
763
+ ? `Unknown dates subcommand '${sub}'. Expected \`weekday\`, \`diff\`, or \`age\`.`
764
+ : 'Missing dates subcommand. Expected `weekday`, `diff`, or `age`.');
765
+ }
766
+ const subArgs = rest.slice(1);
767
+ const { values, positionals } = safeParseArgs({
768
+ args: subArgs,
769
+ allowPositionals: true,
770
+ options: {
771
+ at: { type: 'string', multiple: true },
772
+ json: { type: 'boolean', default: false },
773
+ },
774
+ });
775
+ const [{ runDatesCommand }, { measureCommand }] = await Promise.all([
776
+ import('./commands/ops/dates.js'),
777
+ import('./commands/ops/telemetry.js'),
778
+ ]);
779
+ const result = await measureCommand({
780
+ subcmd: `dates ${sub}`,
781
+ extractResultMeta: (res) => ({
782
+ exitCode: EXIT_OK,
783
+ bytesOut: Buffer.byteLength(res.rendered, 'utf8'),
784
+ }),
785
+ }, async () => {
786
+ if (sub === 'weekday') {
787
+ if (values.at && values.at.length > 0) {
788
+ throw new CliValidationError('Option `--at` is only valid with `kinloom dates age`.');
789
+ }
790
+ if (positionals.length !== 1) {
791
+ throw new CliValidationError('Usage: kinloom dates weekday <YYYY-MM-DD> [--json]');
792
+ }
793
+ return runDatesCommand({
794
+ subcommand: 'weekday',
795
+ date: positionals[0],
796
+ json: values.json,
797
+ });
798
+ }
799
+ if (sub === 'diff') {
800
+ if (values.at && values.at.length > 0) {
801
+ throw new CliValidationError('Option `--at` is only valid with `kinloom dates age`.');
802
+ }
803
+ if (positionals.length !== 2) {
804
+ throw new CliValidationError('Usage: kinloom dates diff <start-YYYY-MM-DD> <end-YYYY-MM-DD> [--json]');
805
+ }
806
+ return runDatesCommand({
807
+ subcommand: 'diff',
808
+ startDate: positionals[0],
809
+ endDate: positionals[1],
810
+ json: values.json,
811
+ });
812
+ }
813
+ if (positionals.length < 1) {
814
+ throw new CliValidationError('Usage: kinloom dates age <birth-YYYY-MM-DD> --at <YYYY-MM-DD> [--at ...] [--json]');
815
+ }
816
+ const [birthDate, ...positionalAts] = positionals;
817
+ const atDates = [...(values.at ?? []), ...positionalAts];
818
+ return runDatesCommand({
819
+ subcommand: 'age',
820
+ birthDate,
821
+ atDates,
822
+ json: values.json,
823
+ });
824
+ });
825
+ writeRenderedOutput(io, result.rendered);
826
+ return EXIT_OK;
827
+ }
828
+ case 'telemetry': {
829
+ const sub = rest[0];
830
+ const subArgs = sub === 'report' ? rest.slice(1) : rest;
831
+ if (sub && sub !== 'report' && !sub.startsWith('-')) {
832
+ throw new CliValidationError(`Unknown telemetry subcommand '${sub}'. Use \`kinloom telemetry report\`.`);
833
+ }
834
+ const { values } = safeParseArgs({
835
+ args: subArgs,
836
+ allowPositionals: false,
837
+ options: {
838
+ 'since-hours': { type: 'string' },
839
+ file: { type: 'string' },
840
+ json: { type: 'boolean', default: false },
841
+ },
842
+ });
843
+ const { measureCommand, runTelemetryReportCommand } = await import('./commands/ops/telemetry.js');
844
+ const result = await measureCommand({
845
+ subcmd: 'telemetry report',
846
+ filePath: values.file,
847
+ extractResultMeta: (res) => ({
848
+ exitCode: EXIT_OK,
849
+ bytesOut: Buffer.byteLength(res.rendered, 'utf8'),
850
+ }),
851
+ }, () => runTelemetryReportCommand({
852
+ filePath: values.file,
853
+ sinceHours: parseOptionalPositiveNumber(values['since-hours'], '--since-hours'),
854
+ json: values.json,
855
+ }));
856
+ writeRenderedOutput(io, result.rendered);
857
+ return EXIT_OK;
858
+ }
403
859
  default:
404
860
  io.stderr(`Unknown command '${command}'. Run \`kinloom --help\` for available commands.`);
405
861
  return EXIT_USAGE;
@@ -438,6 +894,12 @@ function isExecutedDirectly() {
438
894
  }
439
895
  }
440
896
  if (isExecutedDirectly()) {
897
+ process.stdout.on('error', (err) => {
898
+ if (err.code === 'EPIPE') {
899
+ process.exit(0);
900
+ }
901
+ throw err;
902
+ });
441
903
  const exitCode = await runCli(process.argv.slice(2));
442
904
  process.exitCode = exitCode;
443
905
  }