@entifix/react-integration 0.12.1 → 0.14.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 (60) hide show
  1. package/dist/event-source.d.ts +5 -4
  2. package/dist/event-source.d.ts.map +1 -1
  3. package/dist/event-source.js +5 -4
  4. package/dist/event-source.js.map +1 -1
  5. package/dist/hooks/use-data-loading/use-data-loading.d.ts +2 -2
  6. package/dist/hooks/use-data-loading/use-data-loading.d.ts.map +1 -1
  7. package/dist/hooks/use-data-loading/use-data-loading.js.map +1 -1
  8. package/dist/hooks/use-data-loading/use-data-loading.types.d.ts +3 -3
  9. package/dist/hooks/use-data-loading/use-data-loading.types.d.ts.map +1 -1
  10. package/dist/hooks/use-data-loading/use-data-loading.types.js.map +1 -1
  11. package/dist/hooks/use-entity-link-source/use-entity-link-source.d.ts.map +1 -1
  12. package/dist/hooks/use-entity-link-source/use-entity-link-source.js.map +1 -1
  13. package/dist/hooks/use-entity-link-source/use-entity-link-source.types.d.ts +3 -3
  14. package/dist/hooks/use-entity-link-source/use-entity-link-source.types.d.ts.map +1 -1
  15. package/dist/hooks/use-entity-link-source/use-entity-link-source.types.js.map +1 -1
  16. package/dist/hooks/use-entity-mutation/use-entity-mutation.d.ts +2 -2
  17. package/dist/hooks/use-entity-mutation/use-entity-mutation.d.ts.map +1 -1
  18. package/dist/hooks/use-entity-mutation/use-entity-mutation.js.map +1 -1
  19. package/dist/hooks/use-entity-mutation/use-entity-mutation.types.d.ts +4 -4
  20. package/dist/hooks/use-entity-mutation/use-entity-mutation.types.d.ts.map +1 -1
  21. package/dist/hooks/use-entity-mutation/use-entity-mutation.types.js.map +1 -1
  22. package/dist/hooks/use-entity-record/use-entity-record.d.ts +2 -2
  23. package/dist/hooks/use-entity-record/use-entity-record.d.ts.map +1 -1
  24. package/dist/hooks/use-entity-record/use-entity-record.js.map +1 -1
  25. package/dist/hooks/use-entity-record/use-entity-record.types.d.ts +3 -3
  26. package/dist/hooks/use-entity-record/use-entity-record.types.d.ts.map +1 -1
  27. package/dist/hooks/use-entity-record/use-entity-record.types.js.map +1 -1
  28. package/dist/index.d.ts +5 -0
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +5 -0
  31. package/dist/index.js.map +1 -1
  32. package/dist/pending/pending-flow-store.d.ts +86 -0
  33. package/dist/pending/pending-flow-store.d.ts.map +1 -0
  34. package/dist/pending/pending-flow-store.js +124 -0
  35. package/dist/pending/pending-flow-store.js.map +1 -0
  36. package/dist/pending/use-optimistic-mutation.d.ts +61 -0
  37. package/dist/pending/use-optimistic-mutation.d.ts.map +1 -0
  38. package/dist/pending/use-optimistic-mutation.js +88 -0
  39. package/dist/pending/use-optimistic-mutation.js.map +1 -0
  40. package/dist/pending/use-pending-flow-settlement.d.ts +43 -0
  41. package/dist/pending/use-pending-flow-settlement.d.ts.map +1 -0
  42. package/dist/pending/use-pending-flow-settlement.js +126 -0
  43. package/dist/pending/use-pending-flow-settlement.js.map +1 -0
  44. package/dist/reactive/event-source-push-channel.d.ts +56 -0
  45. package/dist/reactive/event-source-push-channel.d.ts.map +1 -0
  46. package/dist/reactive/event-source-push-channel.js +118 -0
  47. package/dist/reactive/event-source-push-channel.js.map +1 -0
  48. package/dist/reactive/push-channel.d.ts +69 -0
  49. package/dist/reactive/push-channel.d.ts.map +1 -0
  50. package/dist/reactive/push-channel.js +33 -0
  51. package/dist/reactive/push-channel.js.map +1 -0
  52. package/dist/reactive/push-router.d.ts +26 -0
  53. package/dist/reactive/push-router.d.ts.map +1 -0
  54. package/dist/reactive/push-router.js +64 -0
  55. package/dist/reactive/push-router.js.map +1 -0
  56. package/dist/reactive/use-reactive-cache.d.ts +49 -0
  57. package/dist/reactive/use-reactive-cache.d.ts.map +1 -0
  58. package/dist/reactive/use-reactive-cache.js +106 -0
  59. package/dist/reactive/use-reactive-cache.js.map +1 -0
  60. package/package.json +8 -8
