capable-kit 0.0.1-alpha.7 → 0.1.0-alpha.10

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 (104) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +6 -0
  3. package/dist/ai-sdk.d.mts +3 -3
  4. package/dist/ai-sdk.mjs +9 -7
  5. package/dist/ai-sdk.mjs.map +1 -1
  6. package/dist/app.d.mts +2 -2
  7. package/dist/app.mjs +2 -2
  8. package/dist/bin.mjs +12 -9
  9. package/dist/bin.mjs.map +1 -1
  10. package/dist/cli.d.mts +9 -1
  11. package/dist/cli.mjs +1 -1
  12. package/dist/core.d.mts +3 -3
  13. package/dist/core.mjs +1 -1
  14. package/dist/eve.d.mts +82 -5
  15. package/dist/eve.mjs +364 -23
  16. package/dist/eve.mjs.map +1 -1
  17. package/dist/http.d.mts +2 -2
  18. package/dist/http.mjs +2 -2
  19. package/dist/{index-Dbc4g9WM.d.mts → index-1A44jLuE.d.mts} +54 -16
  20. package/dist/{index-DwXlaTXI.d.mts → index-CHuCLJIs.d.mts} +20 -4
  21. package/dist/{index-D2CRRUzH.d.mts → index-D-NV4PiU.d.mts} +6 -5
  22. package/dist/{index-Be8-UVBC.d.mts → index-WiBWfyTn.d.mts} +66 -27
  23. package/dist/index.d.mts +4 -4
  24. package/dist/index.mjs +3 -3
  25. package/dist/mcp.d.mts +40 -5
  26. package/dist/mcp.mjs +1 -1
  27. package/dist/mount-BmLHp349.mjs +235 -0
  28. package/dist/mount-BmLHp349.mjs.map +1 -0
  29. package/dist/react-query.d.mts +2 -2
  30. package/dist/react-query.mjs +1 -1
  31. package/dist/react-query.mjs.map +1 -1
  32. package/dist/runtime-support.d.mts +1 -1
  33. package/dist/runtime-support.mjs +8 -8
  34. package/dist/runtime-support.mjs.map +1 -1
  35. package/dist/server.d.mts +1 -1
  36. package/dist/server.mjs +1 -1
  37. package/dist/{src-Db6-XSnU.mjs → src-3LE9S4QE.mjs} +67 -38
  38. package/dist/src-3LE9S4QE.mjs.map +1 -0
  39. package/dist/{src-DdV82An-.mjs → src-B2WeUwUT.mjs} +69 -34
  40. package/dist/src-B2WeUwUT.mjs.map +1 -0
  41. package/dist/{src-CDxL6w3d.mjs → src-C5jGDnuu.mjs} +9 -6
  42. package/dist/src-C5jGDnuu.mjs.map +1 -0
  43. package/dist/src-DePlcG_t.mjs +787 -0
  44. package/dist/src-DePlcG_t.mjs.map +1 -0
  45. package/dist/{src-BF70JLxI.mjs → src-_6OmFRYa.mjs} +185 -38
  46. package/dist/src-_6OmFRYa.mjs.map +1 -0
  47. package/dist/{subscription-Bq792Ad2.d.mts → subscription-DPdwovhw.d.mts} +2 -2
  48. package/dist/swr.d.mts +2 -2
  49. package/dist/swr.mjs +1 -1
  50. package/dist/swr.mjs.map +1 -1
  51. package/docs/CONTEXT.md +42 -21
  52. package/docs/README.md +3 -0
  53. package/docs/internal/README.md +3 -0
  54. package/docs/internal/adr/0001-capability-is-the-semantic-boundary.md +1 -1
  55. package/docs/internal/adr/0002-version-the-capable-value-codec.md +24 -0
  56. package/docs/internal/adr/0003-capability-reference-customization.md +68 -0
  57. package/docs/internal/architecture.md +64 -19
  58. package/docs/internal/capability-first-model.md +127 -18
  59. package/docs/internal/eve-recovery-validation.md +86 -0
  60. package/docs/internal/feedback/v-ray/README.md +258 -0
  61. package/docs/internal/feedback/v-ray/inference.mjs +43 -0
  62. package/docs/internal/feedback/v-ray/reproduce.mjs +36 -0
  63. package/docs/internal/implementation-friction.md +481 -1
  64. package/docs/internal/releases.md +79 -0
  65. package/docs/site/capable-orpc-and-trpc.mdx +5 -5
  66. package/docs/site/concepts/apps.mdx +17 -8
  67. package/docs/site/concepts/architecture.mdx +10 -2
  68. package/docs/site/concepts/capabilities.mdx +41 -4
  69. package/docs/site/concepts/errors.mdx +11 -1
  70. package/docs/site/concepts/presentations.mdx +20 -0
  71. package/docs/site/hosting/any-fetch-host.mdx +2 -2
  72. package/docs/site/hosting/next-js.mdx +38 -4
  73. package/docs/site/hosting/standalone-server.mdx +2 -2
  74. package/docs/site/introduction.mdx +9 -6
  75. package/docs/site/patterns/composition.mdx +159 -11
  76. package/docs/site/patterns/remote-apps.mdx +68 -10
  77. package/docs/site/patterns/subscriptions.mdx +79 -32
  78. package/docs/site/quickstart.mdx +19 -14
  79. package/docs/site/reference/packages-and-entry-points.mdx +52 -5
  80. package/docs/site/reference/surface-metadata.mdx +7 -2
  81. package/docs/site/reference/the-cap-cli.mdx +2 -2
  82. package/docs/site/surfaces/ai-sdk.mdx +3 -3
  83. package/docs/site/surfaces/cli.mdx +47 -3
  84. package/docs/site/surfaces/eve.mdx +67 -20
  85. package/docs/site/surfaces/mcp.mdx +73 -5
  86. package/docs/site/surfaces/react-query.mdx +3 -3
  87. package/docs/site/surfaces/swr.mdx +3 -3
  88. package/docs/site/surfaces/typescript.mdx +8 -8
  89. package/docs/site/surfaces.mdx +1 -1
  90. package/package-docs.mjs +3 -0
  91. package/package.json +11 -11
  92. package/src/bin.ts +0 -0
  93. package/src/index.test.ts +2 -1
  94. package/src/index.ts +6 -1
  95. package/src/mcp.ts +4 -0
  96. package/src/package.test.ts +9 -0
  97. package/dist/mount-xvMsjz1B.mjs +0 -178
  98. package/dist/mount-xvMsjz1B.mjs.map +0 -1
  99. package/dist/src-BF70JLxI.mjs.map +0 -1
  100. package/dist/src-C2MGIlT0.mjs +0 -464
  101. package/dist/src-C2MGIlT0.mjs.map +0 -1
  102. package/dist/src-CDxL6w3d.mjs.map +0 -1
  103. package/dist/src-Db6-XSnU.mjs.map +0 -1
  104. package/dist/src-DdV82An-.mjs.map +0 -1
@@ -1,5 +1,5 @@
1
- import { y as renderPresentationMarkdown } from "./src-DdV82An-.mjs";
2
- import { a as TransportError, c as getAppRuntime } from "./src-C2MGIlT0.mjs";
1
+ import { y as renderPresentationMarkdown } from "./src-B2WeUwUT.mjs";
2
+ import { a as getCapabilityNavigationMeta, c as TransportError, d as getAppRuntime, i as getCapabilityDisplay } from "./src-DePlcG_t.mjs";
3
3
  import { render } from "markdansi";
4
4
  //#region packages/cli/src/commands.ts
5
5
  function collectCommands(nodes, parent = []) {
@@ -15,12 +15,18 @@ function collectCommands(nodes, parent = []) {
15
15
  groups.push(...children.groups);
16
16
  continue;
17
17
  }
18
- const rawMeta = node.meta.cli;
18
+ const capability = {
19
+ ...node,
20
+ ...getCapabilityDisplay(node)
21
+ };
22
+ const rawMeta = capability.meta.cli;
19
23
  if (rawMeta === false) continue;
20
24
  const meta = rawMeta ?? {};
25
+ const navigationMeta = getCapabilityNavigationMeta(node, "cli");
26
+ const navigation = navigationMeta === false ? {} : navigationMeta ?? {};
21
27
  commands.push({
22
- command: meta.command ?? [...parent, meta.name ?? node.path.at(-1)],
23
- capability: node,
28
+ command: navigation.command ?? [...parent, navigation.name ?? node.path.at(-1)],
29
+ capability,
24
30
  meta
25
31
  });
26
32
  }
