capable-kit 0.1.0-alpha.10 → 0.1.0-alpha.9

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 (71) hide show
  1. package/CHANGELOG.md +0 -106
  2. package/dist/ai-sdk.d.mts +3 -3
  3. package/dist/ai-sdk.mjs +7 -9
  4. package/dist/ai-sdk.mjs.map +1 -1
  5. package/dist/app.d.mts +2 -2
  6. package/dist/app.mjs +2 -2
  7. package/dist/bin.mjs +4 -4
  8. package/dist/cli.d.mts +1 -6
  9. package/dist/cli.mjs +1 -1
  10. package/dist/core.d.mts +3 -3
  11. package/dist/core.mjs +1 -1
  12. package/dist/eve.d.mts +3 -3
  13. package/dist/eve.mjs +7 -9
  14. package/dist/eve.mjs.map +1 -1
  15. package/dist/http.d.mts +1 -1
  16. package/dist/http.mjs +1 -1
  17. package/dist/{index-1A44jLuE.d.mts → index-D63DSGZG.d.mts} +17 -50
  18. package/dist/{index-CHuCLJIs.d.mts → index-D8DWjQ9f.d.mts} +3 -3
  19. package/dist/{index-D-NV4PiU.d.mts → index-DgxvtAmv.d.mts} +4 -4
  20. package/dist/{index-WiBWfyTn.d.mts → index-ftQx6OMr.d.mts} +16 -43
  21. package/dist/index.d.mts +4 -4
  22. package/dist/index.mjs +3 -3
  23. package/dist/mcp.d.mts +2 -7
  24. package/dist/mcp.mjs +1 -1
  25. package/dist/{mount-BmLHp349.mjs → mount-B9TrHWHh.mjs} +8 -16
  26. package/dist/mount-B9TrHWHh.mjs.map +1 -0
  27. package/dist/react-query.d.mts +2 -2
  28. package/dist/react-query.mjs +1 -1
  29. package/dist/react-query.mjs.map +1 -1
  30. package/dist/runtime-support.d.mts +1 -1
  31. package/dist/runtime-support.mjs +3 -3
  32. package/dist/server.d.mts +1 -1
  33. package/dist/server.mjs +1 -1
  34. package/dist/{src-DePlcG_t.mjs → src-B592M-6b.mjs} +105 -312
  35. package/dist/src-B592M-6b.mjs.map +1 -0
  36. package/dist/{src-B2WeUwUT.mjs → src-Bd1Vnze8.mjs} +31 -49
  37. package/dist/src-Bd1Vnze8.mjs.map +1 -0
  38. package/dist/{src-C5jGDnuu.mjs → src-CKC1BdXO.mjs} +3 -3
  39. package/dist/{src-C5jGDnuu.mjs.map → src-CKC1BdXO.mjs.map} +1 -1
  40. package/dist/{src-3LE9S4QE.mjs → src-CL9eA6_p.mjs} +17 -29
  41. package/dist/src-CL9eA6_p.mjs.map +1 -0
  42. package/dist/{src-_6OmFRYa.mjs → src-Hw9WBgEW.mjs} +10 -28
  43. package/dist/src-Hw9WBgEW.mjs.map +1 -0
  44. package/dist/{subscription-DPdwovhw.d.mts → subscription-DbnHcm7C.d.mts} +2 -2
  45. package/dist/swr.d.mts +2 -2
  46. package/dist/swr.mjs +1 -1
  47. package/dist/swr.mjs.map +1 -1
  48. package/docs/CONTEXT.md +11 -23
  49. package/docs/internal/architecture.md +14 -27
  50. package/docs/internal/capability-first-model.md +13 -99
  51. package/docs/internal/implementation-friction.md +0 -85
  52. package/docs/site/concepts/apps.mdx +1 -1
  53. package/docs/site/concepts/architecture.mdx +0 -8
  54. package/docs/site/concepts/capabilities.mdx +2 -2
  55. package/docs/site/concepts/presentations.mdx +0 -4
  56. package/docs/site/patterns/composition.mdx +5 -107
  57. package/docs/site/patterns/remote-apps.mdx +1 -5
  58. package/docs/site/patterns/subscriptions.mdx +32 -79
  59. package/docs/site/reference/packages-and-entry-points.mdx +2 -41
  60. package/docs/site/surfaces/cli.mdx +0 -11
  61. package/docs/site/surfaces/typescript.mdx +2 -2
  62. package/package.json +1 -1
  63. package/src/index.test.ts +0 -1
  64. package/src/index.ts +0 -5
  65. package/src/package.test.ts +0 -9
  66. package/dist/mount-BmLHp349.mjs.map +0 -1
  67. package/dist/src-3LE9S4QE.mjs.map +0 -1
  68. package/dist/src-B2WeUwUT.mjs.map +0 -1
  69. package/dist/src-DePlcG_t.mjs.map +0 -1
  70. package/dist/src-_6OmFRYa.mjs.map +0 -1
  71. package/docs/internal/adr/0003-capability-reference-customization.md +0 -68
