@fabricorg/platform 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +48 -2
  2. package/README.md +21 -0
  3. package/dist/actions/index.cjs +11 -11
  4. package/dist/actions/index.d.cts +2 -0
  5. package/dist/actions/index.d.ts +2 -0
  6. package/dist/actions/index.js +1 -1
  7. package/dist/chunk-3JQI3OFC.js +347 -0
  8. package/dist/chunk-3JQI3OFC.js.map +1 -0
  9. package/dist/chunk-3S6UTP4X.js +110 -0
  10. package/dist/chunk-3S6UTP4X.js.map +1 -0
  11. package/dist/{chunk-JSTGOT6P.js → chunk-7WASIL46.js} +58 -3
  12. package/dist/chunk-7WASIL46.js.map +1 -0
  13. package/dist/{chunk-BWNPGRRV.cjs → chunk-HLRIXNVG.cjs} +2 -2
  14. package/dist/chunk-HLRIXNVG.cjs.map +1 -0
  15. package/dist/{chunk-4SMPJPJ6.js → chunk-JM55UQWK.js} +2 -2
  16. package/dist/chunk-JM55UQWK.js.map +1 -0
  17. package/dist/chunk-NFP5DJBT.js +219 -0
  18. package/dist/chunk-NFP5DJBT.js.map +1 -0
  19. package/dist/{chunk-Q3WYIWCN.cjs → chunk-O7IHZ53Y.cjs} +63 -2
  20. package/dist/chunk-O7IHZ53Y.cjs.map +1 -0
  21. package/dist/chunk-ODP3DO6P.cjs +355 -0
  22. package/dist/chunk-ODP3DO6P.cjs.map +1 -0
  23. package/dist/chunk-RYCHDNHZ.cjs +226 -0
  24. package/dist/chunk-RYCHDNHZ.cjs.map +1 -0
  25. package/dist/chunk-XCL2HBMB.cjs +116 -0
  26. package/dist/chunk-XCL2HBMB.cjs.map +1 -0
  27. package/dist/index.cjs +92 -39
  28. package/dist/index.d.cts +4 -3
  29. package/dist/index.d.ts +4 -3
  30. package/dist/index.js +6 -5
  31. package/dist/manifest/index.cjs +40 -0
  32. package/dist/manifest/index.cjs.map +1 -0
  33. package/dist/manifest/index.d.cts +181 -0
  34. package/dist/manifest/index.d.ts +181 -0
  35. package/dist/manifest/index.js +11 -0
  36. package/dist/manifest/index.js.map +1 -0
  37. package/dist/modules/index.cjs +11 -10
  38. package/dist/modules/index.d.cts +49 -1
  39. package/dist/modules/index.d.ts +49 -1
  40. package/dist/modules/index.js +4 -3
  41. package/dist/objects/index.cjs +9 -5
  42. package/dist/objects/index.d.cts +45 -1
  43. package/dist/objects/index.d.ts +45 -1
  44. package/dist/objects/index.js +1 -1
  45. package/dist/projections/index.cjs +26 -2
  46. package/dist/projections/index.d.cts +38 -2
  47. package/dist/projections/index.d.ts +38 -2
  48. package/dist/projections/index.js +1 -1
  49. package/package.json +11 -1
  50. package/dist/chunk-35DD3H55.js +0 -187
  51. package/dist/chunk-35DD3H55.js.map +0 -1
  52. package/dist/chunk-4SMPJPJ6.js.map +0 -1
  53. package/dist/chunk-BWNPGRRV.cjs.map +0 -1
  54. package/dist/chunk-I35B576X.js +0 -30
  55. package/dist/chunk-I35B576X.js.map +0 -1
  56. package/dist/chunk-JSTGOT6P.js.map +0 -1
  57. package/dist/chunk-Q3WYIWCN.cjs.map +0 -1
  58. package/dist/chunk-QETQGAXJ.cjs +0 -35
  59. package/dist/chunk-QETQGAXJ.cjs.map +0 -1
  60. package/dist/chunk-SSYKDXR4.cjs +0 -195
  61. package/dist/chunk-SSYKDXR4.cjs.map +0 -1
@@ -0,0 +1,110 @@
1
+ // objects/index.ts
2
+ var objectTypeRegistry = /* @__PURE__ */ new Set([
3
+ "AssetEvent",
4
+ "ActionInvocation",
5
+ "PolicyEvaluation",
6
+ "ApprovalRequest",
7
+ "ConsentRecord",
8
+ "AgentRun"
9
+ ]);
10
+ var supportedSchemaKeywords = /* @__PURE__ */ new Set([
11
+ "$schema",
12
+ "$id",
13
+ "$ref",
14
+ "$defs",
15
+ "title",
16
+ "description",
17
+ "type",
18
+ "enum",
19
+ "const",
20
+ "properties",
21
+ "required",
22
+ "additionalProperties",
23
+ "items",
24
+ "allOf",
25
+ "anyOf",
26
+ "oneOf",
27
+ "not",
28
+ "minimum",
29
+ "maximum",
30
+ "exclusiveMinimum",
31
+ "exclusiveMaximum",
32
+ "minLength",
33
+ "maxLength",
34
+ "pattern",
35
+ "format",
36
+ "minItems",
37
+ "maxItems",
38
+ "uniqueItems",
39
+ "default",
40
+ "readOnly",
41
+ "writeOnly"
42
+ ]);
43
+ function assertPortableJsonSchema(schema, path = "schema") {
44
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
45
+ throw new Error(`${path} must be a JSON Schema object.`);
46
+ }
47
+ const value = schema;
48
+ for (const keyword of Object.keys(value)) {
49
+ if (!supportedSchemaKeywords.has(keyword) && !keyword.startsWith("x-")) {
50
+ throw new Error(`${path} uses unsupported JSON Schema keyword "${keyword}".`);
51
+ }
52
+ }
53
+ if (value.properties !== void 0) {
54
+ if (!value.properties || typeof value.properties !== "object" || Array.isArray(value.properties)) {
55
+ throw new Error(`${path}.properties must be an object.`);
56
+ }
57
+ for (const [name, child] of Object.entries(value.properties)) {
58
+ assertPortableJsonSchema(child, `${path}.properties.${name}`);
59
+ }
60
+ }
61
+ if (value.$defs !== void 0) {
62
+ if (!value.$defs || typeof value.$defs !== "object" || Array.isArray(value.$defs)) {
63
+ throw new Error(`${path}.$defs must be an object.`);
64
+ }
65
+ for (const [name, child] of Object.entries(value.$defs)) {
66
+ assertPortableJsonSchema(child, `${path}.$defs.${name}`);
67
+ }
68
+ }
69
+ for (const keyword of ["allOf", "anyOf", "oneOf"]) {
70
+ if (value[keyword] !== void 0) {
71
+ if (!Array.isArray(value[keyword])) throw new Error(`${path}.${keyword} must be an array.`);
72
+ value[keyword].forEach((child, index) => assertPortableJsonSchema(child, `${path}.${keyword}[${index}]`));
73
+ }
74
+ }
75
+ if (value.not !== void 0) assertPortableJsonSchema(value.not, `${path}.not`);
76
+ if (value.additionalProperties !== void 0 && typeof value.additionalProperties !== "boolean") {
77
+ assertPortableJsonSchema(value.additionalProperties, `${path}.additionalProperties`);
78
+ }
79
+ if (value.items !== void 0) {
80
+ if (Array.isArray(value.items)) {
81
+ value.items.forEach((child, index) => assertPortableJsonSchema(child, `${path}.items[${index}]`));
82
+ } else {
83
+ assertPortableJsonSchema(value.items, `${path}.items`);
84
+ }
85
+ }
86
+ if (value.required !== void 0 && (!Array.isArray(value.required) || value.required.some((item) => typeof item !== "string"))) {
87
+ throw new Error(`${path}.required must be an array of property names.`);
88
+ }
89
+ }
90
+ function assertObjectType(type) {
91
+ if (!/^[A-Z][a-zA-Z0-9]*$/.test(type)) {
92
+ throw new Error(
93
+ `Invalid object type: "${type}". Object types must be PascalCase alphanumeric.`
94
+ );
95
+ }
96
+ }
97
+ function registerObjectType(type) {
98
+ assertObjectType(type);
99
+ objectTypeRegistry.add(type);
100
+ }
101
+ function isValidObjectType(type) {
102
+ return objectTypeRegistry.has(type);
103
+ }
104
+ function getRegisteredObjectTypes() {
105
+ return Array.from(objectTypeRegistry);
106
+ }
107
+
108
+ export { assertObjectType, assertPortableJsonSchema, getRegisteredObjectTypes, isValidObjectType, registerObjectType };
109
+ //# sourceMappingURL=chunk-3S6UTP4X.js.map
110
+ //# sourceMappingURL=chunk-3S6UTP4X.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../objects/index.ts"],"names":[],"mappings":";AAAA,IAAM,kBAAA,uBAAyB,GAAA,CAAY;AAAA,EAC1C,YAAA;AAAA,EACA,kBAAA;AAAA,EACA,kBAAA;AAAA,EACA,iBAAA;AAAA,EACA,eAAA;AAAA,EACA;AACD,CAAC,CAAA;AA+CD,IAAM,uBAAA,uBAA8B,GAAA,CAAI;AAAA,EACvC,SAAA;AAAA,EAAW,KAAA;AAAA,EAAO,MAAA;AAAA,EAAQ,OAAA;AAAA,EAAS,OAAA;AAAA,EAAS,aAAA;AAAA,EAAe,MAAA;AAAA,EAAQ,MAAA;AAAA,EAAQ,OAAA;AAAA,EAC3E,YAAA;AAAA,EAAc,UAAA;AAAA,EAAY,sBAA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AA;AAAA,MACT,yBAAyB,IAAI,CAAA,gDAAA;AAAA,KAC9B;AAAA,EACD;AACD;AAEO,SAAS,mBAAmB,IAAA,EAAoB;AACtD,EAAA,gBAAA,CAAiB,IAAI,CAAA;AACrB,EAAA,kBAAA,CAAmB,IAAI,IAAI,CAAA;AAC5B;AAEO,SAAS,kBAAkB,IAAA,EAAuB;AACxD,EAAA,OAAO,kBAAA,CAAmB,IAAI,IAAI,CAAA;AACnC;AAEO,SAAS,wBAAA,GAAqC;AACpD,EAAA,OAAO,KAAA,CAAM,KAAK,kBAAkB,CAAA;AACrC","file":"chunk-3S6UTP4X.js","sourcesContent":["const objectTypeRegistry = new Set<string>([\n\t\"AssetEvent\",\n\t\"ActionInvocation\",\n\t\"PolicyEvaluation\",\n\t\"ApprovalRequest\",\n\t\"ConsentRecord\",\n\t\"AgentRun\",\n]);\n\nexport type FabricObjectType = string;\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };\n\n/**\n * Dependency-free JSON Schema profile accepted in portable module manifests.\n * Unknown extension keywords must use an `x-` prefix. Runtime validators may\n * support more vocabulary, but exported entity contracts stay in this profile.\n */\nexport interface PortableJsonSchema {\n\t$schema?: string;\n\t$id?: string;\n\t$ref?: string;\n\t$defs?: Record<string, PortableJsonSchema>;\n\ttitle?: string;\n\tdescription?: string;\n\ttype?: \"null\" | \"boolean\" | \"object\" | \"array\" | \"number\" | \"integer\" | \"string\" | Array<\"null\" | \"boolean\" | \"object\" | \"array\" | \"number\" | \"integer\" | \"string\">;\n\tenum?: JsonValue[];\n\tconst?: JsonValue;\n\tproperties?: Record<string, PortableJsonSchema>;\n\trequired?: string[];\n\tadditionalProperties?: boolean | PortableJsonSchema;\n\titems?: PortableJsonSchema | PortableJsonSchema[];\n\tallOf?: PortableJsonSchema[];\n\tanyOf?: PortableJsonSchema[];\n\toneOf?: PortableJsonSchema[];\n\tnot?: PortableJsonSchema;\n\tminimum?: number;\n\tmaximum?: number;\n\texclusiveMinimum?: number;\n\texclusiveMaximum?: number;\n\tminLength?: number;\n\tmaxLength?: number;\n\tpattern?: string;\n\tformat?: string;\n\tminItems?: number;\n\tmaxItems?: number;\n\tuniqueItems?: boolean;\n\tdefault?: JsonValue;\n\treadOnly?: boolean;\n\twriteOnly?: boolean;\n\t[key: `x-${string}`]: JsonValue | undefined;\n}\n\nconst supportedSchemaKeywords = new Set([\n\t\"$schema\", \"$id\", \"$ref\", \"$defs\", \"title\", \"description\", \"type\", \"enum\", \"const\",\n\t\"properties\", \"required\", \"additionalProperties\", \"items\", \"allOf\", \"anyOf\", \"oneOf\",\n\t\"not\", \"minimum\", \"maximum\", \"exclusiveMinimum\", \"exclusiveMaximum\", \"minLength\",\n\t\"maxLength\", \"pattern\", \"format\", \"minItems\", \"maxItems\", \"uniqueItems\", \"default\",\n\t\"readOnly\", \"writeOnly\",\n]);\n\nexport function assertPortableJsonSchema(\n\tschema: unknown,\n\tpath = \"schema\",\n): asserts schema is PortableJsonSchema {\n\tif (!schema || typeof schema !== \"object\" || Array.isArray(schema)) {\n\t\tthrow new Error(`${path} must be a JSON Schema object.`);\n\t}\n\tconst value = schema as Record<string, unknown>;\n\tfor (const keyword of Object.keys(value)) {\n\t\tif (!supportedSchemaKeywords.has(keyword) && !keyword.startsWith(\"x-\")) {\n\t\t\tthrow new Error(`${path} uses unsupported JSON Schema keyword \"${keyword}\".`);\n\t\t}\n\t}\n\tif (value.properties !== undefined) {\n\t\tif (!value.properties || typeof value.properties !== \"object\" || Array.isArray(value.properties)) {\n\t\t\tthrow new Error(`${path}.properties must be an object.`);\n\t\t}\n\t\tfor (const [name, child] of Object.entries(value.properties)) {\n\t\t\tassertPortableJsonSchema(child, `${path}.properties.${name}`);\n\t\t}\n\t}\n\tif (value.$defs !== undefined) {\n\t\tif (!value.$defs || typeof value.$defs !== \"object\" || Array.isArray(value.$defs)) {\n\t\t\tthrow new Error(`${path}.$defs must be an object.`);\n\t\t}\n\t\tfor (const [name, child] of Object.entries(value.$defs)) {\n\t\t\tassertPortableJsonSchema(child, `${path}.$defs.${name}`);\n\t\t}\n\t}\n\tfor (const keyword of [\"allOf\", \"anyOf\", \"oneOf\"] as const) {\n\t\tif (value[keyword] !== undefined) {\n\t\t\tif (!Array.isArray(value[keyword])) throw new Error(`${path}.${keyword} must be an array.`);\n\t\t\tvalue[keyword].forEach((child, index) => assertPortableJsonSchema(child, `${path}.${keyword}[${index}]`));\n\t\t}\n\t}\n\tif (value.not !== undefined) assertPortableJsonSchema(value.not, `${path}.not`);\n\tif (value.additionalProperties !== undefined && typeof value.additionalProperties !== \"boolean\") {\n\t\tassertPortableJsonSchema(value.additionalProperties, `${path}.additionalProperties`);\n\t}\n\tif (value.items !== undefined) {\n\t\tif (Array.isArray(value.items)) {\n\t\t\tvalue.items.forEach((child, index) => assertPortableJsonSchema(child, `${path}.items[${index}]`));\n\t\t} else {\n\t\t\tassertPortableJsonSchema(value.items, `${path}.items`);\n\t\t}\n\t}\n\tif (value.required !== undefined && (!Array.isArray(value.required) || value.required.some((item) => typeof item !== \"string\"))) {\n\t\tthrow new Error(`${path}.required must be an array of property names.`);\n\t}\n}\n\nexport function assertObjectType(type: string): asserts type is FabricObjectType {\n\tif (!/^[A-Z][a-zA-Z0-9]*$/.test(type)) {\n\t\tthrow new Error(\n\t\t\t`Invalid object type: \"${type}\". Object types must be PascalCase alphanumeric.`,\n\t\t);\n\t}\n}\n\nexport function registerObjectType(type: string): void {\n\tassertObjectType(type);\n\tobjectTypeRegistry.add(type);\n}\n\nexport function isValidObjectType(type: string): boolean {\n\treturn objectTypeRegistry.has(type);\n}\n\nexport function getRegisteredObjectTypes(): string[] {\n\treturn Array.from(objectTypeRegistry);\n}\n"]}
@@ -1,4 +1,59 @@
1
1
  // projections/index.ts