@@ -88,6 +94,7 @@ const GLOBAL_OPTIONS = [{
88
94
  description: "Show help"
89
95
  }];
90
96
  function renderRootHelp(manifest, commands, groups, invocationName, style) {
97
+ const root = commands.find((command) => command.command.length === 0);
91
98
  const sections = commandSections(commands, groups);
92
99
  const nested = sections.some((section) => section.title !== void 0);
93
100
  const column = Math.max(descriptionColumn(sections.flatMap((section) => section.rows), nested ? `${ROW_INDENT} ` : ROW_INDENT), descriptionColumn(GLOBAL_OPTIONS));
@@ -95,15 +102,19 @@ function renderRootHelp(manifest, commands, groups, invocationName, style) {
95
102
  banner({
96
103
  title: manifest.name,
97
104
  ...manifest.description ? { description: manifest.description } : {},
98
- usage: `${invocationName} <command> [options]`,
105
+ usage: [
106
+ invocationName,
107
+ root && commands.length === 1 ? signature(root) : "<command>",
108
+ "[options]"
109
+ ].filter(Boolean).join(" "),
99
110
  style
100
111
  }),
101
112
  renderSection("Commands", sections.map((section) => [section.title ? `${ROW_INDENT}${style.dim(section.title)}` : void 0, renderRows(section.rows, style, {
102
113
  column,
103
114
  ...section.title ? { indent: `${ROW_INDENT} ` } : {}
104
115
  })].filter(Boolean).join("\n")).join("\n\n"), style),
105
- renderSection("Options", renderRows(GLOBAL_OPTIONS, style, { column }), style),
106
- hint(`Run \`${invocationName} <command> --help\` for details on a command.`, style)
116
+ root ? renderCommandInputs(root, style, column) : renderSection("Options", renderRows(GLOBAL_OPTIONS, style, { column }), style),
117
+ commands.some((command) => command.command.length > 0) ? hint(`Run \`${invocationName} <command> --help\` for details on a command.`, style) : void 0
107
118
  ]);
108
119
  }
109
120
  function renderGroupHelp(group, commands, invocationName, style) {
@@ -126,6 +137,18 @@ function renderGroupHelp(group, commands, invocationName, style) {
126
137
  ]);
127
138
  }
128
139
  function renderCommandHelp(command, invocationName, style) {
140
+ return renderHelp([banner({
141
+ ...command.capability.title ? { title: command.capability.title } : {},
142
+ ...command.capability.description ? { description: command.capability.description } : {},
143
+ usage: [
144
+ invocationName,
145
+ signature(command),
146
+ "[options]"
147
+ ].join(" "),
148
+ style
149
+ }), renderCommandInputs(command, style)]);
150
+ }
151
+ function renderCommandInputs(command, style, minColumn = 0) {
129
152
  const properties = fields(command);
130
153
  const required = requiredFields(command);
131
154
  const positionals = command.meta.positional ?? [];
@@ -136,30 +159,20 @@ function renderCommandHelp(command, invocationName, style) {
136
159
  const optionRows = [...Object.entries(properties).filter(([name]) => !positionals.includes(name)).map(([name, schema]) => ({
137
160
  label: optionLabel(name, schema),
138
161
  ...description(schema, { required: required.has(name) })
139
- })), ...command.capability.subscription ? [{
162
+ })), ...command.capability.execution === "live" ? [{
140
163
  label: "--watch",
141
164
  description: "Stream updates until interrupted"
142
165
  }] : []];
143
- const column = descriptionColumn([
166
+ const column = Math.max(minColumn, descriptionColumn([
144
167
  ...argumentRows,
145
168
  ...optionRows,
146
169
  ...GLOBAL_OPTIONS
147
- ]);
148
- return renderHelp([
149
- banner({
150
- ...command.capability.title ? { title: command.capability.title } : {},
151
- ...command.capability.description ? { description: command.capability.description } : {},
152
- usage: [
153
- invocationName,
154
- signature(command),
155
- "[options]"
156
- ].join(" "),
157
- style
158
- }),
170
+ ]));
171
+ return [
159
172
  argumentRows.length ? renderSection("Arguments", renderRows(argumentRows, style, { column }), style) : void 0,
160
173
  optionRows.length ? renderSection("Options", renderRows(optionRows, style, { column }), style) : void 0,
161
174
  renderSection(optionRows.length ? "Global Options" : "Options", renderRows(GLOBAL_OPTIONS, style, { column }), style)
162
- ]);
175
+ ].filter(Boolean).join("\n\n");
163
176
  }
164
177
  /** Root commands are grouped under their top-level group, Vercel style. */
165
178
  function commandSections(commands, groups) {
@@ -245,7 +258,8 @@ function renderCliCapabilityResult(result, options) {
245
258
  function renderCliMarkdown(markdown, options) {
246
259
  return options.isTTY ? render(markdown, {
247
260
  color: options.color,
248
- width: options.columns
261
+ width: options.columns,
262
+ ...options.markdown
249
263
  }) : markdown;
250
264
  }
251
265
  //#endregion
@@ -259,6 +273,7 @@ function createCli(app, cliOptions = {}) {
259
273
  ...cliOptions.color !== void 0 ? { color: cliOptions.color } : {},
260
274
  ...cliOptions.isTTY !== void 0 ? { isTTY: cliOptions.isTTY } : {},
261
275
  ...cliOptions.columns !== void 0 ? { columns: cliOptions.columns } : {},
276
+ ...cliOptions.markdown ? { markdown: cliOptions.markdown } : {},
262
277
  ...options.io ? { io: options.io } : {}
263
278
  });
264
279
  } });
@@ -291,7 +306,14 @@ async function runCli(options) {
291
306
  "--help",
292
307
  "-h"
293
308
  ].includes(argument));
