@vdatacloud/cx-commons 0.8.0 → 0.9.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.
package/README.md CHANGED
@@ -41,8 +41,8 @@ This repository publishes `@vdatacloud/cx-commons` with modular export entry poi
41
41
  @vdatacloud/cx-commons
42
42
  ├── (default) --> exports index.ts (Astro integration plugin `cxCommons()`)
43
43
  ├── /styles/global.css --> exports canonical LNF design system tokens & Tailwind rules
44
- ├── /components/* --> exports shared Astro UI components (Nav, Footer, StatusBadge, EyebrowLabel, ApiErrorNotice, CantonId, LanguageSwitcher)
45
- ├── /sdk/* --> exports browser SDK helpers (i18n, cx-messages, dialogs, api-error, api-error-notice, canton-id, canton-id-view, agreement-sig, pending-approvals, status-colors, oidc-pkce, api-client, html)
44
+ ├── /components/* --> exports shared Astro UI components (Nav, Footer, StatusBadge, EyebrowLabel, ApiErrorNotice, OperationStatus, CantonId, LanguageSwitcher)
45
+ ├── /sdk/* --> exports browser SDK helpers (i18n, cx-messages, dialogs, api-error, api-error-notice, canton-id, canton-id-view, agreement-sig, pending-approvals, push, operations, operation-status, status-colors, oidc-pkce, api-client, html)
46
46
  └── /schema/api-error.json --> the canonical API error JSON Schema
47
47
  ```
48
48
 
@@ -100,6 +100,27 @@ An act that isn't a proposal (daml-escrow PLAN.md Phase 92.5: a staged release i
100
100
 
101
101
  ---
102
102
 
103
+ ### Streaming and long-running writes (`sdk/push`, `sdk/operations`, `sdk/operation-status`, `components/OperationStatus`)
104
+
105
+ The platform's one streaming standard (daml-escrow PLAN.md 112.0.8): server-sent events read with `fetch`, so the bearer
106
+ token goes in the `Authorization` header (never `EventSource`, never a token in a URL). No websockets.
107
+
108
+ - `sdk/push`: `SSEParser` (incremental, tested against daml-escrow-commons `push/testdata/events.json`, the Go encoder's
109
+ output); `subscribe(url, { token, onEvent, onEnd, onError, lastEventId })` follows a topic and reconnects after a drop
110
+ with `Last-Event-ID` and backoff (a 4xx refusal other than 408/429 stops it); `streamResponse(url, init, onEvent)` reads
111
+ one request's own streamed reply, e.g. a chat turn (abort its signal to stop).
112
+ - `sdk/operations`: the `Operation` a 202 Accepted returns (mirrors daml-escrow-commons `operation`, example
113
+ `operation/testdata/operation.json`); `isTerminal`, `isCancellable`, `operationFromResponse`, `getOperation`,
114
+ `cancelOperation` (POST `links.cancel`; a cancel that came too late is a 409 `OPERATION_NOT_CANCELLABLE`, and
115
+ `notCancellableState(err)` returns the state it is really in), and `followOperation(op, { token, onUpdate })`, which follows the push channel
116
+ from `op.seq` and falls back to polling `links.self` if the stream is refused or drops twice.
117
+ - `mountOperationStatus(host, op, { token, onDone })` shows the state, the step (n of N), Cancel while a cancel can still
118
+ stop it (a too-late cancel says why, per state, and refreshes the status), and a refusal through the error notice; `<OperationStatus operation={op} />` renders it server-side and
119
+ hydrates (pages with a bearer token pass `autoHydrate={false}` and call `hydrateOperationStatuses(document, { token })`).
120
+ Strings are `cx.operation.*` (en, fr); an app may add `cx.operation.kind.<kind>` labels.
121
+
122
+ ---
123
+
103
124
  ### Sign-in, API calls and markup (`sdk/oidc-pkce`, `sdk/api-client`, `sdk/html`)
104
125
 
105
126
  Shared by the escrow portal and the operator console (daml-escrow PLAN.md Phase 104).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vdatacloud/cx-commons",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Product CX Commons - Shared design system, UI components, and Astro integration for Data Cloud web applications",
5
5
  "repository": {
6
6
  "type": "git",
@@ -0,0 +1,33 @@
1
+ ---
2
+ // The platform-wide progress display for a long-running write
3
+ // (daml-escrow-commons operation / sdk/operations). Server-renders the
4
+ // operation's state, then hydrates through sdk/operation-status, which
5
+ // follows it over the push channel (polling if the stream isn't available)
6
+ // and offers Cancel while a cancel can still stop it.
7
+ //
8
+ // Following needs the caller's token: pages that authenticate with a bearer
9
+ // token call hydrateOperationStatuses(document, { token }) themselves and set
10
+ // autoHydrate={false}; cookie-session pages can leave the default.
11
+ import type { Operation } from '../sdk/operations';
12
+
13
+ export interface Props {
14
+ operation: Operation;
15
+ class?: string;
16
+ locale?: string;
17
+ autoHydrate?: boolean;
18
+ }
19
+
20
+ const { operation, class: className = '', autoHydrate = true } = Astro.props;
21
+ const locale = Astro.props.locale ?? (Astro.locals as { locale?: string }).locale ?? Astro.currentLocale ?? 'en';
22
+ ---
23
+
24
+ <div data-operation={JSON.stringify(operation)} data-operation-locale={locale} data-operation-auto={autoHydrate ? '' : undefined} class={className}>
25
+ <p role="status" class="rounded-2xl border border-brand-200 bg-brand-50 p-4 text-sm font-semibold text-slate-800 dark:border-brand-800 dark:bg-brand-900/30 dark:text-slate-100">
26
+ {operation.state}
27
+ </p>
28
+ </div>
29
+
30
+ <script>
31
+ import { hydrateOperationStatus } from '../sdk/operation-status';
32
+ document.querySelectorAll<HTMLElement>('[data-operation-auto]').forEach((host) => hydrateOperationStatus(host));
33
+ </script>
@@ -79,6 +79,22 @@ export const cxMessages = {
79
79
  reasonPrompt: 'Why? This goes on the record.',
80
80
  reason: 'Reason',
81
81
  },
82
+ operation: {
83
+ state: {
84
+ QUEUED: 'Queued',
85
+ AWAITING_SIGNER: 'Waiting for a signer',
86
+ SUBMITTED: 'Recording on the ledger',
87
+ COMMITTED: 'Done',
88
+ REJECTED: 'Refused',
89
+ TIMED_OUT: 'Timed out',
90
+ CANCELLED: 'Cancelled',
91
+ },
92
+ step: 'Step {step} of {steps}',
93
+ cancel: 'Cancel',
94
+ cancelling: 'Cancelling…',
95
+ cancelRequested: 'Cancel requested',
96
+ notCancellable: '{state, select, SUBMITTED {Too late to cancel: it is already with the ledger and will finish on its own.} COMMITTED {Too late to cancel: it has already been recorded. Undo it through the matching action instead.} CANCELLED {It was already cancelled.} other {Too late to cancel: it has already finished.}}',
97
+ },
82
98
  language: {
83
99
  label: 'Language',
84
100
  choose: 'Choose language',
@@ -159,6 +175,22 @@ export const cxMessages = {
159
175
  reasonPrompt: 'Pourquoi\u202f? Cela figure au registre.',
160
176
  reason: 'Motif',
161
177
  },
178
+ operation: {
179
+ state: {
180
+ QUEUED: 'En file d’attente',
181
+ AWAITING_SIGNER: 'En attente d’un signataire',
182
+ SUBMITTED: 'Inscription au registre',
183
+ COMMITTED: 'Terminé',
184
+ REJECTED: 'Refusé',
185
+ TIMED_OUT: 'Délai dépassé',
186
+ CANCELLED: 'Annulé',
187
+ },
188
+ step: 'Étape {step} sur {steps}',
189
+ cancel: 'Annuler',
190
+ cancelling: 'Annulation…',
191
+ cancelRequested: 'Annulation demandée',
192
+ notCancellable: '{state, select, SUBMITTED {Trop tard pour annuler : l’opération est déjà au registre et se terminera d’elle-même.} COMMITTED {Trop tard pour annuler : l’opération est déjà enregistrée. Annulez-la plutôt par l’action correspondante.} CANCELLED {L’opération était déjà annulée.} other {Trop tard pour annuler : l’opération est déjà terminée.}}',
193
+ },
162
194
  language: {
163
195
  label: 'Langue',
164
196
  choose: 'Choisir la langue',
@@ -0,0 +1,233 @@
1
+ // One rendering of a long-running write's progress for every app
2
+ // (daml-escrow PLAN.md 112.0.8). Framework-free DOM, like api-error-notice:
3
+ // client code mounts it on the 202 it got back, and OperationStatus.astro
4
+ // hydrates through it. Every value is set with textContent.
5
+ //
6
+ // It follows the operation itself (sdk/operations followOperation: push,
7
+ // then polling), shows the state and step, offers Cancel only while a
8
+ // cancel can still stop it, and shows a failure through the platform's
9
+ // error notice.
10
+
11
+ import { renderApiErrorNotice } from './api-error-notice';
12
+ import { getTranslator, type Translator } from './i18n';
13
+ import {
14
+ cancelOperation,
15
+ followOperation,
16
+ getOperation,
17
+ notCancellableState,
18
+ isCancellable,
19
+ isTerminal,
20
+ type Operation,
21
+ type OperationClientOptions,
22
+ type OperationState,
23
+ } from './operations';
24
+ import './cx-messages';
25
+
26
+ export interface OperationStatusOptions<R = unknown> extends OperationClientOptions {
27
+ locale?: string;
28
+ /** Follow it to the end (default true); false renders this state only. */
29
+ follow?: boolean;
30
+ /** Every change, after it is shown. */
31
+ onUpdate?: (op: Operation<R>) => void;
32
+ /** The terminal state, once. */
33
+ onDone?: (op: Operation<R>) => void;
34
+ /** Hide the Cancel button even when cancellable. */
35
+ noCancel?: boolean;
36
+ }
37
+
38
+ // Class strings spelled out in full for Tailwind's scanner.
39
+ const TONE: Record<'running' | 'waiting' | 'done' | 'failed' | 'cancelled', { box: string; dot: string }> = {
40
+ running: {
41
+ box: 'border-brand-200 bg-brand-50 dark:border-brand-800 dark:bg-brand-900/30',
42
+ dot: 'bg-brand-500 animate-pulse',
43
+ },
44
+ waiting: {
45
+ box: 'border-status-proposed/30 bg-status-proposed/5 dark:border-status-proposed/20 dark:bg-status-proposed/10',
46
+ dot: 'bg-status-proposed animate-pulse',
47
+ },
48
+ done: {
49
+ box: 'border-status-settled/30 bg-status-settled/5 dark:border-status-settled/20 dark:bg-status-settled/10',
50
+ dot: 'bg-status-settled',
51
+ },
52
+ failed: {
53
+ box: 'border-status-disputed/30 bg-status-disputed/5 dark:border-status-disputed/20 dark:bg-status-disputed/10',
54
+ dot: 'bg-status-disputed',
55
+ },
56
+ cancelled: {
57
+ box: 'border-status-lapsed/30 bg-status-lapsed/5 dark:border-status-lapsed/20 dark:bg-status-lapsed/10',
58
+ dot: 'bg-status-lapsed',
59
+ },
60
+ };
61
+
62
+ function toneOf(s: OperationState): keyof typeof TONE {
63
+ switch (s) {
64
+ case 'COMMITTED': return 'done';
65
+ case 'REJECTED':
66
+ case 'TIMED_OUT': return 'failed';
67
+ case 'CANCELLED': return 'cancelled';
68
+ case 'AWAITING_SIGNER': return 'waiting';
69
+ default: return 'running';
70
+ }
71
+ }
72
+
73
+ const BUTTON = 'cx-caps rounded-md border border-slate-200 px-2 py-0.5 text-[10px] font-bold uppercase tracking-widest text-slate-600 hover:bg-slate-100 disabled:opacity-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800';
74
+
75
+ function el<K extends keyof HTMLElementTagNameMap>(tag: K, className = '', text?: string): HTMLElementTagNameMap[K] {
76
+ const n = document.createElement(tag);
77
+ if (className) n.className = className;
78
+ if (text !== undefined) n.textContent = text;
79
+ return n;
80
+ }
81
+
82
+ function stateLabel(t: Translator, op: Operation): string {
83
+ return t.maybe(`cx.operation.state.${op.state}`) ?? op.state;
84
+ }
85
+
86
+ /** The operation's current state as an element (no following). */
87
+ export function renderOperationStatus<R>(op: Operation<R>, opts: OperationStatusOptions<R> & { onCancel?: () => void; cancelling?: boolean } = {}): HTMLElement {
88
+ const t = getTranslator(opts.locale);
89
+ const tone = TONE[toneOf(op.state)];
90
+ const root = el('div', `rounded-2xl border p-4 text-sm text-slate-800 dark:text-slate-100 ${tone.box}`);
91
+ root.setAttribute('role', 'status');
92
+ root.setAttribute('aria-live', 'polite');
93
+ root.dataset.operationId = op.operationId;
94
+ root.dataset.operationState = op.state;
95
+
96
+ const head = el('div', 'flex items-center justify-between gap-3');
97
+ const left = el('div', 'flex min-w-0 items-center gap-3');
98
+ left.append(el('span', `inline-flex h-2 w-2 shrink-0 rounded-full ${tone.dot}`));
99
+ const label = el('div', 'min-w-0');
100
+ label.append(el('p', 'font-semibold', stateLabel(t, op)));
101
+ const sub: string[] = [];
102
+ const kind = t.maybe(`cx.operation.kind.${op.kind}`);
103
+ if (kind) sub.push(kind);
104
+ if (op.steps > 1 && !isTerminal(op)) sub.push(t.t('cx.operation.step', { step: op.step || 1, steps: op.steps }));
105
+ if (op.cancelRequested) sub.push(t.t('cx.operation.cancelRequested'));
106
+ if (sub.length) label.append(el('p', 'text-xs text-slate-600 dark:text-slate-300', sub.join(' · ')));
107
+ left.append(label);
108
+ head.append(left);
109
+
110
+ if (opts.onCancel && !opts.noCancel && isCancellable(op) && !op.cancelRequested) {
111
+ const b = el('button', BUTTON, t.t(opts.cancelling ? 'cx.operation.cancelling' : 'cx.operation.cancel'));
112
+ b.type = 'button';
113
+ b.disabled = !!opts.cancelling;
114
+ b.dataset.operationCancel = '';
115
+ b.addEventListener('click', () => opts.onCancel?.());
116
+ head.append(b);
117
+ }
118
+ root.append(head);
119
+
120
+ if ((op.state === 'REJECTED' || op.state === 'TIMED_OUT') && op.error) {
121
+ const box = el('div', 'mt-3');
122
+ box.append(renderApiErrorNotice(op.error, { locale: opts.locale, level: 'summary' }));
123
+ root.append(box);
124
+ }
125
+ return root;
126
+ }
127
+
128
+ export interface MountedOperationStatus<R> {
129
+ /** Settles with the terminal operation (or the last one seen if following stopped). */
130
+ readonly done: Promise<Operation<R>>;
131
+ /** Stops following (the operation itself goes on). */
132
+ stop(): void;
133
+ }
134
+
135
+ /**
136
+ * Renders op into container and, unless follow is false, keeps it current
137
+ * until it is terminal. Cancel (when shown) posts to links.cancel; a refusal
138
+ * is shown in place.
139
+ */
140
+ export function mountOperationStatus<R>(container: HTMLElement, op: Operation<R>, opts: OperationStatusOptions<R> = {}): MountedOperationStatus<R> {
141
+ const controller = new AbortController();
142
+ let current = op;
143
+ let cancelling = false;
144
+ let cancelError: HTMLElement | null = null; // a failed cancel request; cleared once the operation ends
145
+ let cancelNote: HTMLElement | null = null; // "too late to cancel"; stays with the outcome it explains
146
+ const t = getTranslator(opts.locale);
147
+
148
+ const draw = () => {
149
+ const n = renderOperationStatus(current, { ...opts, cancelling, onCancel: opts.noCancel ? undefined : cancel });
150
+ if (cancelNote) n.append(cancelNote);
151
+ if (cancelError) n.append(cancelError);
152
+ container.replaceChildren(n);
153
+ };
154
+ const update = (next: Operation<R>) => {
155
+ if (next.operationId !== current.operationId || next.seq < current.seq) return;
156
+ current = next;
157
+ if (isTerminal(next)) cancelError = null;
158
+ draw();
159
+ opts.onUpdate?.(next);
160
+ };
161
+ async function cancel() {
162
+ if (cancelling) return;
163
+ cancelling = true;
164
+ cancelError = null;
165
+ cancelNote = null;
166
+ draw();
167
+ try {
168
+ update(await cancelOperation<R>(current, opts));
169
+ } catch (err) {
170
+ const late = notCancellableState(err);
171
+ if (late) {
172
+ // The server says it is past cancelling: say why, then show where it really is.
173
+ cancelNote = el('p', 'mt-3 text-xs font-semibold text-slate-700 dark:text-slate-200', t.t('cx.operation.notCancellable', { state: late }));
174
+ cancelNote.dataset.operationNotCancellable = late;
175
+ try {
176
+ update(await getOperation<R>(current, opts));
177
+ } catch {
178
+ // following continues; the note stands
179
+ }
180
+ } else {
181
+ const apiError = (err as { apiError?: Parameters<typeof renderApiErrorNotice>[0] }).apiError;
182
+ if (apiError) {
183
+ cancelError = el('div', 'mt-3');
184
+ cancelError.append(renderApiErrorNotice(apiError, { locale: opts.locale, level: 'summary' }));
185
+ }
186
+ }
187
+ } finally {
188
+ cancelling = false;
189
+ draw();
190
+ }
191
+ }
192
+
193
+ draw();
194
+ let done: Promise<Operation<R>>;
195
+ if (opts.follow === false || isTerminal(op)) {
196
+ done = Promise.resolve(op);
197
+ if (isTerminal(op)) opts.onDone?.(op);
198
+ } else {
199
+ done = followOperation<R>(op, { ...opts, signal: controller.signal, onUpdate: update })
200
+ .then((final) => {
201
+ update(final);
202
+ opts.onDone?.(final);
203
+ return final;
204
+ })
205
+ .catch(() => current);
206
+ }
207
+ return { done, stop: () => controller.abort() };
208
+ }
209
+
210
+ /**
211
+ * Renders one [data-operation] host (OperationStatus.astro's server output):
212
+ * its attribute holds the operation's JSON. Returns null when it was already
213
+ * rendered or doesn't parse (the server fallback then stays).
214
+ */
215
+ export function hydrateOperationStatus(host: HTMLElement, opts: OperationStatusOptions = {}): MountedOperationStatus<unknown> | null {
216
+ if (host.dataset.operationRendered !== undefined) return null;
217
+ try {
218
+ const op = JSON.parse(host.dataset.operation ?? '') as Operation;
219
+ if (!op || typeof op.operationId !== 'string' || !op.links) return null;
220
+ host.dataset.operationRendered = '';
221
+ return mountOperationStatus(host, op, { ...opts, locale: opts.locale ?? (host.dataset.operationLocale || undefined) });
222
+ } catch {
223
+ return null;
224
+ }
225
+ }
226
+
227
+ /**
228
+ * Renders every [data-operation] element under root not yet rendered. Pass
229
+ * the token getter so following can authenticate.
230
+ */
231
+ export function hydrateOperationStatuses(root: ParentNode = document, opts: OperationStatusOptions = {}): void {
232
+ root.querySelectorAll<HTMLElement>('[data-operation]').forEach((host) => hydrateOperationStatus(host, opts));
233
+ }
@@ -0,0 +1,194 @@
1
+ // A long-running write (daml-escrow PLAN.md 112.0.8): the service answers
2
+ // 202 Accepted with an Operation and the client follows it to a terminal
3
+ // state. Mirrors daml-escrow-commons operation (wire example:
4
+ // test/fixtures/operation/operation.json).
5
+ //
6
+ // followOperation() follows the push channel (sdk/push) and falls back to
7
+ // polling GET links.self when the stream can't be had, so a page always
8
+ // reaches the outcome.
9
+
10
+ import { errorFromResponse } from './api-client';
11
+ import { type ApiError } from './api-error';
12
+ import { subscribe, StreamHTTPError, type PushEvent, type StreamOptions } from './push';
13
+
14
+ export type OperationState = 'QUEUED' | 'AWAITING_SIGNER' | 'SUBMITTED' | 'COMMITTED' | 'REJECTED' | 'TIMED_OUT' | 'CANCELLED';
15
+
16
+ export interface OperationLinks {
17
+ self: string;
18
+ events: string;
19
+ cancel?: string;
20
+ }
21
+
22
+ export interface Operation<R = unknown> {
23
+ operationId: string;
24
+ kind: string;
25
+ state: OperationState;
26
+ /** Increases with every change; the push event id. */
27
+ seq: number;
28
+ step: number;
29
+ steps: number;
30
+ subject?: string;
31
+ result?: R;
32
+ error?: ApiError;
33
+ cancelRequested?: boolean;
34
+ createdAt: string;
35
+ updatedAt: string;
36
+ links: OperationLinks;
37
+ }
38
+
39
+ /** The push event type of an operation change. */
40
+ export const OPERATION_EVENT = 'operation';
41
+
42
+ const TERMINAL: ReadonlySet<OperationState> = new Set(['COMMITTED', 'REJECTED', 'TIMED_OUT', 'CANCELLED']);
43
+
44
+ export function isTerminal(op: Pick<Operation, 'state'>): boolean {
45
+ return TERMINAL.has(op.state);
46
+ }
47
+
48
+ /** Whether a cancel can still stop it (before submission, or waiting for a signer). */
49
+ export function isCancellable(op: Pick<Operation, 'state' | 'links'>): boolean {
50
+ return (op.state === 'QUEUED' || op.state === 'AWAITING_SIGNER') && !!op.links.cancel;
51
+ }
52
+
53
+ /** Parses an operation push event; null for any other event. */
54
+ export function operationFromEvent<R = unknown>(e: PushEvent): Operation<R> | null {
55
+ if (e.type !== OPERATION_EVENT) return null;
56
+ try {
57
+ const op = JSON.parse(e.data) as Operation<R>;
58
+ return op && typeof op.operationId === 'string' && typeof op.state === 'string' ? op : null;
59
+ } catch {
60
+ return null;
61
+ }
62
+ }
63
+
64
+ export interface OperationClientOptions extends StreamOptions {
65
+ /** Prefix for the operation's relative links (e.g. the API origin); default ''. */
66
+ baseUrl?: string;
67
+ }
68
+
69
+ function join(base: string | undefined, path: string): string {
70
+ if (!base || /^https?:\/\//.test(path)) return path;
71
+ return base.replace(/\/$/, '') + path;
72
+ }
73
+
74
+ async function call<R>(url: string, method: string, opts: OperationClientOptions): Promise<Operation<R>> {
75
+ const headers = new Headers({ Accept: 'application/json' });
76
+ const token = opts.token?.();
77
+ if (token) headers.set('Authorization', `Bearer ${token}`);
78
+ const res = await (opts.fetchImpl ?? fetch)(url, { method, headers, cache: 'no-store' });
79
+ if (!res.ok) throw await errorFromResponse(res);
80
+ return (await res.json()) as Operation<R>;
81
+ }
82
+
83
+ /** Reads an operation's current state. */
84
+ export function getOperation<R = unknown>(op: Pick<Operation, 'links'>, opts: OperationClientOptions = {}): Promise<Operation<R>> {
85
+ return call<R>(join(opts.baseUrl, op.links.self), 'GET', opts);
86
+ }
87
+
88
+ /**
89
+ * Asks to cancel it. The answer is the operation with cancelRequested set,
90
+ * or already CANCELLED; a 409 (ApiRequestError) means it is past cancelling.
91
+ */
92
+ export function cancelOperation<R = unknown>(op: Pick<Operation, 'links' | 'operationId'>, opts: OperationClientOptions = {}): Promise<Operation<R>> {
93
+ if (!op.links.cancel) return Promise.reject(new Error(`operation ${op.operationId} has no cancel link`));
94
+ return call<R>(join(opts.baseUrl, op.links.cancel), 'POST', opts);
95
+ }
96
+
97
+ /** The apierror code of a cancel that came too late (409; details.state says where it is). */
98
+ export const NOT_CANCELLABLE = 'OPERATION_NOT_CANCELLABLE';
99
+
100
+ /**
101
+ * The operation's state when err is a cancel refused as too late
102
+ * (OPERATION_NOT_CANCELLABLE), else null: SUBMITTED (with the ledger, it
103
+ * will finish on its own), COMMITTED (undo is a business action), or another
104
+ * terminal state.
105
+ */
106
+ export function notCancellableState(err: unknown): OperationState | null {
107
+ const e = (err as { apiError?: ApiError } | null)?.apiError;
108
+ if (!e || e.code !== NOT_CANCELLABLE) return null;
109
+ const state = (e.details as { state?: unknown } | undefined)?.state;
110
+ return typeof state === 'string' ? (state as OperationState) : 'SUBMITTED';
111
+ }
112
+
113
+ export interface FollowOptions<R> extends OperationClientOptions {
114
+ /** Every change, in order (duplicates and stale versions are dropped). */
115
+ onUpdate?: (op: Operation<R>) => void;
116
+ /** Polling interval when the stream isn't available: first and cap, ms (defaults 1000 and 5000). */
117
+ pollInitialMs?: number;
118
+ pollMaxMs?: number;
119
+ signal?: AbortSignal;
120
+ /** For tests. */
121
+ sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
122
+ }
123
+
124
+ const defaultSleep = (ms: number, signal: AbortSignal) =>
125
+ new Promise<void>((resolve) => {
126
+ const t = setTimeout(resolve, ms);
127
+ signal.addEventListener('abort', () => { clearTimeout(t); resolve(); }, { once: true });
128
+ });
129
+
130
+ /**
131
+ * Follows op until it is terminal and resolves with that state. Uses the
132
+ * push channel, resuming after op.seq; if the stream is refused, drops or
133
+ * ends early, it reads the operation and, while still running, polls with
134
+ * backoff. Rejects only when aborted or when the operation itself can't be
135
+ * read (an ApiRequestError, e.g. 404 or 403).
136
+ */
137
+ export async function followOperation<R = unknown>(op: Operation<R>, opts: FollowOptions<R> = {}): Promise<Operation<R>> {
138
+ const controller = new AbortController();
139
+ const onAbort = () => controller.abort();
140
+ opts.signal?.addEventListener('abort', onAbort, { once: true });
141
+ const sleep = opts.sleep ?? defaultSleep;
142
+ let latest = op;
143
+ const accept = (next: Operation<R>) => {
144
+ if (next.operationId !== op.operationId || next.seq <= latest.seq) return;
145
+ latest = next;
146
+ opts.onUpdate?.(next);
147
+ };
148
+
149
+ try {
150
+ if (isTerminal(latest)) return latest;
151
+ // 1. the stream, while it lasts
152
+ await new Promise<void>((resolve) => {
153
+ const sub = subscribe(join(opts.baseUrl, op.links.events), {
154
+ token: opts.token,
155
+ fetchImpl: opts.fetchImpl,
156
+ sleep,
157
+ lastEventId: String(op.seq),
158
+ onEvent: (e) => {
159
+ const next = operationFromEvent<R>(e);
160
+ if (next) accept(next);
161
+ if (isTerminal(latest)) sub.close();
162
+ },
163
+ // a refusal, or a second drop in a row: fall back to polling
164
+ onError: (err, attempt) => !(err instanceof StreamHTTPError) && attempt < 2,
165
+ });
166
+ controller.signal.addEventListener('abort', () => sub.close(), { once: true });
167
+ void sub.done.then(resolve);
168
+ });
169
+ // 2. polling, until terminal
170
+ let interval = opts.pollInitialMs ?? 1000;
171
+ const max = opts.pollMaxMs ?? 5000;
172
+ for (;;) {
173
+ if (controller.signal.aborted) throw new DOMException('aborted', 'AbortError');
174
+ if (isTerminal(latest)) return latest;
175
+ accept(await getOperation<R>(latest, opts));
176
+ if (isTerminal(latest)) return latest;
177
+ await sleep(interval, controller.signal);
178
+ interval = Math.min(max, interval * 2);
179
+ }
180
+ } finally {
181
+ opts.signal?.removeEventListener('abort', onAbort);
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Reads a 202 Accepted response as an Operation; a non-2xx is an
187
+ * ApiRequestError. For callers that make the write themselves.
188
+ */
189
+ export async function operationFromResponse<R = unknown>(res: Response): Promise<Operation<R>> {
190
+ if (!res.ok) throw await errorFromResponse(res);
191
+ const op = (await res.json()) as Operation<R>;
192
+ if (!op || typeof op.operationId !== 'string' || !op.links) throw new Error(`HTTP ${res.status}: not an operation`);
193
+ return op;
194
+ }
@@ -0,0 +1,200 @@
1
+ // The browser side of the platform's one streaming standard (daml-escrow
2
+ // PLAN.md 112.0.8): server-sent events read with fetch, so the bearer token
3
+ // travels in the Authorization header. Browser EventSource can't send that
4
+ // header, and a token in the URL would land in access logs. Mirrors
5
+ // daml-escrow-commons push (Encode's wire format: test/fixtures/push).
6
+ //
7
+ // Two modes, as on the server:
8
+ // - subscribe(): follow a topic (GET /events?topic=...), reconnecting with
9
+ // Last-Event-ID and backoff, so a dropped stream loses nothing;
10
+ // - streamResponse(): read one request's own streamed reply (e.g. a chat
11
+ // turn: POST the message, the answer streams back); abort it to stop.
12
+
13
+ /** One server-sent event. */
14
+ export interface PushEvent {
15
+ /** The SSE id (the topic's sequence number); '' when the server sent none. */
16
+ id: string;
17
+ /** The event name; 'message' when the server sent none. */
18
+ type: string;
19
+ data: string;
20
+ }
21
+
22
+ /**
23
+ * An incremental SSE parser: feed it text as it arrives, in chunks of any
24
+ * size, and it returns the events completed so far. Comment lines (the
25
+ * server's heartbeat) are skipped.
26
+ */
27
+ export class SSEParser {
28
+ private buffer = '';
29
+ private id = '';
30
+ private type = '';
31
+ private data: string[] = [];
32
+ private sawField = false;
33
+
34
+ feed(chunk: string): PushEvent[] {
35
+ this.buffer += chunk;
36
+ const out: PushEvent[] = [];
37
+ let nl: number;
38
+ while ((nl = this.nextLineEnd()) >= 0) {
39
+ let line = this.buffer.slice(0, nl);
40
+ // a CRLF pair is one line end
41
+ const skip = this.buffer[nl] === '\r' && this.buffer[nl + 1] === '\n' ? 2 : 1;
42
+ this.buffer = this.buffer.slice(nl + skip);
43
+ if (line === '') {
44
+ if (this.sawField) out.push({ id: this.id, type: this.type || 'message', data: this.data.join('\n') });
45
+ this.type = '';
46
+ this.data = [];
47
+ this.sawField = false;
48
+ continue;
49
+ }
50
+ if (line.startsWith(':')) continue;
51
+ const colon = line.indexOf(':');
52
+ const field = colon < 0 ? line : line.slice(0, colon);
53
+ let value = colon < 0 ? '' : line.slice(colon + 1);
54
+ if (value.startsWith(' ')) value = value.slice(1);
55
+ line = '';
56
+ switch (field) {
57
+ case 'id':
58
+ if (!value.includes('\0')) this.id = value;
59
+ this.sawField = true;
60
+ break;
61
+ case 'event':
62
+ this.type = value;
63
+ this.sawField = true;
64
+ break;
65
+ case 'data':
66
+ this.data.push(value);
67
+ this.sawField = true;
68
+ break;
69
+ // 'retry' and unknown fields are ignored
70
+ }
71
+ }
72
+ return out;
73
+ }
74
+
75
+ /** The id of the last event seen: what to send as Last-Event-ID on reconnect. */
76
+ get lastEventId(): string {
77
+ return this.id;
78
+ }
79
+
80
+ private nextLineEnd(): number {
81
+ const n = this.buffer.indexOf('\n');
82
+ const r = this.buffer.indexOf('\r');
83
+ if (r < 0) return n;
84
+ if (n < 0) return r === this.buffer.length - 1 ? -1 : r; // a lone trailing CR may be half a CRLF
85
+ return Math.min(n, r);
86
+ }
87
+ }
88
+
89
+ export interface StreamOptions {
90
+ /** The current access token; null sends no Authorization header. */
91
+ token?: () => string | null;
92
+ fetchImpl?: typeof fetch;
93
+ }
94
+
95
+ /** A non-2xx answer to a stream request. */
96
+ export class StreamHTTPError extends Error {
97
+ constructor(readonly response: Response) {
98
+ super(`stream refused: HTTP ${response.status}`);
99
+ this.name = 'StreamHTTPError';
100
+ }
101
+ }
102
+
103
+ async function openStream(url: string, init: RequestInit, opts: StreamOptions): Promise<Response> {
104
+ const headers = new Headers(init.headers);
105
+ headers.set('Accept', 'text/event-stream');
106
+ const token = opts.token?.();
107
+ if (token) headers.set('Authorization', `Bearer ${token}`);
108
+ const response = await (opts.fetchImpl ?? fetch)(url, { ...init, headers, cache: 'no-store' });
109
+ if (!response.ok || !response.body) throw new StreamHTTPError(response);
110
+ return response;
111
+ }
112
+
113
+ async function pump(response: Response, parser: SSEParser, onEvent: (e: PushEvent) => void): Promise<void> {
114
+ const reader = response.body!.pipeThrough(new TextDecoderStream()).getReader();
115
+ for (;;) {
116
+ const { value, done } = await reader.read();
117
+ if (done) return;
118
+ for (const e of parser.feed(value)) onEvent(e);
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Reads one request's streamed reply (mode b): resolves when the server ends
124
+ * the stream, rejects on a refusal (StreamHTTPError) or a broken connection.
125
+ * Pass an AbortSignal in init to stop it (e.g. a chat's Stop button).
126
+ */
127
+ export async function streamResponse(url: string, init: RequestInit, onEvent: (e: PushEvent) => void, opts: StreamOptions = {}): Promise<void> {
128
+ const response = await openStream(url, init, opts);
129
+ await pump(response, new SSEParser(), onEvent);
130
+ }
131
+
132
+ export interface SubscribeOptions extends StreamOptions {
133
+ onEvent: (e: PushEvent) => void;
134
+ /** Each failed connection; the subscription keeps retrying unless this returns false. */
135
+ onError?: (err: unknown, attempt: number) => boolean | void;
136
+ /** Called once the server ends the stream on its own (the topic's final event). */
137
+ onEnd?: () => void;
138
+ /** Resume after this id (e.g. a snapshot's seq). */
139
+ lastEventId?: string;
140
+ /** Reconnect backoff: first delay and cap, ms (defaults 500 and 15000). */
141
+ initialDelayMs?: number;
142
+ maxDelayMs?: number;
143
+ /** For tests: how to wait between attempts. */
144
+ sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
145
+ }
146
+
147
+ export interface Subscription {
148
+ close(): void;
149
+ /** Settles when the subscription ends (closed, ended by the server, or given up). */
150
+ readonly done: Promise<void>;
151
+ }
152
+
153
+ const defaultSleep = (ms: number, signal: AbortSignal) =>
154
+ new Promise<void>((resolve) => {
155
+ const t = setTimeout(resolve, ms);
156
+ signal.addEventListener('abort', () => { clearTimeout(t); resolve(); }, { once: true });
157
+ });
158
+
159
+ /**
160
+ * Follows a topic (mode a): GET url as a stream, reconnecting after a drop
161
+ * with Last-Event-ID and exponential backoff until close(), the server ends
162
+ * the stream (onEnd), or onError returns false. A refusal (4xx) other than
163
+ * 408/429 stops it: retrying won't help.
164
+ */
165
+ export function subscribe(url: string, opts: SubscribeOptions): Subscription {
166
+ const controller = new AbortController();
167
+ const sleep = opts.sleep ?? defaultSleep;
168
+ const initial = opts.initialDelayMs ?? 500;
169
+ const max = opts.maxDelayMs ?? 15000;
170
+ const parser = new SSEParser();
171
+ let last = opts.lastEventId ?? '';
172
+
173
+ const run = async () => {
174
+ let attempt = 0;
175
+ while (!controller.signal.aborted) {
176
+ try {
177
+ const headers: Record<string, string> = {};
178
+ if (last) headers['Last-Event-ID'] = last;
179
+ const response = await openStream(url, { method: 'GET', headers, signal: controller.signal }, opts);
180
+ attempt = 0;
181
+ await pump(response, parser, (e) => {
182
+ if (e.id) last = e.id;
183
+ opts.onEvent(e);
184
+ });
185
+ if (!controller.signal.aborted) opts.onEnd?.();
186
+ return;
187
+ } catch (err) {
188
+ if (controller.signal.aborted) return;
189
+ attempt++;
190
+ const fatal = err instanceof StreamHTTPError && err.response.status >= 400 && err.response.status < 500
191
+ && err.response.status !== 408 && err.response.status !== 429;
192
+ if (opts.onError?.(err, attempt) === false || fatal) return;
193
+ const delay = Math.min(max, initial * 2 ** (attempt - 1));
194
+ await sleep(delay, controller.signal);
195
+ }
196
+ }
197
+ };
198
+ const done = run();
199
+ return { close: () => controller.abort(), done };
200
+ }