@entifix/core 0.10.2 → 0.12.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 (64) hide show
  1. package/dist/endpoint/endpoint.d.ts +154 -0
  2. package/dist/endpoint/endpoint.d.ts.map +1 -0
  3. package/dist/endpoint/endpoint.js +61 -0
  4. package/dist/endpoint/endpoint.js.map +1 -0
  5. package/dist/endpoint/index.d.ts +2 -0
  6. package/dist/endpoint/index.d.ts.map +1 -0
  7. package/dist/endpoint/index.js +3 -0
  8. package/dist/endpoint/index.js.map +1 -0
  9. package/dist/entity-definition/decorators/use-case/use-case.d.ts.map +1 -1
  10. package/dist/entity-definition/decorators/use-case/use-case.js +2 -1
  11. package/dist/entity-definition/decorators/use-case/use-case.js.map +1 -1
  12. package/dist/entity-definition/describe/describe-entity-use-cases.d.ts +18 -0
  13. package/dist/entity-definition/describe/describe-entity-use-cases.d.ts.map +1 -1
  14. package/dist/entity-definition/describe/describe-entity-use-cases.js +3 -1
  15. package/dist/entity-definition/describe/describe-entity-use-cases.js.map +1 -1
  16. package/dist/entity-definition/helpers/entity-definition-helpers.d.ts +5 -0
  17. package/dist/entity-definition/helpers/entity-definition-helpers.d.ts.map +1 -1
  18. package/dist/entity-definition/helpers/entity-definition-helpers.js +10 -0
  19. package/dist/entity-definition/helpers/entity-definition-helpers.js.map +1 -1
  20. package/dist/entity-definition/meta-entities/meta-use-case/meta-use-case.d.ts +29 -0
  21. package/dist/entity-definition/meta-entities/meta-use-case/meta-use-case.d.ts.map +1 -1
  22. package/dist/entity-definition/meta-entities/meta-use-case/meta-use-case.js +5 -0
  23. package/dist/entity-definition/meta-entities/meta-use-case/meta-use-case.js.map +1 -1
  24. package/dist/envelope/codec.d.ts +123 -0
  25. package/dist/envelope/codec.d.ts.map +1 -0
  26. package/dist/envelope/codec.js +203 -0
  27. package/dist/envelope/codec.js.map +1 -0
  28. package/dist/envelope/index.d.ts +2 -0
  29. package/dist/envelope/index.d.ts.map +1 -1
  30. package/dist/envelope/index.js +2 -0
  31. package/dist/envelope/index.js.map +1 -1
  32. package/dist/envelope/read-envelope.d.ts +20 -37
  33. package/dist/envelope/read-envelope.d.ts.map +1 -1
  34. package/dist/envelope/read-envelope.js +37 -126
  35. package/dist/envelope/read-envelope.js.map +1 -1
  36. package/dist/envelope/registry.d.ts +45 -0
  37. package/dist/envelope/registry.d.ts.map +1 -0
  38. package/dist/envelope/registry.js +55 -0
  39. package/dist/envelope/registry.js.map +1 -0
  40. package/dist/envelope/types.d.ts +48 -33
  41. package/dist/envelope/types.d.ts.map +1 -1
  42. package/dist/envelope/types.js +1 -1
  43. package/dist/envelope/types.js.map +1 -1
  44. package/dist/idempotency/idempotency-key.d.ts +20 -0
  45. package/dist/idempotency/idempotency-key.d.ts.map +1 -0
  46. package/dist/idempotency/idempotency-key.js +42 -0
  47. package/dist/idempotency/idempotency-key.js.map +1 -0
  48. package/dist/idempotency/index.d.ts +2 -0
  49. package/dist/idempotency/index.d.ts.map +1 -0
  50. package/dist/idempotency/index.js +3 -0
  51. package/dist/idempotency/index.js.map +1 -0
  52. package/dist/index.d.ts +3 -0
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.js +3 -0
  55. package/dist/index.js.map +1 -1
  56. package/dist/use-case-runner/index.d.ts +2 -0
  57. package/dist/use-case-runner/index.d.ts.map +1 -0
  58. package/dist/use-case-runner/index.js +3 -0
  59. package/dist/use-case-runner/index.js.map +1 -0
  60. package/dist/use-case-runner/use-case-runner.d.ts +29 -0
  61. package/dist/use-case-runner/use-case-runner.d.ts.map +1 -0
  62. package/dist/use-case-runner/use-case-runner.js +10 -0
  63. package/dist/use-case-runner/use-case-runner.js.map +1 -0
  64. package/package.json +1 -1
@@ -1,149 +1,60 @@
1
- import { _ as _extends } from "@swc/helpers/_/_extends";
2
1
  import { Effect } from 'effect';
3
2
  import { deserializeEntityCollection, deserializeSingleEntity } from '../entity-definition/serializer/index.js';
4
3
  import { InvalidEnvelope } from '../failure/generic.js';
4
+ import { decodeEnvelope } from './codec.js';
5
5
  import { envelopeEntityName } from './make-envelope.js';