294
- if (argv.length === 0) {
309
+ const roots = catalog.commands.filter((command) => command.command.length === 0);
310
+ if (roots.length > 1) {
311
+ io.stderr("Multiple Capabilities map to the root CLI command");
312
+ return 2;
313
+ }
314
+ const root = roots[0];
315
+ const runsRoot = root && !wantsHelp && (json || watch || root.capability.execution === "events");
316
+ if (argv.length === 0 && !runsRoot) {
295
317
  io.stdout(renderRootHelp(manifest, catalog.commands, catalog.groups, invocationName, style));
296
318
  return 0;
297
319
  }
@@ -318,9 +340,9 @@ async function runCli(options) {
318
340
  return 2;
319
341
  }
320
342
  try {
321
- if (watch && !command.capability.subscription) throw new CliUsageError(`Option --watch is only available for subscribable Capabilities`);
343
+ if (watch && command.capability.execution === "unary") throw new CliUsageError(`Option --watch is only available for subscribable Capabilities`);
322
344
  const input = parseArguments(argv.slice(command.command.length), command, invocationName);
323
- if (watch) return await runWatchedCommand({
345
+ if (watch || command.capability.execution === "events") return await runWatchedCommand({
324
346
  runtime,
325
347
  command,
326
348
  input,
@@ -328,7 +350,8 @@ async function runCli(options) {
328
350
  io,
329
351
  color,
330
352
  isTTY,
331
- columns
353
+ columns,
354
+ ...options.markdown ? { markdown: options.markdown } : {}
332
355
  });
333
356
  const result = await runtime.call({
334
357
  id: command.capability.id,
@@ -338,7 +361,8 @@ async function runCli(options) {
338
361
  io.stdout(json ? JSON.stringify(result.output, null, 2) : renderCliCapabilityResult(result, {
339
362
  color,
340
363
  isTTY,
341
- columns
364
+ columns,
365
+ ...options.markdown ? { markdown: options.markdown } : {}
342
366
  }));
343
367
  return 0;
344
368
  } catch (error) {
@@ -361,13 +385,14 @@ async function runWatchedCommand(options) {
361
385
  const controller = new AbortController();
362
386
  const abort = () => controller.abort();
363
387
  process.once("SIGINT", abort);
364
- const stream = options.runtime.subscribe({
365
- id: options.command.capability.id,
366
- input: options.input,
367
- ...!options.json ? { presentation: true } : {},
368
- signal: controller.signal
369
- });
388
+ let stream;
370
389
  try {
390
+ stream = await options.runtime.subscribe({
391
+ id: options.command.capability.id,
392
+ input: options.input,
393
+ ...!options.json ? { presentation: true } : {},
394
+ signal: controller.signal
395
+ });
371
396
  let frame = 0;
372
397
  let previousFrameLines = 0;
373
398
  for await (const result of stream) {
@@ -376,6 +401,10 @@ async function runWatchedCommand(options) {
376
401
  continue;
377
402
  }
378
403
  const presentation = renderCliCapabilityResult(result, options);
404
+ if (options.command.capability.execution === "events") {
405
+ options.io.stdout(withTrailingNewline(presentation));
406
+ continue;
407
+ }
379
408
  options.io.stdout(formatWatchFrame(presentation, frame++, options.isTTY, previousFrameLines));
380
409
  previousFrameLines = countFrameLines(presentation);
381
410
  }
@@ -385,7 +414,7 @@ async function runWatchedCommand(options) {
385
414
  throw error;
386
415
  } finally {
387
416
  process.off("SIGINT", abort);
388
- await stream.return?.();
417
+ await stream?.return?.();
389
418
  }
390
419
  }
391
420
  function formatWatchFrame(value, index, isTTY, previousFrameLines) {
@@ -402,7 +431,7 @@ function isAbortError(error) {
402
431
  function parseArguments(argv, command, invocationName) {
403
432
  const capability = command.capability;
404
433
  const positional = command.meta.positional ?? [];
405
- const commandName = `${invocationName} ${command.command.join(" ")}`;
434
+ const commandName = [invocationName, ...command.command].join(" ");
406
435
  const schema = capability.input;
407
436
  const properties = schema?.properties;
408
437
  const input = {};
@@ -495,4 +524,4 @@ function kebabCase(value) {
495
524
  //#endregion
496
525
  export { createCliStyle as a, renderSection as c, ROW_INDENT as i, supportsColor as l, runCli as n, descriptionColumn as o, MARGIN as r, renderRows as s, createCli as t };
497
526
 
498
- //# sourceMappingURL=src-Db6-XSnU.mjs.map
527
+ //# sourceMappingURL=src-3LE9S4QE.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"src-3LE9S4QE.mjs","names":["kebabCase","renderMarkdown"],"sources":["../../cli/src/commands.ts","../../cli/src/style.ts","../../cli/src/help.ts","../../cli/src/presentation.ts","../../cli/src/index.ts"],"sourcesContent":["import {\n getCapabilityDisplay,\n getCapabilityNavigationMeta,\n} from \"@capable/app\";\nimport type {\n ManifestGroup,\n ManifestNode,\n ManifestCapability,\n} from \"@capable/app\";\nimport type {\n CliGroupMeta,\n CliCapabilityMeta,\n} from \"./index.ts\";\n\nexport type CliCommand = {\n readonly command: readonly string[];\n readonly capability: ManifestCapability;\n readonly meta: Exclude<CliCapabilityMeta, false>;\n};\n\nexport type CliCommandGroup = {\n readonly command: readonly string[];\n readonly title?: string;\n readonly description?: string;\n};\n\nexport type CliCommandCatalog = {\n readonly commands: readonly CliCommand[];\n readonly groups: readonly CliCommandGroup[];\n};\n\nexport function collectCommands(\n nodes: readonly ManifestNode[],\n parent: readonly string[] = [],\n): CliCommandCatalog {\n const commands: CliCommand[] = [];\n const groups: CliCommandGroup[] = [];\n\n for (const node of nodes) {\n if (node.type === \"group\") {\n const meta = (node.meta.cli ?? {}) as CliGroupMeta;\n const command = [...parent, meta.name ?? node.key];\n groups.push(groupFrom(node, command));\n const children = collectCommands(node.children, command);\n commands.push(...children.commands);\n groups.push(...children.groups);\n continue;\n }\n\n const capability = { ...node, ...getCapabilityDisplay(node) };\n const rawMeta = capability.meta.cli as CliCapabilityMeta | undefined;\n if (rawMeta === false) continue;\n const meta = rawMeta ?? {};\n // Curated leaves get navigation from the destination tree, unless explicitly\n // overridden there. Keep source non-navigational metadata (e.g. positionals).\n const navigationMeta = getCapabilityNavigationMeta(node, \"cli\");\n const navigation = navigationMeta === false ? {} : navigationMeta ?? {};\n commands.push({\n command: navigation.command ?? [...parent, navigation.name ?? node.path.at(-1)!],\n capability,\n meta,\n });\n }\n\n return {\n commands: Object.freeze(commands),\n groups: Object.freeze(groups),\n };\n}\n\nfunction groupFrom(\n node: ManifestGroup,\n command: readonly string[],\n): CliCommandGroup {\n return Object.freeze({\n command: Object.freeze(command),\n ...(node.title ? { title: node.title } : {}),\n ...(node.description ? { description: node.description } : {}),\n });\n}\n","export type CliStyle = {\n readonly bold: (text: string) => string;\n readonly accent: (text: string) => string;\n readonly dim: (text: string) => string;\n};\n\nexport type CliRow = {\n readonly label: string;\n readonly description?: string;\n};\n\n/** Every help line hangs off this margin. */\nexport const MARGIN = \" \";\n\n/** Rows sit one step inside their section heading. */\nexport const ROW_INDENT = \" \";\n\n/** Widest label that still keeps descriptions in a single column. */\nconst MAX_LABEL_WIDTH = 30;\n\nconst LABEL_GAP = 2;\n\nexport function createCliStyle(color?: boolean): CliStyle {\n const enabled = color ?? supportsColor();\n return {\n bold: enabled\n ? (text: string) => `\\u001B[1m${text}\\u001B[22m`\n : identity,\n accent: enabled\n ? (text: string) => `\\u001B[36m${text}\\u001B[39m`\n : identity,\n dim: enabled\n ? (text: string) => `\\u001B[2m${text}\\u001B[22m`\n : identity,\n };\n}\n\nexport function supportsColor(\n env: Record<string, string | undefined> = process.env,\n isTTY: boolean = Boolean(process.stdout.isTTY),\n): boolean {\n if (\"NO_COLOR\" in env) return false;\n if (env.FORCE_COLOR !== undefined) return env.FORCE_COLOR !== \"0\";\n return isTTY && env.TERM !== \"dumb\";\n}\n\nexport function renderRows(\n rows: readonly CliRow[],\n style: CliStyle,\n options: {\n readonly indent?: string;\n /** Absolute column for descriptions, so sibling sections stay aligned. */\n readonly column?: number;\n } = {},\n): string {\n const indent = options.indent ?? ROW_INDENT;\n const width = Math.max(\n 0,\n (options.column ?? descriptionColumn(rows, indent)) - indent.length -\n LABEL_GAP,\n );\n return rows.map(({ label, description }) => {\n const line = `${indent}${style.accent(label)}`;\n if (!description) return line;\n return label.length > width\n ? `${line}\\n${indent}${\" \".repeat(width + LABEL_GAP)}${style.dim(description)}`\n : `${line}${\" \".repeat(width - label.length + LABEL_GAP)}${\n style.dim(description)\n }`;\n }).join(\"\\n\");\n}\n\n/** Shared description column so sibling sections stay visually aligned. */\nexport function descriptionColumn(\n rows: readonly CliRow[],\n indent: string = ROW_INDENT,\n): number {\n const labels = rows\n .filter(({ description }) => description !== undefined)\n .map(({ label }) => label.length)\n .filter((length) => length <= MAX_LABEL_WIDTH);\n return indent.length + LABEL_GAP + Math.max(0, ...labels);\n}\n\nexport function renderSection(\n title: string,\n body: string,\n style: CliStyle,\n): string {\n return `${MARGIN}${style.bold(title)}\\n\\n${body}`;\n}\n\nfunction identity(text: string): string {\n return text;\n}\n","import type {\n ApplicationManifest,\n JsonSchema,\n} from \"@capable/app\";\nimport type {\n CliCommand,\n CliCommandGroup,\n} from \"./commands.ts\";\nimport {\n descriptionColumn,\n MARGIN,\n renderRows,\n renderSection,\n ROW_INDENT,\n type CliRow,\n type CliStyle,\n} from \"./style.ts\";\n\nconst GLOBAL_OPTIONS: readonly CliRow[] = [\n { label: \"--json\", description: \"Print canonical JSON\" },\n { label: \"-h, --help\", description: \"Show help\" },\n];\n\nexport function renderRootHelp(\n manifest: Pick<ApplicationManifest, \"name\" | \"description\">,\n commands: readonly CliCommand[],\n groups: readonly CliCommandGroup[],\n invocationName: string,\n style: CliStyle,\n): string {\n const root = commands.find((command) => command.command.length === 0);\n const sections = commandSections(commands, groups);\n const nested = sections.some((section) => section.title !== undefined);\n const column = Math.max(\n descriptionColumn(\n sections.flatMap((section) => section.rows),\n nested ? `${ROW_INDENT}${MARGIN}` : ROW_INDENT,\n ),\n descriptionColumn(GLOBAL_OPTIONS),\n );\n return renderHelp([\n banner({\n title: manifest.name,\n ...(manifest.description ? { description: manifest.description } : {}),\n usage: [invocationName, root && commands.length === 1 ? signature(root) : \"<command>\", \"[options]\"].filter(Boolean).join(\" \"),\n style,\n }),\n renderSection(\n \"Commands\",\n sections\n .map((section) =>\n [\n section.title ? `${ROW_INDENT}${style.dim(section.title)}` : undefined,\n renderRows(section.rows, style, {\n column,\n ...(section.title ? { indent: `${ROW_INDENT}${MARGIN}` } : {}),\n }),\n ].filter(Boolean).join(\"\\n\")\n )\n .join(\"\\n\\n\"),\n style,\n ),\n root\n ? renderCommandInputs(root, style, column)\n : renderSection(\"Options\", renderRows(GLOBAL_OPTIONS, style, { column }), style),\n commands.some((command) => command.command.length > 0)\n ? hint(`Run \\`${invocationName} <command> --help\\` for details on a command.`, style)\n : undefined,\n ]);\n}\n\nexport function renderGroupHelp(\n group: CliCommandGroup,\n commands: readonly CliCommand[],\n invocationName: string,\n style: CliStyle,\n): string {\n const prefix = group.command.join(\" \");\n const rows = commands\n .filter((candidate) => startsWith(candidate.command, group.command))\n .map((candidate) => ({\n label: signature(candidate, candidate.command.slice(group.command.length)),\n ...describe(candidate),\n }));\n const column = descriptionColumn([...rows, ...GLOBAL_OPTIONS]);\n return renderHelp([\n banner({\n ...(group.title ? { title: group.title } : {}),\n ...(group.description ? { description: group.description } : {}),\n usage: `${invocationName} ${prefix} <command> [options]`,\n style,\n }),\n renderSection(\"Commands\", renderRows(rows, style, { column }), style),\n renderSection(\"Options\", renderRows(GLOBAL_OPTIONS, style, { column }), style),\n hint(\n `Run \\`${invocationName} ${prefix} <command> --help\\` for details on a command.`,\n style,\n ),\n ]);\n}\n\nexport function renderCommandHelp(\n command: CliCommand,\n invocationName: string,\n style: CliStyle,\n): string {\n return renderHelp([\n banner({\n ...(command.capability.title ? { title: command.capability.title } : {}),\n ...(command.capability.description\n ? { description: command.capability.description }\n : {}),\n usage: [invocationName, signature(command), \"[options]\"].join(\" \"),\n style,\n }),\n renderCommandInputs(command, style),\n ]);\n}\n\nfunction renderCommandInputs(command: CliCommand, style: CliStyle, minColumn = 0): string {\n const properties = fields(command);\n const required = requiredFields(command);\n const positionals = command.meta.positional ?? [];\n const argumentRows = positionals.map((name) => ({\n label: placeholder(name, required.has(name)),\n ...description(properties[name], { choices: true }),\n }));\n const optionRows = [\n ...Object.entries(properties)\n .filter(([name]) => !positionals.includes(name))\n .map(([name, schema]) => ({\n label: optionLabel(name, schema),\n ...description(schema, { required: required.has(name) }),\n })),\n ...(command.capability.execution === \"live\"\n ? [{ label: \"--watch\", description: \"Stream updates until interrupted\" }]\n : []),\n ];\n const column = Math.max(minColumn, descriptionColumn([\n ...argumentRows,\n ...optionRows,\n ...GLOBAL_OPTIONS,\n ]));\n\n return [\n argumentRows.length\n ? renderSection(\n \"Arguments\",\n renderRows(argumentRows, style, { column }),\n style,\n )\n : undefined,\n optionRows.length\n ? renderSection(\"Options\", renderRows(optionRows, style, { column }), style)\n : undefined,\n renderSection(\n optionRows.length ? \"Global Options\" : \"Options\",\n renderRows(GLOBAL_OPTIONS, style, { column }),\n style,\n ),\n ].filter(Boolean).join(\"\\n\\n\");\n}\n\n/** Root commands are grouped under their top-level group, Vercel style. */\nfunction commandSections(\n commands: readonly CliCommand[],\n groups: readonly CliCommandGroup[],\n): readonly { readonly title?: string; readonly rows: readonly CliRow[] }[] {\n const roots = groups.filter((group) => group.command.length === 1);\n const loose = commands.filter((command) =>\n !roots.some((group) => startsWith(command.command, group.command))\n );\n const sections = roots.map((group) => ({\n ...(roots.length > 1 || loose.length\n ? { title: group.title ?? group.command.join(\" \") }\n : {}),\n rows: commands\n .filter((command) => startsWith(command.command, group.command))\n .map(row),\n })).filter((section) => section.rows.length > 0);\n return [\n ...sections,\n ...(loose.length\n ? [{\n ...(sections.length ? { title: \"General\" } : {}),\n rows: loose.map(row),\n }]\n : []),\n ];\n}\n\nfunction row(command: CliCommand): CliRow {\n return { label: signature(command), ...describe(command) };\n}\n\nfunction describe(command: CliCommand): { description?: string } {\n const text = command.capability.title ?? command.capability.description;\n return text ? { description: text } : {};\n}\n\n/** `todo delete <todoId>` — command path plus its positional slots. */\nfunction signature(\n command: CliCommand,\n path: readonly string[] = command.command,\n): string {\n const required = requiredFields(command);\n return [\n ...path,\n ...(command.meta.positional ?? []).map((name) =>\n placeholder(name, required.has(name))\n ),\n ].join(\" \");\n}\n\nfunction placeholder(name: string, required: boolean): string {\n return required ? `<${name}>` : `[${name}]`;\n}\n\n/** Title, prose, then the invocation line. No heading needed above it. */\nfunction banner(options: {\n readonly title?: string;\n readonly description?: string;\n readonly usage: string;\n readonly style: CliStyle;\n}): string {\n const { style } = options;\n return [\n [\n options.title ? `${MARGIN}${style.bold(options.title)}` : undefined,\n options.description\n ? `${MARGIN}${style.dim(options.description)}`\n : undefined,\n ].filter(Boolean).join(\"\\n\"),\n `${MARGIN}${style.accent(options.usage)}`,\n ].filter(Boolean).join(\"\\n\\n\");\n}\n\nfunction hint(text: string, style: CliStyle): string {\n return `${MARGIN}${style.dim(text)}`;\n}\n\nfunction fields(command: CliCommand): Record<string, JsonSchema> {\n return (command.capability.input?.properties as\n | Record<string, JsonSchema>\n | undefined) ?? {};\n}\n\nfunction requiredFields(command: CliCommand): ReadonlySet<string> {\n return new Set(\n command.capability.input?.required as readonly string[] | undefined,\n );\n}\n\nfunction optionLabel(name: string, schema: JsonSchema): string {\n const flag = `--${kebabCase(name)}`;\n if (schema.type === \"boolean\") return flag;\n if (Array.isArray(schema.enum)) {\n return `${flag} <${schema.enum.map(String).join(\"|\")}>`;\n }\n if (schema.type === \"array\" || schema.type === \"object\") {\n return `${flag} <json>`;\n }\n return `${flag} <${String(schema.type ?? \"value\")}>`;\n}\n\n/**\n * Descriptions stay one short line: prose first, then only the facts a reader\n * cannot guess from the label (requiredness, defaults, choices).\n */\nfunction description(\n schema: JsonSchema | undefined,\n options: { readonly required?: boolean; readonly choices?: boolean } = {},\n): { description?: string } {\n const prose = typeof schema?.description === \"string\"\n ? schema.description\n : undefined;\n const notes = [\n options.choices && Array.isArray(schema?.enum)\n ? `one of ${schema.enum.map(String).join(\", \")}`\n : undefined,\n schema?.default !== undefined\n ? `default: ${String(schema.default)}`\n : undefined,\n options.required ? \"required\" : undefined,\n ].filter(Boolean);\n const text = [prose, notes.length ? `(${notes.join(\", \")})` : undefined]\n .filter(Boolean)\n .join(\" \");\n return text ? { description: text } : {};\n}\n\nfunction startsWith(\n value: readonly string[],\n prefix: readonly string[],\n): boolean {\n return prefix.every((part, index) => value[index] === part);\n}\n\nfunction kebabCase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);\n}\n\nfunction renderHelp(sections: readonly (string | undefined)[]): string {\n return `\\n${sections.filter(Boolean).join(\"\\n\\n\")}\\n`;\n}\n","import type { CapabilityResult } from \"@capable/app\";\nimport { renderPresentationMarkdown } from \"@capable/core\";\nimport { render as renderMarkdown, type RenderOptions } from \"markdansi\";\n\nexport type CliPresentationOptions = {\n readonly color: boolean;\n readonly isTTY: boolean;\n readonly columns: number;\n readonly markdown?: RenderOptions;\n};\n\nexport function renderCliCapabilityResult(\n result: CapabilityResult,\n options: CliPresentationOptions,\n): string {\n if (result.presentation !== undefined) {\n return renderCliMarkdown(\n renderPresentationMarkdown(result.presentation),\n options,\n );\n }\n return typeof result.output === \"string\"\n ? result.output\n : JSON.stringify(result.output, null, 2);\n}\n\nfunction renderCliMarkdown(\n markdown: string,\n options: CliPresentationOptions,\n): string {\n return options.isTTY\n ? renderMarkdown(markdown, {\n color: options.color,\n width: options.columns,\n ...options.markdown,\n })\n : markdown;\n}\n","import type { RenderOptions } from \"markdansi\";\nimport type {\n GroupMetaRegistry,\n CapabilityMetaRegistry,\n} from \"@capable/core\";\nimport {\n getAppRuntime,\n TransportError,\n type AnyApp,\n type JsonSchema,\n} from \"@capable/app\";\nimport {\n collectCommands,\n type CliCommand,\n type CliCommandGroup,\n} from \"./commands.ts\";\nimport {\n renderCommandHelp,\n renderGroupHelp,\n renderRootHelp,\n} from \"./help.ts\";\nimport {\n createCliStyle,\n supportsColor,\n} from \"./style.ts\";\nimport { renderCliCapabilityResult } from \"./presentation.ts\";\n\n/** Shared help layout, so every Capable surface prints the same shape. */\nexport {\n createCliStyle,\n descriptionColumn,\n MARGIN,\n renderRows,\n renderSection,\n ROW_INDENT,\n supportsColor,\n type CliRow,\n type CliStyle,\n} from \"./style.ts\";\n\nexport type CliCapabilityMeta =\n | false\n | {\n readonly name?: string;\n readonly command?: readonly string[];\n readonly positional?: readonly string[];\n };\n\ndeclare global {\n interface CapableCustomizationMeta {\n readonly cli?: CliCapabilityMeta;\n }\n}\n\nexport type CliGroupMeta = {\n readonly name?: string;\n};\n\ndeclare module \"@capable/core\" {\n interface CapabilityMetaRegistry {\n readonly cli?: CliCapabilityMeta;\n }\n\n interface GroupMetaRegistry {\n readonly cli?: CliGroupMeta;\n }\n}\n\nexport type CliIo = {\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n};\n\nexport type CreateCliOptions = {\n readonly invocationName?: string;\n readonly color?: boolean;\n readonly isTTY?: boolean;\n readonly columns?: number;\n readonly markdown?: RenderOptions;\n};\n\nexport function createCli(\n app: AnyApp,\n cliOptions: CreateCliOptions = {},\n): {\n run(\n argv: readonly string[],\n options?: { readonly io?: Partial<CliIo> },\n ): Promise<number>;\n} {\n return Object.freeze({\n run(argv, options = {}) {\n return runCli({\n app,\n argv,\n ...(cliOptions.invocationName\n ? { invocationName: cliOptions.invocationName }\n : {}),\n ...(cliOptions.color !== undefined ? { color: cliOptions.color } : {}),\n ...(cliOptions.isTTY !== undefined ? { isTTY: cliOptions.isTTY } : {}),\n ...(cliOptions.columns !== undefined\n ? { columns: cliOptions.columns }\n : {}),\n ...(cliOptions.markdown ? { markdown: cliOptions.markdown } : {}),\n ...(options.io ? { io: options.io } : {}),\n });\n },\n });\n}\n\nexport async function runCli(options: {\n readonly app: AnyApp;\n readonly argv: readonly string[];\n readonly invocationName?: string;\n readonly color?: boolean;\n readonly isTTY?: boolean;\n readonly columns?: number;\n readonly markdown?: RenderOptions;\n readonly io?: Partial<CliIo>;\n}): Promise<number> {\n const io: CliIo = {\n stdout: options.io?.stdout ??\n ((text) => process.stdout.write(withTrailingNewline(text))),\n stderr: options.io?.stderr ??\n ((text) => process.stderr.write(withTrailingNewline(text))),\n };\n const invocationName = options.invocationName ?? \"cap\";\n const isTTY = options.isTTY ?? Boolean(process.stdout.isTTY);\n const color = options.color ?? supportsColor(process.env, isTTY);\n const columns = options.columns ?? process.stdout.columns ?? 80;\n const style = createCliStyle(color);\n const runtime = getAppRuntime(options.app);\n let manifest;\n try {\n manifest = await runtime.manifest();\n } catch (error) {\n io.stderr(renderRuntimeError(error));\n return 1;\n }\n const catalog = collectCommands(manifest.capabilities);\n const json = options.argv.includes(\"--json\");\n const watch = options.argv.includes(\"--watch\");\n const wantsHelp = options.argv.includes(\"--help\") ||\n options.argv.includes(\"-h\");\n const argv = options.argv.filter((argument) =>\n ![\"--json\", \"--watch\", \"--help\", \"-h\"].includes(argument)\n );\n\n const roots = catalog.commands.filter((command) => command.command.length === 0);\n if (roots.length > 1) {\n io.stderr(\"Multiple Capabilities map to the root CLI command\");\n return 2;\n }\n const root = roots[0];\n const runsRoot = root && !wantsHelp &&\n (json || watch || root.capability.execution === \"events\");\n if (argv.length === 0 && !runsRoot) {\n io.stdout(renderRootHelp(\n manifest,\n catalog.commands,\n catalog.groups,\n invocationName,\n style,\n ));\n return 0;\n }\n\n const command = matchCommand(argv, catalog.commands);\n const group = exactGroup(argv, catalog.groups);\n if (wantsHelp) {\n if (command) {\n io.stdout(renderCommandHelp(command, invocationName, style));\n return 0;\n }\n if (group) {\n io.stdout(renderGroupHelp(\n group,\n catalog.commands,\n invocationName,\n style,\n ));\n return 0;\n }\n io.stderr(unknownCommand(argv, catalog.commands, invocationName));\n return 2;\n }\n\n if (!command) {\n if (group) {\n io.stderr(\n `Missing command after ${group.command.join(\" \")}\\n` +\n `Run \\`${invocationName} ${group.command.join(\" \")} --help\\` to list available commands.`,\n );\n return 2;\n }\n io.stderr(unknownCommand(argv, catalog.commands, invocationName));\n return 2;\n }\n\n try {\n if (watch && command.capability.execution === \"unary\") {\n throw new CliUsageError(\n `Option --watch is only available for subscribable Capabilities`,\n );\n }\n const input = parseArguments(\n argv.slice(command.command.length),\n command,\n invocationName,\n );\n if (watch || command.capability.execution === \"events\") {\n return await runWatchedCommand({\n runtime,\n command,\n input,\n json,\n io,\n color,\n isTTY,\n columns,\n ...(options.markdown ? { markdown: options.markdown } : {}),\n });\n }\n const result = await runtime.call({\n id: command.capability.id,\n input,\n ...(!json ? { presentation: true } : {}),\n });\n io.stdout(\n json\n ? JSON.stringify(result.output, null, 2)\n : renderCliCapabilityResult(result, {\n color,\n isTTY,\n columns,\n ...(options.markdown ? { markdown: options.markdown } : {}),\n }),\n );\n return 0;\n } catch (error) {\n if (error instanceof CliUsageError) {\n io.stderr(error.message);\n return 2;\n }\n if (error instanceof TransportError) {\n io.stderr(renderRuntimeError(error));\n return 1;\n }\n io.stderr(error instanceof Error ? error.message : String(error));\n return 1;\n }\n}\n\nfunction withTrailingNewline(value: string): string {\n return value.endsWith(\"\\n\") ? value : `${value}\\n`;\n}\n\nasync function runWatchedCommand(options: {\n readonly runtime: ReturnType<typeof getAppRuntime>;\n readonly command: CliCommand;\n readonly input: Record<string, unknown>;\n readonly json: boolean;\n readonly io: CliIo;\n readonly color: boolean;\n readonly isTTY: boolean;\n readonly columns: number;\n readonly markdown?: RenderOptions;\n}): Promise<number> {\n const controller = new AbortController();\n const abort = () => controller.abort();\n process.once(\"SIGINT\", abort);\n let stream: Awaited<ReturnType<typeof options.runtime.subscribe>> | undefined;\n\n try {\n stream = await options.runtime.subscribe({\n id: options.command.capability.id,\n input: options.input,\n ...(!options.json ? { presentation: true } : {}),\n signal: controller.signal,\n });\n let frame = 0;\n let previousFrameLines = 0;\n for await (const result of stream) {\n if (options.json) {\n options.io.stdout(`${JSON.stringify(result.output)}\\n`);\n continue;\n }\n const presentation = renderCliCapabilityResult(result, options);\n if (options.command.capability.execution === \"events\") {\n options.io.stdout(withTrailingNewline(presentation));\n continue;\n }\n options.io.stdout(formatWatchFrame(\n presentation,\n frame++,\n options.isTTY,\n previousFrameLines,\n ));\n previousFrameLines = countFrameLines(presentation);\n }\n return 0;\n } catch (error) {\n if (controller.signal.aborted || isAbortError(error)) return 0;\n throw error;\n } finally {\n process.off(\"SIGINT\", abort);\n await stream?.return?.();\n }\n}\n\nfunction formatWatchFrame(\n value: string,\n index: number,\n isTTY: boolean,\n previousFrameLines: number,\n): string {\n const frame = value.endsWith(\"\\n\") ? value : `${value}\\n`;\n if (isTTY) {\n return index === 0\n ? frame\n : `\\u001B[${previousFrameLines}A\\r\\u001B[0J${frame}`;\n }\n return index === 0 ? frame : `\\n---\\n\\n${frame}`;\n}\n\nfunction countFrameLines(value: string): number {\n const frame = value.endsWith(\"\\n\") ? value : `${value}\\n`;\n return frame.split(\"\\n\").length - 1;\n}\n\nfunction isAbortError(error: unknown): boolean {\n return error instanceof DOMException && error.name === \"AbortError\";\n}\n\nfunction parseArguments(\n argv: readonly string[],\n command: CliCommand,\n invocationName: string,\n): Record<string, unknown> {\n const capability = command.capability;\n const positional = command.meta.positional ?? [];\n const commandName = [invocationName, ...command.command].join(\" \");\n const schema = capability.input;\n const properties = schema?.properties as\n | Record<string, JsonSchema>\n | undefined;\n const input: Record<string, unknown> = {};\n let position = 0;\n\n for (let index = 0; index < argv.length; index++) {\n const token = argv[index]!;\n if (token.startsWith(\"--\")) {\n const [rawName, inline] = token.slice(2).split(\"=\", 2);\n const name = camelCase(rawName!);\n const field = properties?.[name];\n if (!field || positional.includes(name)) {\n const suggestion = nearest(\n rawName!,\n Object.keys(properties ?? {})\n .filter((candidate) => !positional.includes(candidate))\n .map(kebabCase),\n );\n throw new CliUsageError([\n `Unknown option --${rawName}`,\n ...(suggestion ? [`Did you mean \\`--${suggestion}\\`?`] : []),\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n ].join(\"\\n\"));\n }\n const boolean = field.type === \"boolean\";\n const raw = inline ?? (boolean ? \"true\" : argv[++index]);\n if (raw === undefined) {\n throw new CliUsageError(\n `Option --${rawName} requires a value\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n input[name] = coerce(raw, field, `--${rawName}`, commandName);\n continue;\n }\n const name = positional[position++];\n if (!name) {\n throw new CliUsageError(\n `Unexpected argument \"${token}\"\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n const field = properties?.[name];\n if (!field) {\n throw new CliUsageError(\n `CLI positional field \"${name}\" is not present in the input schema`,\n );\n }\n input[name] = coerce(token, field, `<${name}>`, commandName);\n }\n\n const required = schema?.required as readonly string[] | undefined;\n for (const name of required ?? []) {\n if (!(name in input)) {\n const label = positional.includes(name)\n ? `positional argument <${name}>`\n : `required option --${kebabCase(name)}`;\n throw new CliUsageError(\n `Missing ${label}\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n }\n return input;\n}\n\nfunction coerce(\n value: string,\n schema: JsonSchema,\n label: string,\n commandName: string,\n): unknown {\n if (schema.type === \"boolean\") return value !== \"false\";\n if (schema.type === \"integer\" || schema.type === \"number\") {\n const number = Number(value);\n if (!Number.isFinite(number)) {\n throw new CliUsageError(\n `Expected a number for ${label}, received \"${value}\"\\n` +\n `Run \\`${commandName} --help\\` to inspect accepted input.`,\n );\n }\n return number;\n }\n return value;\n}\n\nclass CliUsageError extends Error {}\n\nfunction renderRuntimeError(error: unknown): string {\n return error instanceof TransportError\n ? `${error.code}: ${error.message}`\n : error instanceof Error\n ? error.message\n : String(error);\n}\n\nfunction matchCommand(\n argv: readonly string[],\n commands: readonly CliCommand[],\n): CliCommand | undefined {\n return commands\n .filter((candidate) =>\n candidate.command.every((token, index) => argv[index] === token)\n )\n .sort((left, right) => right.command.length - left.command.length)[0];\n}\n\nfunction exactGroup(\n argv: readonly string[],\n groups: readonly CliCommandGroup[],\n): CliCommandGroup | undefined {\n return groups.find((group) =>\n group.command.length === argv.length &&\n group.command.every((token, index) => argv[index] === token)\n );\n}\n\nfunction unknownCommand(\n argv: readonly string[],\n commands: readonly CliCommand[],\n invocationName: string,\n): string {\n const entered = argv.join(\" \");\n const suggestion = nearest(\n entered,\n commands.map((command) => command.command.join(\" \")),\n );\n return [\n `Unknown command: ${entered}`,\n ...(suggestion ? [`Did you mean \\`${suggestion}\\`?`] : []),\n `Run \\`${invocationName} --help\\` to list available commands.`,\n ].join(\"\\n\");\n}\n\nfunction nearest(\n value: string,\n candidates: readonly string[],\n): string | undefined {\n let match: { readonly candidate: string; readonly distance: number } | undefined;\n for (const candidate of new Set(candidates)) {\n const distance = editDistance(value, candidate);\n if (!match || distance < match.distance) {\n match = { candidate, distance };\n }\n }\n if (!match) return undefined;\n return match.distance <= Math.max(2, Math.floor(match.candidate.length / 3))\n ? match.candidate\n : undefined;\n}\n\nfunction editDistance(left: string, right: string): number {\n const previous = Array.from(\n { length: right.length + 1 },\n (_, index) => index,\n );\n for (let leftIndex = 1; leftIndex <= left.length; leftIndex++) {\n const current = [leftIndex];\n for (let rightIndex = 1; rightIndex <= right.length; rightIndex++) {\n current[rightIndex] = Math.min(\n current[rightIndex - 1]! + 1,\n previous[rightIndex]! + 1,\n previous[rightIndex - 1]! +\n (left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1),\n );\n }\n previous.splice(0, previous.length, ...current);\n }\n return previous[right.length]!;\n}\n\nfunction camelCase(value: string): string {\n return value.replace(/-([a-z])/g, (_, character: string) =>\n character.toUpperCase()\n );\n}\n\nfunction kebabCase(value: string): string {\n return value.replace(/[A-Z]/g, (character) => `-${character.toLowerCase()}`);\n}\n"],"mappings":";;;;AA+BA,SAAgB,gBACd,OACA,SAA4B,CAAC,GACV;CACnB,MAAM,WAAyB,CAAC;CAChC,MAAM,SAA4B,CAAC;CAEnC,KAAK,MAAM,QAAQ,OAAO;EACxB,IAAI,KAAK,SAAS,SAAS;GACzB,MAAM,OAAQ,KAAK,KAAK,OAAO,CAAC;GAChC,MAAM,UAAU,CAAC,GAAG,QAAQ,KAAK,QAAQ,KAAK,GAAG;GACjD,OAAO,KAAK,UAAU,MAAM,OAAO,CAAC;GACpC,MAAM,WAAW,gBAAgB,KAAK,UAAU,OAAO;GACvD,SAAS,KAAK,GAAG,SAAS,QAAQ;GAClC,OAAO,KAAK,GAAG,SAAS,MAAM;GAC9B;EACF;EAEA,MAAM,aAAa;GAAE,GAAG;GAAM,GAAG,qBAAqB,IAAI;EAAE;EAC5D,MAAM,UAAU,WAAW,KAAK;EAChC,IAAI,YAAY,OAAO;EACvB,MAAM,OAAO,WAAW,CAAC;EAGzB,MAAM,iBAAiB,4BAA4B,MAAM,KAAK;EAC9D,MAAM,aAAa,mBAAmB,QAAQ,CAAC,IAAI,kBAAkB,CAAC;EACtE,SAAS,KAAK;GACZ,SAAS,WAAW,WAAW,CAAC,GAAG,QAAQ,WAAW,QAAQ,KAAK,KAAK,GAAG,EAAE,CAAE;GAC/E;GACA;EACF,CAAC;CACH;CAEA,OAAO;EACL,UAAU,OAAO,OAAO,QAAQ;EAChC,QAAQ,OAAO,OAAO,MAAM;CAC9B;AACF;AAEA,SAAS,UACP,MACA,SACiB;CACjB,OAAO,OAAO,OAAO;EACnB,SAAS,OAAO,OAAO,OAAO;EAC9B,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;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AS,CAAC,CAAC,IACvE,MAAM,YACN,KAAA;AACN;AAEA,SAAS,aAAa,MAAc,OAAuB;CACzD,MAAM,WAAW,MAAM,KACrB,EAAE,QAAQ,MAAM,SAAS,EAAE,IAC1B,GAAG,UAAU,KAChB;CACA,KAAK,IAAI,YAAY,GAAG,aAAa,KAAK,QAAQ,aAAa;EAC7D,MAAM,UAAU,CAAC,SAAS;EAC1B,KAAK,IAAI,aAAa,GAAG,cAAc,MAAM,QAAQ,cACnD,QAAQ,cAAc,KAAK,IACzB,QAAQ,aAAa,KAAM,GAC3B,SAAS,cAAe,GACxB,SAAS,aAAa,MACnB,KAAK,YAAY,OAAO,MAAM,aAAa,KAAK,IAAI,EACzD;EAEF,SAAS,OAAO,GAAG,SAAS,QAAQ,GAAG,OAAO;CAChD;CACA,OAAO,SAAS,MAAM;AACxB;AAEA,SAAS,UAAU,OAAuB;CACxC,OAAO,MAAM,QAAQ,cAAc,GAAG,cACpC,UAAU,YAAY,CACxB;AACF;AAEA,SAAS,UAAU,OAAuB;CACxC,OAAO,MAAM,QAAQ,WAAW,cAAc,IAAI,UAAU,YAAY,GAAG;AAC7E"}
@@ -229,8 +229,8 @@ function createDemandIterator(produce) {
229
229
  const demands = [];
230
230
  const demandWaiters = [];
231
231
  const cleanups = [];
232
+ const ready = deferred();
232
233
  let activeDemand;
233
- let started = false;
234
234
  let closed = false;
235
235
  let failure;
236
236
  let hasFailure = false;
@@ -261,7 +261,11 @@ function createDemandIterator(produce) {
261
261
  value
262
262
  });
263
263
  },
264
+ markReady() {
265
+ ready.resolve();
266
+ },
264
267
  complete() {
268
+ stream.markReady();
265
269
  closed = true;
266
270
  activeDemand?.resolve({
267
271
  done: true,
@@ -272,6 +276,7 @@ function createDemandIterator(produce) {
272
276
  wakeProducer();
273
277
  },
274
278
  fail(error) {
279
+ ready.reject(error);
275
280
  failure = error;
276
281
  hasFailure = true;
277
282
  closed = true;
@@ -288,14 +293,8 @@ function createDemandIterator(produce) {
288
293
  cleanups.push(cleanup);
289
294
  }
290
295
  };
291
- const start = () => {
292
- if (started) return;
293
- started = true;
294
- task = produce(stream).then(() => {
295
- if (!closed) stream.complete();
296
- }, (error) => stream.fail(error));
297
- };
298
- return {
296
+ ready.promise.catch(() => void 0);
297
+ const iterator = {
299
298
  [Symbol.asyncIterator]() {
300
299
  return this;
301
300
  },
@@ -310,7 +309,6 @@ function createDemandIterator(produce) {
310
309
  });
311
310
  const demand = deferred();
312
311
  demands.push(demand);
313
- start();
314
312
  wakeProducer();
315
313
  return demand.promise;
316
314
  },
@@ -333,6 +331,13 @@ function createDemandIterator(produce) {
333
331
  };
334
332
  }
335
333
  };
334
+ task = produce(stream).then(() => {
335
+ if (!closed) stream.complete();
336
+ }, (error) => stream.fail(error));
337
+ return {
338
+ iterator,
339
+ ready: ready.promise
340
+ };
336
341
  }
337
342
  //#endregion
338
343
  //#region packages/core/src/schema.ts
@@ -341,8 +346,11 @@ async function parseSchema(schema, value) {
341
346
  if (result.issues) throw new SchemaValidationError(result.issues);
342
347
  return result.value;
343
348
  }
344
- function schemaToJsonSchema(schema, direction) {
345
- const projected = schema["~standard"].jsonSchema[direction]({ target: "draft-2020-12" });
349
+ function schemaToJsonSchema(schema, direction, options = {}) {
350
+ const projected = schema["~standard"].jsonSchema[direction]({
351
+ target: "draft-2020-12",
352
+ ...options.allowUnrepresentable ? { libraryOptions: { unrepresentable: "any" } } : {}
353
+ });
346
354
  return JSON.parse(JSON.stringify(projected));
347
355
  }
348
356
  var SchemaValidationError = class extends Error {
@@ -364,9 +372,12 @@ const capability = Object.assign(function capability(config) {
364
372
  return config === void 0 ? createCapability : createCapability(config);
365
373
  }, { withContext: capabilityWithContext });
366
374
  function createCapability(config) {
375
+ const id = config.id;
367
376
  if (!config.id) throw new Error("Capability id must not be empty");
368
- if (config.subscribe && config.effect !== "read") throw new Error(`Capability "${config.id}" must declare effect "read" to subscribe`);
369
- if (typeof config.handler !== "function") throw new Error(`Capability "${config.id}" requires a handler`);
377
+ if (config.subscribe && config.effect !== "read") throw new Error(`Capability "${id}" must declare effect "read" to subscribe`);
378
+ if (config.handler !== void 0 && typeof config.handler !== "function") throw new Error(`Capability "${id}" handler must be a function`);
379
+ if (config.subscribe !== void 0 && typeof config.subscribe !== "function") throw new Error(`Capability "${id}" subscribe must be a function`);
380
+ if (!config.handler && !config.subscribe) throw new Error(`Capability "${id}" requires a handler or subscribe`);
370
381
  return Object.freeze({
371
382
  [CAPABILITY_SYMBOL]: true,
372
383
  id: config.id,
@@ -379,7 +390,8 @@ function createCapability(config) {
379
390
  errors: config.errors ?? NO_ERRORS$1,
380
391
  middleware: Object.freeze([...config.middleware ?? []]),
381
392
  meta: Object.freeze({ ...config.meta ?? {} }),
382
- handler: config.handler,
393
+ execution: config.handler ? config.subscribe ? "live" : "unary" : "events",
394
+ ...config.handler ? { handler: config.handler } : {},
383
395
  ...config.subscribe ? { subscribe: config.subscribe } : {},
384
396
  ...config.toPresentation ? { toPresentation: config.toPresentation } : {}
385
397
  });
@@ -398,14 +410,24 @@ async function executeCapability(capability, options) {
398
410
  });
399
411
  }
400
412
  async function executeLocatedCapability(located, input, options) {
413
+ const handler = located.capability.handler;
414
+ if (!handler) throw new CapableError("METHOD_NOT_ALLOWED", {
415
+ status: 405,
416
+ message: `Capability "${located.capability.id}" only supports subscribe`
417
+ });
401
418
  const parsedInput = await parseCapabilityInput(located.capability, input);
402
419
  let rawOutput;
403
420
  try {
404
421
  rawOutput = await runCapabilityMiddleware(located.middleware, {
422
+ capability: Object.freeze({
423
+ id: located.capability.id,
424
+ effect: located.capability.effect
425
+ }),
426
+ mode: "call",
405
427
  input: parsedInput,
406
428
  context: options.context,
407
429
  ...options.signal ? { signal: options.signal } : {}
408
- }, () => located.capability.handler({
430
+ }, () => handler({
409
431
  input: parsedInput,
410
432
  context: options.context,
411
433
  ...options.signal ? { signal: options.signal } : {}
@@ -416,30 +438,30 @@ async function executeLocatedCapability(located, input, options) {
416
438
  return validateCapabilityOutput(located.capability, rawOutput);
417
439
  }
418
440
  function subscribeCapability(capability, options) {
419
- return subscribeLocatedCapability(Object.freeze({
441
+ const located = Object.freeze({
420
442
  path: Object.freeze([]),
421
443
  groups: Object.freeze([]),
422
444
  groupPaths: Object.freeze([]),
423
445
  capability,
424
446
  errors: Object.freeze({ ...errorDefinitions(capability.errors) }),
425
447
  middleware: capability.middleware
426
- }), options.input ?? {}, {
427
- context: options.context,
428
- ...options.signal ? { signal: options.signal } : {}
429
448
  });
449
+ return (async function* () {
450
+ yield* await subscribeLocatedCapability(located, options.input ?? {}, {
451
+ context: options.context,
452
+ ...options.signal ? { signal: options.signal } : {}
453
+ });
454
+ })();
430
455
  }
431
- function subscribeLocatedCapability(located, input, options) {
456
+ async function subscribeLocatedCapability(located, input, options) {
432
457
  const subscriber = located.capability.subscribe;
433
- if (!subscriber) throw new Error(`Capability "${located.capability.id}" is not subscribable`);
434
- return createDemandIterator(async (stream) => {
458
+ if (!subscriber) throw new CapableError("METHOD_NOT_ALLOWED", {
459
+ status: 405,
460
+ message: `Capability "${located.capability.id}" only supports call`
461
+ });
462
+ const parsedInput = await parseCapabilityInput(located.capability, input);
463
+ const subscription = createDemandIterator(async (stream) => {
435
464
  let cleanupSource = async (_abort) => {};
436
- let parsedInput;
437
- try {
438
- parsedInput = await parseCapabilityInput(located.capability, input);
439
- } catch (error) {
440
- stream.fail(error);
441
- return;
442
- }
443
465
  try {
444
466
  const controller = new AbortController();
445
467
  const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
@@ -454,6 +476,11 @@ function subscribeLocatedCapability(located, input, options) {
454
476
  stream.onCancel(() => cleanupSource(true));
455
477
  let emitted = false;
456
478
  await runCapabilityMiddleware(located.middleware, {
479
+ capability: Object.freeze({
480
+ id: located.capability.id,
481
+ effect: located.capability.effect
482
+ }),
483
+ mode: "subscribe",
457
484
  input: parsedInput,
458
485
  context: options.context,
459
486
  signal
@@ -466,17 +493,19 @@ function subscribeLocatedCapability(located, input, options) {
466
493
  if (!iterable || typeof iterable !== "object" || !(Symbol.asyncIterator in iterable)) throw new CapableError("INTERNAL_SERVER_ERROR", { message: `Capability "${located.capability.id}" subscribe must return an AsyncIterable` });
467
494
  const sourceIterator = iterable[Symbol.asyncIterator]();
468
495
  iterator = sourceIterator;
496
+ stream.markReady();
469
497
  while (await stream.waitForDemand()) {
470
498
  const result = await sourceIterator.next();
471
499
  if (result.done) {
472
- if (!emitted) throw emptySubscriptionError(located.capability);
500
+ if (!emitted && located.capability.execution === "live") throw emptySubscriptionError(located.capability);
473
501
  return;
474
502
  }
475
503
  emitted = true;
476
504
  stream.emit(await validateCapabilityOutput(located.capability, result.value));
477
505
  }
478
506
  });
479
- if (!emitted) throw emptySubscriptionError(located.capability);
507
+ if (!emitted && located.capability.execution === "live") throw emptySubscriptionError(located.capability);
508
+ stream.markReady();
480
509
  await cleanupSource(false);
481
510
  stream.complete();
482
511
  } catch (error) {
@@ -484,6 +513,8 @@ function subscribeLocatedCapability(located, input, options) {
484
513
  stream.fail(await normalizeCapabilityError(located, error));
485
514
  }
486
515
  });
516
+ await subscription.ready;
517
+ return subscription.iterator;
487
518
  }
488
519
  function emptySubscriptionError(capability) {
489
520
  return new CapableError("INTERNAL_SERVER_ERROR", { message: `Capability "${capability.id}" subscription completed before yielding a value` });
@@ -586,13 +617,17 @@ function group(config) {
586
617
  }
587
618
  function defineApp(config) {
588
619
  assertCapabilityTree(config.capabilities, "application.capabilities");
589
- const located = locateCapabilities(config.capabilities);
620
+ const errors = config.errors ?? NO_ERRORS;
621
+ const middleware = Object.freeze([...config.middleware ?? []]);
622
+ const located = locateCapabilities(config.capabilities, [], [], [], errorDefinitions(errors), middleware);
590
623
  assertUniqueCapabilities(located);
591
624
  return Object.freeze({
592
625
  [APPLICATION_SYMBOL]: true,
593
626
  name: config.name ?? "Capable application",
594
627
  version: config.version ?? "0.0.0",
595
628
  ...config.description ? { description: config.description } : {},
629
+ errors,
630
+ middleware,
596
631
  capabilities: config.capabilities,
597
632
  locatedCapabilities: Object.freeze(located)
598
633
  });
@@ -669,4 +704,4 @@ function isRecord(value) {
669
704
  //#endregion
670
705
  export { defineErrors as S, normalizePresentation as _, isCapabilityGroup as a, CAPABILITY_ERRORS_SYMBOL as b, executeCapability as c, subscribeCapability as d, subscribeLocatedCapability as f, watchQuery as g, schemaToJsonSchema as h, group as i, executeLocatedCapability as l, parseSchema as m, CAPABILITY_GROUP_SYMBOL as n, CAPABILITY_SYMBOL as o, SchemaValidationError as p, defineApp as r, capability as s, APPLICATION_SYMBOL as t, isCapability as u, present as v, CapableError as x, renderPresentationMarkdown as y };
671
706
 
672
- //# sourceMappingURL=src-DdV82An-.mjs.map
707
+ //# sourceMappingURL=src-B2WeUwUT.mjs.map