2
+ var viewRegistry = /* @__PURE__ */ new Map();
3
+ function viewContractKey(view) {
4
+ return `${view.name}@${view.version}`;
5
+ }
6
+ function registerViewContract(view) {
7
+ const key = viewContractKey(view);
8
+ if (viewRegistry.has(key)) throw new Error(`View contract "${key}" is already registered.`);
9
+ viewRegistry.set(key, view);
10
+ }
11
+ function registerViewContractIfMissing(view) {
12
+ if (!viewRegistry.has(viewContractKey(view))) registerViewContract(view);
13
+ }
14
+ function resolveViewContract(name, version) {
15
+ return viewRegistry.get(`${name}@${version}`);
16
+ }
17
+ function getRegisteredViewContractKeys() {
18
+ return Array.from(viewRegistry.keys());
19
+ }
20
+ async function replayView({
21
+ view,
22
+ events,
23
+ scope,
24
+ snapshot
25
+ }) {
26
+ if (snapshot && snapshot.snapshotVersion !== view.snapshotVersion && !view.compatibleSnapshotVersions?.includes(snapshot.snapshotVersion)) {
27
+ throw new Error(
28
+ `View "${viewContractKey(view)}" cannot resume snapshot version ${snapshot.snapshotVersion}.`
29
+ );
30
+ }
31
+ if (snapshot && snapshot.snapshotVersion !== view.snapshotVersion && !view.upgradeSnapshot) {
32
+ throw new Error(
33
+ `View "${viewContractKey(view)}" must provide upgradeSnapshot for snapshot version ${snapshot.snapshotVersion}.`
34
+ );
35
+ }
36
+ const upgradedSnapshot = snapshot && snapshot.snapshotVersion !== view.snapshotVersion ? { ...snapshot, snapshotVersion: view.snapshotVersion, snapshotData: await view.upgradeSnapshot(snapshot.snapshotData, snapshot.snapshotVersion) } : snapshot;
37
+ const accepted = new Map(
38
+ view.consumes.map((consumption) => [consumption.eventType, new Set(consumption.schemaVersions)])
39
+ );
40
+ const versionWarnings = [];
41
+ const filtered = async function* () {
42
+ for await (const event of events) {
43
+ const versions = accepted.get(event.eventType);
44
+ if (versions?.has(event.eventSchemaVersion ?? 1)) yield event;
45
+ else if (versions) versionWarnings.push({ code: "unsupported_event_version", eventId: event.id, message: `View "${viewContractKey(view)}" does not consume ${event.eventType} schema version ${event.eventSchemaVersion ?? 1}.` });
46
+ }
47
+ };
48
+ const result = await replayEvents({
49
+ events: filtered(),
50
+ scope,
51
+ initialState: view.initialState,
52
+ snapshot: upgradedSnapshot,
53
+ applyEvent: view.applyEvent
54
+ });
55
+ return { ...result, warnings: [...versionWarnings, ...result.warnings] };
56
+ }
2
57
  async function replayEvents({
3
58
  events,
4
59
  scope,
@@ -176,6 +231,6 @@ function toTimestamp(value) {
176
231
  return value instanceof Date ? value.getTime() : new Date(value).getTime();
177
232
  }
178
233
 
179
- export { replayEvents };
180
- //# sourceMappingURL=chunk-JSTGOT6P.js.map
181
- //# sourceMappingURL=chunk-JSTGOT6P.js.map
234
+ export { getRegisteredViewContractKeys, registerViewContract, registerViewContractIfMissing, replayEvents, replayView, resolveViewContract, viewContractKey };
235
+ //# sourceMappingURL=chunk-7WASIL46.js.map
236
+ //# sourceMappingURL=chunk-7WASIL46.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../projections/index.ts"],"names":[],"mappings":";AAsCA,IAAM,YAAA,uBAAmB,GAAA,EAA0B;AAE5C,SAAS,gBAAgB,IAAA,EAAsD;AACrF,EAAA,OAAO,CAAA,EAAG,IAAA,CAAK,IAAI,CAAA,CAAA,EAAI,KAAK,OAAO,CAAA,CAAA;AACpC;AAEO,SAAS,qBAAqB,IAAA,EAA0B;AAC9D,EAAA,MAAM,GAAA,GAAM,gBAAgB,IAAI,CAAA;AAChC,EAAA,IAAI,YAAA,CAAa,IAAI,GAAG,CAAA,QAAS,IAAI,KAAA,CAAM,CAAA,eAAA,EAAkB,GAAG,CAAA,wBAAA,CAA0B,CAAA;AAC1F,EAAA,YAAA,CAAa,GAAA,CAAI,KAAK,IAAI,CAAA;AAC3B;AAEO,SAAS,8BAA8B,IAAA,EAA0B;AACvE,EAAA,IAAI,CAAC,aAAa,GAAA,CAAI,eAAA,CAAgB,IAAI,CAAC,CAAA,uBAAwB,IAAI,CAAA;AACxE;AAEO,SAAS,mBAAA,CAAoB,MAAc,OAAA,EAA2C;AAC5F,EAAA,OAAO,aAAa,GAAA,CAAI,CAAA,EAAG,IAAI,CAAA,CAAA,EAAI,OAAO,CAAA,CAAE,CAAA;AAC7C;AAEO,SAA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AI,IAAA,CAAK,KAAK,CAAA,CAAE,OAAA,EAAQ;AAC1E","file":"chunk-7WASIL46.js","sourcesContent":["export interface ReplayableAssetEvent<Payload = unknown> {\n\tid: string;\n\ttenantId: string;\n\tspaceId: string;\n\teventType: string;\n\teventSchemaVersion?: number;\n\tsubjectType: string;\n\tsubjectId: string;\n\tpayload: Payload;\n\tsequence: number;\n\toccurredAt: Date | string;\n\trecordedAt: Date | string;\n\tactionInvocationId: string;\n\tcorrelationId: string;\n}\n\nimport type { PortableJsonSchema } from \"../objects\";\n\nexport interface ViewEventConsumption {\n\teventType: string;\n\tschemaVersions: number[];\n}\n\nexport interface ViewContract<State = unknown, Event extends ReplayableAssetEvent = ReplayableAssetEvent> {\n\t/** Stable module-qualified logical identity, for example `orders/summary`. */\n\tname: `${string}/${string}`;\n\tversion: string;\n\tshape: PortableJsonSchema;\n\tconsumes: ViewEventConsumption[];\n\tscope: \"tenant-space\";\n\tsnapshotVersion: number;\n\tcompatibleSnapshotVersions?: number[];\n\t/** Required to transform any older compatible snapshot into the current state shape. */\n\tupgradeSnapshot?: (data: unknown, fromVersion: number) => State | Promise<State>;\n\tinitialState: State;\n\tapplyEvent: (state: State, event: Event) => State | Promise<State>;\n}\n\nconst viewRegistry = new Map<string, ViewContract>();\n\nexport function viewContractKey(view: Pick<ViewContract, \"name\" | \"version\">): string {\n\treturn `${view.name}@${view.version}`;\n}\n\nexport function registerViewContract(view: ViewContract): void {\n\tconst key = viewContractKey(view);\n\tif (viewRegistry.has(key)) throw new Error(`View contract \"${key}\" is already registered.`);\n\tviewRegistry.set(key, view);\n}\n\nexport function registerViewContractIfMissing(view: ViewContract): void {\n\tif (!viewRegistry.has(viewContractKey(view))) registerViewContract(view);\n}\n\nexport function resolveViewContract(name: string, version: string): ViewContract | undefined {\n\treturn viewRegistry.get(`${name}@${version}`);\n}\n\nexport function getRegisteredViewContractKeys(): string[] {\n\treturn Array.from(viewRegistry.keys());\n}\n\nexport interface ReplayViewOptions<State, Event extends ReplayableAssetEvent = ReplayableAssetEvent> {\n\tview: ViewContract<State, Event>;\n\tevents: Iterable<Event> | AsyncIterable<Event>;\n\tscope: ReplayScope;\n\tsnapshot?: (ReplaySnapshot<State> & { snapshotVersion: number }) | null;\n}\n\nexport async function replayView<State, Event extends ReplayableAssetEvent = ReplayableAssetEvent>({\n\tview,\n\tevents,\n\tscope,\n\tsnapshot,\n}: ReplayViewOptions<State, Event>): Promise<ReplayEventsResult<State, Event>> {\n\tif (\n\t\tsnapshot &&\n\t\tsnapshot.snapshotVersion !== view.snapshotVersion &&\n\t\t!view.compatibleSnapshotVersions?.includes(snapshot.snapshotVersion)\n\t) {\n\t\tthrow new Error(\n\t\t\t`View \"${viewContractKey(view)}\" cannot resume snapshot version ${snapshot.snapshotVersion}.`,\n\t\t);\n\t}\n\tif (snapshot && snapshot.snapshotVersion !== view.snapshotVersion && !view.upgradeSnapshot) {\n\t\tthrow new Error(\n\t\t\t`View \"${viewContractKey(view)}\" must provide upgradeSnapshot for snapshot version ${snapshot.snapshotVersion}.`,\n\t\t);\n\t}\n\tconst upgradedSnapshot = snapshot && snapshot.snapshotVersion !== view.snapshotVersion\n\t\t? { ...snapshot, snapshotVersion: view.snapshotVersion, snapshotData: await view.upgradeSnapshot!(snapshot.snapshotData, snapshot.snapshotVersion) }\n\t\t: snapshot;\n\tconst accepted = new Map(\n\t\tview.consumes.map((consumption) => [consumption.eventType, new Set(consumption.schemaVersions)]),\n\t);\n\tconst versionWarnings: ReplayWarning[] = [];\n\tconst filtered = async function* (): AsyncIterable<Event> {\n\t\tfor await (const event of events) {\n\t\t\tconst versions = accepted.get(event.eventType);\n\t\t\tif (versions?.has(event.eventSchemaVersion ?? 1)) yield event;\n\t\t\telse if (versions) versionWarnings.push({ code: \"unsupported_event_version\", eventId: event.id, message: `View \"${viewContractKey(view)}\" does not consume ${event.eventType} schema version ${event.eventSchemaVersion ?? 1}.` });\n\t\t}\n\t};\n\tconst result = await replayEvents({\n\t\tevents: filtered(),\n\t\tscope,\n\t\tinitialState: view.initialState,\n\t\tsnapshot: upgradedSnapshot,\n\t\tapplyEvent: view.applyEvent,\n\t});\n\treturn { ...result, warnings: [...versionWarnings, ...result.warnings] };\n}\n\nexport interface ReplayScope {\n\ttenantId: string;\n\tspaceId: string;\n\tsubjectType?: string;\n\tsubjectId?: string;\n}\n\nexport interface ReplaySnapshot<State = unknown> {\n\tsnapshotData: State;\n\teventCursor?: string | null;\n\teventSequence?: number | null;\n}\n\nexport type ReplayWarningCode =\n\t| \"cursor_not_found\"\n\t| \"duplicate_event\"\n\t| \"missing_sequence\"\n\t| \"subject_scope_incomplete\"\n\t| \"unsupported_event_version\";\n\nexport interface ReplayWarning {\n\tcode: ReplayWarningCode;\n\tmessage: string;\n\teventId?: string;\n\tsubjectType?: string;\n\tsubjectId?: string;\n\texpectedSequence?: number;\n\tactualSequence?: number;\n}\n\nexport interface ReplayEventsOptions<State, Event extends ReplayableAssetEvent = ReplayableAssetEvent> {\n\tevents: Iterable<Event> | AsyncIterable<Event>;\n\tscope: ReplayScope;\n\tinitialState: State;\n\tsnapshot?: ReplaySnapshot<State> | null;\n\tapplyEvent: (state: State, event: Event) => State | Promise<State>;\n}\n\nexport interface ReplayEventsResult<State, Event extends ReplayableAssetEvent = ReplayableAssetEvent> {\n\tstate: State;\n\tappliedEvents: Event[];\n\twarnings: ReplayWarning[];\n\teventCursor: string | null;\n\teventSequence: number;\n}\n\nexport async function replayEvents<State, Event extends ReplayableAssetEvent = ReplayableAssetEvent>({\n\tevents,\n\tscope,\n\tinitialState,\n\tsnapshot,\n\tapplyEvent,\n}: ReplayEventsOptions<State, Event>): Promise<ReplayEventsResult<State, Event>> {\n\tconst warnings: ReplayWarning[] = [];\n\tconst scopedEvents = filterEventsByScope(await collectEvents(events), scope, warnings);\n\tconst orderedEvents = sortEvents(scopedEvents, isSubjectScoped(scope));\n\tconst uniqueEvents = removeDuplicateEvents(orderedEvents, warnings);\n\tconst resumableEvents = applyCursor(uniqueEvents, snapshot, isSubjectScoped(scope), warnings);\n\n\tlet state = snapshot?.snapshotData ?? initialState;\n\tconst appliedEvents: Event[] = [];\n\tlet eventCursor = snapshot?.eventCursor ?? null;\n\tlet eventSequence = snapshot?.eventSequence ?? 0;\n\n\tfor (const event of resumableEvents) {\n\t\tstate = await applyEvent(state, event);\n\t\tappliedEvents.push(event);\n\t\teventCursor = event.id;\n\t\teventSequence = event.sequence;\n\t}\n\n\treturn {\n\t\tstate,\n\t\tappliedEvents,\n\t\twarnings,\n\t\teventCursor,\n\t\teventSequence,\n\t};\n}\n\nasync function collectEvents<Event extends ReplayableAssetEvent>(\n\tevents: Iterable<Event> | AsyncIterable<Event>,\n): Promise<Event[]> {\n\tconst collected: Event[] = [];\n\n\tif (Symbol.asyncIterator in events) {\n\t\tfor await (const event of events) {\n\t\t\tcollected.push(event);\n\t\t}\n\n\t\treturn collected;\n\t}\n\n\tfor (const event of events) {\n\t\tcollected.push(event);\n\t}\n\n\treturn collected;\n}\n\nfunction filterEventsByScope<Event extends ReplayableAssetEvent>(\n\tevents: Event[],\n\tscope: ReplayScope,\n\twarnings: ReplayWarning[],\n): Event[] {\n\tif ((scope.subjectType && !scope.subjectId) || (!scope.subjectType && scope.subjectId)) {\n\t\twarnings.push({\n\t\t\tcode: \"subject_scope_incomplete\",\n\t\t\tmessage: \"Both subjectType and subjectId are required for subject-scoped replay.\",\n\t\t\tsubjectType: scope.subjectType,\n\t\t\tsubjectId: scope.subjectId,\n\t\t});\n\t}\n\n\treturn events.filter((event) => {\n\t\tif (event.tenantId !== scope.tenantId || event.spaceId !== scope.spaceId) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (scope.subjectType && event.subjectType !== scope.subjectType) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (scope.subjectId && event.subjectId !== scope.subjectId) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t});\n}\n\nfunction removeDuplicateEvents<Event extends ReplayableAssetEvent>(\n\tevents: Event[],\n\twarnings: ReplayWarning[],\n): Event[] {\n\tconst seenEventIds = new Set<string>();\n\tconst uniqueEvents: Event[] = [];\n\n\tfor (const event of events) {\n\t\tif (seenEventIds.has(event.id)) {\n\t\t\twarnings.push({\n\t\t\t\tcode: \"duplicate_event\",\n\t\t\t\tmessage: `Duplicate event ${event.id} ignored during replay.`,\n\t\t\t\teventId: event.id,\n\t\t\t\tsubjectType: event.subjectType,\n\t\t\t\tsubjectId: event.subjectId,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tseenEventIds.add(event.id);\n\t\tuniqueEvents.push(event);\n\t}\n\n\trecordMissingSequenceWarnings(uniqueEvents, warnings);\n\n\treturn uniqueEvents;\n}\n\nfunction recordMissingSequenceWarnings<Event extends ReplayableAssetEvent>(\n\tevents: Event[],\n\twarnings: ReplayWarning[],\n): void {\n\tconst lastSequenceBySubject = new Map<string, number>();\n\n\tfor (const event of events) {\n\t\tconst subjectKey = `${event.subjectType}:${event.subjectId}`;\n\t\tconst previousSequence = lastSequenceBySubject.get(subjectKey);\n\t\tconst expectedSequence = previousSequence === undefined ? event.sequence : previousSequence + 1;\n\n\t\tif (previousSequence !== undefined && event.sequence > expectedSequence) {\n\t\t\twarnings.push({\n\t\t\t\tcode: \"missing_sequence\",\n\t\t\t\tmessage: `Missing event sequence for ${subjectKey}: expected ${expectedSequence}, received ${event.sequence}.`,\n\t\t\t\teventId: event.id,\n\t\t\t\tsubjectType: event.subjectType,\n\t\t\t\tsubjectId: event.subjectId,\n\t\t\t\texpectedSequence,\n\t\t\t\tactualSequence: event.sequence,\n\t\t\t});\n\t\t}\n\n\t\tlastSequenceBySubject.set(subjectKey, Math.max(previousSequence ?? event.sequence, event.sequence));\n\t}\n}\n\nfunction applyCursor<Event extends ReplayableAssetEvent>(\n\tevents: Event[],\n\tsnapshot: ReplaySnapshot | null | undefined,\n\tsubjectScoped: boolean,\n\twarnings: ReplayWarning[],\n): Event[] {\n\tconst eventCursor = snapshot?.eventCursor;\n\n\tif (eventCursor) {\n\t\tconst cursorIndex = events.findIndex((event) => event.id === eventCursor);\n\n\t\tif (cursorIndex >= 0) {\n\t\t\treturn events.slice(cursorIndex + 1);\n\t\t}\n\n\t\twarnings.push({\n\t\t\tcode: \"cursor_not_found\",\n\t\t\tmessage: `Snapshot cursor ${eventCursor} was not found in the scoped event stream.`,\n\t\t\teventId: eventCursor,\n\t\t});\n\t}\n\n\tif (subjectScoped && snapshot?.eventSequence !== undefined && snapshot.eventSequence !== null) {\n\t\treturn events.filter((event) => event.sequence > snapshot.eventSequence!);\n\t}\n\n\treturn events;\n}\n\nfunction sortEvents<Event extends ReplayableAssetEvent>(events: Event[], subjectScoped: boolean): Event[] {\n\treturn [...events].sort((first, second) =>\n\t\tsubjectScoped ? compareSubjectEvents(first, second) : compareGlobalEvents(first, second),\n\t);\n}\n\nfunction compareSubjectEvents(first: ReplayableAssetEvent, second: ReplayableAssetEvent): number {\n\treturn compareValues(\n\t\t[first.sequence, toTimestamp(first.recordedAt), toTimestamp(first.occurredAt), first.id],\n\t\t[second.sequence, toTimestamp(second.recordedAt), toTimestamp(second.occurredAt), second.id],\n\t);\n}\n\nfunction compareGlobalEvents(first: ReplayableAssetEvent, second: ReplayableAssetEvent): number {\n\treturn compareValues(\n\t\t[\n\t\t\ttoTimestamp(first.recordedAt),\n\t\t\ttoTimestamp(first.occurredAt),\n\t\t\tfirst.actionInvocationId,\n\t\t\tfirst.correlationId,\n\t\t\tfirst.subjectType,\n\t\t\tfirst.subjectId,\n\t\t\tfirst.sequence,\n\t\t\tfirst.id,\n\t\t],\n\t\t[\n\t\t\ttoTimestamp(second.recordedAt),\n\t\t\ttoTimestamp(second.occurredAt),\n\t\t\tsecond.actionInvocationId,\n\t\t\tsecond.correlationId,\n\t\t\tsecond.subjectType,\n\t\t\tsecond.subjectId,\n\t\t\tsecond.sequence,\n\t\t\tsecond.id,\n\t\t],\n\t);\n}\n\nfunction compareValues(firstValues: Array<number | string>, secondValues: Array<number | string>): number {\n\tfor (const [index, firstValue] of firstValues.entries()) {\n\t\tconst secondValue = secondValues[index];\n\n\t\tif (firstValue < secondValue) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tif (firstValue > secondValue) {\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\treturn 0;\n}\n\nfunction isSubjectScoped(scope: ReplayScope): boolean {\n\treturn Boolean(scope.subjectType && scope.subjectId);\n}\n\nfunction toTimestamp(value: Date | string): number {\n\treturn value instanceof Date ? value.getTime() : new Date(value).getTime();\n}\n"]}
@@ -66,5 +66,5 @@ exports.registerAction = registerAction;
66
66
  exports.registerActionIfMissing = registerActionIfMissing;
67
67
  exports.resolveAction = resolveAction;
68
68
  exports.resolveRegisteredAction = resolveRegisteredAction;
69
- //# sourceMappingURL=chunk-BWNPGRRV.cjs.map
70
- //# sourceMappingURL=chunk-BWNPGRRV.cjs.map
69
+ //# sourceMappingURL=chunk-HLRIXNVG.cjs.map
70
+ //# sourceMappingURL=chunk-HLRIXNVG.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../actions/index.ts"],"names":[],"mappings":";;;AAwBO,IAAM,WAAA,GAAoC;AAAA,EAChD,gBAAA;AAAA,EACA,OAAA;AAAA,EACA,QAAA;AAAA,EACA,iBAAA;AAAA,EACA,iBAAA;AAAA,EACA;AACD;AAEO,SAAS,YAAY,KAAA,EAAmC;AAC9D,EAAA,OAAQ,WAAA,CAAkC,SAAS,KAAK,CAAA;AACzD;AAEO,SAAS,gBAAgB,KAAA,EAA2C;AAC1E,EAAA,IAAI,CAAC,WAAA,CAAY,KAAK,CAAA,EAAG;AACxB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,mBAAA,EAAsB,KAAK,CAAA,CAAE,CAAA;AAAA,EAC9C;AACD;AAuJA,IAAM,QAAA,uBAAe,GAAA,EAAgC;AAE9C,SAAS,eAAe,QAAA,EAAgD;AAC9E,EAAA,IAAI,CAAC,oCAAA,CAAqC,IAAA,CAAK,QAAQ,CAAA,EAAG;AACz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A;AAAA,EAC1B;AACD","file":"chunk-HLRIXNVG.cjs","sourcesContent":["export type ActionId = `${string}.${string}`;\n\nexport interface SchemaParseIssue {\n\tpath: PropertyKey[];\n\tmessage: string;\n}\n\nexport type SchemaParseResult<T = unknown> =\n\t| { success: true; data: T }\n\t| { success: false; error: { issues: SchemaParseIssue[] } };\n\nexport interface SchemaValidator<T = unknown> {\n\tparse(input: unknown): T;\n\tsafeParse(input: unknown): SchemaParseResult<T>;\n}\n\nexport type ActorType =\n\t| \"natural_person\"\n\t| \"agent\"\n\t| \"system\"\n\t| \"service_account\"\n\t| \"external_system\"\n\t| \"integration\";\n\nexport const ACTOR_TYPES: readonly ActorType[] = [\n\t\"natural_person\",\n\t\"agent\",\n\t\"system\",\n\t\"service_account\",\n\t\"external_system\",\n\t\"integration\",\n] as const;\n\nexport function isActorType(value: string): value is ActorType {\n\treturn (ACTOR_TYPES as readonly string[]).includes(value);\n}\n\nexport function assertActorType(value: string): asserts value is ActorType {\n\tif (!isActorType(value)) {\n\t\tthrow new Error(`Invalid actorType: ${value}`);\n\t}\n}\n\nexport type ActionStatus =\n\t| \"pending\"\n\t| \"running\"\n\t| \"completed\"\n\t| \"failed\"\n\t| \"blocked_by_policy\"\n\t| \"waiting_for_approval\"\n\t| \"validation_failed\";\n\nexport interface FabricRuntimeServices {\n\treadonly [serviceName: string]: unknown;\n}\n\nexport interface ActionContext<TDb = unknown> {\n\tactionInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\tactorId: string;\n\tactorType: ActorType;\n\tcorrelationId: string;\n\tcausationId?: string;\n\tdb: TDb;\n\tservices?: FabricRuntimeServices;\n}\n\nexport interface ActionResult {\n\tsuccess: boolean;\n\tdata?: Record<string, unknown>;\n\terror?: string;\n}\n\nexport type ActionHandler<TDb = unknown> = (\n\tctx: ActionContext<TDb>,\n\tparams: unknown,\n) => Promise<ActionResult>;\n\nexport interface AdapterStepRetryPolicy {\n\tidempotent: boolean;\n\tmaxAttempts?: number;\n\tinitialDelayMs?: number;\n\tbackoffMultiplier?: number;\n\tmaxDelayMs?: number;\n}\n\nexport interface AdapterStep {\n\tadapterType: string;\n\toperation: string;\n\tretryPolicy?: AdapterStepRetryPolicy;\n\tgetInput: (\n\t\tparams: unknown,\n\t\thandlerResult: Record<string, unknown>,\n\t) => Record<string, unknown> | undefined;\n}\n\nexport interface ActionStateMachineBinding {\n\tentityType: string;\n\ttargetState: string | ((params: unknown) => string);\n\tgetEntityId: (params: unknown) => string | undefined;\n}\n\nexport interface ActionDefinition<TDb = unknown> {\n\tactionId: ActionId;\n\tnamespace: string;\n\tversion: number;\n\tschema: SchemaValidator;\n\t/** Optional validation contract for the public handler result data. */\n\tresultSchema?: SchemaValidator;\n\thandler?: ActionHandler<TDb>;\n\trequiredRoles?: string[];\n\trequiredPermissions?: string[];\n\tpolicies?: `${string}.v${number}`[];\n\temitsEvents: string[];\n\tidempotent: boolean;\n\tmutatesDomain: boolean;\n\tstateMachine?: ActionStateMachineBinding;\n\tadapterSteps?: AdapterStep[];\n\t/** Completion actions can attest only after all external adapter work succeeds. */\n\teventPhase?: \"before_adapters\" | \"after_adapters\";\n\t/**\n\t * If \"saga\", the action is a multi-step orchestration. The worker dispatches\n\t * to a registered saga implementation instead of running `handler` directly.\n\t */\n\tkind?: \"atomic\" | \"saga\";\n}\n\nexport interface SagaContext {\n\tactionInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\tparameters: unknown;\n\tsleep?: (delayMs: number) => Promise<void>;\n\tquery?: <T = unknown>(model: string, operation: string, args: unknown) => Promise<T>;\n\t/**\n\t * Wait for a named external signal carrying a payload of `T`, with a timeout.\n\t *\n\t * Resolves with the payload of the first signal received, or `null` if the timeout\n\t * fires first. Subsequent signals with the same name received before another\n\t * `awaitSignal` call are buffered (FIFO) so no signal is lost.\n\t *\n\t * Intended for agent-driven and webhook-driven coordination: replace polling loops\n\t * with push-based wakeups while preserving the saga's deterministic replay\n\t * semantics (the runtime is responsible for capturing signals into workflow history).\n\t *\n\t * Optional. Runtimes that cannot implement push-based signaling (e.g. an in-memory\n\t * test harness) may omit this; sagas should treat absence as a fallback condition\n\t * and use `sleep` + `query` polling instead.\n\t *\n\t * Signal *senders* are runtime-specific (e.g. a Temporal `WorkflowClient.signal()`\n\t * call from an action handler). Apps that need to send signals from action\n\t * handlers should expose a coordination service via `ActionContext.services`\n\t * — the platform does not prescribe the sender API.\n\t *\n\t * @example\n\t * const payload = await ctx.awaitSignal?.<{ result: Record<string, unknown> }>(\n\t * \"userInputProcessed\",\n\t * 5 * 60 * 1000,\n\t * );\n\t * if (payload) { /* handle pushed result *\\/ }\n\t * else { /* timeout — fall back to deterministic path *\\/ }\n\t */\n\tawaitSignal?: <T = unknown>(signalName: string, timeoutMs: number) => Promise<T | null>;\n}\n\nexport interface SagaChildActionInput {\n\tsuffix: string;\n\tactionId: string;\n\tparameters: Record<string, unknown>;\n}\n\nexport type SagaRunChild = (input: SagaChildActionInput) => Promise<Record<string, unknown>>;\n\nexport interface SagaCompletionEvent {\n\teventType: string;\n\tsubjectType: string;\n\tsubjectId: string;\n\tpayload: unknown;\n\teventSchemaVersion?: number;\n}\n\nexport interface SagaCompletion {\n\tresultData: Record<string, unknown>;\n\tevent?: SagaCompletionEvent;\n}\n\nexport type SagaImplementation = (\n\tctx: SagaContext,\n\trunChild: SagaRunChild,\n) => Promise<SagaCompletion>;\n\nconst registry = new Map<ActionId, ActionDefinition>();\n\nexport function assertActionId(actionId: string): asserts actionId is ActionId {\n\tif (!/^[a-z][a-z0-9-]*\\.[a-z][a-z0-9_]*$/.test(actionId)) {\n\t\tthrow new Error(`Invalid action ID: ${actionId}`);\n\t}\n}\n\nexport function registerAction(definition: ActionDefinition): void {\n\tassertActionId(definition.actionId);\n\n\tif (registry.has(definition.actionId)) {\n\t\tthrow new Error(`Action \"${definition.actionId}\" is already registered`);\n\t}\n\n\tif (definition.mutatesDomain && definition.emitsEvents.length === 0) {\n\t\tthrow new Error(\n\t\t\t`Action \"${definition.actionId}\" mutates domain but emits no events. ` +\n\t\t\t\t`Every mutating action must emit at least one AssetEvent.`,\n\t\t);\n\t}\n\n\tregistry.set(definition.actionId, definition);\n}\n\nexport function resolveAction(actionId: ActionId): ActionDefinition | undefined {\n\treturn registry.get(actionId);\n}\n\nexport function isRegisteredActionId(actionId: string): actionId is ActionId {\n\treturn registry.has(actionId as ActionId);\n}\n\nexport function resolveRegisteredAction(actionId: string): ActionDefinition | undefined {\n\tif (!isRegisteredActionId(actionId)) {\n\t\treturn undefined;\n\t}\n\n\treturn resolveAction(actionId);\n}\n\nexport function getRegisteredActionIds(): ActionId[] {\n\treturn Array.from(registry.keys());\n}\n\nexport function registerActionIfMissing(definition: ActionDefinition): void {\n\tif (!registry.has(definition.actionId)) {\n\t\tregisterAction(definition);\n\t}\n}\n"]}
@@ -55,5 +55,5 @@ function registerActionIfMissing(definition) {
55
55
  }
56
56
 
57
57
  export { ACTOR_TYPES, assertActionId, assertActorType, getRegisteredActionIds, isActorType, isRegisteredActionId, registerAction, registerActionIfMissing, resolveAction, resolveRegisteredAction };
58
- //# sourceMappingURL=chunk-4SMPJPJ6.js.map
59
- //# sourceMappingURL=chunk-4SMPJPJ6.js.map
58
+ //# sourceMappingURL=chunk-JM55UQWK.js.map
59
+ //# sourceMappingURL=chunk-JM55UQWK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../actions/index.ts"],"names":[],"mappings":";AAwBO,IAAM,WAAA,GAAoC;AAAA,EAChD,gBAAA;AAAA,EACA,OAAA;AAAA,EACA,QAAA;AAAA,EACA,iBAAA;AAAA,EACA,iBAAA;AAAA,EACA;AACD;AAEO,SAAS,YAAY,KAAA,EAAmC;AAC9D,EAAA,OAAQ,WAAA,CAAkC,SAAS,KAAK,CAAA;AACzD;AAEO,SAAS,gBAAgB,KAAA,EAA2C;AAC1E,EAAA,IAAI,CAAC,WAAA,CAAY,KAAK,CAAA,EAAG;AACxB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,mBAAA,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IAAA,CAAK,QAAA,CAAS,IAAA,EAAM,CAAA;AAClC;AAEO,SAAS,wBAAwB,UAAA,EAAoC;AAC3E,EAAA,IAAI,CAAC,QAAA,CAAS,GAAA,CAAI,UAAA,CAAW,QAAQ,CAAA,EAAG;AACvC,IAAA,cAAA,CAAe,UAAU,CAAA;AAAA,EAC1B;AACD","file":"chunk-JM55UQWK.js","sourcesContent":["export type ActionId = `${string}.${string}`;\n\nexport interface SchemaParseIssue {\n\tpath: PropertyKey[];\n\tmessage: string;\n}\n\nexport type SchemaParseResult<T = unknown> =\n\t| { success: true; data: T }\n\t| { success: false; error: { issues: SchemaParseIssue[] } };\n\nexport interface SchemaValidator<T = unknown> {\n\tparse(input: unknown): T;\n\tsafeParse(input: unknown): SchemaParseResult<T>;\n}\n\nexport type ActorType =\n\t| \"natural_person\"\n\t| \"agent\"\n\t| \"system\"\n\t| \"service_account\"\n\t| \"external_system\"\n\t| \"integration\";\n\nexport const ACTOR_TYPES: readonly ActorType[] = [\n\t\"natural_person\",\n\t\"agent\",\n\t\"system\",\n\t\"service_account\",\n\t\"external_system\",\n\t\"integration\",\n] as const;\n\nexport function isActorType(value: string): value is ActorType {\n\treturn (ACTOR_TYPES as readonly string[]).includes(value);\n}\n\nexport function assertActorType(value: string): asserts value is ActorType {\n\tif (!isActorType(value)) {\n\t\tthrow new Error(`Invalid actorType: ${value}`);\n\t}\n}\n\nexport type ActionStatus =\n\t| \"pending\"\n\t| \"running\"\n\t| \"completed\"\n\t| \"failed\"\n\t| \"blocked_by_policy\"\n\t| \"waiting_for_approval\"\n\t| \"validation_failed\";\n\nexport interface FabricRuntimeServices {\n\treadonly [serviceName: string]: unknown;\n}\n\nexport interface ActionContext<TDb = unknown> {\n\tactionInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\tactorId: string;\n\tactorType: ActorType;\n\tcorrelationId: string;\n\tcausationId?: string;\n\tdb: TDb;\n\tservices?: FabricRuntimeServices;\n}\n\nexport interface ActionResult {\n\tsuccess: boolean;\n\tdata?: Record<string, unknown>;\n\terror?: string;\n}\n\nexport type ActionHandler<TDb = unknown> = (\n\tctx: ActionContext<TDb>,\n\tparams: unknown,\n) => Promise<ActionResult>;\n\nexport interface AdapterStepRetryPolicy {\n\tidempotent: boolean;\n\tmaxAttempts?: number;\n\tinitialDelayMs?: number;\n\tbackoffMultiplier?: number;\n\tmaxDelayMs?: number;\n}\n\nexport interface AdapterStep {\n\tadapterType: string;\n\toperation: string;\n\tretryPolicy?: AdapterStepRetryPolicy;\n\tgetInput: (\n\t\tparams: unknown,\n\t\thandlerResult: Record<string, unknown>,\n\t) => Record<string, unknown> | undefined;\n}\n\nexport interface ActionStateMachineBinding {\n\tentityType: string;\n\ttargetState: string | ((params: unknown) => string);\n\tgetEntityId: (params: unknown) => string | undefined;\n}\n\nexport interface ActionDefinition<TDb = unknown> {\n\tactionId: ActionId;\n\tnamespace: string;\n\tversion: number;\n\tschema: SchemaValidator;\n\t/** Optional validation contract for the public handler result data. */\n\tresultSchema?: SchemaValidator;\n\thandler?: ActionHandler<TDb>;\n\trequiredRoles?: string[];\n\trequiredPermissions?: string[];\n\tpolicies?: `${string}.v${number}`[];\n\temitsEvents: string[];\n\tidempotent: boolean;\n\tmutatesDomain: boolean;\n\tstateMachine?: ActionStateMachineBinding;\n\tadapterSteps?: AdapterStep[];\n\t/** Completion actions can attest only after all external adapter work succeeds. */\n\teventPhase?: \"before_adapters\" | \"after_adapters\";\n\t/**\n\t * If \"saga\", the action is a multi-step orchestration. The worker dispatches\n\t * to a registered saga implementation instead of running `handler` directly.\n\t */\n\tkind?: \"atomic\" | \"saga\";\n}\n\nexport interface SagaContext {\n\tactionInvocationId: string;\n\ttenantId: string;\n\tspaceId: string;\n\tparameters: unknown;\n\tsleep?: (delayMs: number) => Promise<void>;\n\tquery?: <T = unknown>(model: string, operation: string, args: unknown) => Promise<T>;\n\t/**\n\t * Wait for a named external signal carrying a payload of `T`, with a timeout.\n\t *\n\t * Resolves with the payload of the first signal received, or `null` if the timeout\n\t * fires first. Subsequent signals with the same name received before another\n\t * `awaitSignal` call are buffered (FIFO) so no signal is lost.\n\t *\n\t * Intended for agent-driven and webhook-driven coordination: replace polling loops\n\t * with push-based wakeups while preserving the saga's deterministic replay\n\t * semantics (the runtime is responsible for capturing signals into workflow history).\n\t *\n\t * Optional. Runtimes that cannot implement push-based signaling (e.g. an in-memory\n\t * test harness) may omit this; sagas should treat absence as a fallback condition\n\t * and use `sleep` + `query` polling instead.\n\t *\n\t * Signal *senders* are runtime-specific (e.g. a Temporal `WorkflowClient.signal()`\n\t * call from an action handler). Apps that need to send signals from action\n\t * handlers should expose a coordination service via `ActionContext.services`\n\t * — the platform does not prescribe the sender API.\n\t *\n\t * @example\n\t * const payload = await ctx.awaitSignal?.<{ result: Record<string, unknown> }>(\n\t * \"userInputProcessed\",\n\t * 5 * 60 * 1000,\n\t * );\n\t * if (payload) { /* handle pushed result *\\/ }\n\t * else { /* timeout — fall back to deterministic path *\\/ }\n\t */\n\tawaitSignal?: <T = unknown>(signalName: string, timeoutMs: number) => Promise<T | null>;\n}\n\nexport interface SagaChildActionInput {\n\tsuffix: string;\n\tactionId: string;\n\tparameters: Record<string, unknown>;\n}\n\nexport type SagaRunChild = (input: SagaChildActionInput) => Promise<Record<string, unknown>>;\n\nexport interface SagaCompletionEvent {\n\teventType: string;\n\tsubjectType: string;\n\tsubjectId: string;\n\tpayload: unknown;\n\teventSchemaVersion?: number;\n}\n\nexport interface SagaCompletion {\n\tresultData: Record<string, unknown>;\n\tevent?: SagaCompletionEvent;\n}\n\nexport type SagaImplementation = (\n\tctx: SagaContext,\n\trunChild: SagaRunChild,\n) => Promise<SagaCompletion>;\n\nconst registry = new Map<ActionId, ActionDefinition>();\n\nexport function assertActionId(actionId: string): asserts actionId is ActionId {\n\tif (!/^[a-z][a-z0-9-]*\\.[a-z][a-z0-9_]*$/.test(actionId)) {\n\t\tthrow new Error(`Invalid action ID: ${actionId}`);\n\t}\n}\n\nexport function registerAction(definition: ActionDefinition): void {\n\tassertActionId(definition.actionId);\n\n\tif (registry.has(definition.actionId)) {\n\t\tthrow new Error(`Action \"${definition.actionId}\" is already registered`);\n\t}\n\n\tif (definition.mutatesDomain && definition.emitsEvents.length === 0) {\n\t\tthrow new Error(\n\t\t\t`Action \"${definition.actionId}\" mutates domain but emits no events. ` +\n\t\t\t\t`Every mutating action must emit at least one AssetEvent.`,\n\t\t);\n\t}\n\n\tregistry.set(definition.actionId, definition);\n}\n\nexport function resolveAction(actionId: ActionId): ActionDefinition | undefined {\n\treturn registry.get(actionId);\n}\n\nexport function isRegisteredActionId(actionId: string): actionId is ActionId {\n\treturn registry.has(actionId as ActionId);\n}\n\nexport function resolveRegisteredAction(actionId: string): ActionDefinition | undefined {\n\tif (!isRegisteredActionId(actionId)) {\n\t\treturn undefined;\n\t}\n\n\treturn resolveAction(actionId);\n}\n\nexport function getRegisteredActionIds(): ActionId[] {\n\treturn Array.from(registry.keys());\n}\n\nexport function registerActionIfMissing(definition: ActionDefinition): void {\n\tif (!registry.has(definition.actionId)) {\n\t\tregisterAction(definition);\n\t}\n}\n"]}
@@ -0,0 +1,219 @@
1
+ import { getEventTypeName, getObjectTypeName, getModuleDependencyNamespace } from './chunk-3JQI3OFC.js';
2
+
3
+ // manifest/index.ts
4
+ var MODULE_MANIFEST_VERSION = 2;
5
+ function normalizeModuleManifest(manifest) {
6
+ const version = manifest.manifestVersion;
7
+ if (version !== 1 && version !== MODULE_MANIFEST_VERSION) {
8
+ throw new Error(`Unsupported module manifest version: ${String(version)}`);
9
+ }
10
+ return {
11
+ ...manifest,
12
+ manifestVersion: MODULE_MANIFEST_VERSION,
13
+ views: "views" in manifest && Array.isArray(manifest.views) ? manifest.views : []
14
+ };
15
+ }
16
+ function normalizeModuleManifestBundle(bundle) {
17
+ const version = bundle.manifestVersion;
18
+ if (version !== 1 && version !== MODULE_MANIFEST_VERSION) {
19
+ throw new Error(`Unsupported module manifest bundle version: ${String(version)}`);
20
+ }
21
+ return {
22
+ manifestVersion: MODULE_MANIFEST_VERSION,
23
+ modules: bundle.modules.map((manifest) => normalizeModuleManifest(manifest))
24
+ };
25
+ }
26
+ function isJsonSchemaExportableValidator(schema) {
27
+ return typeof schema.toJSONSchema === "function";
28
+ }
29
+ function isRecord(value) {
30
+ return value !== null && typeof value === "object" && !Array.isArray(value);
31
+ }
32
+ function exportDependency(dependency) {
33
+ const namespace = getModuleDependencyNamespace(dependency);
34
+ if (typeof dependency === "string") {
35
+ return { namespace };
36
+ }
37
+ const normalized = { namespace };
38
+ if (dependency.version !== void 0) normalized.version = dependency.version;
39
+ if (dependency.optional !== void 0) normalized.optional = dependency.optional;
40
+ return normalized;
41
+ }
42
+ function exportObjectType(objectType) {
43
+ if (typeof objectType === "string") {
44
+ return { type: objectType };
45
+ }
46
+ const normalized = { type: getObjectTypeName(objectType) };
47
+ if (objectType.displayName !== void 0) normalized.displayName = objectType.displayName;
48
+ if (objectType.idPrefix !== void 0) normalized.idPrefix = objectType.idPrefix;
49
+ if (objectType.schema !== void 0) normalized.schema = cloneJson(objectType.schema);
50
+ if (objectType.semantics !== void 0) normalized.semantics = cloneJson(objectType.semantics);
51
+ if (objectType.relations !== void 0) {
52
+ normalized.relations = objectType.relations.map((relation) => ({ ...relation }));
53
+ }
54
+ if (objectType.invariants !== void 0) {
55
+ normalized.invariants = objectType.invariants.map((invariant) => ({ ...invariant }));
56
+ }
57
+ return normalized;
58
+ }
59
+ function cloneJson(value) {
60
+ if (Array.isArray(value)) return value.map((item) => cloneJson(item));
61
+ if (value !== null && typeof value === "object") {
62
+ return Object.fromEntries(
63
+ Object.entries(value).map(([key, child]) => [key, cloneJson(child)])
64
+ );
65
+ }
66
+ return value;
67
+ }
68
+ function exportEventType(eventType) {
69
+ if (typeof eventType === "string") {
70
+ return { eventType, schemaVersion: 1 };
71
+ }
72
+ const normalized = {
73
+ eventType: getEventTypeName(eventType),
74
+ schemaVersion: eventType.schemaVersion
75
+ };
76
+ if (eventType.description !== void 0) normalized.description = eventType.description;
77
+ return normalized;
78
+ }
79
+ function exportAction(action) {
80
+ const manifest = {
81
+ actionId: action.actionId,
82
+ version: action.version,
83
+ kind: action.kind ?? "atomic",
84
+ idempotent: action.idempotent,
85
+ mutatesDomain: action.mutatesDomain,
86
+ emitsEvents: [...action.emitsEvents]
87
+ };
88
+ if (action.policies !== void 0) manifest.policies = [...action.policies];
89
+ if (action.requiredRoles !== void 0) manifest.requiredRoles = [...action.requiredRoles];
90
+ if (action.requiredPermissions !== void 0) {
91
+ manifest.requiredPermissions = [...action.requiredPermissions];
92
+ }
93
+ if (action.eventPhase !== void 0) manifest.eventPhase = action.eventPhase;
94
+ if (isJsonSchemaExportableValidator(action.schema)) {
95
+ manifest.parameterSchema = action.schema.toJSONSchema();
96
+ manifest.parameterSchemaFormat = "json-schema";
97
+ }
98
+ if (action.resultSchema && isJsonSchemaExportableValidator(action.resultSchema)) {
99
+ manifest.resultSchema = action.resultSchema.toJSONSchema();
100
+ manifest.resultSchemaFormat = "json-schema";
101
+ }
102
+ if (action.stateMachine !== void 0) {
103
+ const binding = {
104
+ entityType: action.stateMachine.entityType
105
+ };
106
+ if (typeof action.stateMachine.targetState === "string") {
107
+ binding.targetState = action.stateMachine.targetState;
108
+ }
109
+ manifest.stateMachine = binding;
110
+ }
111
+ if (action.adapterSteps !== void 0) {
112
+ manifest.adapterSteps = action.adapterSteps.map((step) => {
113
+ const exported = {
114
+ adapterType: step.adapterType,
115
+ operation: step.operation
116
+ };
117
+ if (step.retryPolicy !== void 0) exported.retryPolicy = { ...step.retryPolicy };
118
+ return exported;
119
+ });
120
+ }
121
+ return manifest;
122
+ }
123
+ function exportPolicy(policy) {
124
+ if (!isRecord(policy) || typeof policy.policyId !== "string") {
125
+ return void 0;
126
+ }
127
+ if (typeof policy.evaluate === "function") {
128
+ const exported = {
129
+ type: "code",
130
+ policyId: policy.policyId,
131
+ version: typeof policy.version === "number" ? policy.version : 1
132
+ };
133
+ if (typeof policy.previewSafe === "boolean") exported.previewSafe = policy.previewSafe;
134
+ return exported;
135
+ }
136
+ if (typeof policy.kind === "string" && typeof policy.policyVersion === "number") {
137
+ const exported = {
138
+ type: "data",
139
+ policyId: policy.policyId,
140
+ policyVersion: policy.policyVersion,
141
+ kind: policy.kind
142
+ };
143
+ if (isRecord(policy.dataDefinition)) {
144
+ exported.dataDefinition = policy.dataDefinition;
145
+ }
146
+ if (typeof policy.codeEvaluatorPolicyId === "string") {
147
+ exported.codeEvaluatorPolicyId = policy.codeEvaluatorPolicyId;
148
+ }
149
+ if (isRecord(policy.fallback)) {
150
+ exported.fallback = policy.fallback;
151
+ }
152
+ return exported;
153
+ }
154
+ return void 0;
155
+ }
156
+ function exportStateMachine(machine) {
157
+ if (!isRecord(machine) || typeof machine.entityType !== "string" || !isRecord(machine.states) || !Array.isArray(machine.transitions)) {
158
+ return void 0;
159
+ }
160
+ const definition = machine;
161
+ return {
162
+ entityType: definition.entityType,
163
+ states: Object.values(definition.states),
164
+ transitions: definition.transitions.map((transition) => ({
165
+ from: transition.from,
166
+ to: transition.to,
167
+ causedByAction: transition.causedByAction,
168
+ hasGuard: typeof transition.guard === "function"
169
+ }))
170
+ };
171
+ }
172
+ function exportView(view) {
173
+ const output = {
174
+ name: view.name,
175
+ version: view.version,
176
+ shape: cloneJson(view.shape),
177
+ consumes: view.consumes.map((consumption) => ({
178
+ eventType: consumption.eventType,
179
+ schemaVersions: [...consumption.schemaVersions]
180
+ })),
181
+ scope: view.scope,
182
+ snapshotVersion: view.snapshotVersion
183
+ };
184
+ if (view.compatibleSnapshotVersions) output.compatibleSnapshotVersions = [...view.compatibleSnapshotVersions];
185
+ return output;
186
+ }
187
+ function exportModuleManifest(module) {
188
+ const manifest = {
189
+ manifestVersion: MODULE_MANIFEST_VERSION,
190
+ namespace: module.namespace,
191
+ dependencies: (module.dependencies ?? []).map(exportDependency),
192
+ objectTypes: (module.objectTypes ?? []).map(exportObjectType),
193
+ subjectTypes: [...module.subjectTypes ?? []],
194
+ idPrefixes: (module.idPrefixes ?? []).map((registration) => ({
195
+ prefix: registration.prefix,
196
+ name: registration.name
197
+ })),
198
+ eventTypes: (module.eventTypes ?? []).map(exportEventType),
199
+ actions: (module.actions ?? []).map(exportAction),
200
+ policies: (module.policies ?? []).map(exportPolicy).filter((policy) => policy !== void 0),
201
+ stateMachines: (module.stateMachines ?? []).map(exportStateMachine).filter((machine) => machine !== void 0),
202
+ views: (module.views ?? []).map(exportView)
203
+ };
204
+ if (module.version !== void 0) manifest.version = module.version;
205
+ if (module.displayName !== void 0) manifest.displayName = module.displayName;
206
+ if (module.description !== void 0) manifest.description = module.description;
207
+ if (module.capability !== void 0) manifest.capability = cloneJson(module.capability);
208
+ return manifest;
209
+ }
210
+ function exportModuleManifestBundle(modules) {
211
+ return {
212
+ manifestVersion: MODULE_MANIFEST_VERSION,
213
+ modules: modules.map(exportModuleManifest)
214
+ };
215
+ }
216
+
217
+ export { MODULE_MANIFEST_VERSION, exportModuleManifest, exportModuleManifestBundle, isJsonSchemaExportableValidator, normalizeModuleManifest, normalizeModuleManifestBundle };
218
+ //# sourceMappingURL=chunk-NFP5DJBT.js.map
219
+ //# sourceMappingURL=chunk-NFP5DJBT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../manifest/index.ts"],"names":[],"mappings":";;;AA6BO,IAAM,uBAAA,GAA0B;AA8JhC,SAAS,wBACf,QAAA,EACiB;AACjB,EAAA,MAAM,UAAkB,QAAA,CAAS,eAAA;AACjC,EAAA,IAAI,OAAA,KAAY,CAAA,IAAK,OAAA,KAAY,uBAAA,EAAyB;AACzD,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,qCAAA,EAAwC,MAAA,CAAO,OAAO,CAAC,CAAA,CAAE,CAAA;AAAA,EAC1E;AACA,EAAA,OAAO;AAAA,IACN,GAAG,QAAA;AAAA,IACH,eAAA,EAAiB,uBAAA;AAAA,IACjB,KAAA,EAAO,OAAA,IAAW,QAAA,IAAY,KAAA,CAAM,OAAA,CA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O,WAAA,KAAgB,MAAA,EAAW,QAAA,CAAS,cAAc,MAAA,CAAO,WAAA;AACpE,EAAA,IAAI,MAAA,CAAO,WAAA,KAAgB,MAAA,EAAW,QAAA,CAAS,cAAc,MAAA,CAAO,WAAA;AACpE,EAAA,IAAI,OAAO,UAAA,KAAe,MAAA,WAAoB,UAAA,GAAa,SAAA,CAAU,OAAO,UAAU,CAAA;AAEtF,EAAA,OAAO,QAAA;AACR;AAMO,SAAS,2BACf,OAAA,EACuB;AACvB,EAAA,OAAO;AAAA,IACN,eAAA,EAAiB,uBAAA;AAAA,IACjB,OAAA,EAAS,OAAA,CAAQ,GAAA,CAAI,oBAAoB;AAAA,GAC1C;AACD","file":"chunk-NFP5DJBT.js","sourcesContent":["import type {\n\tActionDefinition,\n\tAdapterStepRetryPolicy,\n\tSchemaValidator,\n} from \"../actions\";\nimport {\n\tgetEventTypeName,\n\tgetModuleDependencyNamespace,\n\tgetObjectTypeName,\n\ttype FabricModule,\n\ttype CapabilityMetadata,\n\ttype DeclarativeInvariant,\n\ttype ModuleDependency,\n\ttype ModuleDependencyInput,\n\ttype ObjectRelationDefinition,\n} from \"../modules\";\nimport type { JsonValue, PortableJsonSchema } from \"../objects\";\nimport type {\n\tDataPolicyDefinition,\n\tPolicyFallbackDefinition,\n\tPolicyKind,\n} from \"../policies\";\nimport type { StateDefinition, StateMachineDefinition } from \"../state-machines\";\nimport type { ViewContract } from \"../projections\";\n\n/**\n * Version of the module manifest contract. Bump when the serialized shape\n * changes in a way consumers must detect.\n */\nexport const MODULE_MANIFEST_VERSION = 2 as const;\n\nexport interface ModuleManifestObjectType {\n\ttype: string;\n\tdisplayName?: string;\n\tidPrefix?: string;\n\tschema?: PortableJsonSchema;\n\tsemantics?: Record<string, JsonValue>;\n\trelations?: ObjectRelationDefinition[];\n\tinvariants?: DeclarativeInvariant[];\n}\n\nexport interface ModuleManifestIdPrefix {\n\tprefix: string;\n\tname: string;\n}\n\nexport interface ModuleManifestEventType {\n\teventType: string;\n\tschemaVersion: number;\n\tdescription?: string;\n}\n\nexport interface ModuleManifestActionStateMachine {\n\tentityType: string;\n\t/** Present only when the binding declares a static target state. */\n\ttargetState?: string;\n}\n\nexport interface ModuleManifestAdapterStep {\n\tadapterType: string;\n\toperation: string;\n\tretryPolicy?: AdapterStepRetryPolicy;\n}\n\nexport interface ModuleManifestAction {\n\tactionId: string;\n\tversion: number;\n\tkind: \"atomic\" | \"saga\";\n\tidempotent: boolean;\n\tmutatesDomain: boolean;\n\temitsEvents: string[];\n\tpolicies?: string[];\n\trequiredRoles?: string[];\n\trequiredPermissions?: string[];\n\teventPhase?: \"before_adapters\" | \"after_adapters\";\n\t/**\n\t * JSON Schema for the action parameters, present only when the action's\n\t * `schema` validator implements {@link JsonSchemaExportableValidator}.\n\t */\n\tparameterSchema?: unknown;\n\tparameterSchemaFormat?: \"json-schema\";\n\tresultSchema?: unknown;\n\tresultSchemaFormat?: \"json-schema\";\n\tstateMachine?: ModuleManifestActionStateMachine;\n\tadapterSteps?: ModuleManifestAdapterStep[];\n}\n\nexport interface ModuleManifestCodePolicy {\n\ttype: \"code\";\n\tpolicyId: string;\n\tversion: number;\n\tpreviewSafe?: boolean;\n}\n\nexport interface ModuleManifestDataPolicy {\n\ttype: \"data\";\n\tpolicyId: string;\n\tpolicyVersion: number;\n\tkind: PolicyKind;\n\tdataDefinition?: DataPolicyDefinition;\n\tcodeEvaluatorPolicyId?: string;\n\tfallback?: PolicyFallbackDefinition;\n}\n\nexport type ModuleManifestPolicy = ModuleManifestCodePolicy | ModuleManifestDataPolicy;\n\nexport interface ModuleManifestStateMachineTransition {\n\tfrom: string;\n\tto: string;\n\tcausedByAction: string;\n\t/** `true` when the transition declares a guard function. The guard itself is never serialized. */\n\thasGuard: boolean;\n}\n\nexport interface ModuleManifestStateMachine {\n\tentityType: string;\n\t/** States in declaration order (`Object.values` order of the definition record). */\n\tstates: StateDefinition[];\n\ttransitions: ModuleManifestStateMachineTransition[];\n}\n\nexport interface ModuleManifestView {\n\tname: string;\n\tversion: string;\n\tshape: PortableJsonSchema;\n\tconsumes: Array<{ eventType: string; schemaVersions: number[] }>;\n\tscope: \"tenant-space\";\n\tsnapshotVersion: number;\n\tcompatibleSnapshotVersions?: number[];\n}\n\n/**\n * Stable, JSON-serializable description of a {@link FabricModule}'s ontology:\n * object types, subject types, id prefixes, event types, actions, policies,\n * and state machines. Intended for downstream tooling (semantics exporters,\n * docs generators, tool generators) that cannot consume live module code.\n *\n * The manifest contains definitions only — never raw parameter values,\n * secrets, or runtime data. Function fields (`handler`, `evaluate`, `guard`,\n * dynamic `targetState`, adapter `getInput`) are never serialized.\n */\nexport interface ModuleManifest {\n\tmanifestVersion: typeof MODULE_MANIFEST_VERSION;\n\tnamespace: string;\n\tversion?: string;\n\tdisplayName?: string;\n\tdescription?: string;\n\tcapability?: CapabilityMetadata;\n\tdependencies: ModuleDependency[];\n\tobjectTypes: ModuleManifestObjectType[];\n\tsubjectTypes: string[];\n\tidPrefixes: ModuleManifestIdPrefix[];\n\teventTypes: ModuleManifestEventType[];\n\tactions: ModuleManifestAction[];\n\tpolicies: ModuleManifestPolicy[];\n\tstateMachines: ModuleManifestStateMachine[];\n\tviews: ModuleManifestView[];\n}\n\nexport interface ModuleManifestBundle {\n\tmanifestVersion: typeof MODULE_MANIFEST_VERSION;\n\t/** Manifests in the input module order. */\n\tmodules: ModuleManifest[];\n}\n\n/** Manifest v1 remains accepted by v2 readers; missing v2 fields normalize to absence. */\nexport type ModuleManifestObjectTypeV1 = Omit<\n\tModuleManifestObjectType,\n\t\"schema\" | \"semantics\" | \"relations\" | \"invariants\"\n>;\nexport type ModuleManifestActionV1 = Omit<\n\tModuleManifestAction,\n\t\"resultSchema\" | \"resultSchemaFormat\"\n>;\nexport type ModuleManifestV1 = Omit<\n\tModuleManifest,\n\t\"manifestVersion\" | \"objectTypes\" | \"actions\" | \"views\"\n> & {\n\tmanifestVersion: 1;\n\tobjectTypes: ModuleManifestObjectTypeV1[];\n\tactions: ModuleManifestActionV1[];\n};\nexport type ModuleManifestBundleV1 = Omit<ModuleManifestBundle, \"manifestVersion\" | \"modules\"> & {\n\tmanifestVersion: 1;\n\tmodules: ModuleManifestV1[];\n};\n\nexport function normalizeModuleManifest(\n\tmanifest: ModuleManifest | ModuleManifestV1,\n): ModuleManifest {\n\tconst version: number = manifest.manifestVersion;\n\tif (version !== 1 && version !== MODULE_MANIFEST_VERSION) {\n\t\tthrow new Error(`Unsupported module manifest version: ${String(version)}`);\n\t}\n\treturn {\n\t\t...manifest,\n\t\tmanifestVersion: MODULE_MANIFEST_VERSION,\n\t\tviews: \"views\" in manifest && Array.isArray(manifest.views) ? manifest.views : [],\n\t};\n}\n\nexport function normalizeModuleManifestBundle(\n\tbundle: ModuleManifestBundle | ModuleManifestBundleV1,\n): ModuleManifestBundle {\n\tconst version: number = bundle.manifestVersion;\n\tif (version !== 1 && version !== MODULE_MANIFEST_VERSION) {\n\t\tthrow new Error(`Unsupported module manifest bundle version: ${String(version)}`);\n\t}\n\treturn {\n\t\tmanifestVersion: MODULE_MANIFEST_VERSION,\n\t\tmodules: bundle.modules.map((manifest) => normalizeModuleManifest(manifest)),\n\t};\n}\n\n/**\n * A {@link SchemaValidator} that can also export its parameter schema as JSON\n * Schema (for example a Zod 4 schema via `z.toJSONSchema`). Keeps the platform\n * zero-dependency while letting schema-bearing actions flow into manifests.\n */\nexport interface JsonSchemaExportableValidator extends SchemaValidator {\n\ttoJSONSchema(): Record<string, unknown>;\n}\n\nexport function isJsonSchemaExportableValidator(\n\tschema: SchemaValidator,\n): schema is JsonSchemaExportableValidator {\n\treturn (\n\t\ttypeof (schema as Partial<JsonSchemaExportableValidator>).toJSONSchema === \"function\"\n\t);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction exportDependency(dependency: ModuleDependencyInput): ModuleDependency {\n\tconst namespace = getModuleDependencyNamespace(dependency);\n\tif (typeof dependency === \"string\") {\n\t\treturn { namespace };\n\t}\n\tconst normalized: ModuleDependency = { namespace };\n\tif (dependency.version !== undefined) normalized.version = dependency.version;\n\tif (dependency.optional !== undefined) normalized.optional = dependency.optional;\n\treturn normalized;\n}\n\nfunction exportObjectType(\n\tobjectType: NonNullable<FabricModule[\"objectTypes\"]>[number],\n): ModuleManifestObjectType {\n\tif (typeof objectType === \"string\") {\n\t\treturn { type: objectType };\n\t}\n\tconst normalized: ModuleManifestObjectType = { type: getObjectTypeName(objectType) };\n\tif (objectType.displayName !== undefined) normalized.displayName = objectType.displayName;\n\tif (objectType.idPrefix !== undefined) normalized.idPrefix = objectType.idPrefix;\n\tif (objectType.schema !== undefined) normalized.schema = cloneJson(objectType.schema);\n\tif (objectType.semantics !== undefined) normalized.semantics = cloneJson(objectType.semantics);\n\tif (objectType.relations !== undefined) {\n\t\tnormalized.relations = objectType.relations.map((relation) => ({ ...relation }));\n\t}\n\tif (objectType.invariants !== undefined) {\n\t\tnormalized.invariants = objectType.invariants.map((invariant) => ({ ...invariant }));\n\t}\n\treturn normalized;\n}\n\nfunction cloneJson<T>(value: T): T {\n\tif (Array.isArray(value)) return value.map((item) => cloneJson(item)) as T;\n\tif (value !== null && typeof value === \"object\") {\n\t\treturn Object.fromEntries(\n\t\t\tObject.entries(value as Record<string, unknown>).map(([key, child]) => [key, cloneJson(child)]),\n\t\t) as T;\n\t}\n\treturn value;\n}\n\nfunction exportEventType(\n\teventType: NonNullable<FabricModule[\"eventTypes\"]>[number],\n): ModuleManifestEventType {\n\tif (typeof eventType === \"string\") {\n\t\t// String registrations carry no explicit schema version; the events\n\t\t// registry treats the bare name as the initial version of the type.\n\t\treturn { eventType, schemaVersion: 1 };\n\t}\n\tconst normalized: ModuleManifestEventType = {\n\t\teventType: getEventTypeName(eventType),\n\t\tschemaVersion: eventType.schemaVersion,\n\t};\n\tif (eventType.description !== undefined) normalized.description = eventType.description;\n\treturn normalized;\n}\n\nfunction exportAction(action: ActionDefinition): ModuleManifestAction {\n\tconst manifest: ModuleManifestAction = {\n\t\tactionId: action.actionId,\n\t\tversion: action.version,\n\t\tkind: action.kind ?? \"atomic\",\n\t\tidempotent: action.idempotent,\n\t\tmutatesDomain: action.mutatesDomain,\n\t\temitsEvents: [...action.emitsEvents],\n\t};\n\n\tif (action.policies !== undefined) manifest.policies = [...action.policies];\n\tif (action.requiredRoles !== undefined) manifest.requiredRoles = [...action.requiredRoles];\n\tif (action.requiredPermissions !== undefined) {\n\t\tmanifest.requiredPermissions = [...action.requiredPermissions];\n\t}\n\tif (action.eventPhase !== undefined) manifest.eventPhase = action.eventPhase;\n\n\tif (isJsonSchemaExportableValidator(action.schema)) {\n\t\tmanifest.parameterSchema = action.schema.toJSONSchema();\n\t\tmanifest.parameterSchemaFormat = \"json-schema\";\n\t}\n\tif (action.resultSchema && isJsonSchemaExportableValidator(action.resultSchema)) {\n\t\tmanifest.resultSchema = action.resultSchema.toJSONSchema();\n\t\tmanifest.resultSchemaFormat = \"json-schema\";\n\t}\n\n\tif (action.stateMachine !== undefined) {\n\t\tconst binding: ModuleManifestActionStateMachine = {\n\t\t\tentityType: action.stateMachine.entityType,\n\t\t};\n\t\tif (typeof action.stateMachine.targetState === \"string\") {\n\t\t\tbinding.targetState = action.stateMachine.targetState;\n\t\t}\n\t\tmanifest.stateMachine = binding;\n\t}\n\n\tif (action.adapterSteps !== undefined) {\n\t\tmanifest.adapterSteps = action.adapterSteps.map((step) => {\n\t\t\tconst exported: ModuleManifestAdapterStep = {\n\t\t\t\tadapterType: step.adapterType,\n\t\t\t\toperation: step.operation,\n\t\t\t};\n\t\t\tif (step.retryPolicy !== undefined) exported.retryPolicy = { ...step.retryPolicy };\n\t\t\treturn exported;\n\t\t});\n\t}\n\n\treturn manifest;\n}\n\nfunction exportPolicy(policy: unknown): ModuleManifestPolicy | undefined {\n\tif (!isRecord(policy) || typeof policy.policyId !== \"string\") {\n\t\treturn undefined;\n\t}\n\n\t// Code evaluator: identified by its `evaluate` function (never serialized).\n\tif (typeof policy.evaluate === \"function\") {\n\t\tconst exported: ModuleManifestCodePolicy = {\n\t\t\ttype: \"code\",\n\t\t\tpolicyId: policy.policyId,\n\t\t\tversion: typeof policy.version === \"number\" ? policy.version : 1,\n\t\t};\n\t\tif (typeof policy.previewSafe === \"boolean\") exported.previewSafe = policy.previewSafe;\n\t\treturn exported;\n\t}\n\n\t// Declarative runtime policy definition: pure data, serialized as-is.\n\tif (typeof policy.kind === \"string\" && typeof policy.policyVersion === \"number\") {\n\t\tconst exported: ModuleManifestDataPolicy = {\n\t\t\ttype: \"data\",\n\t\t\tpolicyId: policy.policyId,\n\t\t\tpolicyVersion: policy.policyVersion,\n\t\t\tkind: policy.kind as PolicyKind,\n\t\t};\n\t\tif (isRecord(policy.dataDefinition)) {\n\t\t\texported.dataDefinition = policy.dataDefinition as unknown as DataPolicyDefinition;\n\t\t}\n\t\tif (typeof policy.codeEvaluatorPolicyId === \"string\") {\n\t\t\texported.codeEvaluatorPolicyId = policy.codeEvaluatorPolicyId;\n\t\t}\n\t\tif (isRecord(policy.fallback)) {\n\t\t\texported.fallback = policy.fallback as unknown as PolicyFallbackDefinition;\n\t\t}\n\t\treturn exported;\n\t}\n\n\t// Unknown policy shape: omit rather than guess.\n\treturn undefined;\n}\n\nfunction exportStateMachine(machine: unknown): ModuleManifestStateMachine | undefined {\n\tif (\n\t\t!isRecord(machine) ||\n\t\ttypeof machine.entityType !== \"string\" ||\n\t\t!isRecord(machine.states) ||\n\t\t!Array.isArray(machine.transitions)\n\t) {\n\t\treturn undefined;\n\t}\n\n\tconst definition = machine as unknown as StateMachineDefinition;\n\treturn {\n\t\tentityType: definition.entityType,\n\t\tstates: Object.values(definition.states),\n\t\ttransitions: definition.transitions.map((transition) => ({\n\t\t\tfrom: transition.from,\n\t\t\tto: transition.to,\n\t\t\tcausedByAction: transition.causedByAction,\n\t\t\thasGuard: typeof transition.guard === \"function\",\n\t\t})),\n\t};\n}\n\nfunction exportView(view: ViewContract): ModuleManifestView {\n\tconst output: ModuleManifestView = {\n\t\tname: view.name,\n\t\tversion: view.version,\n\t\tshape: cloneJson(view.shape),\n\t\tconsumes: view.consumes.map((consumption) => ({\n\t\t\teventType: consumption.eventType,\n\t\t\tschemaVersions: [...consumption.schemaVersions],\n\t\t})),\n\t\tscope: view.scope,\n\t\tsnapshotVersion: view.snapshotVersion,\n\t};\n\tif (view.compatibleSnapshotVersions) output.compatibleSnapshotVersions = [...view.compatibleSnapshotVersions];\n\treturn output;\n}\n\n/**\n * Export a stable, JSON-serializable manifest of a module's ontology.\n *\n * This is a pure function of the module object: it does not read or mutate the\n * global module/action/policy/state-machine registries, and the module does\n * not need to be registered first. Declaration order is preserved everywhere\n * (nothing is sorted), so the same module object always produces a\n * byte-identical `JSON.stringify` result.\n *\n * The manifest contains definitions only — never raw parameter values,\n * secrets, or runtime data. Function fields are elided (`handler`,\n * policy `evaluate`, transition `guard` → `hasGuard`, dynamic `targetState`,\n * adapter `getInput`).\n */\nexport function exportModuleManifest(module: FabricModule<unknown>): ModuleManifest {\n\tconst manifest: ModuleManifest = {\n\t\tmanifestVersion: MODULE_MANIFEST_VERSION,\n\t\tnamespace: module.namespace,\n\t\tdependencies: (module.dependencies ?? []).map(exportDependency),\n\t\tobjectTypes: (module.objectTypes ?? []).map(exportObjectType),\n\t\tsubjectTypes: [...(module.subjectTypes ?? [])],\n\t\tidPrefixes: (module.idPrefixes ?? []).map((registration) => ({\n\t\t\tprefix: registration.prefix,\n\t\t\tname: registration.name,\n\t\t})),\n\t\teventTypes: (module.eventTypes ?? []).map(exportEventType),\n\t\tactions: (module.actions ?? []).map(exportAction),\n\t\tpolicies: (module.policies ?? [])\n\t\t\t.map(exportPolicy)\n\t\t\t.filter((policy): policy is ModuleManifestPolicy => policy !== undefined),\n\t\tstateMachines: (module.stateMachines ?? [])\n\t\t\t.map(exportStateMachine)\n\t\t\t.filter((machine): machine is ModuleManifestStateMachine => machine !== undefined),\n\t\tviews: (module.views ?? []).map(exportView),\n\t};\n\n\tif (module.version !== undefined) manifest.version = module.version;\n\tif (module.displayName !== undefined) manifest.displayName = module.displayName;\n\tif (module.description !== undefined) manifest.description = module.description;\n\tif (module.capability !== undefined) manifest.capability = cloneJson(module.capability);\n\n\treturn manifest;\n}\n\n/**\n * Export manifests for a set of modules, preserving the input order.\n * Like {@link exportModuleManifest}, this is pure and registry-free.\n */\nexport function exportModuleManifestBundle(\n\tmodules: FabricModule<unknown>[],\n): ModuleManifestBundle {\n\treturn {\n\t\tmanifestVersion: MODULE_MANIFEST_VERSION,\n\t\tmodules: modules.map(exportModuleManifest),\n\t};\n}\n"]}