6
6
  /**
7
- * Structural check only — `meta.type` is validated separately so a mismatch
8
- * reports the expected/actual types rather than a generic "not an envelope".
9
- */ export function isEntifixEnvelope(body) {
10
- if (body == null || typeof body !== 'object') {
11
- return false;
12
- }
13
- const meta = body.meta;
14
- return meta != null && typeof meta === 'object' && typeof meta.type === 'string';
15
- }
16
- /**
17
- * Narrows an arbitrary body to an envelope of the expected `meta.type`, failing
18
- * with an {@link InvalidEnvelope} otherwise. A wrong shape must never
19
- * silently deserialize into a half-populated entity.
20
- */ function assertEnvelope(entityConstructor, body, expected) {
21
- const entity = envelopeEntityName(entityConstructor);
22
- if (!isEntifixEnvelope(body)) {
23
- return Effect.fail(new InvalidEnvelope({
24
- reason: `Expected an EntifixEnvelope for "${entity}" but the payload carried no meta.type`
25
- }));
26
- }
27
- if (body.meta.type !== expected) {
28
- return Effect.fail(new InvalidEnvelope({
29
- reason: `Expected an EntifixEnvelope of type "${expected}" for "${entity}" but got "${body.meta.type}"`
7
+ * Decodes a body a **caller sent** — a request to this service — into an
8
+ * envelope of the expected type, its `data` decoded against the registered
9
+ * schema.
10
+ *
11
+ * The same decode as {@link decodeEnvelope}, failing with an
12
+ * {@link InvalidEnvelope} instead of a protocol failure: a malformed request is
13
+ * the sender's fault and answers `400`, where a peer's malformed *answer* is a
14
+ * `502`.
15
+ */ export const decodeRequestEnvelope = (body, expected, label = 'message')=>Effect.mapError(decodeEnvelope(body, expected), (failure)=>new InvalidEnvelope({
16
+ reason: `"${label}": ${failure.reason}`
30
17
  }));
31
- }
32
- return Effect.succeed(body);
33
- }
18
+ const decodeFor = (entityConstructor, body, expected)=>decodeRequestEnvelope(body, expected, envelopeEntityName(entityConstructor));
34
19
  /**
35
- * Narrows an arbitrary body to an envelope of the expected `meta.type` without
36
- * requiring an entity constructor — for `command`/`transactionRecord` messages
37
- * whose `data` is not a serialized entity. `label` only sharpens error text.
38
- */ export function readEnvelope(body, expected, label = 'message') {
39
- if (!isEntifixEnvelope(body)) {
40
- return Effect.fail(new InvalidEnvelope({
41
- reason: `Expected an EntifixEnvelope for "${label}" but the payload carried no meta.type`
42
- }));
43
- }
44
- if (body.meta.type !== expected) {
45
- return Effect.fail(new InvalidEnvelope({
46
- reason: `Expected an EntifixEnvelope of type "${expected}" for "${label}" but got "${body.meta.type}"`
47
- }));
48
- }
49
- return Effect.succeed(body);
50
- }
20
+ * A record the entity cannot be built from — a member of the wrong type — is
21
+ * the sender's fault exactly as a malformed envelope is, so it answers the
22
+ * same `400` rather than leaving the deserializer's own error to the caller.
23
+ */ const refusedRecord = (entityConstructor)=>(error)=>new InvalidEnvelope({
24
+ reason: `"${envelopeEntityName(entityConstructor)}": ${error.message}`
25
+ });
51
26
  export const readEntityEnvelope = (entityConstructor, body)=>Effect.gen(function*() {
52
- const envelope = yield* assertEnvelope(entityConstructor, body, 'entity');
53
- const entity = yield* deserializeSingleEntity(entityConstructor, envelope.data);
54
- if (entity === undefined) {
55
- return yield* Effect.fail(new InvalidEnvelope({
56
- reason: `EntifixEnvelope for "${envelopeEntityName(entityConstructor)}" carried no data`
57
- }));
58
- }
59
- return entity;
27
+ const envelope = yield* decodeFor(entityConstructor, body, 'entity');
28
+ // The registered schema already refused a missing or non-object `data`,
29
+ // so the deserializer always has a record to build from.
30
+ return yield* deserializeSingleEntity(entityConstructor, envelope.data).pipe(Effect.mapError(refusedRecord(entityConstructor)));
60
31
  });
61
32
  export const readEntityCollectionEnvelope = (entityConstructor, body)=>Effect.gen(function*() {
62
- const envelope = yield* assertEnvelope(entityConstructor, body, 'entityCollection');
63
- const items = yield* deserializeEntityCollection(entityConstructor, envelope.data);
33
+ const envelope = yield* decodeFor(entityConstructor, body, 'entityCollection');
34
+ const items = yield* deserializeEntityCollection(entityConstructor, envelope.data).pipe(Effect.mapError(refusedRecord(entityConstructor)));
64
35
  return items;
65
36
  });
66
37
  export const readEntityPageEnvelope = (entityConstructor, body)=>Effect.gen(function*() {
67
- var _ref, _ref1;
68
- var _envelope_data, _envelope_data1, _envelope_data2;
69
- const envelope = yield* assertEnvelope(entityConstructor, body, 'entityPage');
70
- const items = yield* deserializeEntityCollection(entityConstructor, (_envelope_data = envelope.data) == null ? void 0 : _envelope_data.items);
38
+ var _envelope_data_request;
39
+ const envelope = yield* decodeFor(entityConstructor, body, 'entityPage');
40
+ const items = yield* deserializeEntityCollection(entityConstructor, envelope.data.items).pipe(Effect.mapError(refusedRecord(entityConstructor)));
71
41
  return {
72
42
  items: items,
73
- total: (_ref = (_envelope_data1 = envelope.data) == null ? void 0 : _envelope_data1.total) != null ? _ref : 0,
74
- request: (_ref1 = (_envelope_data2 = envelope.data) == null ? void 0 : _envelope_data2.request) != null ? _ref1 : {}
43
+ total: envelope.data.total,
44
+ request: (_envelope_data_request = envelope.data.request) != null ? _envelope_data_request : {}
75
45
  };
76
46
  });
77
47
  /**
78
48
  * Reads a `$metadata` response back into its document.
79
49
  *
80
- * No deserialization step, and no defaulting of the members either: an envelope
81
- * whose `data` is missing a list would leave a form guessing whether "no
82
- * actions" meant "denied" or "malformed", so a broken payload fails loudly here
83
- * the way a half-populated entity does.
84
- */ export const readEntityMetadataEnvelope = (entityConstructor, body)=>Effect.gen(function*() {
85
- const envelope = yield* assertEnvelope(entityConstructor, body, 'entityMetadata');
86
- const document = envelope.data;
87
- if (!Array.isArray(document == null ? void 0 : document.actions) || !Array.isArray(document == null ? void 0 : document.useCases)) {
88
- return yield* Effect.fail(new InvalidEnvelope({
89
- reason: `EntifixEnvelope for "${envelopeEntityName(entityConstructor)}" carried no metadata document`
90
- }));
91
- }
92
- return document;
93
- });
94
- const isFacetValueRow = (row)=>row != null && typeof row === 'object' && [
95
- 'string',
96
- 'number',
97
- 'boolean'
98
- ].includes(typeof row.value) && typeof row.count === 'number';
50
+ * No defaulting of the members: the registered schema refuses a document
51
+ * missing either list, so a form never has to guess whether "no actions" meant
52
+ * "denied" or "malformed".
53
+ */ export const readEntityMetadataEnvelope = (entityConstructor, body)=>Effect.map(decodeFor(entityConstructor, body, 'entityMetadata'), (envelope)=>envelope.data);
99
54
  /**
100
- * Reads a `$facets` response back into its counts, refusing a body whose lists
101
- * are not `{ value, count }` rows — a panel that rendered a malformed count
102
- * would show a number nobody computed.
103
- */ export const readEntityFacetsEnvelope = (entityConstructor, body)=>Effect.gen(function*() {
104
- const envelope = yield* assertEnvelope(entityConstructor, body, 'entityFacets');
105
- const counts = envelope.data;
106
- const wellFormed = counts != null && typeof counts === 'object' && Object.values(counts).every((rows)=>Array.isArray(rows) && rows.every(isFacetValueRow));
107
- if (!wellFormed) {
108
- return yield* Effect.fail(new InvalidEnvelope({
109
- reason: `EntifixEnvelope for "${envelopeEntityName(entityConstructor)}" carried no facet counts`
110
- }));
111
- }
112
- return counts;
113
- });
114
- /** Every member `meta.event` must carry for a message to be routable at all. */ const REQUIRED_EVENT_META = [
115
- 'name',
116
- 'id',
117
- 'source',
118
- 'at'
119
- ];
120
- /**
121
- * Reads a bus message back into a {@link DomainEvent}.
122
- *
123
- * The metadata is validated rather than defaulted, and that is the point: a
124
- * message missing `id` cannot be deduplicated and a message missing `name`
125
- * cannot be routed, so both are failures a consumer must see rather than
126
- * absences it silently works around. It is the same call
127
- * {@link readEntityMetadataEnvelope} makes — a broken payload fails loudly
128
- * instead of arriving half-populated.
129
- *
130
- * Note this does not validate `data`. The transport has no idea what a
131
- * `catalog.published` payload should look like, and inventing an opinion here
132
- * is how the bus would start knowing about domains.
133
- */ export function readEventEnvelope(body) {
134
- return Effect.gen(function*() {
135
- const envelope = yield* readEnvelope(body, 'event', 'event');
136
- const event = envelope.meta.event;
137
- const missing = REQUIRED_EVENT_META.filter((member)=>typeof (event == null ? void 0 : event[member]) !== 'string' || event[member] === '');
138
- if (missing.length > 0) {
139
- return yield* Effect.fail(new InvalidEnvelope({
140
- reason: `event envelope carried incomplete meta.event (missing ${missing.join(', ')})`
141
- }));
142
- }
143
- return _extends({}, event, {
144
- data: envelope.data
145
- });
146
- });
147
- }
55
+ * Reads a `$facets` response back into its counts. The registered schema
56
+ * refuses a body whose lists are not `{ value, count }` rows — a panel that
57
+ * rendered a malformed count would show a number nobody computed.
58
+ */ export const readEntityFacetsEnvelope = (entityConstructor, body)=>Effect.map(decodeFor(entityConstructor, body, 'entityFacets'), (envelope)=>envelope.data);
148
59
 
149
60
  //# sourceMappingURL=read-envelope.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/envelope/read-envelope.ts"],"sourcesContent":["import { Effect } from 'effect';\n\nimport type { EntityMetadataDocument } from '../entity-definition/metadata/index.js';\nimport {\n deserializeEntityCollection,\n deserializeSingleEntity,\n} from '../entity-definition/serializer/index.js';\nimport { InvalidEnvelope } from '../failure/generic.js';\nimport type { Entity, EntityConstructor } from '../types/Entity.js';\nimport type {\n EntityFacetCounts,\n EntityFacetValue,\n} from '../types/EntityFacets.js';\nimport type { EntityPage } from '../types/EntityPage.js';\nimport { envelopeEntityName } from './make-envelope.js';\nimport type {\n DomainEvent,\n EntifixEnvelope,\n EntifixEnvelopeType,\n EntifixEventMeta,\n SerializedEntityPage,\n} from './types.js';\n\n/**\n * Structural check only — `meta.type` is validated separately so a mismatch\n * reports the expected/actual types rather than a generic \"not an envelope\".\n */\nexport function isEntifixEnvelope(body: unknown): body is EntifixEnvelope {\n if (body == null || typeof body !== 'object') {\n return false;\n }\n const meta = (body as EntifixEnvelope).meta;\n return (\n meta != null && typeof meta === 'object' && typeof meta.type === 'string'\n );\n}\n\n/**\n * Narrows an arbitrary body to an envelope of the expected `meta.type`, failing\n * with an {@link InvalidEnvelope} otherwise. A wrong shape must never\n * silently deserialize into a half-populated entity.\n */\nfunction assertEnvelope<TEntity extends Entity, TData>(\n entityConstructor: EntityConstructor<TEntity>,\n body: unknown,\n expected: EntifixEnvelopeType,\n): Effect.Effect<EntifixEnvelope<TData>, InvalidEnvelope> {\n const entity = envelopeEntityName(entityConstructor);\n\n if (!isEntifixEnvelope(body)) {\n return Effect.fail(\n new InvalidEnvelope({\n reason: `Expected an EntifixEnvelope for \"${entity}\" but the payload carried no meta.type`,\n }),\n );\n }\n if (body.meta.type !== expected) {\n return Effect.fail(\n new InvalidEnvelope({\n reason: `Expected an EntifixEnvelope of type \"${expected}\" for \"${entity}\" but got \"${body.meta.type}\"`,\n }),\n );\n }\n return Effect.succeed(body as EntifixEnvelope<TData>);\n}\n\n/**\n * Narrows an arbitrary body to an envelope of the expected `meta.type` without\n * requiring an entity constructor — for `command`/`transactionRecord` messages\n * whose `data` is not a serialized entity. `label` only sharpens error text.\n */\nexport function readEnvelope<TData>(\n body: unknown,\n expected: EntifixEnvelopeType,\n label = 'message',\n): Effect.Effect<EntifixEnvelope<TData>, InvalidEnvelope> {\n if (!isEntifixEnvelope(body)) {\n return Effect.fail(\n new InvalidEnvelope({\n reason: `Expected an EntifixEnvelope for \"${label}\" but the payload carried no meta.type`,\n }),\n );\n }\n if (body.meta.type !== expected) {\n return Effect.fail(\n new InvalidEnvelope({\n reason: `Expected an EntifixEnvelope of type \"${expected}\" for \"${label}\" but got \"${body.meta.type}\"`,\n }),\n );\n }\n return Effect.succeed(body as EntifixEnvelope<TData>);\n}\n\nexport const readEntityEnvelope = <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n body: unknown,\n) =>\n Effect.gen(function* () {\n const envelope = yield* assertEnvelope<TEntity, unknown>(\n entityConstructor,\n body,\n 'entity',\n );\n const entity = yield* deserializeSingleEntity(\n entityConstructor,\n envelope.data,\n );\n if (entity === undefined) {\n return yield* Effect.fail(\n new InvalidEnvelope({\n reason: `EntifixEnvelope for \"${envelopeEntityName(\n entityConstructor,\n )}\" carried no data`,\n }),\n );\n }\n return entity;\n });\n\nexport const readEntityCollectionEnvelope = <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n body: unknown,\n) =>\n Effect.gen(function* () {\n const envelope = yield* assertEnvelope<TEntity, unknown>(\n entityConstructor,\n body,\n 'entityCollection',\n );\n const items = yield* deserializeEntityCollection(\n entityConstructor,\n envelope.data,\n );\n return items as TEntity[];\n });\n\nexport const readEntityPageEnvelope = <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n body: unknown,\n) =>\n Effect.gen(function* () {\n const envelope = yield* assertEnvelope<\n TEntity,\n SerializedEntityPage<TEntity>\n >(entityConstructor, body, 'entityPage');\n const items = yield* deserializeEntityCollection(\n entityConstructor,\n envelope.data?.items,\n );\n return {\n items: items as TEntity[],\n total: envelope.data?.total ?? 0,\n request: envelope.data?.request ?? {},\n } satisfies EntityPage<TEntity>;\n });\n\n/**\n * Reads a `$metadata` response back into its document.\n *\n * No deserialization step, and no defaulting of the members either: an envelope\n * whose `data` is missing a list would leave a form guessing whether \"no\n * actions\" meant \"denied\" or \"malformed\", so a broken payload fails loudly here\n * the way a half-populated entity does.\n */\nexport const readEntityMetadataEnvelope = <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n body: unknown,\n) =>\n Effect.gen(function* () {\n const envelope = yield* assertEnvelope<TEntity, EntityMetadataDocument>(\n entityConstructor,\n body,\n 'entityMetadata',\n );\n const document = envelope.data;\n if (\n !Array.isArray(document?.actions) ||\n !Array.isArray(document?.useCases)\n ) {\n return yield* Effect.fail(\n new InvalidEnvelope({\n reason: `EntifixEnvelope for \"${envelopeEntityName(\n entityConstructor,\n )}\" carried no metadata document`,\n }),\n );\n }\n return document;\n });\n\nconst isFacetValueRow = (row: unknown): row is EntityFacetValue =>\n row != null &&\n typeof row === 'object' &&\n ['string', 'number', 'boolean'].includes(\n typeof (row as EntityFacetValue).value,\n ) &&\n typeof (row as EntityFacetValue).count === 'number';\n\n/**\n * Reads a `$facets` response back into its counts, refusing a body whose lists\n * are not `{ value, count }` rows — a panel that rendered a malformed count\n * would show a number nobody computed.\n */\nexport const readEntityFacetsEnvelope = <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n body: unknown,\n) =>\n Effect.gen(function* () {\n const envelope = yield* assertEnvelope<TEntity, EntityFacetCounts>(\n entityConstructor,\n body,\n 'entityFacets',\n );\n const counts = envelope.data;\n const wellFormed =\n counts != null &&\n typeof counts === 'object' &&\n Object.values(counts).every(\n rows => Array.isArray(rows) && rows.every(isFacetValueRow),\n );\n if (!wellFormed) {\n return yield* Effect.fail(\n new InvalidEnvelope({\n reason: `EntifixEnvelope for \"${envelopeEntityName(\n entityConstructor,\n )}\" carried no facet counts`,\n }),\n );\n }\n return counts;\n });\n\n/** Every member `meta.event` must carry for a message to be routable at all. */\nconst REQUIRED_EVENT_META = ['name', 'id', 'source', 'at'] as const;\n\n/**\n * Reads a bus message back into a {@link DomainEvent}.\n *\n * The metadata is validated rather than defaulted, and that is the point: a\n * message missing `id` cannot be deduplicated and a message missing `name`\n * cannot be routed, so both are failures a consumer must see rather than\n * absences it silently works around. It is the same call\n * {@link readEntityMetadataEnvelope} makes — a broken payload fails loudly\n * instead of arriving half-populated.\n *\n * Note this does not validate `data`. The transport has no idea what a\n * `catalog.published` payload should look like, and inventing an opinion here\n * is how the bus would start knowing about domains.\n */\nexport function readEventEnvelope<TData = unknown>(\n body: unknown,\n): Effect.Effect<DomainEvent<TData>, InvalidEnvelope> {\n return Effect.gen(function* () {\n const envelope = yield* readEnvelope<TData>(body, 'event', 'event');\n const event = envelope.meta.event;\n const missing = REQUIRED_EVENT_META.filter(\n member => typeof event?.[member] !== 'string' || event[member] === '',\n );\n if (missing.length > 0) {\n return yield* Effect.fail(\n new InvalidEnvelope({\n reason: `event envelope carried incomplete meta.event (missing ${missing.join(\n ', ',\n )})`,\n }),\n );\n }\n return { ...(event as EntifixEventMeta), data: envelope.data };\n });\n}\n"],"names":["Effect","deserializeEntityCollection","deserializeSingleEntity","InvalidEnvelope","envelopeEntityName","isEntifixEnvelope","body","meta","type","assertEnvelope","entityConstructor","expected","entity","fail","reason","succeed","readEnvelope","label","readEntityEnvelope","gen","envelope","data","undefined","readEntityCollectionEnvelope","items","readEntityPageEnvelope","total","request","readEntityMetadataEnvelope","document","Array","isArray","actions","useCases","isFacetValueRow","row","includes","value","count","readEntityFacetsEnvelope","counts","wellFormed","Object","values","every","rows","REQUIRED_EVENT_META","readEventEnvelope","event","missing","filter","member","length","join"],"mappings":";AAAA,SAASA,MAAM,QAAQ,SAAS;AAGhC,SACEC,2BAA2B,EAC3BC,uBAAuB,QAClB,2CAA2C;AAClD,SAASC,eAAe,QAAQ,wBAAwB;AAOxD,SAASC,kBAAkB,QAAQ,qBAAqB;AASxD;;;CAGC,GACD,OAAO,SAASC,kBAAkBC,IAAa;IAC7C,IAAIA,QAAQ,QAAQ,OAAOA,SAAS,UAAU;QAC5C,OAAO;IACT;IACA,MAAMC,OAAO,AAACD,KAAyBC,IAAI;IAC3C,OACEA,QAAQ,QAAQ,OAAOA,SAAS,YAAY,OAAOA,KAAKC,IAAI,KAAK;AAErE;AAEA;;;;CAIC,GACD,SAASC,eACPC,iBAA6C,EAC7CJ,IAAa,EACbK,QAA6B;IAE7B,MAAMC,SAASR,mBAAmBM;IAElC,IAAI,CAACL,kBAAkBC,OAAO;QAC5B,OAAON,OAAOa,IAAI,CAChB,IAAIV,gBAAgB;YAClBW,QAAQ,CAAC,iCAAiC,EAAEF,OAAO,sCAAsC,CAAC;QAC5F;IAEJ;IACA,IAAIN,KAAKC,IAAI,CAACC,IAAI,KAAKG,UAAU;QAC/B,OAAOX,OAAOa,IAAI,CAChB,IAAIV,gBAAgB;YAClBW,QAAQ,CAAC,qCAAqC,EAAEH,SAAS,OAAO,EAAEC,OAAO,WAAW,EAAEN,KAAKC,IAAI,CAACC,IAAI,CAAC,CAAC,CAAC;QACzG;IAEJ;IACA,OAAOR,OAAOe,OAAO,CAACT;AACxB;AAEA;;;;CAIC,GACD,OAAO,SAASU,aACdV,IAAa,EACbK,QAA6B,EAC7BM,QAAQ,SAAS;IAEjB,IAAI,CAACZ,kBAAkBC,OAAO;QAC5B,OAAON,OAAOa,IAAI,CAChB,IAAIV,gBAAgB;YAClBW,QAA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M,sBAAsB;IAAC;IAAQ;IAAM;IAAU;CAAK;AAE1D;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC,kBACdzC,IAAa;IAEb,OAAON,OAAOmB,GAAG,CAAC;QAChB,MAAMC,WAAW,OAAOJ,aAAoBV,MAAM,SAAS;QAC3D,MAAM0C,QAAQ5B,SAASb,IAAI,CAACyC,KAAK;QACjC,MAAMC,UAAUH,oBAAoBI,MAAM,CACxCC,CAAAA,SAAU,QAAOH,yBAAAA,KAAO,CAACG,OAAO,MAAK,YAAYH,KAAK,CAACG,OAAO,KAAK;QAErE,IAAIF,QAAQG,MAAM,GAAG,GAAG;YACtB,OAAO,OAAOpD,OAAOa,IAAI,CACvB,IAAIV,gBAAgB;gBAClBW,QAAQ,CAAC,sDAAsD,EAAEmC,QAAQI,IAAI,CAC3E,MACA,CAAC,CAAC;YACN;QAEJ;QACA,OAAO,aAAML;YAA4B3B,MAAMD,SAASC,IAAI;;IAC9D;AACF"}
1
+ {"version":3,"sources":["../../src/envelope/read-envelope.ts"],"sourcesContent":["import { Effect } from 'effect';\n\nimport type { EntityMetadataDocument } from '../entity-definition/metadata/index.js';\nimport {\n deserializeEntityCollection,\n deserializeSingleEntity,\n} from '../entity-definition/serializer/index.js';\nimport { InvalidEnvelope } from '../failure/generic.js';\nimport type { Entity, EntityConstructor } from '../types/Entity.js';\nimport type { EntityFacetCounts } from '../types/EntityFacets.js';\nimport type { EntityPage } from '../types/EntityPage.js';\nimport { decodeEnvelope } from './codec.js';\nimport { envelopeEntityName } from './make-envelope.js';\nimport type {\n EntifixEnvelope,\n EntifixEnvelopeType,\n SerializedEntityPage,\n} from './types.js';\n\n/**\n * Decodes a body a **caller sent** — a request to this service — into an\n * envelope of the expected type, its `data` decoded against the registered\n * schema.\n *\n * The same decode as {@link decodeEnvelope}, failing with an\n * {@link InvalidEnvelope} instead of a protocol failure: a malformed request is\n * the sender's fault and answers `400`, where a peer's malformed *answer* is a\n * `502`.\n */\nexport const decodeRequestEnvelope = (\n body: unknown,\n expected: EntifixEnvelopeType,\n label = 'message',\n): Effect.Effect<EntifixEnvelope, InvalidEnvelope> =>\n Effect.mapError(\n decodeEnvelope(body, expected),\n failure =>\n new InvalidEnvelope({\n reason: `\"${label}\": ${failure.reason}`,\n }),\n );\n\nconst decodeFor = <TEntity extends Entity, TData>(\n entityConstructor: EntityConstructor<TEntity>,\n body: unknown,\n expected: EntifixEnvelopeType,\n): Effect.Effect<EntifixEnvelope<TData>, InvalidEnvelope> =>\n decodeRequestEnvelope(\n body,\n expected,\n envelopeEntityName(entityConstructor),\n ) as Effect.Effect<EntifixEnvelope<TData>, InvalidEnvelope>;\n\n/**\n * A record the entity cannot be built from — a member of the wrong type — is\n * the sender's fault exactly as a malformed envelope is, so it answers the\n * same `400` rather than leaving the deserializer's own error to the caller.\n */\nconst refusedRecord =\n <TEntity extends Entity>(entityConstructor: EntityConstructor<TEntity>) =>\n (error: { readonly message: string }) =>\n new InvalidEnvelope({\n reason: `\"${envelopeEntityName(entityConstructor)}\": ${error.message}`,\n });\n\nexport const readEntityEnvelope = <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n body: unknown,\n) =>\n Effect.gen(function* () {\n const envelope = yield* decodeFor<TEntity, unknown>(\n entityConstructor,\n body,\n 'entity',\n );\n // The registered schema already refused a missing or non-object `data`,\n // so the deserializer always has a record to build from.\n return (yield* deserializeSingleEntity(\n entityConstructor,\n envelope.data,\n ).pipe(Effect.mapError(refusedRecord(entityConstructor)))) as TEntity;\n });\n\nexport const readEntityCollectionEnvelope = <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n body: unknown,\n) =>\n Effect.gen(function* () {\n const envelope = yield* decodeFor<TEntity, unknown>(\n entityConstructor,\n body,\n 'entityCollection',\n );\n const items = yield* deserializeEntityCollection(\n entityConstructor,\n envelope.data,\n ).pipe(Effect.mapError(refusedRecord(entityConstructor)));\n return items as TEntity[];\n });\n\nexport const readEntityPageEnvelope = <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n body: unknown,\n) =>\n Effect.gen(function* () {\n const envelope = yield* decodeFor<TEntity, SerializedEntityPage<TEntity>>(\n entityConstructor,\n body,\n 'entityPage',\n );\n const items = yield* deserializeEntityCollection(\n entityConstructor,\n envelope.data.items,\n ).pipe(Effect.mapError(refusedRecord(entityConstructor)));\n return {\n items: items as TEntity[],\n total: envelope.data.total,\n request: envelope.data.request ?? {},\n } satisfies EntityPage<TEntity>;\n });\n\n/**\n * Reads a `$metadata` response back into its document.\n *\n * No defaulting of the members: the registered schema refuses a document\n * missing either list, so a form never has to guess whether \"no actions\" meant\n * \"denied\" or \"malformed\".\n */\nexport const readEntityMetadataEnvelope = <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n body: unknown,\n) =>\n Effect.map(\n decodeFor<TEntity, EntityMetadataDocument>(\n entityConstructor,\n body,\n 'entityMetadata',\n ),\n envelope => envelope.data,\n );\n\n/**\n * Reads a `$facets` response back into its counts. The registered schema\n * refuses a body whose lists are not `{ value, count }` rows — a panel that\n * rendered a malformed count would show a number nobody computed.\n */\nexport const readEntityFacetsEnvelope = <TEntity extends Entity>(\n entityConstructor: EntityConstructor<TEntity>,\n body: unknown,\n) =>\n Effect.map(\n decodeFor<TEntity, EntityFacetCounts>(\n entityConstructor,\n body,\n 'entityFacets',\n ),\n envelope => envelope.data,\n );\n"],"names":["Effect","deserializeEntityCollection","deserializeSingleEntity","InvalidEnvelope","decodeEnvelope","envelopeEntityName","decodeRequestEnvelope","body","expected","label","mapError","failure","reason","decodeFor","entityConstructor","refusedRecord","error","message","readEntityEnvelope","gen","envelope","data","pipe","readEntityCollectionEnvelope","items","readEntityPageEnvelope","total","request","readEntityMetadataEnvelope","map","readEntityFacetsEnvelope"],"mappings":"AAAA,SAASA,MAAM,QAAQ,SAAS;AAGhC,SACEC,2BAA2B,EAC3BC,uBAAuB,QAClB,2CAA2C;AAClD,SAASC,eAAe,QAAQ,wBAAwB;AAIxD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,KAAK,EACnBF,IAAI,CAACtB,OAAOU,QAAQ,CAACK,cAAcD;QACrC,OAAO;YACLU,OAAOA;YACPE,OAAON,SAASC,IAAI,CAACK,KAAK;YAC1BC,OAAO,GAAEP,yBAAAA,SAASC,IAAI,CAACM,OAAO,YAArBP,yBAAyB,CAAC;QACrC;IACF,GAAG;AAEL;;;;;;CAMC,GACD,OAAO,MAAMQ,6BAA6B,CACxCd,mBACAP,OAEAP,OAAO6B,GAAG,CACRhB,UACEC,mBACAP,MACA,mBAEFa,CAAAA,WAAYA,SAASC,IAAI,EACzB;AAEJ;;;;CAIC,GACD,OAAO,MAAMS,2BAA2B,CACtChB,mBACAP,OAEAP,OAAO6B,GAAG,CACRhB,UACEC,mBACAP,MACA,iBAEFa,CAAAA,WAAYA,SAASC,IAAI,EACzB"}
@@ -0,0 +1,45 @@
1
+ import { Schema } from 'effect';
2
+ /**
3
+ * What a registered message requires of its `meta`, beside its `data` schema.
4
+ *
5
+ * - `versioned` — the message describes one version of one aggregate, so it
6
+ * must carry `meta.event.version`; a consumer discards anything older than
7
+ * what it already applied.
8
+ * - `audience` — `required` (the default) means the message must name who may
9
+ * receive it, because an empty audience reaches nobody; `none` declares a
10
+ * message nobody outside the fleet ever receives, such as an announcement
11
+ * folded into a projection anyone may read.
12
+ */
13
+ export interface MessageRequirements {
14
+ readonly versioned?: boolean;
15
+ readonly audience?: 'required' | 'none';
16
+ }
17
+ /** One registration: the schema `data` decodes against, plus its requirements. */
18
+ export interface RegisteredMessage {
19
+ /** The `meta.type`, or the event name for an `event`. */
20
+ readonly name: string;
21
+ readonly kind: 'type' | 'event';
22
+ readonly schema: Schema.Codec<unknown, unknown>;
23
+ readonly versioned: boolean;
24
+ readonly audience: 'required' | 'none';
25
+ }
26
+ /**
27
+ * Registers the schema an envelope of `meta.type === type` carries in `data`.
28
+ * Called at module load by the package that owns the shape; a second call with
29
+ * a different schema throws.
30
+ */
31
+ export declare const registerMessage: <A, I>(type: string, schema: Schema.Codec<A, I>, requirements?: MessageRequirements) => void;
32
+ /**
33
+ * Registers the schema an `event` envelope named `name` carries in `data`,
34
+ * and what its `meta.event` must state.
35
+ */
36
+ export declare const registerEvent: <A, I>(name: string, schema: Schema.Codec<A, I>, requirements?: MessageRequirements) => void;
37
+ /** The registration for a `meta.type`, if any package made one. */
38
+ export declare const lookupMessage: (type: string) => RegisteredMessage | undefined;
39
+ /** The registration for an event name, if any package made one. */
40
+ export declare const lookupEvent: (name: string) => RegisteredMessage | undefined;
41
+ /** Every registered event, ordered by name — what a register check walks. */
42
+ export declare const registeredEvents: () => readonly RegisteredMessage[];
43
+ /** Every registered `meta.type`, ordered by name. */
44
+ export declare const registeredMessages: () => readonly RegisteredMessage[];
45
+ //# sourceMappingURL=registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/envelope/registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC;;;;;;;;;;GAUG;AACH,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,SAAS,CAAC,EAAE,OAAO,CAAC;IAC7B,QAAQ,CAAC,QAAQ,CAAC,EAAE,UAAU,GAAG,MAAM,CAAC;CACzC;AAED,kFAAkF;AAClF,MAAM,WAAW,iBAAiB;IAChC,yDAAyD;IACzD,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IAChC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IAChD,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;IAC5B,QAAQ,CAAC,QAAQ,EAAE,UAAU,GAAG,MAAM,CAAC;CACxC;AA6DD;;;;GAIG;AACH,eAAO,MAAM,eAAe,GAAI,CAAC,EAAE,CAAC,EAClC,MAAM,MAAM,EACZ,QAAQ,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,EAC1B,eAAc,mBAAwB,KACrC,IASA,CAAC;AAEJ;;;GAGG;AACH,eAAO,MAAM,aAAa,GAAI,CAAC,EAAE,CAAC,EAChC,MAAM,MAAM,EACZ,QAAQ,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,EAC1B,eAAc,mBAAwB,KACrC,IASA,CAAC;AAEJ,mEAAmE;AACnE,eAAO,MAAM,aAAa,GAAI,MAAM,MAAM,KAAG,iBAAiB,GAAG,SACrC,CAAC;AAE7B,mEAAmE;AACnE,eAAO,MAAM,WAAW,GAAI,MAAM,MAAM,KAAG,iBAAiB,GAAG,SAClC,CAAC;AAE9B,6EAA6E;AAC7E,eAAO,MAAM,gBAAgB,QAAO,SAAS,iBAAiB,EACgB,CAAC;AAE/E,qDAAqD;AACrD,eAAO,MAAM,kBAAkB,QAAO,SAAS,iBAAiB,EACa,CAAC"}
@@ -0,0 +1,55 @@
1
+ import { Schema } from 'effect';
2
+ /**
3
+ * Shared through `globalThis` under a registered symbol, for the reason the
4
+ * failure registry is: two copies of `@entifix/core` in one process would
5
+ * otherwise hold two tables, and a schema registered against one would not
6
+ * decode through the other.
7
+ */ const REGISTRY_KEY = Symbol.for('@entifix/core/message-registry');
8
+ const registry = ()=>{
9
+ var _holder, _REGISTRY_KEY, _;
10
+ const holder = globalThis;
11
+ (_ = (_holder = holder)[_REGISTRY_KEY = REGISTRY_KEY]) != null ? _ : _holder[_REGISTRY_KEY] = {
12
+ types: new Map(),
13
+ events: new Map()
14
+ };
15
+ return holder[REGISTRY_KEY];
16
+ };
17
+ /**
18
+ * A structural fingerprint of a schema, so a module evaluated twice — a hot
19
+ * reload, a test re-importing — registers an equal schema object without
20
+ * tripping the duplicate check.
21
+ */ const fingerprint = (schema)=>JSON.stringify(Schema.toJsonSchemaDocument(schema));
22
+ const register = (table, entry)=>{
23
+ const existing = table.get(entry.name);
24
+ if (existing !== undefined && (fingerprint(existing.schema) !== fingerprint(entry.schema) || existing.versioned !== entry.versioned || existing.audience !== entry.audience)) throw new Error(`message '${entry.name}' is already registered with a different schema. ` + 'A name means one shape on every transport: give this one its own name, ' + 'or bump the existing one.');
25
+ table.set(entry.name, entry);
26
+ };
27
+ const entry = (name, kind, schema, requirements)=>{
28
+ var _requirements_versioned, _requirements_audience;
29
+ return {
30
+ name,
31
+ kind,
32
+ schema,
33
+ versioned: (_requirements_versioned = requirements.versioned) != null ? _requirements_versioned : false,
34
+ audience: (_requirements_audience = requirements.audience) != null ? _requirements_audience : 'required'
35
+ };
36
+ };
37
+ /**
38
+ * Registers the schema an envelope of `meta.type === type` carries in `data`.
39
+ * Called at module load by the package that owns the shape; a second call with
40
+ * a different schema throws.
41
+ */ export const registerMessage = (type, schema, requirements = {})=>register(registry().types, entry(type, 'type', schema, requirements));
42
+ /**
43
+ * Registers the schema an `event` envelope named `name` carries in `data`,
44
+ * and what its `meta.event` must state.
45
+ */ export const registerEvent = (name, schema, requirements = {})=>register(registry().events, entry(name, 'event', schema, requirements));
46
+ /** The registration for a `meta.type`, if any package made one. */ export const lookupMessage = (type)=>registry().types.get(type);
47
+ /** The registration for an event name, if any package made one. */ export const lookupEvent = (name)=>registry().events.get(name);
48
+ /** Every registered event, ordered by name — what a register check walks. */ export const registeredEvents = ()=>[
49
+ ...registry().events.values()
50
+ ].sort((a, b)=>a.name.localeCompare(b.name));
51
+ /** Every registered `meta.type`, ordered by name. */ export const registeredMessages = ()=>[
52
+ ...registry().types.values()
53
+ ].sort((a, b)=>a.name.localeCompare(b.name));
54
+
55
+ //# sourceMappingURL=registry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/envelope/registry.ts"],"sourcesContent":["import { Schema } from 'effect';\n\n/**\n * What a registered message requires of its `meta`, beside its `data` schema.\n *\n * - `versioned` — the message describes one version of one aggregate, so it\n * must carry `meta.event.version`; a consumer discards anything older than\n * what it already applied.\n * - `audience` — `required` (the default) means the message must name who may\n * receive it, because an empty audience reaches nobody; `none` declares a\n * message nobody outside the fleet ever receives, such as an announcement\n * folded into a projection anyone may read.\n */\nexport interface MessageRequirements {\n readonly versioned?: boolean;\n readonly audience?: 'required' | 'none';\n}\n\n/** One registration: the schema `data` decodes against, plus its requirements. */\nexport interface RegisteredMessage {\n /** The `meta.type`, or the event name for an `event`. */\n readonly name: string;\n readonly kind: 'type' | 'event';\n readonly schema: Schema.Codec<unknown, unknown>;\n readonly versioned: boolean;\n readonly audience: 'required' | 'none';\n}\n\n/**\n * Shared through `globalThis` under a registered symbol, for the reason the\n * failure registry is: two copies of `@entifix/core` in one process would\n * otherwise hold two tables, and a schema registered against one would not\n * decode through the other.\n */\nconst REGISTRY_KEY = Symbol.for('@entifix/core/message-registry');\n\ninterface Registry {\n readonly types: Map<string, RegisteredMessage>;\n readonly events: Map<string, RegisteredMessage>;\n}\n\nconst registry = (): Registry => {\n const holder = globalThis as { [REGISTRY_KEY]?: Registry };\n holder[REGISTRY_KEY] ??= { types: new Map(), events: new Map() };\n return holder[REGISTRY_KEY];\n};\n\n/**\n * A structural fingerprint of a schema, so a module evaluated twice — a hot\n * reload, a test re-importing — registers an equal schema object without\n * tripping the duplicate check.\n */\nconst fingerprint = (schema: Schema.Codec<unknown, unknown>): string =>\n JSON.stringify(Schema.toJsonSchemaDocument(schema));\n\nconst register = (\n table: Map<string, RegisteredMessage>,\n entry: RegisteredMessage,\n): void => {\n const existing = table.get(entry.name);\n if (\n existing !== undefined &&\n (fingerprint(existing.schema) !== fingerprint(entry.schema) ||\n existing.versioned !== entry.versioned ||\n existing.audience !== entry.audience)\n )\n throw new Error(\n `message '${entry.name}' is already registered with a different schema. ` +\n 'A name means one shape on every transport: give this one its own name, ' +\n 'or bump the existing one.',\n );\n table.set(entry.name, entry);\n};\n\nconst entry = (\n name: string,\n kind: RegisteredMessage['kind'],\n schema: Schema.Codec<unknown, unknown>,\n requirements: MessageRequirements,\n): RegisteredMessage => ({\n name,\n kind,\n schema,\n versioned: requirements.versioned ?? false,\n audience: requirements.audience ?? 'required',\n});\n\n/**\n * Registers the schema an envelope of `meta.type === type` carries in `data`.\n * Called at module load by the package that owns the shape; a second call with\n * a different schema throws.\n */\nexport const registerMessage = <A, I>(\n type: string,\n schema: Schema.Codec<A, I>,\n requirements: MessageRequirements = {},\n): void =>\n register(\n registry().types,\n entry(\n type,\n 'type',\n schema as unknown as Schema.Codec<unknown, unknown>,\n requirements,\n ),\n );\n\n/**\n * Registers the schema an `event` envelope named `name` carries in `data`,\n * and what its `meta.event` must state.\n */\nexport const registerEvent = <A, I>(\n name: string,\n schema: Schema.Codec<A, I>,\n requirements: MessageRequirements = {},\n): void =>\n register(\n registry().events,\n entry(\n name,\n 'event',\n schema as unknown as Schema.Codec<unknown, unknown>,\n requirements,\n ),\n );\n\n/** The registration for a `meta.type`, if any package made one. */\nexport const lookupMessage = (type: string): RegisteredMessage | undefined =>\n registry().types.get(type);\n\n/** The registration for an event name, if any package made one. */\nexport const lookupEvent = (name: string): RegisteredMessage | undefined =>\n registry().events.get(name);\n\n/** Every registered event, ordered by name — what a register check walks. */\nexport const registeredEvents = (): readonly RegisteredMessage[] =>\n [...registry().events.values()].sort((a, b) => a.name.localeCompare(b.name));\n\n/** Every registered `meta.type`, ordered by name. */\nexport const registeredMessages = (): readonly RegisteredMessage[] =>\n [...registry().types.values()].sort((a, b) => a.name.localeCompare(b.name));\n"],"names":["Schema","REGISTRY_KEY","Symbol","for","registry","holder","globalThis","types","Map","events","fingerprint","schema","JSON","stringify","toJsonSchemaDocument","register","table","entry","existing","get","name","undefined","versioned","audience","Error","set","kind","requirements","registerMessage","type","registerEvent","lookupMessage","lookupEvent","registeredEvents","values","sort","a","b","localeCompare","registeredMessages"],"mappings":"AAAA,SAASA,MAAM,QAAQ,SAAS;AA4BhC;;;;;CAKC,GACD,MAAMC,eAAeC,OAAOC,GAAG,CAAC;AAOhC,MAAMC,WAAW;QAEfC,SAAOJ,eAAPI;IADA,MAAMA,SAASC;KACfD,IAAA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AWG,KAAK,CAACY,GAAG,CAACU,MAAM;AAE7B,iEAAiE,GACjE,OAAO,MAAMG,cAAc,CAACZ,OAC1BhB,WAAWK,MAAM,CAACU,GAAG,CAACC,MAAM;AAE9B,2EAA2E,GAC3E,OAAO,MAAMa,mBAAmB,IAC9B;WAAI7B,WAAWK,MAAM,CAACyB,MAAM;KAAG,CAACC,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAEhB,IAAI,CAACkB,aAAa,CAACD,EAAEjB,IAAI,GAAG;AAE/E,mDAAmD,GACnD,OAAO,MAAMmB,qBAAqB,IAChC;WAAInC,WAAWG,KAAK,CAAC2B,MAAM;KAAG,CAACC,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAEhB,IAAI,CAACkB,aAAa,CAACD,EAAEjB,IAAI,GAAG"}
@@ -4,40 +4,21 @@ import type { Entity, EntityId } from '../types/Entity.js';
4
4
  import type { EntityFacetCounts } from '../types/EntityFacets.js';
5
5
  import type { EntityLoadRequest } from '../types/EntityLoadRequest.js';
6
6
  /**
7
- * Discriminates what {@link EntifixEnvelope.data} carries.
7
+ * Names what {@link EntifixEnvelope.data} carries — a name in the open message
8
+ * registry (`registerMessage`), not a member of a closed union.
8
9
  *
9
- * `command` extends the contract for the transactions layer: a write is issued
10
- * as a `command`, whose `data` shape lives in `@entifix/transactions` —
11
- * core only owns the discriminant so every artifact agrees on it.
10
+ * Core registers only what core owns: `entity`, `entityCollection`,
11
+ * `entityPage`, `entityMetadata`, `entityFacets`, and `event`, whose `data` is
12
+ * looked up by `meta.event.name` instead (`registerEvent`). Every other shape is
13
+ * registered by the package that owns it — `@entifix/transactions` registers
14
+ * `command` and its accept, record and saga shapes — so adding a kind of message
15
+ * never means changing core.
12
16
  *
13
- * `event` is what actually rides the bus, and it is deliberately not named
14
- * after one publisher's flow: once a message can be `catalog.published` as
15
- * easily as `transaction.completed`, `transactionEvent` would be the wrong
16
- * name for it.
17
- *
18
- * ⚠️ **The four transaction-shaped discriminants below are four because they
19
- * carry four shapes.** `transactionEvent` used to mean all of them, and a
20
- * discriminant that means several things asserts nothing when it is read —
21
- * which is what `readTransactionEventEnvelope` was doing on the `202`: checking
22
- * a name that the record route and the event type both also answered to.
23
- *
24
- * - `transactionAccepted` — the `202` accept body, `{ transactionId, state }`.
25
- * Not a record: it has no `createdAt` and names no entity id yet.
26
- * - `transactionRecord` — the fold a client polls, a `TransactionRecord`.
27
- * - `sagaResult` — how a settled multi-step walk ended: which steps ran and
28
- * what each returned.
29
- * - `sagaInstance` — the durable instance itself, which is what a resumable
30
- * coordinator reads and what `GET /api/saga/:id` serves. It differs from
31
- * `sagaResult` in carrying the inputs and the resume count, because those are
32
- * what an operator needs to answer *why is this one still here*.
33
- *
34
- * `entityMetadata` is the same extension made once more, for the action model:
35
- * its `data` is an {@link EntityMetadataDocument}, which core does own because
36
- * both the service that computes it and the controls that render it are already
37
- * below the layer that would otherwise host it.
17
+ * A read never trusts the name: `decodeEnvelope` decodes `data` against the
18
+ * registered schema, and an unregistered name is a protocol failure.
38
19
  */
39
- export type EntifixEnvelopeType = 'entity' | 'entityCollection' | 'entityPage' | 'command' | 'event' | 'transactionAccepted' | 'transactionRecord' | 'sagaResult' | 'sagaInstance' | 'entityMetadata' | 'entityFacets';
40
- export type EntifixEnvelopeMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
20
+ export type EntifixEnvelopeType = string;
21
+ export type EntifixEnvelopeMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
41
22
  /**
42
23
  * A HATEOAS affordance: where the peer can go next from this message. Optional —
43
24
  * the envelope stands on its own without links, and only the artifact that owns
@@ -84,8 +65,42 @@ export interface EntifixEventMeta {
84
65
  source: string;
85
66
  /** ISO-8601 emission time. */
86
67
  at: string;
87
- /** Ties every message of one flow together — a transaction id, a saga id. */
68
+ /** Ties every message of one flow together — a transaction id, a flow id. */
88
69
  correlationId?: string;
70
+ /**
71
+ * The aggregate this message is about — the unit its `version` counts, and
72
+ * the unit an outbox keeps order within. A consumer discards a message older
73
+ * than the last version it applied **for this aggregate**.
74
+ */
75
+ aggregate?: AggregateRef;
76
+ /**
77
+ * The version of the aggregate this message describes. Required on a
78
+ * message registered `versioned`, and what a consumer orders on: one that
79
+ * already applied version `n` discards a late `n - 1` instead of letting it
80
+ * overwrite (`discardIfStale`).
81
+ */
82
+ version?: number;
83
+ /**
84
+ * Who may receive this message. Absent or empty, it reaches **nobody** —
85
+ * `audienceAdmits` fails closed, so a publisher that forgot to address a
86
+ * message leaks nothing.
87
+ */
88
+ audience?: readonly AudienceEntry[];
89
+ }
90
+ /** Names one aggregate: its type and its id, `{ type: 'product-order', id }`. */
91
+ export interface AggregateRef {
92
+ type: string;
93
+ id: string;
94
+ }
95
+ /**
96
+ * One recipient of a message: every member of an organization, one party, or
97
+ * whoever holds a flow's capability — whose SHA-256 digest is `digest`, so the
98
+ * audience never carries the credential itself.
99
+ */
100
+ export interface AudienceEntry {
101
+ kind: 'organization' | 'party' | 'flow';
102
+ id: string;
103
+ digest?: string;
89
104
  }
90
105
  export interface EntifixEnvelopeMeta {
91
106
  type: EntifixEnvelopeType;
@@ -163,7 +178,7 @@ export type EntityMetadataEnvelope = EntifixEnvelope<EntityMetadataDocument>;
163
178
  export type EntityFacetsEnvelope = EntifixEnvelope<EntityFacetCounts>;
164
179
  /**
165
180
  * A bus message on the wire. `meta.event` is always populated, and
166
- * `readEventEnvelope` is what proves it before a consumer sees the payload.
181
+ * `decodeEvent` is what proves it before a consumer sees the payload.
167
182
  */
168
183
  export type EventEnvelope<TData = unknown> = EntifixEnvelope<TData> & {
169
184
  meta: EntifixEnvelopeMeta & {
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/envelope/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AACjF,OAAO,KAAK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,CAAC;AAC7E,MAAM,MAAM,oBAAoB,GAAG,eAAe,CAAC,iBAAiB,CAAC,CAAC;AAEtE;;;GAGG;AACH,MAAM,MAAM,aAAa,CAAC,KAAK,GAAG,OAAO,IAAI,eAAe,CAAC,KAAK,CAAC,GAAG;IACpE,IAAI,EAAE,mBAAmB,GAAG;QAAE,KAAK,EAAE,gBAAgB,CAAA;KAAE,CAAC;CACzD,CAAC"}
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * A bus message on the wire. `meta.event` is always populated, and
3
- * `readEventEnvelope` is what proves it before a consumer sees the payload.
3
+ * `decodeEvent` is what proves it before a consumer sees the payload.
4
4
  */ export { };
5
5
 
6
6
  //# sourceMappingURL=types.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/envelope/types.ts"],"sourcesContent":["import type { EntityMetadataDocument } from '../entity-definition/metadata/index.js';\nimport type { SerializedEntity } from '../entity-definition/serializer/index.js';\nimport type { Entity, EntityId } from '../types/Entity.js';\nimport type { EntityFacetCounts } from '../types/EntityFacets.js';\nimport type { EntityLoadRequest } from '../types/EntityLoadRequest.js';\n\n/**\n * Discriminates what {@link EntifixEnvelope.data} carries.\n *\n * `command` extends the contract for the transactions layer: a write is issued\n * as a `command`, whose `data` shape lives in `@entifix/transactions` —\n * core only owns the discriminant so every artifact agrees on it.\n *\n * `event` is what actually rides the bus, and it is deliberately not named\n * after one publisher's flow: once a message can be `catalog.published` as\n * easily as `transaction.completed`, `transactionEvent` would be the wrong\n * name for it.\n *\n * ⚠️ **The four transaction-shaped discriminants below are four because they\n * carry four shapes.** `transactionEvent` used to mean all of them, and a\n * discriminant that means several things asserts nothing when it is read —\n * which is what `readTransactionEventEnvelope` was doing on the `202`: checking\n * a name that the record route and the event type both also answered to.\n *\n * - `transactionAccepted` — the `202` accept body, `{ transactionId, state }`.\n * Not a record: it has no `createdAt` and names no entity id yet.\n * - `transactionRecord` — the fold a client polls, a `TransactionRecord`.\n * - `sagaResult` — how a settled multi-step walk ended: which steps ran and\n * what each returned.\n * - `sagaInstance` — the durable instance itself, which is what a resumable\n * coordinator reads and what `GET /api/saga/:id` serves. It differs from\n * `sagaResult` in carrying the inputs and the resume count, because those are\n * what an operator needs to answer *why is this one still here*.\n *\n * `entityMetadata` is the same extension made once more, for the action model:\n * its `data` is an {@link EntityMetadataDocument}, which core does own because\n * both the service that computes it and the controls that render it are already\n * below the layer that would otherwise host it.\n */\nexport type EntifixEnvelopeType =\n | 'entity'\n | 'entityCollection'\n | 'entityPage'\n | 'command'\n | 'event'\n | 'transactionAccepted'\n | 'transactionRecord'\n | 'sagaResult'\n | 'sagaInstance'\n | 'entityMetadata'\n | 'entityFacets';\n\nexport type EntifixEnvelopeMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\n/**\n * A HATEOAS affordance: where the peer can go next from this message. Optional —\n * the envelope stands on its own without links, and only the artifact that owns\n * a route surface (today the REST service) is able to fill them in.\n */\nexport interface EntifixEnvelopeLink {\n rel: string;\n href: string;\n method?: EntifixEnvelopeMethod;\n}\n\n/**\n * The facts a message carries about *itself*, as opposed to about what\n * happened. Present only when the envelope is a bus message.\n *\n * The split rule: `meta` describes the message, `data` describes the\n * occurrence. So `correlationId` belongs here and an outcome's `code` does not.\n *\n * **`source` is never a consumer branch.** It is there for routing,\n * observability and audit. A handler that behaves differently depending on who\n * published re-couples the two services the bus decoupled — which is why .NET's\n * canonical `(sender, eventArgs)` types its sender as bare `object`, making the\n * dependency awkward on purpose. TypeScript cannot reproduce that friction, so\n * here it is a rule rather than a type.\n */\nexport interface EntifixEventMeta {\n /**\n * What happened, in the register's vocabulary: `catalog.published`,\n * `transaction.completed`. Declared in `tools/slices/*.slice.ts` as\n * `publishedEvents`/`subscriptions`, and used verbatim as the AMQP routing\n * key — which is what makes a subscriber's declared interest and its actual\n * queue binding the same string.\n */\n name: string;\n /**\n * Unique per message, and **the** deduplication key. Delivery is\n * at-least-once, so a consumer that must not fold twice keys on this.\n *\n * Not `correlationId`: one flow emits several messages, so correlating and\n * deduplicating are different questions. Keying dedup on the correlation id\n * makes a transaction's `completed` look like a duplicate of its `accepted`.\n */\n id: string;\n /** The emitting **slice** — the unit that owns a store — e.g. `catalog`. */\n source: string;\n /** ISO-8601 emission time. */\n at: string;\n /** Ties every message of one flow together — a transaction id, a saga id. */\n correlationId?: string;\n}\n\nexport interface EntifixEnvelopeMeta {\n type: EntifixEnvelopeType;\n /**\n * The target entity's `key` (falling back to its class name).\n *\n * Optional, because a bus message need not be about an entity at all —\n * `settlement.run.completed` is about a run. What a message *is* lives in\n * {@link EntifixEventMeta.name}; this stays the entity label the HTTP arm\n * routes on.\n */\n entity?: string;\n links?: EntifixEnvelopeLink[];\n /** Present only on a bus message. */\n event?: EntifixEventMeta;\n}\n\n/**\n * One message on the bus: its own metadata, plus the payload describing what\n * happened.\n *\n * Generic in the payload so a publisher keeps its own shape —\n * `DomainEvent<TransactionEvent>` today, `DomainEvent<PublishedOffering>` when\n * a projection's event lands — without the transport learning either.\n */\nexport interface DomainEvent<TData = unknown> extends EntifixEventMeta {\n data: TData;\n}\n\n/**\n * A change to an entity that happened on the server, delivered out-of-band —\n * the `data` of a bus/stream `event` envelope rather than a framing of its own\n *. `entity` is the `key ?? name` an adapter routes on, the same\n * string `entityQueryScope` uses, so a subscriber can invalidate exactly the\n * affected query keys.\n *\n * It lives in core rather than beside the React `ReactiveChannel` that consumes\n * it because both ends need it: the service maps a `TransactionEvent` onto it,\n * and the React packages sit above every tier that does the mapping.\n *\n * Deliberately **no** `transactionId`, timestamp or sequence: all three already\n * exist one level up as `meta.event.correlationId`, `.at` and `.id`, and\n * duplicating them onto the payload is how two sources of the same fact drift.\n */\nexport interface EntityChangeEvent {\n entity: string;\n change: 'created' | 'updated' | 'deleted';\n id: EntityId;\n}\n\n/**\n * The standard message exchanged between entifix artifacts.\n *\n * Every request and response body is an envelope: `meta` describes the payload,\n * `data` is the payload. It is deliberately transport-free — it lives in `core`\n * and knows nothing about HTTP — so the same contract can carry entities over\n * REST today and amqp or websockets later.\n */\nexport interface EntifixEnvelope<TData = unknown> {\n meta: EntifixEnvelopeMeta;\n data: TData;\n}\n\n/**\n * `data` shape when `meta.type` is `entityPage`. Generic in the entity so the\n * echoed `request` keeps its `keyof TEntity` filter/sort types — `EntityLoadRequest`\n * is invariant in its entity, so a non-generic `EntityLoadRequest<Entity>` here\n * would not accept a caller's `EntityLoadRequest<Product>`.\n */\nexport interface SerializedEntityPage<TEntity extends Entity = Entity> {\n items: SerializedEntity[];\n total: number;\n request?: EntityLoadRequest<TEntity>;\n}\n\nexport type EntityEnvelope = EntifixEnvelope<SerializedEntity>;\nexport type EntityCollectionEnvelope = EntifixEnvelope<SerializedEntity[]>;\nexport type EntityPageEnvelope<TEntity extends Entity = Entity> =\n EntifixEnvelope<SerializedEntityPage<TEntity>>;\nexport type EntityMetadataEnvelope = EntifixEnvelope<EntityMetadataDocument>;\nexport type EntityFacetsEnvelope = EntifixEnvelope<EntityFacetCounts>;\n\n/**\n * A bus message on the wire. `meta.event` is always populated, and\n * `readEventEnvelope` is what proves it before a consumer sees the payload.\n */\nexport type EventEnvelope<TData = unknown> = EntifixEnvelope<TData> & {\n meta: EntifixEnvelopeMeta & { event: EntifixEventMeta };\n};\n"],"names":[],"mappings":"AA0LA;;;CAGC,GACD,WAEE"}
1
+ {"version":3,"sources":["../../src/envelope/types.ts"],"sourcesContent":["import type { EntityMetadataDocument } from '../entity-definition/metadata/index.js';\nimport type { SerializedEntity } from '../entity-definition/serializer/index.js';\nimport type { Entity, EntityId } from '../types/Entity.js';\nimport type { EntityFacetCounts } from '../types/EntityFacets.js';\nimport type { EntityLoadRequest } from '../types/EntityLoadRequest.js';\n\n/**\n * Names what {@link EntifixEnvelope.data} carries — a name in the open message\n * registry (`registerMessage`), not a member of a closed union.\n *\n * Core registers only what core owns: `entity`, `entityCollection`,\n * `entityPage`, `entityMetadata`, `entityFacets`, and `event`, whose `data` is\n * looked up by `meta.event.name` instead (`registerEvent`). Every other shape is\n * registered by the package that owns it — `@entifix/transactions` registers\n * `command` and its accept, record and saga shapes — so adding a kind of message\n * never means changing core.\n *\n * A read never trusts the name: `decodeEnvelope` decodes `data` against the\n * registered schema, and an unregistered name is a protocol failure.\n */\nexport type EntifixEnvelopeType = string;\n\nexport type EntifixEnvelopeMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * A HATEOAS affordance: where the peer can go next from this message. Optional —\n * the envelope stands on its own without links, and only the artifact that owns\n * a route surface (today the REST service) is able to fill them in.\n */\nexport interface EntifixEnvelopeLink {\n rel: string;\n href: string;\n method?: EntifixEnvelopeMethod;\n}\n\n/**\n * The facts a message carries about *itself*, as opposed to about what\n * happened. Present only when the envelope is a bus message.\n *\n * The split rule: `meta` describes the message, `data` describes the\n * occurrence. So `correlationId` belongs here and an outcome's `code` does not.\n *\n * **`source` is never a consumer branch.** It is there for routing,\n * observability and audit. A handler that behaves differently depending on who\n * published re-couples the two services the bus decoupled — which is why .NET's\n * canonical `(sender, eventArgs)` types its sender as bare `object`, making the\n * dependency awkward on purpose. TypeScript cannot reproduce that friction, so\n * here it is a rule rather than a type.\n */\nexport interface EntifixEventMeta {\n /**\n * What happened, in the register's vocabulary: `catalog.published`,\n * `transaction.completed`. Declared in `tools/slices/*.slice.ts` as\n * `publishedEvents`/`subscriptions`, and used verbatim as the AMQP routing\n * key — which is what makes a subscriber's declared interest and its actual\n * queue binding the same string.\n */\n name: string;\n /**\n * Unique per message, and **the** deduplication key. Delivery is\n * at-least-once, so a consumer that must not fold twice keys on this.\n *\n * Not `correlationId`: one flow emits several messages, so correlating and\n * deduplicating are different questions. Keying dedup on the correlation id\n * makes a transaction's `completed` look like a duplicate of its `accepted`.\n */\n id: string;\n /** The emitting **slice** — the unit that owns a store — e.g. `catalog`. */\n source: string;\n /** ISO-8601 emission time. */\n at: string;\n /** Ties every message of one flow together — a transaction id, a flow id. */\n correlationId?: string;\n /**\n * The aggregate this message is about — the unit its `version` counts, and\n * the unit an outbox keeps order within. A consumer discards a message older\n * than the last version it applied **for this aggregate**.\n */\n aggregate?: AggregateRef;\n /**\n * The version of the aggregate this message describes. Required on a\n * message registered `versioned`, and what a consumer orders on: one that\n * already applied version `n` discards a late `n - 1` instead of letting it\n * overwrite (`discardIfStale`).\n */\n version?: number;\n /**\n * Who may receive this message. Absent or empty, it reaches **nobody** —\n * `audienceAdmits` fails closed, so a publisher that forgot to address a\n * message leaks nothing.\n */\n audience?: readonly AudienceEntry[];\n}\n\n/** Names one aggregate: its type and its id, `{ type: 'product-order', id }`. */\nexport interface AggregateRef {\n type: string;\n id: string;\n}\n\n/**\n * One recipient of a message: every member of an organization, one party, or\n * whoever holds a flow's capability — whose SHA-256 digest is `digest`, so the\n * audience never carries the credential itself.\n */\nexport interface AudienceEntry {\n kind: 'organization' | 'party' | 'flow';\n id: string;\n digest?: string;\n}\n\nexport interface EntifixEnvelopeMeta {\n type: EntifixEnvelopeType;\n /**\n * The target entity's `key` (falling back to its class name).\n *\n * Optional, because a bus message need not be about an entity at all —\n * `settlement.run.completed` is about a run. What a message *is* lives in\n * {@link EntifixEventMeta.name}; this stays the entity label the HTTP arm\n * routes on.\n */\n entity?: string;\n links?: EntifixEnvelopeLink[];\n /** Present only on a bus message. */\n event?: EntifixEventMeta;\n}\n\n/**\n * One message on the bus: its own metadata, plus the payload describing what\n * happened.\n *\n * Generic in the payload so a publisher keeps its own shape —\n * `DomainEvent<TransactionEvent>` today, `DomainEvent<PublishedOffering>` when\n * a projection's event lands — without the transport learning either.\n */\nexport interface DomainEvent<TData = unknown> extends EntifixEventMeta {\n data: TData;\n}\n\n/**\n * A change to an entity that happened on the server, delivered out-of-band —\n * the `data` of a bus/stream `event` envelope rather than a framing of its own\n *. `entity` is the `key ?? name` an adapter routes on, the same\n * string `entityQueryScope` uses, so a subscriber can invalidate exactly the\n * affected query keys.\n *\n * It lives in core rather than beside the React `ReactiveChannel` that consumes\n * it because both ends need it: the service maps a `TransactionEvent` onto it,\n * and the React packages sit above every tier that does the mapping.\n *\n * Deliberately **no** `transactionId`, timestamp or sequence: all three already\n * exist one level up as `meta.event.correlationId`, `.at` and `.id`, and\n * duplicating them onto the payload is how two sources of the same fact drift.\n */\nexport interface EntityChangeEvent {\n entity: string;\n change: 'created' | 'updated' | 'deleted';\n id: EntityId;\n}\n\n/**\n * The standard message exchanged between entifix artifacts.\n *\n * Every request and response body is an envelope: `meta` describes the payload,\n * `data` is the payload. It is deliberately transport-free — it lives in `core`\n * and knows nothing about HTTP — so the same contract can carry entities over\n * REST today and amqp or websockets later.\n */\nexport interface EntifixEnvelope<TData = unknown> {\n meta: EntifixEnvelopeMeta;\n data: TData;\n}\n\n/**\n * `data` shape when `meta.type` is `entityPage`. Generic in the entity so the\n * echoed `request` keeps its `keyof TEntity` filter/sort types — `EntityLoadRequest`\n * is invariant in its entity, so a non-generic `EntityLoadRequest<Entity>` here\n * would not accept a caller's `EntityLoadRequest<Product>`.\n */\nexport interface SerializedEntityPage<TEntity extends Entity = Entity> {\n items: SerializedEntity[];\n total: number;\n request?: EntityLoadRequest<TEntity>;\n}\n\nexport type EntityEnvelope = EntifixEnvelope<SerializedEntity>;\nexport type EntityCollectionEnvelope = EntifixEnvelope<SerializedEntity[]>;\nexport type EntityPageEnvelope<TEntity extends Entity = Entity> =\n EntifixEnvelope<SerializedEntityPage<TEntity>>;\nexport type EntityMetadataEnvelope = EntifixEnvelope<EntityMetadataDocument>;\nexport type EntityFacetsEnvelope = EntifixEnvelope<EntityFacetCounts>;\n\n/**\n * A bus message on the wire. `meta.event` is always populated, and\n * `decodeEvent` is what proves it before a consumer sees the payload.\n */\nexport type EventEnvelope<TData = unknown> = EntifixEnvelope<TData> & {\n meta: EntifixEnvelopeMeta & { event: EntifixEventMeta };\n};\n"],"names":[],"mappings":"AAgMA;;;CAGC,GACD,WAEE"}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The one idempotency header, browser to shell and coordinator to participant
3
+ * (draft-ietf-httpapi-idempotency-key-header). Lower case, as a Node request
4
+ * presents every header name.
5
+ */
6
+ export declare const IDEMPOTENCY_KEY_HEADER = "idempotency-key";
7
+ /**
8
+ * Formats a key as an RFC 9651 String item: quoted, with `\` and `"` escaped.
9
+ * Refuses a key with a character a String cannot carry, rather than sending a
10
+ * header the participant would refuse.
11
+ */
12
+ export declare const formatIdempotencyKey: (key: string) => string;
13
+ /**
14
+ * Parses an `Idempotency-Key` header as an RFC 9651 String item. Answers the
15
+ * key, or `undefined` for a header that is absent, empty, unquoted, badly
16
+ * escaped or carries anything after its closing quote — every one of which a
17
+ * route treats as "no key".
18
+ */
19
+ export declare const parseIdempotencyKey: (header: string | undefined) => string | undefined;
20
+ //# sourceMappingURL=idempotency-key.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idempotency-key.d.ts","sourceRoot":"","sources":["../../src/idempotency/idempotency-key.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,oBAAoB,CAAC;AAKxD;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,GAAI,KAAK,MAAM,KAAG,MAMlD,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,mBAAmB,GAC9B,QAAQ,MAAM,GAAG,SAAS,KACzB,MAAM,GAAG,SAqBX,CAAC"}
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The one idempotency header, browser to shell and coordinator to participant
3
+ * (draft-ietf-httpapi-idempotency-key-header). Lower case, as a Node request
4
+ * presents every header name.
5
+ */ export const IDEMPOTENCY_KEY_HEADER = 'idempotency-key';
6
+ /** Printable ASCII, the only characters an RFC 9651 String may hold. */ const PRINTABLE = /^[\x20-\x7e]*$/;
7
+ /**
8
+ * Formats a key as an RFC 9651 String item: quoted, with `\` and `"` escaped.
9
+ * Refuses a key with a character a String cannot carry, rather than sending a
10
+ * header the participant would refuse.
11
+ */ export const formatIdempotencyKey = (key)=>{
12
+ if (key === '' || !PRINTABLE.test(key)) throw new Error('an Idempotency-Key is a non-empty run of printable ASCII characters');
13
+ return `"${key.replace(/[\\"]/g, (char)=>`\\${char}`)}"`;
14
+ };
15
+ /**
16
+ * Parses an `Idempotency-Key` header as an RFC 9651 String item. Answers the
17
+ * key, or `undefined` for a header that is absent, empty, unquoted, badly
18
+ * escaped or carries anything after its closing quote — every one of which a
19
+ * route treats as "no key".
20
+ */ export const parseIdempotencyKey = (header)=>{
21
+ const value = header == null ? void 0 : header.trim();
22
+ if (value === undefined || value.length < 2 || !value.startsWith('"')) return undefined;
23
+ let key = '';
24
+ for(let index = 1; index < value.length; index += 1){
25
+ const char = value.charAt(index);
26
+ if (char === '\\') {
27
+ const next = value.charAt(index + 1);
28
+ if (next !== '\\' && next !== '"') return undefined;
29
+ key += next;
30
+ index += 1;
31
+ } else if (char === '"') {
32
+ return index === value.length - 1 && key !== '' ? key : undefined;
33
+ } else if (!PRINTABLE.test(char)) {
34
+ return undefined;
35
+ } else {
36
+ key += char;
37
+ }
38
+ }
39
+ return undefined;
40
+ };
41
+
42
+ //# sourceMappingURL=idempotency-key.js.map