@@ -1,9 +1,9 @@
1
- import { _ as normalizePresentation, a as isCapabilityGroup, f as subscribeLocatedCapability, h as schemaToJsonSchema, l as executeLocatedCapability, u as isCapability, x as CapableError } from "./src-B2WeUwUT.mjs";
1
+ import { _ as normalizePresentation, a as isCapabilityGroup, f as subscribeLocatedCapability, h as schemaToJsonSchema, l as executeLocatedCapability, u as isCapability, x as CapableError } from "./src-Bd1Vnze8.mjs";
2
2
  //#region packages/app/src/manifest.ts
3
3
  function createAppManifest(definition) {
4
4
  const byCapability = new Map(definition.locatedCapabilities.map((entry) => [entry.capability, entry]));
5
5
  return Object.freeze({
6
- protocol: "capable.capabilities.v4",
6
+ protocol: "capable.capabilities.v3",
7
7
  name: definition.name,
8
8
  version: definition.version,
9
9
  ...definition.description ? { description: definition.description } : {},
@@ -11,17 +11,11 @@ function createAppManifest(definition) {
11
11
  });
12
12
  }
13
13
  function validateManifest(manifest, label) {
14
- if (manifest.protocol !== "capable.capabilities.v4") throw new Error(`${label} uses unsupported protocol "${manifest.protocol}"`);
14
+ if (manifest.protocol !== "capable.capabilities.v3") throw new Error(`${label} uses unsupported protocol "${manifest.protocol}"`);
15
15
  const capabilities = flattenManifestCapabilities(manifest.capabilities);
16
16
  const ids = /* @__PURE__ */ new Map();
17
17
  const paths = /* @__PURE__ */ new Set();
18
18
  for (const capability of capabilities) {
19
- if (![
20
- "unary",
21
- "live",
22
- "events"
23
- ].includes(capability.execution)) throw new Error(`${label} contains unsupported execution kind for Capability "${capability.id}"`);
24
- if (capability.execution !== "unary" && capability.effect !== "read") throw new Error(`${label} subscribable Capability "${capability.id}" must have effect "read"`);
25
19
  const path = capability.path.join(".");
26
20
  const previous = ids.get(capability.id);
27
21
  if (previous && !sameCapabilityContract(previous, capability)) throw new Error(`${label} contains conflicting definitions for Capability id "${capability.id}"`);
@@ -35,9 +29,9 @@ function composeApplicationManifests(sources) {
35
29
  const conflicts = collectManifestConflicts(sources);
36
30
  if (conflicts.length) throw new Error(`Cannot compose Apps:\n${conflicts.map((item) => `- ${item}`).join("\n")}`);
37
31
  const manifests = sources.map(({ manifest }) => manifest);
38
- const applications = sources.filter((source, index) => sources.findIndex(({ application }) => application === source.application) === index).map(({ manifest }) => manifest);
32
+ const applications = sources.filter((source, index) => sources.findIndex(({ owner }) => owner === source.owner) === index).map(({ manifest }) => manifest);
39
33
  return Object.freeze({
40
- protocol: "capable.capabilities.v4",
34
+ protocol: "capable.capabilities.v3",
41
35
  name: applications.map(({ name }) => name).join(" + "),
42
36
  version: applications.map(({ version }) => version).join(" + "),
43
37
  capabilities: mergeManifestNodes(manifests.flatMap(({ capabilities }) => capabilities))
@@ -67,17 +61,12 @@ function flattenManifestCapabilities(nodes) {
67
61
  return nodes.flatMap((node) => node.type === "capability" ? [node] : flattenManifestCapabilities(node.children));
68
62
  }
69
63
  function findManifestCapability(nodes, path) {
70
- const node = findManifestNode(nodes, path);
71
- return node?.type === "capability" ? node : void 0;
72
- }
73
- function findManifestNode(nodes, path) {
74
64
  let current = nodes;
75
65
  for (let index = 0; index < path.length; index++) {
76
66
  const key = path[index];
77
67
  const node = current.find((candidate) => candidate.type === "group" ? candidate.key === key : candidate.path.at(-1) === key);
78
68
  if (!node) return void 0;
79
69
  if (node.type === "capability") return index === path.length - 1 ? node : void 0;
80
- if (index === path.length - 1) return node;
81
70
  current = node.children;
82
71
  }
83
72
  }
@@ -112,7 +101,7 @@ function manifestCapability(entry) {
112
101
  ...capability.description ? { description: capability.description } : {},
113
102
  deprecated: capability.deprecated,
114
103
  ...capability.effect ? { effect: capability.effect } : {},
115
- execution: capability.execution,
104
+ ...capability.subscribe ? { subscription: { mode: "replace" } } : {},
116
105
  ...capability.input ? { input: manifestJsonSchema(capability.input, "input") } : {},
117
106
  ...capability.output ? { output: manifestJsonSchema(capability.output, "output") } : {},
118
107
  errors: Object.fromEntries(Object.entries(entry.errors).map(([code, definition]) => [code, {
@@ -143,10 +132,10 @@ function collectManifestConflicts(sources) {
143
132
  } catch (error) {
144
133
  conflicts.push(error instanceof Error ? error.message : String(error));
145
134
  }
146
- const capabilities = sources.flatMap(({ manifest, owners }, source) => flattenManifestCapabilities(manifest.capabilities).map((capability) => ({
135
+ const capabilities = sources.flatMap(({ manifest, owner }, source) => flattenManifestCapabilities(manifest.capabilities).map((capability) => ({
147
136
  capability,
148
137
  source,
149
- owner: requiredOwner(owners, capability.id, manifest.name),
138
+ owner,
150
139
  label: manifest.name
151
140
  })));
152
141
  for (let leftIndex = 0; leftIndex < capabilities.length; leftIndex++) for (let rightIndex = leftIndex + 1; rightIndex < capabilities.length; rightIndex++) {
@@ -169,14 +158,9 @@ function collectManifestConflicts(sources) {
169
158
  }
170
159
  return [...new Set(conflicts)];
171
160
  }
172
- function requiredOwner(owners, capabilityId, application) {
173
- const owner = owners.get(capabilityId);
174
- if (!owner) throw new Error(`Missing execution owner for Capability "${capabilityId}" in "${application}"`);
175
- return owner;
176
- }
177
161
  function sameCapabilityContract(left, right) {
178
- const { path: _leftPath, customization: _leftCustomization, ...leftContract } = left;
179
- const { path: _rightPath, customization: _rightCustomization, ...rightContract } = right;
162
+ const { path: _leftPath, ...leftContract } = left;
163
+ const { path: _rightPath, ...rightContract } = right;
180
164
  return JSON.stringify(leftContract) === JSON.stringify(rightContract);
181
165
  }
182
166
  function mergeManifestNodes(nodes) {
@@ -245,52 +229,9 @@ function isPathPrefix(prefix, path) {
245
229
  }
246
230
  //#endregion
247
231
  //#region packages/app/src/runtime.ts
248
- function mapAsyncIterator(source, transform, transformError = (error) => error) {
249
- let failed = false;
250
- return {
251
- [Symbol.asyncIterator]() {
252
- return this;
253
- },
254
- async next() {
255
- try {
256
- const result = await source.next();
257
- return result.done ? {
258
- done: true,
259
- value: void 0
260
- } : {
261
- done: false,
262
- value: await transform(result.value)
263
- };
264
- } catch (error) {
265
- failed = true;
266
- await source.return?.().catch(() => void 0);
267
- throw transformError(error);
268
- }
269
- },
270
- async return() {
271
- if (failed) return {
272
- done: true,
273
- value: void 0
274
- };
275
- try {
276
- await source.return?.();
277
- return {
278
- done: true,
279
- value: void 0
280
- };
281
- } catch (error) {
282
- throw transformError(error);
283
- }
284
- }
285
- };
286
- }
287
232
  const APP_RUNTIME_SYMBOL = Symbol.for("capable.app.runtime");
288
233
  const APP_CAPABILITIES_SYMBOL = Symbol.for("capable.app.capabilities");
289
234
  const APP_CALL_SYMBOL = Symbol.for("capable.app.call");
290
- /** @internal Shared by composition and subscriptions; ordinary functions are not references. */
291
- function getCapabilityBinding(value) {
292
- return typeof value === "function" ? value[APP_CALL_SYMBOL] : void 0;
293
- }
294
235
  function getAppRuntime(app) {
295
236
  return app[APP_RUNTIME_SYMBOL];
296
237
  }
@@ -326,7 +267,6 @@ function appFromRuntime(runtime) {
326
267
  const signal = args[1]?.signal;
327
268
  const binding = await runtime.resolve(path);
328
269
  if (!binding) throw new Error(`No Capability exists at "${path.join(".")}"`);
329
- if (binding.capability.execution === "events") throw wrongExecutionMode(binding.capability.id, "subscribe");
330
270
  return (await binding.transport.call({
331
271
  id: binding.capability.id,
332
272
  input: args[0] ?? {},
@@ -338,18 +278,23 @@ function appFromRuntime(runtime) {
338
278
  return proxy([], true);
339
279
  }
340
280
  function subscribe(capabilityCall, ...args) {
341
- const binding = getCapabilityBinding(capabilityCall);
281
+ const binding = capabilityCall[APP_CALL_SYMBOL];
342
282
  if (!binding) throw new Error("subscribe() requires a Capability call from a Capable App");
343
283
  return (async function* () {
344
284
  const signal = args[1]?.signal;
345
285
  const resolved = await binding.runtime.resolve(binding.path);
346
286
  if (!resolved) throw new Error(`No Capability exists at "${binding.path.join(".")}"`);
347
- if (resolved.capability.execution === "unary") throw wrongExecutionMode(resolved.capability.id, "call");
348
- yield* mapAsyncIterator(await resolved.transport.subscribe({
287
+ if (!resolved.capability.subscription) throw new Error(`Capability "${resolved.capability.id}" is not subscribable`);
288
+ const stream = resolved.transport.subscribe({
349
289
  id: resolved.capability.id,
350
290
  input: args[0] ?? {},
351
291
  ...signal ? { signal } : {}
352
- }), (result) => result.output);
292
+ });
293
+ try {
294
+ for await (const result of stream) yield result.output;
295
+ } finally {
296
+ await stream.return?.();
297
+ }
353
298
  })();
354
299
  }
355
300
  const localManifestCache = /* @__PURE__ */ new WeakMap();
@@ -379,7 +324,6 @@ function createApp(definition, ...[options]) {
379
324
  async call({ id, input = {}, signal, presentation: wantsPresentation }) {
380
325
  const located = byId.get(id);
381
326
  if (!located) throw new TransportError("NOT_FOUND", { status: 404 });
382
- if (located.capability.execution === "events") throw wrongExecutionMode(id, "subscribe");
383
327
  let context;
384
328
  try {
385
329
  context = options?.context ? await options.context({
@@ -410,10 +354,10 @@ function createApp(definition, ...[options]) {
410
354
  ...presentation ? { presentation } : {}
411
355
  };
412
356
  },
413
- async subscribe({ id, input = {}, signal, presentation: wantsPresentation }) {
357
+ async *subscribe({ id, input = {}, signal, presentation: wantsPresentation }) {
414
358
  const located = byId.get(id);
415
359
  if (!located) throw new TransportError("NOT_FOUND", { status: 404 });
416
- if (!located.capability.subscribe) throw wrongExecutionMode(id, "call");
360
+ if (!located.capability.subscribe) throw new TransportError("NOT_FOUND", { status: 404 });
417
361
  let context;
418
362
  try {
419
363
  context = options?.context ? await options.context({
@@ -423,28 +367,29 @@ function createApp(definition, ...[options]) {
423
367
  } catch (cause) {
424
368
  throw new TransportError("INTERNAL_SERVER_ERROR", { cause });
425
369
  }
426
- let stream;
370
+ const stream = subscribeLocatedCapability(located, input, {
371
+ context,
372
+ ...signal ? { signal } : {}
373
+ });
427
374
  try {
428
- stream = await subscribeLocatedCapability(located, input, {
429
- context,
430
- ...signal ? { signal } : {}
431
- });
375
+ for await (const output of stream) {
376
+ const presentation = await materializePresentation(located.capability, output, context, wantsPresentation);
377
+ yield {
378
+ output,
379
+ ...presentation ? { presentation } : {}
380
+ };
381
+ }
432
382
  } catch (error) {
433
383
  throw toTransportError(error);
384
+ } finally {
385
+ await stream.return?.();
434
386
  }
435
- return mapAsyncIterator(stream, async (output) => {
436
- const presentation = await materializePresentation(located.capability, output, context, wantsPresentation);
437
- return {
438
- output,
439
- ...presentation ? { presentation } : {}
440
- };
441
- }, toTransportError);
442
387
  }
443
388
  });
444
389
  return appFromRuntime(runtime);
445
390
  }
446
391
  function createRemoteApp(transport) {
447
- const manifest = cacheAsync(async () => {
392
+ const manifest = createManifestResolver(async () => {
448
393
  const manifest = await transport.manifest();
449
394
  validateManifest(manifest, "Remote App");
450
395
  return manifest;
@@ -462,13 +407,13 @@ function createRemoteApp(transport) {
462
407
  await manifest();
463
408
  return transport.call(call);
464
409
  },
465
- async subscribe(call) {
410
+ async *subscribe(call) {
466
411
  await manifest();
467
- return transport.subscribe(call);
412
+ yield* transport.subscribe(call);
468
413
  }
469
414
  }));
470
415
  }
471
- function cacheAsync(load) {
416
+ function createManifestResolver(load) {
472
417
  let cached;
473
418
  return () => {
474
419
  if (cached) return cached;
@@ -511,99 +456,19 @@ function toTransportError(error) {
511
456
  });
512
457
  return new TransportError("INTERNAL_SERVER_ERROR", { cause: error });
513
458
  }
514
- function wrongExecutionMode(id, supported) {
515
- return new TransportError("METHOD_NOT_ALLOWED", {
516
- status: 405,
517
- message: `Capability "${id}" only supports ${supported}`
518
- });
519
- }
520
- //#endregion
521
- //#region packages/app/src/customization.ts
522
- const CUSTOMIZED_SYMBOL = Symbol.for("capable.customized");
523
- /** Customize a bound local or remote reference without changing its execution. */
524
- function customize(reference, options) {
525
- const previous = isCustomizedCapability(reference) ? reference : void 0;
526
- const original = previous ? previous.reference : reference;
527
- if (!getCapabilityBinding(original)) throw new TypeError("customize() requires a Capability reference from a Capable App");
528
- if (!isRecord(options)) throw new TypeError("customize() options must be an object");
529
- for (const key of Object.keys(options)) if (key !== "title" && key !== "description" && key !== "meta") throw new TypeError(`customize() does not support "${key}"`);
530
- for (const key of ["title", "description"]) if (options[key] !== void 0 && typeof options[key] !== "string") throw new TypeError(`customize() ${key} must be a string`);
531
- if (options.meta !== void 0 && !isRecord(options.meta)) throw new TypeError("customize() meta must be an object");
532
- return Object.freeze({
533
- [CUSTOMIZED_SYMBOL]: true,
534
- reference: original,
535
- customization: mergeCustomization(previous?.customization, options)
536
- });
537
- }
538
- function isCustomizedCapability(value) {
539
- return isRecord(value) && value[CUSTOMIZED_SYMBOL] === true;
540
- }
541
- /** Outer customizations replace supplied namespaces; no generic deep merge. */
542
- function mergeCustomization(source, override) {
543
- return snapshot({
544
- ...source,
545
- ...override,
546
- ...source?.meta || override.meta ? { meta: {
547
- ...source?.meta,
548
- ...override.meta
549
- } } : {}
550
- });
551
- }
552
- /** Surface-facing fields only. Policies and executors retain the source contract. */
553
- function getCapabilityDisplay(capability) {
554
- const { customization } = capability;
555
- return {
556
- ...capability.title !== void 0 ? { title: capability.title } : {},
557
- ...capability.description !== void 0 ? { description: capability.description } : {},
558
- ...customization?.title !== void 0 ? { title: customization.title } : {},
559
- ...customization?.description !== void 0 ? { description: customization.description } : {},
560
- meta: {
561
- ...capability.meta,
562
- ...customization?.meta
563
- }
564
- };
565
- }
566
- /** Navigation overrides come from the destination only for relocated leaves. */
567
- function getCapabilityNavigationMeta(capability, surface) {
568
- return capability.customization?.navigation === "destination" ? capability.customization.meta?.[surface] : capability.meta[surface];
569
- }
570
- function snapshot(value, ancestors = /* @__PURE__ */ new Set()) {
571
- if (value === null || typeof value === "string" || typeof value === "boolean") return value;
572
- if (typeof value === "number" && Number.isFinite(value)) return value;
573
- if (Array.isArray(value) || isRecord(value)) {
574
- if (ancestors.has(value)) throw new TypeError("customize() metadata must not contain cycles");
575
- ancestors.add(value);
576
- const copy = Array.isArray(value) ? value.map((child) => snapshot(child, ancestors)) : Object.fromEntries(Object.entries(value).filter(([, child]) => child !== void 0).sort(([left], [right]) => left.localeCompare(right)).map(([key, child]) => [key, snapshot(child, ancestors)]));
577
- ancestors.delete(value);
578
- return Object.freeze(copy);
579
- }
580
- throw new TypeError("customize() metadata must contain only JSON values");
581
- }
582
- function isRecord(value) {
583
- return value !== null && typeof value === "object" && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
584
- }
585
459
  //#endregion
586
460
  //#region packages/app/src/composition.ts
587
- /** Compose executable Apps, subtrees, and Capability references into one tree. */
461
+ /** Compose root Apps and tree-shaped App placements into one executable App. */
588
462
  function composeApps(...nodes) {
589
463
  const placements = nodes.flatMap((node) => collectPlacements(node, []));
590
- return appFromRuntime(createCompositionRuntime(placements.filter((placement, index) => placements.findIndex((candidate) => candidate.runtime === placement.runtime && samePath(candidate.path, placement.path) && samePath(candidate.sourcePath, placement.sourcePath) && JSON.stringify(candidate.customization) === JSON.stringify(placement.customization)) === index)));
464
+ return appFromRuntime(createCompositionRuntime(placements.filter((placement, index) => placements.findIndex((candidate) => candidate.runtime === placement.runtime && samePath(candidate.path, placement.path)) === index)));
591
465
  }
592
466
  function collectPlacements(node, path) {
593
- const customized = isCustomizedCapability(node) ? node : void 0;
594
- const binding = getCapabilityBinding(customized ? customized.reference : node);
595
- if (binding) return [{
596
- path: Object.freeze(path),
597
- runtime: binding.runtime,
598
- sourcePath: Object.freeze(binding.path),
599
- ...customized ? { customization: customized.customization } : {}
600
- }];
601
467
  if (isApp(node)) return [{
602
468
  path: Object.freeze(path),
603
- runtime: getInternalAppRuntime(node),
604
- sourcePath: Object.freeze([])
469
+ runtime: getInternalAppRuntime(node)
605
470
  }];
606
- if (!node || typeof node !== "object" || Array.isArray(node)) throw new TypeError("composeApps() entries must be Apps, executable subtree references, Capability references, or named object trees");
471
+ if (!node || typeof node !== "object" || Array.isArray(node)) throw new TypeError("composeApps() entries must be Apps or named object trees");
607
472
  const entries = Object.entries(node);
608
473
  if (entries.length === 0) throw new Error(`composeApps() contains an empty object at "${path.join(".") || "<root>"}"`);
609
474
  return entries.flatMap(([key, child]) => {
@@ -613,166 +478,94 @@ function collectPlacements(node, path) {
613
478
  });
614
479
  }
615
480
  function createCompositionRuntime(placements) {
616
- return derivedRuntime(async () => {
617
- const sources = await Promise.all(placements.map(resolvePlacement));
618
- const manifest = composeApplicationManifests(sources);
619
- const dispatch = /* @__PURE__ */ new Map();
620
- for (const { owners } of sources) for (const [id, target] of owners) dispatch.set(id, target);
621
- return {
622
- manifest,
623
- dispatch
624
- };
625
- }, async (path) => {
626
- const matches = (await Promise.all(placements.filter((placement) => isPathPrefixOrEqual(placement.path, path)).map(async (placement) => {
627
- const resolved = await placement.runtime.resolve([...placement.sourcePath, ...path.slice(placement.path.length)]);
628
- if (!resolved) return void 0;
629
- const relocatedLeaf = samePath(placement.path, path);
630
- if (placement.customization && !relocatedLeaf) throw new TypeError("customize() requires a Capability reference, not an App subtree");
631
- return {
632
- transport: resolved.transport,
633
- capability: placeCapability(resolved.capability, {
634
- path,
635
- relocatedLeaf,
636
- ...relocatedLeaf && placement.customization ? { customization: placement.customization } : {}
637
- })
638
- };
639
- }))).filter((match) => match !== void 0).filter((match, index, all) => all.findIndex((candidate) => candidate.capability.id === match.capability.id && candidate.transport === match.transport && JSON.stringify(candidate.capability.customization) === JSON.stringify(match.capability.customization)) === index);
640
- if (matches.length > 1) throw new Error(`Cannot resolve ambiguous App path "${path.join(".")}"`);
641
- return matches[0];
642
- });
643
- }
644
- async function resolvePlacement(placement) {
645
- const source = await placement.runtime.manifest();
646
- const placed = placeSourceManifest(source, placement);
647
- const targets = /* @__PURE__ */ new Map();
648
- for (const capability of placed.sourceCapabilities) {
649
- const resolved = await placement.runtime.resolve(capability.path);
650
- if (!resolved) throw missingReference(capability.path);
651
- const previous = targets.get(capability.id);
652
- if (previous && previous !== resolved.transport) throw new Error(`Capability id "${capability.id}" has multiple execution owners in "${source.name}"`);
653
- targets.set(capability.id, resolved.transport);
654
- }
655
- return {
656
- manifest: placed.manifest,
657
- application: placement.runtime,
658
- owners: targets
659
- };
660
- }
661
- function placeSourceManifest(source, placement) {
662
- if (placement.sourcePath.length === 0) return {
663
- manifest: placeManifest(placement.path, source),
664
- sourceCapabilities: flattenManifestCapabilities(source.capabilities)
665
- };
666
- const node = findManifestNode(source.capabilities, placement.sourcePath);
667
- if (!node) throw missingReference(placement.sourcePath);
668
- if (node.type === "capability") {
669
- if (placement.path.length === 0) throw new TypeError("Capability references require a named key in composeApps()");
670
- return {
671
- manifest: Object.freeze({
672
- ...source,
673
- capabilities: wrapGroups(Object.freeze([placeCapability(node, {
674
- path: placement.path,
675
- relocatedLeaf: true,
676
- ...placement.customization ? { customization: placement.customization } : {}
677
- })]), placement.path.slice(0, -1))
678
- }),
679
- sourceCapabilities: Object.freeze([node])
680
- };
681
- }
682
- if (placement.customization) throw new TypeError("customize() requires a Capability reference, not an App subtree");
683
- return {
684
- manifest: Object.freeze({
685
- ...source,
686
- capabilities: placeGroup(node, placement.sourcePath, placement.path)
687
- }),
688
- sourceCapabilities: flattenManifestCapabilities(node.children)
689
- };
690
- }
691
- function placeGroup(group, sourcePath, path) {
692
- if (path.length === 0) return rebaseManifestPaths(group.children, sourcePath, []);
693
- const placed = Object.freeze({
694
- ...group,
695
- key: path.at(-1),
696
- meta: Object.freeze({}),
697
- children: rebaseManifestPaths(group.children, sourcePath, path)
698
- });
699
- return wrapGroups(Object.freeze([placed]), path.slice(0, -1));
700
- }
701
- function placeCapability(capability, placement) {
702
- return Object.freeze({
703
- ...capability,
704
- path: placement.path,
705
- ...placement.relocatedLeaf ? { customization: mergeCustomization(capability.customization, {
706
- ...placement.customization,
707
- navigation: "destination"
708
- }) } : {}
481
+ let dispatch;
482
+ const resolve = createManifestResolver(async () => {
483
+ const sources = await Promise.all(placements.map(async (placement) => ({
484
+ manifest: placeManifest(placement.path, await placement.runtime.manifest()),
485
+ owner: placement.runtime
486
+ })));
487
+ const composed = composeApplicationManifests(sources);
488
+ const nextDispatch = /* @__PURE__ */ new Map();
489
+ sources.forEach(({ manifest }, index) => {
490
+ for (const capability of flattenManifestCapabilities(manifest.capabilities)) nextDispatch.set(capability.id, placements[index].runtime);
491
+ });
492
+ dispatch = nextDispatch;
493
+ return composed;
709
494
  });
710
- }
711
- function missingReference(path) {
712
- return /* @__PURE__ */ new Error(`No executable App node exists at "${path.join(".")}"`);
713
- }
714
- /** One cached manifest/dispatch snapshot for both composition and selection. */
715
- function derivedRuntime(load, resolve) {
716
- const snapshot = cacheAsync(load);
717
- const target = async (id) => {
718
- const runtime = (await snapshot()).dispatch.get(id);
719
- if (!runtime) throw new TransportError("NOT_FOUND", { status: 404 });
720
- return runtime;
721
- };
722
495
  return Object.freeze({
723
- manifest: async () => (await snapshot()).manifest,
724
- resolve,
496
+ manifest: resolve,
497
+ async resolve(path) {
498
+ const matches = (await Promise.all(placements.filter((placement) => isPathPrefixOrEqual(placement.path, path)).map((placement) => placement.runtime.resolve(path.slice(placement.path.length))))).filter((match) => match !== void 0).filter((match, index, all) => all.findIndex((candidate) => candidate.capability.id === match.capability.id && candidate.transport === match.transport) === index);
499
+ if (matches.length === 0) return void 0;
500
+ if (matches.length > 1) throw new Error(`Cannot resolve ambiguous App path "${path.join(".")}"`);
501
+ return matches[0];
502
+ },
725
503
  async call(call) {
726
- return (await target(call.id)).call(call);
504
+ await resolve();
505
+ const target = dispatch?.get(call.id);
506
+ if (!target) throw new TransportError("NOT_FOUND", { status: 404 });
507
+ return target.call(call);
727
508
  },
728
- async subscribe(call) {
729
- return (await target(call.id)).subscribe(call);
509
+ async *subscribe(call) {
510
+ await resolve();
511
+ const target = dispatch?.get(call.id);
512
+ if (!target) throw new TransportError("NOT_FOUND", { status: 404 });
513
+ yield* target.subscribe(call);
730
514
  }
731
515
  });
732
516
  }
733
517
  function selectApp(application, selection) {
734
518
  const runtime = getInternalAppRuntime(application);
735
- const manifest = cacheAsync(async () => selectManifest(await runtime.manifest(), selection));
736
- return appFromRuntime(derivedRuntime(async () => {
737
- const selected = await manifest();
738
- return {
739
- manifest: selected,
740
- dispatch: new Map(flattenManifestCapabilities(selected.capabilities).map((capability) => [capability.id, runtime]))
741
- };
742
- }, async (path) => {
743
- if (!findManifestCapability((await manifest()).capabilities, path)) return void 0;
744
- return runtime.resolve(path);
519
+ let ids;
520
+ const manifest = createManifestResolver(async () => {
521
+ const selected = selectManifest(await runtime.manifest(), selection);
522
+ ids = new Set(flattenManifestCapabilities(selected.capabilities).map((capability) => capability.id));
523
+ return selected;
524
+ });
525
+ return appFromRuntime(Object.freeze({
526
+ manifest,
527
+ async resolve(path) {
528
+ if (!findManifestCapability((await manifest()).capabilities, path)) return;
529
+ return runtime.resolve(path);
530
+ },
531
+ async call(call) {
532
+ await manifest();
533
+ if (!ids?.has(call.id)) throw new TransportError("NOT_FOUND", { status: 404 });
534
+ return runtime.call(call);
535
+ },
536
+ async *subscribe(call) {
537
+ await manifest();
538
+ if (!ids?.has(call.id)) throw new TransportError("NOT_FOUND", { status: 404 });
539
+ yield* runtime.subscribe(call);
540
+ }
745
541
  }));
746
542
  }
747
543
  function placeManifest(path, source) {
748
544
  if (path.length === 0) return source;
749
- return Object.freeze({
750
- ...source,
751
- capabilities: wrapGroups(rebaseManifestPaths(source.capabilities, [], path), path, source)
752
- });
753
- }
754
- function wrapGroups(nodes, path, source) {
755
- let capabilities = nodes;
545
+ let capabilities = prefixManifestPaths(source.capabilities, path);
756
546
  for (let index = path.length - 1; index >= 0; index--) {
757
547
  const leaf = index === path.length - 1;
758
548
  capabilities = Object.freeze([Object.freeze({
759
549
  type: "group",
760
550
  key: path[index],
761
- ...leaf && source ? { title: source.name } : {},
762
- ...leaf && source?.description ? { description: source.description } : {},
551
+ ...leaf ? { title: source.name } : {},
552
+ ...leaf && source.description ? { description: source.description } : {},
763
553
  meta: Object.freeze({}),
764
554
  children: capabilities
765
555
  })]);
766
556
  }
767
- return capabilities;
557
+ return Object.freeze({
558
+ ...source,
559
+ capabilities
560
+ });
768
561
  }
769
- function rebaseManifestPaths(nodes, sourcePath, destinationPath) {
562
+ function prefixManifestPaths(nodes, prefix) {
770
563
  return Object.freeze(nodes.map((node) => node.type === "capability" ? Object.freeze({
771
564
  ...node,
772
- path: Object.freeze([...destinationPath, ...node.path.slice(sourcePath.length)])
565
+ path: Object.freeze([...prefix, ...node.path])
773
566
  }) : Object.freeze({
774
567
  ...node,
775
- children: rebaseManifestPaths(node.children, sourcePath, destinationPath)
568
+ children: prefixManifestPaths(node.children, prefix)
776
569
  })));
777
570
  }
778
571
  function isPathPrefixOrEqual(prefix, path) {
@@ -782,6 +575,6 @@ function samePath(left, right) {
782
575
  return left.length === right.length && left.every((segment, index) => segment === right[index]);
783
576
  }
784
577
  //#endregion
785
- export { getCapabilityNavigationMeta as a, TransportError as c, getAppRuntime as d, isApp as f, flattenManifestCapabilities as h, getCapabilityDisplay as i, createApp as l, createAppManifest as m, selectApp as n, APP_CAPABILITIES_SYMBOL as o, subscribe as p, customize as r, APP_RUNTIME_SYMBOL as s, composeApps as t, createRemoteApp as u };
578
+ export { TransportError as a, getAppRuntime as c, createAppManifest as d, APP_RUNTIME_SYMBOL as i, isApp as l, selectApp as n, createApp as o, APP_CAPABILITIES_SYMBOL as r, createRemoteApp as s, composeApps as t, subscribe as u };
786
579
 
787
- //# sourceMappingURL=src-DePlcG_t.mjs.map
580
+ //# sourceMappingURL=src-B592M-6b.mjs.map