@swirls/looms 0.20.0 → 0.22.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.
@@ -4,7 +4,7 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>Looms debugger</title>
7
- <script type="module" crossorigin src="./assets/index-Et8_0gnF.js"></script>
7
+ <script type="module" crossorigin src="./assets/index-CxbIGkpY.js"></script>
8
8
  <link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-CbXtAM7H.js">
9
9
  <link rel="stylesheet" crossorigin href="./assets/index-CO5gIvV8.css">
10
10
  </head>
@@ -0,0 +1,2 @@
1
+ export { LoomsHeaders, NatsProjectorError, natsProjector, type NatsConnectionSource, type NatsProjectorOptions, type NatsProjectorSettings, } from './projector';
2
+ export { encodeEventType, encodeSubjectToken, eventSubject, runSubjectFilter, streamSubject, } from './subjects';
@@ -0,0 +1,2 @@
1
+ export { LoomsHeaders, NatsProjectorError, natsProjector, } from './projector.js';
2
+ export { encodeEventType, encodeSubjectToken, eventSubject, runSubjectFilter, streamSubject, } from './subjects.js';
@@ -0,0 +1,69 @@
1
+ import type { StreamConfig } from '@nats-io/jetstream';
2
+ import type { NatsConnection } from '@nats-io/nats-core';
3
+ import { type Projector } from '@swirls/looms/projectors';
4
+ /** Headers on every message, so consumers can route without decoding the body. */
5
+ export declare const LoomsHeaders: {
6
+ readonly runId: 'Looms-Run-Id';
7
+ readonly seq: 'Looms-Seq';
8
+ readonly eventId: 'Looms-Event-Id';
9
+ readonly type: 'Looms-Type';
10
+ readonly threadId: 'Looms-Thread-Id';
11
+ readonly ephemeral: 'Looms-Ephemeral';
12
+ };
13
+ declare const NatsProjectorError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
14
+ readonly _tag: "NatsProjectorError";
15
+ } & Readonly<A>;
16
+ export declare class NatsProjectorError extends NatsProjectorError_base<{
17
+ readonly message: string;
18
+ readonly cause?: unknown;
19
+ /** JetStream `err_code` when the server rejected the request. */
20
+ readonly errCode?: number;
21
+ }> {
22
+ }
23
+ /**
24
+ * Where the projector gets its connection. Use whichever transport fits the runtime:
25
+ * `@nats-io/transport-node`, `wsconnect`, and so on.
26
+ */
27
+ export type NatsConnectionSource = {
28
+ /** A connection the caller owns. The projector never closes it. */
29
+ readonly connection: NatsConnection;
30
+ readonly connect?: never;
31
+ } | {
32
+ /**
33
+ * Opens a connection the projector owns: called on first use, called again after the
34
+ * connection closes, and drained on `dispose`.
35
+ */
36
+ readonly connect: () => PromiseLike<NatsConnection>;
37
+ readonly connection?: never;
38
+ };
39
+ export type NatsProjectorOptions = NatsConnectionSource & NatsProjectorSettings;
40
+ export interface NatsProjectorSettings {
41
+ /** JetStream stream name. Defaults to `LOOMS`. */
42
+ readonly stream?: string;
43
+ /** Subject prefix; events go to `<prefix>.run.<runId>.<type>`. Defaults to `looms`. */
44
+ readonly subjectPrefix?: string;
45
+ /**
46
+ * Stream config used when `init` finds no stream. `name`, `subjects` and `allow_atomic` are
47
+ * always set by the projector. Pass `false` when the stream is managed elsewhere.
48
+ */
49
+ readonly createStream?: Partial<StreamConfig> | false;
50
+ /** Events per atomic batch (at most 1000). Defaults to 1000. */
51
+ readonly maxBatch?: number;
52
+ /** Milliseconds to wait for a batch commit. Defaults to 5000. */
53
+ readonly timeoutMs?: number;
54
+ /** Projector name for delivery cursors and diagnostics. Defaults to `nats`. */
55
+ readonly name?: string;
56
+ }
57
+ /**
58
+ * Replicates committed events to a NATS JetStream stream, one subject per event:
59
+ * `<prefix>.run.<runId>.<type tokens>`. The body is the JSON envelope.
60
+ *
61
+ * Each batch is a JetStream atomic batch whose first message expects the run's last stream
62
+ * sequence, so a batch lands whole or not at all, and a concurrent writer or a hole in the run
63
+ * is refused by the server instead of reordering the copy. `position` reads the run's last
64
+ * message, so durable delivery rewinds and catches up when the stream is behind its cursor.
65
+ *
66
+ * Requires nats-server 2.12 or newer (atomic batch publish).
67
+ */
68
+ export declare function natsProjector(options: NatsProjectorOptions): Projector;
69
+ export {};
@@ -0,0 +1,278 @@
1
+ import { JetStreamApiCodes, JetStreamApiError, jetstreamManager } from '@nats-io/jetstream';
2
+ import { headers, nuid } from '@nats-io/nats-core';
3
+ import { Data, Effect, Schema } from 'effect';
4
+ import { encodeLoomsEvent } from '@swirls/looms/core';
5
+ import { ReplicaGapError } from '@swirls/looms/projectors';
6
+ import { eventSubject, isValidSubjectPrefix, runSubjectFilter, streamSubject } from './subjects.js';
7
+ /** Headers on every message, so consumers can route without decoding the body. */
8
+ export const LoomsHeaders = {
9
+ runId: 'Looms-Run-Id',
10
+ seq: 'Looms-Seq',
11
+ eventId: 'Looms-Event-Id',
12
+ type: 'Looms-Type',
13
+ threadId: 'Looms-Thread-Id',
14
+ ephemeral: 'Looms-Ephemeral',
15
+ };
16
+ /** The server refuses atomic batches over 1000 messages. */
17
+ const SERVER_BATCH_LIMIT = 1000;
18
+ /** JetStream `err_code` for a failed `Nats-Expected-Last-Subject-Sequence` check. */
19
+ const WRONG_LAST_SEQUENCE = 10071;
20
+ export class NatsProjectorError extends Data.TaggedError('NatsProjectorError') {
21
+ }
22
+ const CommitResponse = Schema.Union([
23
+ Schema.Struct({
24
+ error: Schema.Struct({
25
+ code: Schema.Finite,
26
+ err_code: Schema.optional(Schema.Finite),
27
+ description: Schema.String,
28
+ }),
29
+ }),
30
+ Schema.Struct({
31
+ stream: Schema.String,
32
+ seq: Schema.Finite,
33
+ }),
34
+ ]);
35
+ const decodeCommitResponse = Schema.decodeUnknownEffect(Schema.fromJsonString(CommitResponse));
36
+ const encoder = new TextEncoder();
37
+ function natsFailure(message) {
38
+ return (cause) => new NatsProjectorError({
39
+ message: `${message}: ${cause instanceof Error ? cause.message : String(cause)}`,
40
+ cause,
41
+ errCode: cause instanceof JetStreamApiError ? cause.code : undefined,
42
+ });
43
+ }
44
+ function attempt(message, operation) {
45
+ return Effect.tryPromise({ try: () => Promise.resolve(operation()), catch: natsFailure(message) });
46
+ }
47
+ function groupByRun(events) {
48
+ const groups = new Map();
49
+ for (const event of events) {
50
+ const batch = groups.get(event.runId) ?? [];
51
+ batch.push(event);
52
+ groups.set(event.runId, batch);
53
+ }
54
+ return groups;
55
+ }
56
+ function chunk(items, size) {
57
+ const chunks = [];
58
+ for (let index = 0; index < items.length; index += size) {
59
+ chunks.push(items.slice(index, index + size));
60
+ }
61
+ return chunks;
62
+ }
63
+ /** Events after `tail.loomsSeq`, refusing the batch if one is missing in front of them. */
64
+ function unpublished(runId, tail, events) {
65
+ const pending = [];
66
+ let cursor = tail.loomsSeq;
67
+ for (const event of events) {
68
+ if (event.seq <= cursor) {
69
+ continue;
70
+ }
71
+ if (event.seq !== cursor + 1) {
72
+ return Effect.fail(new ReplicaGapError({ runId, replicatedSeq: tail.loomsSeq, batchFrom: event.seq }));
73
+ }
74
+ pending.push(event);
75
+ cursor = event.seq;
76
+ }
77
+ return Effect.succeed(pending);
78
+ }
79
+ function batchMessage(prefix, runId, event, batch) {
80
+ const header = headers();
81
+ header.set('Nats-Batch-Id', batch.batchId);
82
+ header.set('Nats-Batch-Sequence', String(batch.position));
83
+ // No Nats-Msg-Id: the run-sequence expectation already refuses duplicates, and message ids
84
+ // outlive a purge inside the dedup window, which would block refilling a reset stream.
85
+ header.set(LoomsHeaders.runId, runId);
86
+ header.set(LoomsHeaders.seq, String(event.seq));
87
+ header.set(LoomsHeaders.eventId, event.id);
88
+ header.set(LoomsHeaders.type, event.type);
89
+ if (event.threadId) {
90
+ header.set(LoomsHeaders.threadId, event.threadId);
91
+ }
92
+ if (event.ephemeral) {
93
+ header.set(LoomsHeaders.ephemeral, 'true');
94
+ }
95
+ if (batch.expected !== undefined) {
96
+ header.set('Nats-Expected-Last-Subject-Sequence', String(batch.expected));
97
+ header.set('Nats-Expected-Last-Subject-Sequence-Subject', runSubjectFilter(prefix, runId));
98
+ }
99
+ if (batch.commit) {
100
+ header.set('Nats-Batch-Commit', '1');
101
+ }
102
+ return {
103
+ subject: eventSubject(prefix, runId, event.type),
104
+ payload: encoder.encode(JSON.stringify(encodeLoomsEvent(event))),
105
+ headers: header,
106
+ };
107
+ }
108
+ /**
109
+ * Replicates committed events to a NATS JetStream stream, one subject per event:
110
+ * `<prefix>.run.<runId>.<type tokens>`. The body is the JSON envelope.
111
+ *
112
+ * Each batch is a JetStream atomic batch whose first message expects the run's last stream
113
+ * sequence, so a batch lands whole or not at all, and a concurrent writer or a hole in the run
114
+ * is refused by the server instead of reordering the copy. `position` reads the run's last
115
+ * message, so durable delivery rewinds and catches up when the stream is behind its cursor.
116
+ *
117
+ * Requires nats-server 2.12 or newer (atomic batch publish).
118
+ */
119
+ export function natsProjector(options) {
120
+ const stream = options.stream ?? 'LOOMS';
121
+ const prefix = options.subjectPrefix ?? 'looms';
122
+ const maxBatch = Math.min(options.maxBatch ?? SERVER_BATCH_LIMIT, SERVER_BATCH_LIMIT);
123
+ const timeout = options.timeoutMs ?? 5_000;
124
+ const name = options.name ?? 'nats';
125
+ if (!isValidSubjectPrefix(prefix)) {
126
+ throw new NatsProjectorError({
127
+ message: `Subject prefix "${prefix}" must be dot-separated [A-Za-z0-9_-] tokens`,
128
+ });
129
+ }
130
+ if (!Number.isInteger(maxBatch) || maxBatch < 1) {
131
+ throw new NatsProjectorError({ message: 'maxBatch must be a positive integer' });
132
+ }
133
+ const open = options.connect;
134
+ const borrowed = options.connection;
135
+ let opened;
136
+ let live;
137
+ let manager;
138
+ let ready;
139
+ const connection = Effect.suspend(() => {
140
+ if (!open) {
141
+ return borrowed
142
+ ? Effect.succeed(borrowed)
143
+ : Effect.fail(new NatsProjectorError({ message: 'Pass `connection` or `connect`' }));
144
+ }
145
+ return attempt('NATS connect failed', () => {
146
+ if (live?.isClosed()) {
147
+ live = undefined;
148
+ opened = undefined;
149
+ }
150
+ opened ??= Promise.resolve(open()).then((nc) => {
151
+ live = nc;
152
+ return nc;
153
+ }, (cause) => {
154
+ opened = undefined;
155
+ throw cause;
156
+ });
157
+ return opened;
158
+ });
159
+ });
160
+ const jsm = connection.pipe(Effect.flatMap((nc) => {
161
+ if (manager?.connection === nc) {
162
+ return Effect.succeed(manager.jsm);
163
+ }
164
+ return attempt('JetStream unavailable', () => jetstreamManager(nc)).pipe(Effect.tap((created) => Effect.sync(() => {
165
+ manager = { connection: nc, jsm: created };
166
+ })));
167
+ }));
168
+ const ensureStream = Effect.gen(function* () {
169
+ const streams = (yield* jsm).streams;
170
+ const info = yield* attempt(`Reading stream ${stream} failed`, () => streams.info(stream)).pipe(Effect.catchIf((error) => error.errCode === JetStreamApiCodes.StreamNotFound, () => Effect.succeed(null)));
171
+ if (info?.config.allow_atomic === true) {
172
+ return info;
173
+ }
174
+ if (info) {
175
+ return yield* new NatsProjectorError({
176
+ message: `Stream ${stream} must set allow_atomic: true for the Looms NATS projector`,
177
+ });
178
+ }
179
+ if (options.createStream === false) {
180
+ return yield* new NatsProjectorError({ message: `Stream ${stream} does not exist` });
181
+ }
182
+ return yield* attempt(`Creating stream ${stream} failed`, () => streams.add({
183
+ ...options.createStream,
184
+ name: stream,
185
+ subjects: [streamSubject(prefix)],
186
+ allow_atomic: true,
187
+ }));
188
+ });
189
+ const init = () => {
190
+ ready ??= Effect.runPromise(Effect.asVoid(ensureStream)).catch((cause) => {
191
+ ready = undefined;
192
+ throw cause;
193
+ });
194
+ return ready;
195
+ };
196
+ const readTail = (runId) => Effect.gen(function* () {
197
+ const streams = (yield* jsm).streams;
198
+ const last = yield* attempt(`Reading the last message of ${runId} failed`, () => streams.getMessage(stream, { last_by_subj: runSubjectFilter(prefix, runId) }));
199
+ if (!last) {
200
+ return { loomsSeq: 0, streamSeq: 0 };
201
+ }
202
+ const loomsSeq = Number(last.header?.get(LoomsHeaders.seq));
203
+ if (!Number.isSafeInteger(loomsSeq) || loomsSeq < 1) {
204
+ return yield* new NatsProjectorError({
205
+ message: `Message ${last.seq} on ${last.subject} has no ${LoomsHeaders.seq} header`,
206
+ });
207
+ }
208
+ return { loomsSeq, streamSeq: last.seq };
209
+ });
210
+ const publishBatch = (runId, batch, expected) => Effect.gen(function* () {
211
+ const nc = yield* connection;
212
+ const batchId = nuid.next();
213
+ const commit = yield* Effect.try({
214
+ try: () => {
215
+ const messages = batch.map((event, index) => batchMessage(prefix, runId, event, {
216
+ batchId,
217
+ position: index + 1,
218
+ expected: index === 0 ? expected : undefined,
219
+ commit: index === batch.length - 1,
220
+ }));
221
+ for (const message of messages.slice(0, -1)) {
222
+ nc.publish(message.subject, message.payload, { headers: message.headers });
223
+ }
224
+ return messages.at(-1);
225
+ },
226
+ catch: natsFailure(`Publishing ${runId} failed`),
227
+ });
228
+ if (!commit) {
229
+ return expected;
230
+ }
231
+ const reply = yield* attempt(`Committing ${runId} batch failed`, () => nc.request(commit.subject, commit.payload, { headers: commit.headers, timeout }));
232
+ const response = yield* decodeCommitResponse(reply.string()).pipe(Effect.mapError(natsFailure(`Unreadable commit reply for ${runId}`)));
233
+ if ('error' in response) {
234
+ const errCode = response.error.err_code;
235
+ const conflict = errCode === WRONG_LAST_SEQUENCE;
236
+ return yield* new NatsProjectorError({
237
+ message: conflict
238
+ ? `Another writer published to ${runId} first (${response.error.description})`
239
+ : `JetStream refused the ${runId} batch: ${response.error.description}`,
240
+ errCode,
241
+ });
242
+ }
243
+ return response.seq;
244
+ });
245
+ const projectRun = (runId, events) => Effect.gen(function* () {
246
+ const tail = yield* readTail(runId);
247
+ const pending = yield* unpublished(runId, tail, events);
248
+ let expected = tail.streamSeq;
249
+ for (const batch of chunk(pending, maxBatch)) {
250
+ expected = yield* publishBatch(runId, batch, expected);
251
+ }
252
+ });
253
+ return {
254
+ name,
255
+ version: '1',
256
+ init,
257
+ position: (runId) => init().then(() => Effect.runPromise(readTail(runId).pipe(Effect.map((tail) => tail.loomsSeq)))),
258
+ project: (events) => {
259
+ if (events.length === 0) {
260
+ return Promise.resolve();
261
+ }
262
+ return init().then(() => Effect.runPromise(Effect.forEach(groupByRun(events), ([runId, batch]) => projectRun(runId, batch), {
263
+ discard: true,
264
+ })));
265
+ },
266
+ dispose: () => {
267
+ const owned = opened;
268
+ opened = undefined;
269
+ live = undefined;
270
+ manager = undefined;
271
+ ready = undefined;
272
+ if (!owned) {
273
+ return Promise.resolve();
274
+ }
275
+ return owned.then((nc) => (nc.isClosed() ? undefined : nc.drain()), () => undefined);
276
+ },
277
+ };
278
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Encode one subject token. Characters outside `[A-Za-z0-9_-]` become `~HH` per UTF-8 byte,
3
+ * and the empty string becomes `~`. Raw tokens never contain `~`, so two different inputs
4
+ * never share a token: a run's subjects can't collide with another run's.
5
+ */
6
+ export declare function encodeSubjectToken(value: string): string;
7
+ /** Each dot-separated part of an event type becomes its own token, so `>` and `*` filter by type. */
8
+ export declare function encodeEventType(type: string): string;
9
+ export declare function isValidSubjectPrefix(prefix: string): boolean;
10
+ /** `<prefix>.run.>`: everything this projector publishes. */
11
+ export declare function streamSubject(prefix: string): string;
12
+ /** `<prefix>.run.<runId>.>`: one run's events, in the order they were published. */
13
+ export declare function runSubjectFilter(prefix: string, runId: string): string;
14
+ export declare function eventSubject(prefix: string, runId: string, type: string): string;
@@ -0,0 +1,44 @@
1
+ const SAFE_TOKEN = /^[A-Za-z0-9_-]+$/;
2
+ const encoder = new TextEncoder();
3
+ /**
4
+ * Encode one subject token. Characters outside `[A-Za-z0-9_-]` become `~HH` per UTF-8 byte,
5
+ * and the empty string becomes `~`. Raw tokens never contain `~`, so two different inputs
6
+ * never share a token: a run's subjects can't collide with another run's.
7
+ */
8
+ export function encodeSubjectToken(value) {
9
+ if (value.length === 0) {
10
+ return '~';
11
+ }
12
+ if (SAFE_TOKEN.test(value)) {
13
+ return value;
14
+ }
15
+ let token = '';
16
+ for (const char of value) {
17
+ if (SAFE_TOKEN.test(char)) {
18
+ token += char;
19
+ continue;
20
+ }
21
+ for (const byte of encoder.encode(char)) {
22
+ token += `~${byte.toString(16).toUpperCase().padStart(2, '0')}`;
23
+ }
24
+ }
25
+ return token;
26
+ }
27
+ /** Each dot-separated part of an event type becomes its own token, so `>` and `*` filter by type. */
28
+ export function encodeEventType(type) {
29
+ return type.split('.').map(encodeSubjectToken).join('.');
30
+ }
31
+ export function isValidSubjectPrefix(prefix) {
32
+ return prefix.split('.').every((token) => SAFE_TOKEN.test(token));
33
+ }
34
+ /** `<prefix>.run.>`: everything this projector publishes. */
35
+ export function streamSubject(prefix) {
36
+ return `${prefix}.run.>`;
37
+ }
38
+ /** `<prefix>.run.<runId>.>`: one run's events, in the order they were published. */
39
+ export function runSubjectFilter(prefix, runId) {
40
+ return `${prefix}.run.${encodeSubjectToken(runId)}.>`;
41
+ }
42
+ export function eventSubject(prefix, runId, type) {
43
+ return `${prefix}.run.${encodeSubjectToken(runId)}.${encodeEventType(type)}`;
44
+ }
@@ -5,4 +5,4 @@ export type { StoreObservation, StoreObserver } from './observer';
5
5
  export { materializeEvents } from './materialize';
6
6
  export { emptyTables, type MaterializedTables, type RunRow, type ThreadRow } from './tables';
7
7
  export type { LoomsRegister, RegisteredEvent, AnyEventEnvelope } from '@swirls/looms/core';
8
- export { LoomsProvider, preloadRunStore, useRunStore, useProjection, useRunSelector, useRunSummary, useRunEvents, useThreadTree, useEventCounts, useEventBySeq, useLatestEvent, useLiveFold, type LoomsProviderProps, type PreloadRunStoreOptions, type RunStoreOptions, type UseRunStoreOptions, type RunSummary, } from './react';
8
+ export { LoomsProvider, preloadRunStore, useRunStore, useProjection, useRunSelector, useRunSummary, useRunEvents, useThreadTree, useEventCounts, useEventBySeq, useLatestEvent, useLiveFold, type LoomsProviderProps, type PreloadRunStoreOptions, type RunGrantSource, type RunStoreOptions, type UseRunStoreOptions, type RunSummary, } from './react';
@@ -1,4 +1,5 @@
1
1
  import { type ReactNode } from 'react';
2
+ import type { SubscriptionSocketConstructor } from '@swirls/looms/client';
2
3
  import { type AnyEventEnvelope, type ProjectionDefinition, type RegisteredEvent, type RunAttributes, type RunLaunchSource, type RunStatus, type SubscriptionTransport, type ThreadTree } from '@swirls/looms/core';
3
4
  import type { EventCache } from './cache';
4
5
  import { defineLiveFold, foldLive, type LiveFoldDefinition } from './derived';
@@ -19,8 +20,25 @@ export interface LoomsProviderProps {
19
20
  cache?: EventCache;
20
21
  /** Told how long each run took to show and how long each commit took. */
21
22
  observer?: StoreObserver;
23
+ /** Makes every HTTP request a run store sends. See `LoomsClientStoreOptions.fetch`. */
24
+ fetch?: typeof fetch;
25
+ /** Opens a run store's live socket, in place of the global `WebSocket`. */
26
+ webSocket?: SubscriptionSocketConstructor;
27
+ /**
28
+ * The read grant for a run, for a host on another origin than the page. Asked each time a
29
+ * store connects. See `LoomsClientStoreOptions.grant`.
30
+ */
31
+ grant?: RunGrantSource;
32
+ }
33
+ /** What gives a run's current read grant, or undefined when it has none. */
34
+ export type RunGrantSource = (runId: string) => string | undefined;
35
+ /** How a store reaches its host. Not part of which store a run gets: the first to open it decides. */
36
+ interface StoreReach {
37
+ readonly fetch?: typeof fetch;
38
+ readonly webSocket?: SubscriptionSocketConstructor;
39
+ readonly grant?: RunGrantSource;
22
40
  }
23
- interface ProviderContextValue {
41
+ interface ProviderContextValue extends StoreReach {
24
42
  endpoint: string;
25
43
  coalesce?: CoalesceOption;
26
44
  transport?: SubscriptionTransport;
@@ -29,7 +47,7 @@ interface ProviderContextValue {
29
47
  observer?: StoreObserver;
30
48
  }
31
49
  /** Root provider that supplies the Looms host endpoint to run stores. */
32
- export declare function LoomsProvider({ children, endpoint, coalesce, transport, retainMs, cache, observer, }: LoomsProviderProps): import("react").FunctionComponentElement<import("react").ProviderProps<ProviderContextValue>>;
50
+ export declare function LoomsProvider({ children, endpoint, coalesce, transport, retainMs, cache, observer, fetch, webSocket, grant, }: LoomsProviderProps): import("react").FunctionComponentElement<import("react").ProviderProps<ProviderContextValue>>;
33
51
  export interface UseRunStoreOptions {
34
52
  endpoint?: string;
35
53
  reconnectDelayMs?: number;
@@ -44,9 +62,15 @@ export interface UseRunStoreOptions {
44
62
  /**
45
63
  * Everything that decides which store a run gets when there is no provider to supply part of
46
64
  * it. Inside React the provider gives `endpoint`, `coalesce`, `transport`, `retainMs`, `cache`
47
- * and `observer`; outside it the caller passes them.
65
+ * `observer`, `fetch`, `webSocket` and `grant`; outside it the caller passes them.
48
66
  */
49
67
  export interface RunStoreOptions extends UseRunStoreOptions {
68
+ /** Makes every HTTP request the store sends. See `LoomsClientStoreOptions.fetch`. */
69
+ fetch?: typeof fetch;
70
+ /** Opens the store's live socket, in place of the global `WebSocket`. */
71
+ webSocket?: SubscriptionSocketConstructor;
72
+ /** The read grant for a run. See `LoomsClientStoreOptions.grant`. */
73
+ grant?: RunGrantSource;
50
74
  /** Keeps the run's durable events on the device. See `indexedDbEventCache`. */
51
75
  cache?: EventCache;
52
76
  /** Told how long the run took to show and how long each commit took. */
@@ -43,6 +43,9 @@ function peekStore(runId, identity) {
43
43
  fromSeq: identity.fromSeq,
44
44
  cache: identity.cache,
45
45
  observer: identity.observer,
46
+ fetch: identity.fetch,
47
+ webSocket: identity.webSocket,
48
+ grant: identity.grant === undefined ? undefined : () => identity.grant?.(runId),
46
49
  });
47
50
  const retainMs = Math.max(0, identity.retainMs ?? DEFAULT_RETAIN_MS);
48
51
  registry.set(key, {
@@ -79,8 +82,8 @@ function releaseStore(runId, identity) {
79
82
  }
80
83
  }
81
84
  /** Root provider that supplies the Looms host endpoint to run stores. */
82
- export function LoomsProvider({ children, endpoint = '', coalesce, transport, retainMs, cache, observer, }) {
83
- const value = useMemo(() => ({ endpoint, coalesce, transport, retainMs, cache, observer }), [endpoint, coalesce, transport, retainMs, cache, observer]);
85
+ export function LoomsProvider({ children, endpoint = '', coalesce, transport, retainMs, cache, observer, fetch, webSocket, grant, }) {
86
+ const value = useMemo(() => ({ endpoint, coalesce, transport, retainMs, cache, observer, fetch, webSocket, grant }), [endpoint, coalesce, transport, retainMs, cache, observer, fetch, webSocket, grant]);
84
87
  return createElement(LoomsContext.Provider, { value, children });
85
88
  }
86
89
  /**
@@ -160,6 +163,9 @@ export function useRunStore(runId, options) {
160
163
  retainMs,
161
164
  cache: context.cache,
162
165
  observer: context.observer,
166
+ fetch: context.fetch,
167
+ webSocket: context.webSocket,
168
+ grant: context.grant,
163
169
  };
164
170
  const store = peekStore(runId, identity);
165
171
  useEffect(() => {
@@ -46,7 +46,19 @@ export interface LoomsClientStoreOptions {
46
46
  endpoint: string;
47
47
  /** Backoff between reconnects. The delay stays fixed, matching the SSE client. */
48
48
  reconnectDelayMs?: number;
49
+ /**
50
+ * Makes every HTTP request the store sends, so a host can add what its backend authenticates
51
+ * by. With one, the live stream is read through it too, in place of `EventSource`, which
52
+ * cannot carry headers.
53
+ */
49
54
  fetch?: typeof fetch;
55
+ /**
56
+ * A read grant for this run (see `issueRunGrant`), or what gives the current one. Sent as
57
+ * `grant` on the requests that read the log, the WebSocket included, which has no other way
58
+ * to carry a credential across origins. Asked again on every connection, so a host can hand
59
+ * out short-lived grants and renew them. Never sent with a commit.
60
+ */
61
+ grant?: string | (() => string | undefined);
50
62
  coalesce?: CoalesceOption;
51
63
  /**
52
64
  * `undefined` keeps the current SSE path. `websocket` and `auto` use a hibernating
@@ -292,8 +292,16 @@ export function createLoomsStore(options) {
292
292
  }
293
293
  }
294
294
  };
295
+ /** Adds the run's read grant to a request that reads its log, when the host gave one. */
296
+ const withGrant = (params) => {
297
+ const grant = Predicate.isFunction(options.grant) ? options.grant() : options.grant;
298
+ if (grant !== undefined && grant !== '') {
299
+ params.set('grant', grant);
300
+ }
301
+ return params;
302
+ };
295
303
  const liveUrl = () => {
296
- const params = new URLSearchParams({ live: 'true', fromSeq: String(fromSeq) });
304
+ const params = withGrant(new URLSearchParams({ live: 'true', fromSeq: String(fromSeq) }));
297
305
  if (options.threadId) {
298
306
  params.set('threadId', options.threadId);
299
307
  }
@@ -303,7 +311,8 @@ export function createLoomsStore(options) {
303
311
  return `${endpoint}/runs/${encodeURIComponent(options.storeId)}/events?${params.toString()}`;
304
312
  };
305
313
  const pull = Effect.gen(function* () {
306
- const url = `${endpoint}/runs/${encodeURIComponent(options.storeId)}/events?fromSeq=${fromSeq}`;
314
+ const query = withGrant(new URLSearchParams({ fromSeq: String(fromSeq) }));
315
+ const url = `${endpoint}/runs/${encodeURIComponent(options.storeId)}/events?${query.toString()}`;
307
316
  const res = yield* Effect.tryPromise({
308
317
  try: (signal) => fetchFn(url, { signal }),
309
318
  catch: (cause) => new LoomsStoreError('Event pull failed', cause),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swirls/looms",
3
- "version": "0.20.0",
3
+ "version": "0.22.0",
4
4
  "description": "Pluggable event-sourced runtime for durable agents and workflows",
5
5
  "homepage": "https://github.com/ByteSliceHQ/looms#readme",
6
6
  "bugs": {
@@ -85,6 +85,10 @@
85
85
  "types": "./dist/evaluator/index.d.ts",
86
86
  "import": "./dist/evaluator/index.js"
87
87
  },
88
+ "./nats": {
89
+ "types": "./dist/nats/index.d.ts",
90
+ "import": "./dist/nats/index.js"
91
+ },
88
92
  "./projectors": {
89
93
  "types": "./dist/projectors/index.d.ts",
90
94
  "import": "./dist/projectors/index.js"
@@ -194,6 +198,8 @@
194
198
  },
195
199
  "dependencies": {
196
200
  "@effect/platform-bun": "^4.1.4",
201
+ "@nats-io/jetstream": "3.4.0",
202
+ "@nats-io/nats-core": "3.4.0",
197
203
  "@noble/hashes": "^2.0.1",
198
204
  "@s2-dev/streamstore": "^0.23.0",
199
205
  "@standard-schema/spec": "^1.1.0",
@@ -218,6 +224,7 @@
218
224
  "@looms/debugger": "workspace:*",
219
225
  "@looms/debugger-app": "workspace:*",
220
226
  "@looms/evaluator": "workspace:*",
227
+ "@looms/nats": "workspace:*",
221
228
  "@looms/projectors": "workspace:*",
222
229
  "@looms/react": "workspace:*",
223
230
  "@looms/runtime": "workspace:*",