@@ -0,0 +1,86 @@
1
+ import type { DomainEvent, EntifixFailure } from '@entifix/core';
2
+ import { type PushTopic } from '../reactive/push-channel.js';
3
+ /**
4
+ * The shape version of what a store persists. A stored value at any other
5
+ * version is discarded, never migrated: the store is a cache of in-flight
6
+ * work, and losing it costs a re-read
7
+ * ([ADR 0022](../../../../../docs/adr/0022-two-settle-modes-and-the-pending-flow-store.md)).
8
+ */
9
+ export declare const PENDING_FLOW_STORE_VERSION = 1;
10
+ /** One write the server handed to a flow, waiting for the flow's outcome. */
11
+ export interface PendingFlow {
12
+ readonly flowId: string;
13
+ /** Where the outcome is pushed: `flow:<flowId>`. */
14
+ readonly topic: PushTopic;
15
+ /** ISO-8601, when the write was answered `202`. */
16
+ readonly createdAt: string;
17
+ /** The flow's `status` link, read when its push may have been missed. */
18
+ readonly status?: string;
19
+ /** What the write meant, for the screen that resumes it. JSON only. */
20
+ readonly intent?: unknown;
21
+ }
22
+ /**
23
+ * How a pending flow ended. A `failed` outcome with no `failure` is a flow
24
+ * nobody could account for within the age bound: it is no longer shown as
25
+ * pending, and there is nothing to tell the user why.
26
+ */
27
+ export type FlowOutcome = {
28
+ readonly kind: 'confirmed';
29
+ readonly event?: DomainEvent;
30
+ } | {
31
+ readonly kind: 'failed';
32
+ readonly failure?: EntifixFailure;
33
+ };
34
+ /**
35
+ * Where a store persists, supplied by the host and scoped by it to one
36
+ * principal. Zustand's `StateStorage` satisfies it.
37
+ */
38
+ export interface PendingFlowStorage {
39
+ getItem(name: string): string | null | Promise<string | null>;
40
+ setItem(name: string, value: string): unknown;
41
+ }
42
+ export interface PendingFlowStoreOptions {
43
+ /** Omitted, the store lives in memory and a reload forgets it. */
44
+ readonly storage?: PendingFlowStorage;
45
+ /** The storage key. Defaults to `entifix.pending-flows`. */
46
+ readonly key?: string;
47
+ /**
48
+ * An anonymous scope keeps flow ids and their age only: an intent or a
49
+ * status link could carry personal data or a capability, and nothing scopes
50
+ * an anonymous storage to one person.
51
+ */
52
+ readonly anonymous?: boolean;
53
+ readonly now?: () => Date;
54
+ }
55
+ export interface PendingFlowInput {
56
+ readonly flowId: string;
57
+ readonly status?: string;
58
+ readonly intent?: unknown;
59
+ }
60
+ export interface PendingFlowStore {
61
+ /** Settles once whatever was persisted has been read back. */
62
+ readonly ready: Promise<void>;
63
+ /** The pending flows, oldest first. The same array until something changes. */
64
+ list(): readonly PendingFlow[];
65
+ /**
66
+ * Records a pending flow. Throws a `TypeError`, and records nothing, when
67
+ * the intent is not JSON: a value that cannot be read back must never reach
68
+ * storage.
69
+ */
70
+ add(input: PendingFlowInput): PendingFlow;
71
+ /**
72
+ * Ends a pending flow with its outcome. Answers `true` only for the call
73
+ * that ended it, so a redelivered outcome is told apart from the first.
74
+ */
75
+ settle(flowId: string, outcome: FlowOutcome): boolean;
76
+ /** Runs whenever the list changes. */
77
+ subscribe(listener: () => void): () => void;
78
+ /** Runs once, when the named flow settles. */
79
+ onSettled(flowId: string, listener: (outcome: FlowOutcome) => void): () => void;
80
+ }
81
+ /**
82
+ * The pending-flow store: held in memory, written through to the host's
83
+ * storage as `{ v, flows }`, and read back from it once on creation.
84
+ */
85
+ export declare function makePendingFlowStore({ storage, key, anonymous, now, }?: PendingFlowStoreOptions): PendingFlowStore;
86
+ //# sourceMappingURL=pending-flow-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pending-flow-store.d.ts","sourceRoot":"","sources":["../../src/pending/pending-flow-store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAGjE,OAAO,EAAa,KAAK,SAAS,EAAE,MAAM,6BAA6B,CAAC;AAExE;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,IAAI,CAAC;AAE5C,6EAA6E;AAC7E,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,oDAAoD;IACpD,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC;IAC1B,mDAAmD;IACnD,QAAQ,CAAC,SAAS,EAAE,MAAM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SAAS,WAAW,EAAE,CAAC;IAC/B;;;;OAIG;IACH,GAAG,CAAC,KAAK,EAAE,gBAAgB,GAAG,WAAW,CAAC;IAC1C;;;OAGG;IACH,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,GAAG,OAAO,CAAC;IACtD,sCAAsC;IACtC,SAAS,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC;IAC5C,8CAA8C;IAC9C,SAAS,CACP,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,CAAC,OAAO,EAAE,WAAW,KAAK,IAAI,GACvC,MAAM,IAAI,CAAC;CACf;AAsDD;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,EACnC,OAAO,EACP,GAA6B,EAC7B,SAAiB,EACjB,GAAsB,GACvB,GAAE,uBAA4B,GAAG,gBAAgB,CAiFjD"}
@@ -0,0 +1,124 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ import { Effect, Result, Schema } from 'effect';
3
+ import { flowTopic } from '../reactive/push-channel.js';
4
+ /**
5
+ * The shape version of what a store persists. A stored value at any other
6
+ * version is discarded, never migrated: the store is a cache of in-flight
7
+ * work, and losing it costs a re-read
8
+ * ([ADR 0022](../../../../../docs/adr/0022-two-settle-modes-and-the-pending-flow-store.md)).
9
+ */ export const PENDING_FLOW_STORE_VERSION = 1;
10
+ const isJson = (value)=>{
11
+ if (value === null) return true;
12
+ switch(typeof value){
13
+ case 'string':
14
+ case 'boolean':
15
+ return true;
16
+ case 'number':
17
+ return Number.isFinite(value);
18
+ case 'object':
19
+ {
20
+ if (Array.isArray(value)) return value.every(isJson);
21
+ const prototype = Object.getPrototypeOf(value);
22
+ return (prototype === Object.prototype || prototype === null) && Object.values(value).every(isJson);
23
+ }
24
+ default:
25
+ return false;
26
+ }
27
+ };
28
+ const Stored = Schema.Struct({
29
+ v: Schema.Literal(PENDING_FLOW_STORE_VERSION),
30
+ flows: Schema.Array(Schema.Struct({
31
+ flowId: Schema.String,
32
+ createdAt: Schema.String,
33
+ status: Schema.optionalKey(Schema.String),
34
+ intent: Schema.optionalKey(Schema.Unknown)
35
+ }))
36
+ });
37
+ // Whatever the storage holds, as pending flows: nothing at all when it is
38
+ // missing, unreadable, or at another version.
39
+ const decodeStored = (raw)=>{
40
+ if (raw === null) return [];
41
+ const decoded = Effect.runSync(Effect.result(Effect.flatMap(Effect.try(()=>JSON.parse(raw)), Schema.decodeUnknownEffect(Stored))));
42
+ if (Result.isFailure(decoded)) return [];
43
+ return decoded.success.flows.map((flow)=>_extends({}, flow, {
44
+ topic: flowTopic(flow.flowId)
45
+ }));
46
+ };
47
+ /**
48
+ * The pending-flow store: held in memory, written through to the host's
49
+ * storage as `{ v, flows }`, and read back from it once on creation.
50
+ */ export function makePendingFlowStore({ storage, key = 'entifix.pending-flows', anonymous = false, now = ()=>new Date() } = {}) {
51
+ let flows = [];
52
+ const listeners = new Set();
53
+ const settledListeners = new Map();
54
+ let writing = Promise.resolve();
55
+ const changed = (next)=>{
56
+ flows = next;
57
+ for (const listener of listeners)listener();
58
+ };
59
+ const persist = ()=>{
60
+ if (storage === undefined) return;
61
+ const value = JSON.stringify({
62
+ v: PENDING_FLOW_STORE_VERSION,
63
+ flows
64
+ });
65
+ // Serialized, so a slow write never lands after a later one. A write that
66
+ // fails costs only the reload-survival of what is pending.
67
+ writing = writing.then(()=>storage.setItem(key, value)).catch(()=>undefined);
68
+ };
69
+ const ready = storage === undefined ? Promise.resolve() : Promise.resolve().then(()=>storage.getItem(key)).then((raw)=>decodeStored(raw), ()=>[]).then((stored)=>{
70
+ const held = new Set(flows.map((flow)=>flow.flowId));
71
+ const restored = stored.filter((flow)=>!held.has(flow.flowId));
72
+ if (restored.length > 0) changed([
73
+ ...restored,
74
+ ...flows
75
+ ]);
76
+ });
77
+ return {
78
+ ready,
79
+ list: ()=>flows,
80
+ add ({ flowId, status, intent }) {
81
+ if (!anonymous && intent !== undefined && !isJson(intent)) throw new TypeError(`the intent of pending flow '${flowId}' is not JSON, so it cannot be stored`);
82
+ const flow = _extends({
83
+ flowId,
84
+ topic: flowTopic(flowId),
85
+ createdAt: now().toISOString()
86
+ }, anonymous || status === undefined ? {} : {
87
+ status
88
+ }, anonymous || intent === undefined ? {} : {
89
+ intent
90
+ });
91
+ changed([
92
+ ...flows.filter((held)=>held.flowId !== flowId),
93
+ flow
94
+ ]);
95
+ persist();
96
+ return flow;
97
+ },
98
+ settle (flowId, outcome) {
99
+ if (!flows.some((flow)=>flow.flowId === flowId)) return false;
100
+ changed(flows.filter((flow)=>flow.flowId !== flowId));
101
+ persist();
102
+ const waiting = settledListeners.get(flowId);
103
+ settledListeners.delete(flowId);
104
+ for (const listener of waiting != null ? waiting : [])listener(outcome);
105
+ return true;
106
+ },
107
+ subscribe (listener) {
108
+ listeners.add(listener);
109
+ return ()=>{
110
+ listeners.delete(listener);
111
+ };
112
+ },
113
+ onSettled (flowId, listener) {
114
+ var _settledListeners_get;
115
+ const waiting = (_settledListeners_get = settledListeners.get(flowId)) != null ? _settledListeners_get : new Set();
116
+ settledListeners.set(flowId, waiting.add(listener));
117
+ return ()=>{
118
+ waiting.delete(listener);
119
+ };
120
+ }
121
+ };
122
+ }
123
+
124
+ //# sourceMappingURL=pending-flow-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/pending/pending-flow-store.ts"],"sourcesContent":["import type { DomainEvent, EntifixFailure } from '@entifix/core';\nimport { Effect, Result, Schema } from 'effect';\n\nimport { flowTopic, type PushTopic } from '../reactive/push-channel.js';\n\n/**\n * The shape version of what a store persists. A stored value at any other\n * version is discarded, never migrated: the store is a cache of in-flight\n * work, and losing it costs a re-read\n * ([ADR 0022](../../../../../docs/adr/0022-two-settle-modes-and-the-pending-flow-store.md)).\n */\nexport const PENDING_FLOW_STORE_VERSION = 1;\n\n/** One write the server handed to a flow, waiting for the flow's outcome. */\nexport interface PendingFlow {\n readonly flowId: string;\n /** Where the outcome is pushed: `flow:<flowId>`. */\n readonly topic: PushTopic;\n /** ISO-8601, when the write was answered `202`. */\n readonly createdAt: string;\n /** The flow's `status` link, read when its push may have been missed. */\n readonly status?: string;\n /** What the write meant, for the screen that resumes it. JSON only. */\n readonly intent?: unknown;\n}\n\n/**\n * How a pending flow ended. A `failed` outcome with no `failure` is a flow\n * nobody could account for within the age bound: it is no longer shown as\n * pending, and there is nothing to tell the user why.\n */\nexport type FlowOutcome =\n | { readonly kind: 'confirmed'; readonly event?: DomainEvent }\n | { readonly kind: 'failed'; readonly failure?: EntifixFailure };\n\n/**\n * Where a store persists, supplied by the host and scoped by it to one\n * principal. Zustand's `StateStorage` satisfies it.\n */\nexport interface PendingFlowStorage {\n getItem(name: string): string | null | Promise<string | null>;\n setItem(name: string, value: string): unknown;\n}\n\nexport interface PendingFlowStoreOptions {\n /** Omitted, the store lives in memory and a reload forgets it. */\n readonly storage?: PendingFlowStorage;\n /** The storage key. Defaults to `entifix.pending-flows`. */\n readonly key?: string;\n /**\n * An anonymous scope keeps flow ids and their age only: an intent or a\n * status link could carry personal data or a capability, and nothing scopes\n * an anonymous storage to one person.\n */\n readonly anonymous?: boolean;\n readonly now?: () => Date;\n}\n\nexport interface PendingFlowInput {\n readonly flowId: string;\n readonly status?: string;\n readonly intent?: unknown;\n}\n\nexport interface PendingFlowStore {\n /** Settles once whatever was persisted has been read back. */\n readonly ready: Promise<void>;\n /** The pending flows, oldest first. The same array until something changes. */\n list(): readonly PendingFlow[];\n /**\n * Records a pending flow. Throws a `TypeError`, and records nothing, when\n * the intent is not JSON: a value that cannot be read back must never reach\n * storage.\n */\n add(input: PendingFlowInput): PendingFlow;\n /**\n * Ends a pending flow with its outcome. Answers `true` only for the call\n * that ended it, so a redelivered outcome is told apart from the first.\n */\n settle(flowId: string, outcome: FlowOutcome): boolean;\n /** Runs whenever the list changes. */\n subscribe(listener: () => void): () => void;\n /** Runs once, when the named flow settles. */\n onSettled(\n flowId: string,\n listener: (outcome: FlowOutcome) => void,\n ): () => void;\n}\n\nconst isJson = (value: unknown): boolean => {\n if (value === null) return true;\n switch (typeof value) {\n case 'string':\n case 'boolean':\n return true;\n case 'number':\n return Number.isFinite(value);\n case 'object': {\n if (Array.isArray(value)) return value.every(isJson);\n const prototype = Object.getPrototypeOf(value) as unknown;\n return (\n (prototype === Object.prototype || prototype === null) &&\n Object.values(value).every(isJson)\n );\n }\n default:\n return false;\n }\n};\n\nconst Stored = Schema.Struct({\n v: Schema.Literal(PENDING_FLOW_STORE_VERSION),\n flows: Schema.Array(\n Schema.Struct({\n flowId: Schema.String,\n createdAt: Schema.String,\n status: Schema.optionalKey(Schema.String),\n intent: Schema.optionalKey(Schema.Unknown),\n }),\n ),\n});\n\n// Whatever the storage holds, as pending flows: nothing at all when it is\n// missing, unreadable, or at another version.\nconst decodeStored = (raw: string | null): readonly PendingFlow[] => {\n if (raw === null) return [];\n const decoded = Effect.runSync(\n Effect.result(\n Effect.flatMap(\n Effect.try(() => JSON.parse(raw) as unknown),\n Schema.decodeUnknownEffect(Stored),\n ),\n ),\n );\n if (Result.isFailure(decoded)) return [];\n return decoded.success.flows.map(flow => ({\n ...flow,\n topic: flowTopic(flow.flowId),\n }));\n};\n\n/**\n * The pending-flow store: held in memory, written through to the host's\n * storage as `{ v, flows }`, and read back from it once on creation.\n */\nexport function makePendingFlowStore({\n storage,\n key = 'entifix.pending-flows',\n anonymous = false,\n now = () => new Date(),\n}: PendingFlowStoreOptions = {}): PendingFlowStore {\n let flows: readonly PendingFlow[] = [];\n const listeners = new Set<() => void>();\n const settledListeners = new Map<\n string,\n Set<(outcome: FlowOutcome) => void>\n >();\n let writing: Promise<unknown> = Promise.resolve();\n\n const changed = (next: readonly PendingFlow[]): void => {\n flows = next;\n for (const listener of listeners) listener();\n };\n\n const persist = (): void => {\n if (storage === undefined) return;\n const value = JSON.stringify({ v: PENDING_FLOW_STORE_VERSION, flows });\n // Serialized, so a slow write never lands after a later one. A write that\n // fails costs only the reload-survival of what is pending.\n writing = writing\n .then(() => storage.setItem(key, value))\n .catch(() => undefined);\n };\n\n const ready =\n storage === undefined\n ? Promise.resolve()\n : Promise.resolve()\n .then(() => storage.getItem(key))\n .then(\n raw => decodeStored(raw),\n () => [],\n )\n .then(stored => {\n const held = new Set(flows.map(flow => flow.flowId));\n const restored = stored.filter(flow => !held.has(flow.flowId));\n if (restored.length > 0) changed([...restored, ...flows]);\n });\n\n return {\n ready,\n list: () => flows,\n add({ flowId, status, intent }) {\n if (!anonymous && intent !== undefined && !isJson(intent))\n throw new TypeError(\n `the intent of pending flow '${flowId}' is not JSON, so it cannot be stored`,\n );\n const flow: PendingFlow = {\n flowId,\n topic: flowTopic(flowId),\n createdAt: now().toISOString(),\n ...(anonymous || status === undefined ? {} : { status }),\n ...(anonymous || intent === undefined ? {} : { intent }),\n };\n changed([...flows.filter(held => held.flowId !== flowId), flow]);\n persist();\n return flow;\n },\n settle(flowId, outcome) {\n if (!flows.some(flow => flow.flowId === flowId)) return false;\n changed(flows.filter(flow => flow.flowId !== flowId));\n persist();\n const waiting = settledListeners.get(flowId);\n settledListeners.delete(flowId);\n for (const listener of waiting ?? []) listener(outcome);\n return true;\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n onSettled(flowId, listener) {\n const waiting = settledListeners.get(flowId) ?? new Set();\n settledListeners.set(flowId, waiting.add(listener));\n return () => {\n waiting.delete(listener);\n };\n },\n };\n}\n"],"names":["Effect","Result","Schema","flowTopic","PENDING_FLOW_STORE_VERSION","isJson","value","Number","isFinite","Array","isArray","every","prototype","Object","getPrototypeOf","values","Stored","Struct","v","Literal","flows","flowId","String","createdAt","status","optionalKey","intent","Unknown","decodeStored","raw","decoded","runSync","result","flatMap","try","JSON","parse","decodeUnknownEffect","isFailure","success","map","flow","topic","makePendingFlowStore","storage","key","anonymous","now","Date","listeners","Set","settledListeners","Map","writing","Promise","resolve","changed","next","listener","persist","undefined","stringify","then","setItem","catch","ready","getItem","stored","held","restored","filter","has","length","list","add","TypeError","toISOString","settle","outcome","some","waiting","get","delete","subscribe","onSettled","set"],"mappings":";AACA,SAASA,MAAM,EAAEC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAEhD,SAASC,SAAS,QAAwB,8BAA8B;AAExE;;;;;CAKC,GACD,OAAO,MAAMC,6BAA6B,EAAE;AA8E5C,MAAMC,SAAS,CAACC;IACd,IAAIA,UAAU,MAAM,OAAO;IAC3B,OAAQ,OAAOA;QACb,KAAK;QACL,KAAK;YACH,OAAO;QACT,KAAK;YACH,OAAOC,OAAOC,QAAQ,CAACF;QACzB,KAAK;YAAU;gBACb,IAAIG,MAAMC,OAAO,CAACJ,QAAQ,OAAOA,MAAMK,KAAK,CAACN;gBAC7C,MAAMO,YAAYC,OAAOC,cAAc,CAACR;gBACxC,OACE,AAACM,CAAAA,cAAcC,OAAOD,SAAS,IAAIA,cAAc,IAAG,KACpDC,OAAOE,MAAM,CAACT,OAAOK,KAAK,CAACN;YAE/B;QACA;YACE,OAAO;IACX;AACF;AAEA,MAAMW,SAASd,OAAOe,MAAM,CAAC;IAC3BC,GAAGhB,OAAOiB,OAAO,CAACf;IAClBgB,OAAOlB,OAAOO,KAAK,CACjBP,OAAOe,MAAM,CAAC;QACZI,QAAQnB,OAAOoB,MAAM;QACrBC,WAAWrB,OAAOoB,MAAM;QACxBE,QAAQtB,OAAOuB,WAAW,CAACvB,OAAOoB,MAAM;QACxCI,QAAQxB,OAAOuB,WAAW,CAACvB,OAAOyB,OAAO;IAC3C;AAEJ;AAEA,0EAA0E;AAC1E,8CAA8C;AAC9C,MAAMC,eAAe,CAACC;IACpB,IAAIA,QAAQ,MAAM,OAAO,EAAE;IAC3B,MAAMC,UAAU9B,OAAO+B,OAAO,CAC5B/B,OAAOgC,MAAM,CACXhC,OAAOiC,OAAO,CACZjC,OAAOkC,GAAG,CAAC,IAAMC,KAAKC,KAAK,CAACP,OAC5B3B,OAAOmC,mBAAmB,CAACrB;IAIjC,IAAIf,OAAOqC,SAAS,CAACR,UA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QE,MAAM,CAACxB;YACjB;QACF;IACF;AACF"}
@@ -0,0 +1,61 @@
1
+ import type { EntifixFailure, WriteResult } from '@entifix/core';
2
+ import { Effect } from 'effect';
3
+ import { type ReactNode } from 'react';
4
+ import type { PendingFlowStore } from './pending-flow-store.js';
5
+ /** Makes `store` the one every optimistic mutation below records into. */
6
+ export declare function PendingFlowStoreProvider({ store, children, }: {
7
+ readonly store: PendingFlowStore;
8
+ readonly children: ReactNode;
9
+ }): import("react").JSX.Element;
10
+ /** The store a {@link PendingFlowStoreProvider} above provides, if any. */
11
+ export declare const usePendingFlowStore: () => PendingFlowStore | undefined;
12
+ /**
13
+ * Where an optimistic write stands. `settled` is a write that happened;
14
+ * `pending`, `confirmed` and `failed` are a flow's, and nothing finer: a
15
+ * `202` never says a payment was captured or an order placed, so neither may
16
+ * the screen.
17
+ */
18
+ export type OptimisticStatus = 'idle' | 'running' | 'settled' | 'pending' | 'confirmed' | 'failed';
19
+ export interface UseOptimisticMutationOptions<TVariables, TValue, TContext> {
20
+ /** The write: a save, a delete or a verb, answering either mode. */
21
+ readonly write: (variables: TVariables) => Effect.Effect<WriteResult<TValue>, EntifixFailure>;
22
+ /** Applies the write to what the screen shows, before it is sent. */
23
+ readonly apply?: (variables: TVariables) => TContext;
24
+ /**
25
+ * Undoes `apply`: on a write that failed, and on a flow that failed. It runs
26
+ * for a flow even after the screen that started it unmounted.
27
+ */
28
+ readonly rollback?: (variables: TVariables, context: TContext) => void;
29
+ /** Runs when a flow this mutation started completed. */
30
+ readonly confirm?: (variables: TVariables, context: TContext) => void;
31
+ /** What a pending write means, stored beside it. JSON only. */
32
+ readonly intent?: (variables: TVariables) => unknown;
33
+ /** Defaults to the {@link PendingFlowStoreProvider}'s store. */
34
+ readonly store?: PendingFlowStore;
35
+ }
36
+ export interface OptimisticMutation<TVariables, TValue> {
37
+ readonly status: OptimisticStatus;
38
+ /** What a settled write answered. */
39
+ readonly value: TValue | undefined;
40
+ /** Why the write or its flow failed, when it said why. */
41
+ readonly failure: unknown;
42
+ readonly flowId: string | undefined;
43
+ /**
44
+ * Sends the write. Resolves with its result in either mode, and rejects
45
+ * with the failure — after rolling back — when the write itself fails.
46
+ */
47
+ readonly mutate: (variables: TVariables) => Promise<WriteResult<TValue>>;
48
+ readonly reset: () => void;
49
+ }
50
+ /**
51
+ * One mutation API for both settle modes
52
+ * ([ADR 0022](../../../../../docs/adr/0022-two-settle-modes-and-the-pending-flow-store.md)).
53
+ *
54
+ * A settled write behaves as a TanStack Query optimistic mutation: `apply` on
55
+ * mutate, `rollback` when it fails. A pending one records its flow in the
56
+ * pending-flow store and stays `pending` until `usePendingFlowSettlement`
57
+ * settles it: `confirmed`, or `failed` and rolled back. A screen never
58
+ * branches on a status code.
59
+ */
60
+ export declare function useOptimisticMutation<TVariables, TValue, TContext = undefined>({ write, apply, rollback, confirm, intent, store, }: UseOptimisticMutationOptions<TVariables, TValue, TContext>): OptimisticMutation<TVariables, TValue>;
61
+ //# sourceMappingURL=use-optimistic-mutation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-optimistic-mutation.d.ts","sourceRoot":"","sources":["../../src/pending/use-optimistic-mutation.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAGjE,OAAO,EAAS,MAAM,EAAQ,MAAM,QAAQ,CAAC;AAC7C,OAAO,EAEL,KAAK,SAAS,EAIf,MAAM,OAAO,CAAC;AAEf,OAAO,KAAK,EAAe,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAM7E,0EAA0E;AAC1E,wBAAgB,wBAAwB,CAAC,EACvC,KAAK,EACL,QAAQ,GACT,EAAE;IACD,QAAQ,CAAC,KAAK,EAAE,gBAAgB,CAAC;IACjC,QAAQ,CAAC,QAAQ,EAAE,SAAS,CAAC;CAC9B,+BAMA;AAED,2EAA2E;AAC3E,eAAO,MAAM,mBAAmB,QAAO,gBAAgB,GAAG,SACrB,CAA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AC,CAAC;IACzE,QAAQ,CAAC,KAAK,EAAE,MAAM,IAAI,CAAC;CAC5B;AAQD;;;;;;;;;GASG;AACH,wBAAgB,qBAAqB,CACnC,UAAU,EACV,MAAM,EACN,QAAQ,GAAG,SAAS,EACpB,EACA,KAAK,EACL,KAAK,EACL,QAAQ,EACR,OAAO,EACP,MAAM,EACN,KAAK,GACN,EAAE,4BAA4B,CAC7B,UAAU,EACV,MAAM,EACN,QAAQ,CACT,GAAG,kBAAkB,CAAC,UAAU,EAAE,MAAM,CAAC,CA4EzC"}
@@ -0,0 +1,88 @@
1
+ 'use client';
2
+ import { _ as _extends } from "@swc/helpers/_/_extends";
3
+ import { jsx as _jsx } from "react/jsx-runtime";
4
+ import { flowLink } from '@entifix/core';
5
+ import { useMutation } from '@tanstack/react-query';
6
+ import { Cause, Effect, Exit } from 'effect';
7
+ import { createContext, useCallback, useContext, useState } from 'react';
8
+ const PendingFlowStoreContext = /*#__PURE__*/ createContext(undefined);
9
+ /** Makes `store` the one every optimistic mutation below records into. */ export function PendingFlowStoreProvider({ store, children }) {
10
+ return /*#__PURE__*/ _jsx(PendingFlowStoreContext.Provider, {
11
+ value: store,
12
+ children: children
13
+ });
14
+ }
15
+ /** The store a {@link PendingFlowStoreProvider} above provides, if any. */ export const usePendingFlowStore = ()=>useContext(PendingFlowStoreContext);
16
+ /**
17
+ * One mutation API for both settle modes
18
+ * ([ADR 0022](../../../../../docs/adr/0022-two-settle-modes-and-the-pending-flow-store.md)).
19
+ *
20
+ * A settled write behaves as a TanStack Query optimistic mutation: `apply` on
21
+ * mutate, `rollback` when it fails. A pending one records its flow in the
22
+ * pending-flow store and stays `pending` until `usePendingFlowSettlement`
23
+ * settles it: `confirmed`, or `failed` and rolled back. A screen never
24
+ * branches on a status code.
25
+ */ export function useOptimisticMutation({ write, apply, rollback, confirm, intent, store }) {
26
+ var _ref, _mutation_error;
27
+ var _mutation_data;
28
+ const provided = usePendingFlowStore();
29
+ const pendingStore = store != null ? store : provided;
30
+ const [flow, setFlow] = useState(undefined);
31
+ const mutation = useMutation({
32
+ mutationFn: (variables)=>Effect.runPromiseExit(write(variables)).then((exit)=>Exit.isSuccess(exit) ? exit.value : Promise.reject(Cause.squash(exit.cause))),
33
+ onMutate: (variables)=>apply == null ? void 0 : apply(variables),
34
+ onError: (_failure, variables, context)=>{
35
+ rollback == null ? void 0 : rollback(variables, context);
36
+ },
37
+ onSuccess: (result, variables, context)=>{
38
+ if (result._tag === 'settled') return;
39
+ if (pendingStore === undefined) throw new Error(`flow '${result.flowId}' was accepted but no PendingFlowStore is provided to wait for it`);
40
+ const status = flowLink(result, 'status');
41
+ pendingStore.add(_extends({
42
+ flowId: result.flowId
43
+ }, status === undefined ? {} : {
44
+ status
45
+ }, intent === undefined ? {} : {
46
+ intent: intent(variables)
47
+ }));
48
+ setFlow({
49
+ flowId: result.flowId,
50
+ status: 'pending'
51
+ });
52
+ pendingStore.onSettled(result.flowId, (outcome)=>{
53
+ if (outcome.kind === 'confirmed') confirm == null ? void 0 : confirm(variables, context);
54
+ else rollback == null ? void 0 : rollback(variables, context);
55
+ setFlow(_extends({
56
+ flowId: result.flowId,
57
+ status: outcome.kind === 'confirmed' ? 'confirmed' : 'failed'
58
+ }, outcome.kind === 'failed' ? {
59
+ failure: outcome.failure
60
+ } : {}));
61
+ });
62
+ }
63
+ });
64
+ const { mutateAsync, reset: resetMutation } = mutation;
65
+ const mutate = useCallback((variables)=>{
66
+ setFlow(undefined);
67
+ return mutateAsync(variables);
68
+ }, [
69
+ mutateAsync
70
+ ]);
71
+ const reset = useCallback(()=>{
72
+ setFlow(undefined);
73
+ resetMutation();
74
+ }, [
75
+ resetMutation
76
+ ]);
77
+ const status = mutation.status === 'pending' ? 'running' : mutation.status === 'error' ? 'failed' : mutation.status === 'idle' ? 'idle' : (_ref = flow == null ? void 0 : flow.status) != null ? _ref : 'settled';
78
+ return {
79
+ status,
80
+ value: ((_mutation_data = mutation.data) == null ? void 0 : _mutation_data._tag) === 'settled' ? mutation.data.value : undefined,
81
+ failure: (_mutation_error = mutation.error) != null ? _mutation_error : flow == null ? void 0 : flow.failure,
82
+ flowId: flow == null ? void 0 : flow.flowId,
83
+ mutate,
84
+ reset
85
+ };
86
+ }
87
+
88
+ //# sourceMappingURL=use-optimistic-mutation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/pending/use-optimistic-mutation.tsx"],"sourcesContent":["'use client';\n\nimport type { EntifixFailure, WriteResult } from '@entifix/core';\nimport { flowLink } from '@entifix/core';\nimport { useMutation } from '@tanstack/react-query';\nimport { Cause, Effect, Exit } from 'effect';\nimport {\n createContext,\n type ReactNode,\n useCallback,\n useContext,\n useState,\n} from 'react';\n\nimport type { FlowOutcome, PendingFlowStore } from './pending-flow-store.js';\n\nconst PendingFlowStoreContext = createContext<PendingFlowStore | undefined>(\n undefined,\n);\n\n/** Makes `store` the one every optimistic mutation below records into. */\nexport function PendingFlowStoreProvider({\n store,\n children,\n}: {\n readonly store: PendingFlowStore;\n readonly children: ReactNode;\n}) {\n return (\n <PendingFlowStoreContext.Provider value={store}>\n {children}\n </PendingFlowStoreContext.Provider>\n );\n}\n\n/** The store a {@link PendingFlowStoreProvider} above provides, if any. */\nexport const usePendingFlowStore = (): PendingFlowStore | undefined =>\n useContext(PendingFlowStoreContext);\n\n/**\n * Where an optimistic write stands. `settled` is a write that happened;\n * `pending`, `confirmed` and `failed` are a flow's, and nothing finer: a\n * `202` never says a payment was captured or an order placed, so neither may\n * the screen.\n */\nexport type OptimisticStatus =\n 'idle' | 'running' | 'settled' | 'pending' | 'confirmed' | 'failed';\n\nexport interface UseOptimisticMutationOptions<TVariables, TValue, TContext> {\n /** The write: a save, a delete or a verb, answering either mode. */\n readonly write: (\n variables: TVariables,\n ) => Effect.Effect<WriteResult<TValue>, EntifixFailure>;\n /** Applies the write to what the screen shows, before it is sent. */\n readonly apply?: (variables: TVariables) => TContext;\n /**\n * Undoes `apply`: on a write that failed, and on a flow that failed. It runs\n * for a flow even after the screen that started it unmounted.\n */\n readonly rollback?: (variables: TVariables, context: TContext) => void;\n /** Runs when a flow this mutation started completed. */\n readonly confirm?: (variables: TVariables, context: TContext) => void;\n /** What a pending write means, stored beside it. JSON only. */\n readonly intent?: (variables: TVariables) => unknown;\n /** Defaults to the {@link PendingFlowStoreProvider}'s store. */\n readonly store?: PendingFlowStore;\n}\n\nexport interface OptimisticMutation<TVariables, TValue> {\n readonly status: OptimisticStatus;\n /** What a settled write answered. */\n readonly value: TValue | undefined;\n /** Why the write or its flow failed, when it said why. */\n readonly failure: unknown;\n readonly flowId: string | undefined;\n /**\n * Sends the write. Resolves with its result in either mode, and rejects\n * with the failure — after rolling back — when the write itself fails.\n */\n readonly mutate: (variables: TVariables) => Promise<WriteResult<TValue>>;\n readonly reset: () => void;\n}\n\ninterface FlowState {\n readonly flowId: string;\n readonly status: 'pending' | 'confirmed' | 'failed';\n readonly failure?: unknown;\n}\n\n/**\n * One mutation API for both settle modes\n * ([ADR 0022](../../../../../docs/adr/0022-two-settle-modes-and-the-pending-flow-store.md)).\n *\n * A settled write behaves as a TanStack Query optimistic mutation: `apply` on\n * mutate, `rollback` when it fails. A pending one records its flow in the\n * pending-flow store and stays `pending` until `usePendingFlowSettlement`\n * settles it: `confirmed`, or `failed` and rolled back. A screen never\n * branches on a status code.\n */\nexport function useOptimisticMutation<\n TVariables,\n TValue,\n TContext = undefined,\n>({\n write,\n apply,\n rollback,\n confirm,\n intent,\n store,\n}: UseOptimisticMutationOptions<\n TVariables,\n TValue,\n TContext\n>): OptimisticMutation<TVariables, TValue> {\n const provided = usePendingFlowStore();\n const pendingStore = store ?? provided;\n const [flow, setFlow] = useState<FlowState | undefined>(undefined);\n\n const mutation = useMutation<\n WriteResult<TValue>,\n unknown,\n TVariables,\n TContext\n >({\n mutationFn: variables =>\n Effect.runPromiseExit(write(variables)).then(exit =>\n Exit.isSuccess(exit)\n ? exit.value\n : Promise.reject(Cause.squash(exit.cause)),\n ),\n onMutate: variables => apply?.(variables) as TContext,\n onError: (_failure, variables, context) => {\n rollback?.(variables, context as TContext);\n },\n onSuccess: (result, variables, context) => {\n if (result._tag === 'settled') return;\n if (pendingStore === undefined)\n throw new Error(\n `flow '${result.flowId}' was accepted but no PendingFlowStore is provided to wait for it`,\n );\n const status = flowLink(result, 'status');\n pendingStore.add({\n flowId: result.flowId,\n ...(status === undefined ? {} : { status }),\n ...(intent === undefined ? {} : { intent: intent(variables) }),\n });\n setFlow({ flowId: result.flowId, status: 'pending' });\n pendingStore.onSettled(result.flowId, (outcome: FlowOutcome) => {\n if (outcome.kind === 'confirmed') confirm?.(variables, context);\n else rollback?.(variables, context);\n setFlow({\n flowId: result.flowId,\n status: outcome.kind === 'confirmed' ? 'confirmed' : 'failed',\n ...(outcome.kind === 'failed' ? { failure: outcome.failure } : {}),\n });\n });\n },\n });\n\n const { mutateAsync, reset: resetMutation } = mutation;\n const mutate = useCallback(\n (variables: TVariables) => {\n setFlow(undefined);\n return mutateAsync(variables);\n },\n [mutateAsync],\n );\n const reset = useCallback(() => {\n setFlow(undefined);\n resetMutation();\n }, [resetMutation]);\n\n const status: OptimisticStatus =\n mutation.status === 'pending'\n ? 'running'\n : mutation.status === 'error'\n ? 'failed'\n : mutation.status === 'idle'\n ? 'idle'\n : (flow?.status ?? 'settled');\n\n return {\n status,\n value: mutation.data?._tag === 'settled' ? mutation.data.value : undefined,\n failure: mutation.error ?? flow?.failure,\n flowId: flow?.flowId,\n mutate,\n reset,\n };\n}\n"],"names":["flowLink","useMutation","Cause","Effect","Exit","createContext","useCallback","useContext","useState","PendingFlowStoreContext","undefined","PendingFlowStoreProvider","store","children","Provider","value","usePendingFlowStore","useOptimisticMutation","write","apply","rollback","confirm","intent","mutation","provided","pendingStore","flow","setFlow","mutationFn","variables","runPromiseExit","then","exit","isSuccess","Promise","reject","squash","cause","onMutate","onError","_failure","context","onSuccess","result","_tag","Error","flowId","status","add","onSettled","outcome","kind","failure","mutateAsync","reset","resetMutation","mutate","data","error"],"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AAM;QACpBU;QACAF;IACF;AACF"}
@@ -0,0 +1,43 @@
1
+ import { type EntifixFailure } from '@entifix/core';
2
+ import { type FlowStatusBody } from '@entifix/transactions';
3
+ import { Effect } from 'effect';
4
+ import { type PushChannel } from '../reactive/push-channel.js';
5
+ import type { PendingFlow, PendingFlowStore } from './pending-flow-store.js';
6
+ /** Reads a flow's `status` link; `undefined` is a flow not projected yet. */
7
+ export type FlowStatusRead = (href: string) => Effect.Effect<FlowStatusBody | undefined, unknown>;
8
+ export interface UsePendingFlowSettlementOptions {
9
+ readonly channel: PushChannel;
10
+ readonly store: PendingFlowStore;
11
+ /**
12
+ * Reads a flow's status when its push may have been missed: on every
13
+ * (re)connection and on a resync. Omitted, a flow settles by push alone.
14
+ */
15
+ readonly readStatus?: FlowStatusRead;
16
+ /**
17
+ * How long a flow nobody can account for stays pending, in milliseconds.
18
+ * Past it, a flow whose status read still answers `404` — or that has no
19
+ * status link — is dropped as failed, with nothing to tell the user why.
20
+ */
21
+ readonly maxAgeMs: number;
22
+ readonly now?: () => number;
23
+ /**
24
+ * The toast event: runs exactly once for each flow that failed with a
25
+ * reason, carrying the decoded failure.
26
+ */
27
+ readonly onFailure?: (failure: EntifixFailure, flow: PendingFlow) => void;
28
+ /** Runs once for each flow that completed. */
29
+ readonly onConfirmed?: (flow: PendingFlow) => void;
30
+ }
31
+ /**
32
+ * Settles every pending flow in `store`
33
+ * ([ADR 0022](../../../../../docs/adr/0022-two-settle-modes-and-the-pending-flow-store.md)).
34
+ *
35
+ * Each pending flow's topic is subscribed: `flow.completed` confirms it and
36
+ * `flow.failed` fails it. A push may have been missed while the stream was
37
+ * down or before the topic was subscribed, so each (re)connection and each
38
+ * resync re-reads the status of the flows it touches. A status read that
39
+ * answers `404` means not projected yet, never failed. Mount it once, where
40
+ * the host mounts its toast region.
41
+ */
42
+ export declare function usePendingFlowSettlement({ channel, store, readStatus, maxAgeMs, now, onFailure, onConfirmed, }: UsePendingFlowSettlementOptions): void;
43
+ //# sourceMappingURL=use-pending-flow-settlement.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"use-pending-flow-settlement.d.ts","sourceRoot":"","sources":["../../src/pending/use-pending-flow-settlement.tsx"],"names":[],"mappings":"AAEA,OAAO,EAGL,KAAK,cAAc,EAEpB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAiB,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC3E,OAAO,EAAE,MAAM,EAAU,MAAM,QAAQ,CAAC;AAGxC,OAAO,EAAa,KAAK,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC1E,OAAO,KAAK,EAEV,WAAW,EACX,gBAAgB,EACjB,MAAM,yBAAyB,CAAC;AAEjC,6EAA6E;AAC7E,MAAM,MAAM,cAAc,GAAG,CAC3B,IAAI,EAAE,MAAM,KACT,MAAM,CAAC,MAAM,CAAC,cAAc,GAAG,SAAS,EAAE,OAAO,CAAC,CAAC;AAExD,MAAM,WAAW,+BAA+B;IAC9C,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC;IAC9B,QAAQ,CAAC,KAAK,EAAE,gBAAgB,CAAC;IACjC;;;OAGG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,cAAc,CAAC;IACrC;;;;OAIG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IAC5B;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,IAAI,EAAE,WAAW,KAAK,IAAI,CAAC;IAC1E,8CAA8C;IAC9C,QAAQ,CAAC,WAAW,CAAC,EAAE,CAAC,IAAI,EAAE,WAAW,KAAK,IAAI,CAAC;CACpD;AAWD;;;;;;;;;;GAUG;AACH,wBAAgB,wBAAwB,CAAC,EACvC,OAAO,EACP,KAAK,EACL,UAAU,EACV,QAAQ,EACR,GAAc,EACd,SAAS,EACT,WAAW,GACZ,EAAE,+BAA+B,GAAG,IAAI,CAyFxC"}
@@ -0,0 +1,126 @@
1
+ 'use client';
2
+ import { decodeProblem, Internal } from '@entifix/core';
3
+ import { FlowEventData } from '@entifix/transactions';
4
+ import { Effect, Schema } from 'effect';
5
+ import { useEffect, useRef, useSyncExternalStore } from 'react';
6
+ import { flowTopic } from '../reactive/push-channel.js';
7
+ const isFlowEvent = Schema.is(FlowEventData);
8
+ // A failure the flow named, decoded into its registered class; a flow that
9
+ // ended badly without naming one is an internal failure.
10
+ const failureOf = (named)=>named === undefined ? new Internal() : decodeProblem(named);
11
+ /**
12
+ * Settles every pending flow in `store`
13
+ * ([ADR 0022](../../../../../docs/adr/0022-two-settle-modes-and-the-pending-flow-store.md)).
14
+ *
15
+ * Each pending flow's topic is subscribed: `flow.completed` confirms it and
16
+ * `flow.failed` fails it. A push may have been missed while the stream was
17
+ * down or before the topic was subscribed, so each (re)connection and each
18
+ * resync re-reads the status of the flows it touches. A status read that
19
+ * answers `404` means not projected yet, never failed. Mount it once, where
20
+ * the host mounts its toast region.
21
+ */ export function usePendingFlowSettlement({ channel, store, readStatus, maxAgeMs, now = Date.now, onFailure, onConfirmed }) {
22
+ const flows = useSyncExternalStore(store.subscribe, store.list, store.list);
23
+ const latest = useRef({
24
+ readStatus,
25
+ maxAgeMs,
26
+ now,
27
+ onFailure,
28
+ onConfirmed
29
+ });
30
+ useEffect(()=>{
31
+ latest.current = {
32
+ readStatus,
33
+ maxAgeMs,
34
+ now,
35
+ onFailure,
36
+ onConfirmed
37
+ };
38
+ });
39
+ // Settles one flow, telling the host only if this call is what settled it:
40
+ // a redelivered outcome, or a push racing a status read, settles nothing.
41
+ const settleIn = (held)=>(flow, outcome)=>{
42
+ if (!held.settle(flow.flowId, outcome)) return;
43
+ if (outcome.kind === 'confirmed') latest.current.onConfirmed == null ? void 0 : latest.current.onConfirmed.call(latest.current, flow);
44
+ else if (outcome.failure !== undefined) latest.current.onFailure == null ? void 0 : latest.current.onFailure.call(latest.current, outcome.failure, flow);
45
+ };
46
+ const settleRef = useRef(settleIn);
47
+ const key = flows.map((flow)=>flow.flowId).join(' ');
48
+ useEffect(()=>{
49
+ const settle = settleRef.current(store);
50
+ const onEvent = (flow)=>(event)=>{
51
+ if (event.name === 'flow.completed') settle(flow, {
52
+ kind: 'confirmed',
53
+ event
54
+ });
55
+ else if (event.name === 'flow.failed' && isFlowEvent(event.data)) settle(flow, {
56
+ kind: 'failed',
57
+ failure: failureOf(event.data.failure)
58
+ });
59
+ };
60
+ const unsubscribes = store.list().map((flow)=>channel.subscribe(flowTopic(flow.flowId), onEvent(flow)));
61
+ return ()=>{
62
+ for (const unsubscribe of unsubscribes)unsubscribe();
63
+ };
64
+ }, [
65
+ channel,
66
+ key,
67
+ store
68
+ ]);
69
+ useEffect(()=>{
70
+ const settle = settleRef.current(store);
71
+ const expire = (flow)=>{
72
+ const { now: clock, maxAgeMs: bound } = latest.current;
73
+ if (clock() - Date.parse(flow.createdAt) > bound) settle(flow, {
74
+ kind: 'failed'
75
+ });
76
+ };
77
+ const reconcile = (pending)=>{
78
+ const read = latest.current.readStatus;
79
+ for (const flow of pending){
80
+ if (read === undefined || flow.status === undefined) {
81
+ expire(flow);
82
+ continue;
83
+ }
84
+ void Effect.runPromise(Effect.match(read(flow.status), {
85
+ // An unreachable status read is not an answer: the flow waits for
86
+ // the next connection.
87
+ onFailure: ()=>undefined,
88
+ onSuccess: (status)=>{
89
+ switch(status == null ? void 0 : status.state){
90
+ case undefined:
91
+ return expire(flow);
92
+ case 'completed':
93
+ return settle(flow, {
94
+ kind: 'confirmed'
95
+ });
96
+ case 'failed':
97
+ case 'compensated':
98
+ case 'interrupted':
99
+ return settle(flow, {
100
+ kind: 'failed',
101
+ failure: failureOf(status.failure)
102
+ });
103
+ default:
104
+ return undefined;
105
+ }
106
+ }
107
+ }));
108
+ }
109
+ };
110
+ const stopConnect = channel.onConnect(()=>{
111
+ void store.ready.then(()=>reconcile(store.list()));
112
+ });
113
+ const stopResync = channel.onResync((topics)=>{
114
+ reconcile(store.list().filter((flow)=>topics.includes(flow.topic)));
115
+ });
116
+ return ()=>{
117
+ stopConnect();
118
+ stopResync();
119
+ };
120
+ }, [
121
+ channel,
122
+ store
123
+ ]);
124
+ }
125
+
126
+ //# sourceMappingURL=use-pending-flow-settlement.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/pending/use-pending-flow-settlement.tsx"],"sourcesContent":["'use client';\n\nimport {\n decodeProblem,\n type DomainEvent,\n type EntifixFailure,\n Internal,\n} from '@entifix/core';\nimport { FlowEventData, type FlowStatusBody } from '@entifix/transactions';\nimport { Effect, Schema } from 'effect';\nimport { useEffect, useRef, useSyncExternalStore } from 'react';\n\nimport { flowTopic, type PushChannel } from '../reactive/push-channel.js';\nimport type {\n FlowOutcome,\n PendingFlow,\n PendingFlowStore,\n} from './pending-flow-store.js';\n\n/** Reads a flow's `status` link; `undefined` is a flow not projected yet. */\nexport type FlowStatusRead = (\n href: string,\n) => Effect.Effect<FlowStatusBody | undefined, unknown>;\n\nexport interface UsePendingFlowSettlementOptions {\n readonly channel: PushChannel;\n readonly store: PendingFlowStore;\n /**\n * Reads a flow's status when its push may have been missed: on every\n * (re)connection and on a resync. Omitted, a flow settles by push alone.\n */\n readonly readStatus?: FlowStatusRead;\n /**\n * How long a flow nobody can account for stays pending, in milliseconds.\n * Past it, a flow whose status read still answers `404` — or that has no\n * status link — is dropped as failed, with nothing to tell the user why.\n */\n readonly maxAgeMs: number;\n readonly now?: () => number;\n /**\n * The toast event: runs exactly once for each flow that failed with a\n * reason, carrying the decoded failure.\n */\n readonly onFailure?: (failure: EntifixFailure, flow: PendingFlow) => void;\n /** Runs once for each flow that completed. */\n readonly onConfirmed?: (flow: PendingFlow) => void;\n}\n\nconst isFlowEvent = Schema.is(FlowEventData);\n\n// A failure the flow named, decoded into its registered class; a flow that\n// ended badly without naming one is an internal failure.\nconst failureOf = (\n named: FlowStatusBody['failure'] | undefined,\n): EntifixFailure =>\n named === undefined ? new Internal() : decodeProblem(named);\n\n/**\n * Settles every pending flow in `store`\n * ([ADR 0022](../../../../../docs/adr/0022-two-settle-modes-and-the-pending-flow-store.md)).\n *\n * Each pending flow's topic is subscribed: `flow.completed` confirms it and\n * `flow.failed` fails it. A push may have been missed while the stream was\n * down or before the topic was subscribed, so each (re)connection and each\n * resync re-reads the status of the flows it touches. A status read that\n * answers `404` means not projected yet, never failed. Mount it once, where\n * the host mounts its toast region.\n */\nexport function usePendingFlowSettlement({\n channel,\n store,\n readStatus,\n maxAgeMs,\n now = Date.now,\n onFailure,\n onConfirmed,\n}: UsePendingFlowSettlementOptions): void {\n const flows = useSyncExternalStore(store.subscribe, store.list, store.list);\n const latest = useRef({ readStatus, maxAgeMs, now, onFailure, onConfirmed });\n useEffect(() => {\n latest.current = { readStatus, maxAgeMs, now, onFailure, onConfirmed };\n });\n\n // Settles one flow, telling the host only if this call is what settled it:\n // a redelivered outcome, or a push racing a status read, settles nothing.\n const settleIn =\n (held: PendingFlowStore) => (flow: PendingFlow, outcome: FlowOutcome) => {\n if (!held.settle(flow.flowId, outcome)) return;\n if (outcome.kind === 'confirmed') latest.current.onConfirmed?.(flow);\n else if (outcome.failure !== undefined)\n latest.current.onFailure?.(outcome.failure, flow);\n };\n const settleRef = useRef(settleIn);\n\n const key = flows.map(flow => flow.flowId).join(' ');\n useEffect(() => {\n const settle = settleRef.current(store);\n const onEvent = (flow: PendingFlow) => (event: DomainEvent) => {\n if (event.name === 'flow.completed')\n settle(flow, { kind: 'confirmed', event });\n else if (event.name === 'flow.failed' && isFlowEvent(event.data))\n settle(flow, {\n kind: 'failed',\n failure: failureOf(event.data.failure),\n });\n };\n const unsubscribes = store\n .list()\n .map(flow => channel.subscribe(flowTopic(flow.flowId), onEvent(flow)));\n return () => {\n for (const unsubscribe of unsubscribes) unsubscribe();\n };\n }, [channel, key, store]);\n\n useEffect(() => {\n const settle = settleRef.current(store);\n const expire = (flow: PendingFlow) => {\n const { now: clock, maxAgeMs: bound } = latest.current;\n if (clock() - Date.parse(flow.createdAt) > bound)\n settle(flow, { kind: 'failed' });\n };\n const reconcile = (pending: readonly PendingFlow[]) => {\n const read = latest.current.readStatus;\n for (const flow of pending) {\n if (read === undefined || flow.status === undefined) {\n expire(flow);\n continue;\n }\n void Effect.runPromise(\n Effect.match(read(flow.status), {\n // An unreachable status read is not an answer: the flow waits for\n // the next connection.\n onFailure: () => undefined,\n onSuccess: status => {\n switch (status?.state) {\n case undefined:\n return expire(flow);\n case 'completed':\n return settle(flow, { kind: 'confirmed' });\n case 'failed':\n case 'compensated':\n case 'interrupted':\n return settle(flow, {\n kind: 'failed',\n failure: failureOf(status.failure),\n });\n default:\n return undefined;\n }\n },\n }),\n );\n }\n };\n const stopConnect = channel.onConnect(() => {\n void store.ready.then(() => reconcile(store.list()));\n });\n const stopResync = channel.onResync(topics => {\n reconcile(store.list().filter(flow => topics.includes(flow.topic)));\n });\n return () => {\n stopConnect();\n stopResync();\n };\n }, [channel, store]);\n}\n"],"names":["decodeProblem","Internal","FlowEventData","Effect","Schema","useEffect","useRef","useSyncExternalStore","flowTopic","isFlowEvent","is","failureOf","named","undefined","usePendingFlowSettlement","channel","store","readStatus","maxAgeMs","now","Date","onFailure","onConfirmed","flows","subscribe","list","latest","current","settleIn","held","flow","outcome","settle","flowId","kind","failure","settleRef","key","map","join","onEvent","event","name","data","unsubscribes","unsubscribe","expire","clock","bound","parse","createdAt","reconcile","pending","read","status","runPromise","match","onSuccess","state","stopConnect","onConnect","ready","then","stopResync","onResync","topics","filter","includes","topic"],"mappings":"AAAA;AAEA,SACEA,aAAa,EAGbC,QAAQ,QACH,gBAAgB;AACvB,SAASC,aAAa,QAA6B,wBAAwB;AAC3E,SAASC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AACxC,SAASC,SAAS,EAAEC,MAAM,EAAEC,oBAAoB,QAAQ,QAAQ;AAEhE,SAASC,SAAS,QAA0B,8BAA8B;AAoC1E,MAAMC,cAAcL,OAAOM,EA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