@streamsy/core 0.2.0 → 0.4.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/dist/index.d.ts CHANGED
@@ -1,792 +1,3 @@
1
- //#region src/types/storage.d.ts
2
- /**
3
- * Simplified storage boundary for Streamsy.
4
- *
5
- * Adapters persist facts and may provide runtime capabilities (notification,
6
- * expiration scheduling). Atomic mutation is expressed through append and
7
- * lifecycle intents on the storage adapter; protocol/lifecycle policy lives in
8
- * core.
9
- */
10
- type StreamId = string;
11
- /**
12
- * Public stream offset. **Seam guarantee**: offsets are fixed-width,
13
- * lexicographically ordered strings of the form `<counter:16>_<sub:16>` where
14
- * both parts are zero-padded decimals, so **lexicographic order = offset
15
- * order**. Adapters rely on this to compare and window offsets inside their own
16
- * storage engines (SQL `WHERE offset > ?`, key-range scans, line filtering).
17
- * `compareOffsets` and `ZERO_OFFSET` are exported from the package root.
18
- * Within one stream incarnation an offset only ever advances; a purge followed
19
- * by a re-create restarts the offset sequence.
20
- */
21
- type Offset = string;
22
- /**
23
- * One stored message. `data` is binary (`Uint8Array`) — it survives structured
24
- * clone (the Durable Object RPC boundary) but is NOT plain JSON; a remote
25
- * adapter transporting messages over JSON must encode it (e.g. base64).
26
- */
27
- interface StoredMessage {
28
- data: Uint8Array;
29
- offset: Offset;
30
- timestamp: number;
31
- }
32
- interface StreamConfig {
33
- contentType: string;
34
- ttlSeconds?: number;
35
- expiresAt?: string;
36
- createdAt: number;
37
- }
38
- interface StreamLifecycleState {
39
- lastSeq?: string;
40
- closed?: boolean;
41
- closedAt?: number;
42
- forkedFrom?: StreamId;
43
- forkOffset?: Offset;
44
- /**
45
- * Sub-message boundary inside the source message that follows `forkOffset`.
46
- * Only recorded when a fork materialized a partial-message prefix (`> 0`).
47
- * For binary/text it counts bytes within the next source message; for JSON it
48
- * counts flattened messages/items. Kept purely for fork idempotency/config
49
- * matching — reads use the materialized prefix stored as the child's own
50
- * messages, not this value.
51
- */
52
- forkSubOffset?: number;
53
- softDeleted?: boolean;
54
- /**
55
- * Effective expiration deadline in epoch ms. Core updates this on create
56
- * and on TTL touches; lazy `expireIfNeeded()` reads it. Absent when the
57
- * stream has neither `ttlSeconds` nor `expiresAt`.
58
- */
59
- expiresAtMs?: number;
60
- }
61
- interface StreamRecord {
62
- id: StreamId;
63
- config: StreamConfig;
64
- lifecycle: StreamLifecycleState;
65
- currentOffset: Offset;
66
- counter: number;
67
- }
68
- /**
69
- * **Patches set values; they never delete them.** An absent field means "leave
70
- * unchanged". Clearing a field is deliberately inexpressible: `undefined` is
71
- * dropped by JSON but preserved by structured clone, so "set to undefined"
72
- * would behave differently across transports. Core never clears fields.
73
- */
74
- interface StreamRecordPatch {
75
- config?: Partial<StreamConfig>;
76
- lifecycle?: Partial<StreamLifecycleState>;
77
- currentOffset?: Offset;
78
- counter?: number;
79
- }
80
- interface ProducerState {
81
- epoch: number;
82
- lastSeq: number;
83
- }
84
- interface ListMessagesOptions {
85
- after?: Offset;
86
- until?: Offset;
87
- limit?: number;
88
- }
89
- /**
90
- * Observable, serializable snapshot of the change-relevant state of one stream.
91
- * Every field is a JSON-serializable primitive so the snapshot crosses a Durable
92
- * Object RPC (or any future remote adapter) boundary unchanged.
93
- */
94
- interface StreamChangeSnapshot {
95
- /** `false` once the record has been purged. */
96
- present: boolean;
97
- currentOffset: Offset;
98
- closed: boolean;
99
- softDeleted: boolean;
100
- }
101
- /**
102
- * Serializable, closure-free input to the level-triggered live-wait seam. The
103
- * caller passes the position/lifecycle state it already observed; the adapter
104
- * re-reads durable state and decides whether anything relevant advanced.
105
- */
106
- interface AwaitChangeOptions {
107
- /** The offset the live reader is parked at. */
108
- fromOffset: Offset;
109
- /** Closed state the caller already observed (treated as `false` when absent). */
110
- observedClosed?: boolean;
111
- /** Soft-deleted state the caller already observed (treated as `false` when absent). */
112
- observedSoftDeleted?: boolean;
113
- timeoutMs: number;
114
- }
115
- /**
116
- * Result of {@link AwaitChangeOptions}. There is no `aborted` status:
117
- * cancellation is caller-local and the adapter never learns about it.
118
- *
119
- * `timeout` means "no relevant change observed yet" — it does NOT promise the
120
- * full `timeoutMs` budget elapsed. Adapters MAY return `timeout` early (bounded
121
- * parks are encouraged for remote backends, e.g. a Durable Object capping the
122
- * total wait so a single RPC never strands the actor). Callers MUST re-park on
123
- * `timeout` rather than assume the budget was consumed.
124
- */
125
- type AwaitChangeResult = {
126
- status: "changed";
127
- snapshot: StreamChangeSnapshot;
128
- } | {
129
- status: "timeout";
130
- snapshot: StreamChangeSnapshot;
131
- };
132
- interface Clock {
133
- now(): number;
134
- date(value?: number | string): Date;
135
- } //#endregion
136
- //#region src/types/storage-adapter.d.ts
137
- interface StreamReader {
138
- getRecord(streamId: StreamId): Promise<StreamRecord | null>;
139
- listMessages(streamId: StreamId, options?: ListMessagesOptions): Promise<StoredMessage[]>;
140
- getProducerState(streamId: StreamId, producerId: string): Promise<ProducerState | undefined>;
141
- }
142
- /**
143
- * Streamsy's real atomic write: messages + record advance + optional producer
144
- * compare-and-set + preconditions, in one transaction. `recordPatch` is required.
145
- * A message-bearing append advances `currentOffset` / `counter` (a pure close folds
146
- * into the same patch via `lifecycle.closed`); a lifecycle-only TTL renewal
147
- * (`ExpiryPolicy.touch`) is the one append shape that patches the record without
148
- * advancing offset/counter. Closure-free and serializable.
149
- */
150
- interface AppendPlan {
151
- preconditions: {
152
- expectedOffset?: Offset;
153
- expectedClosed?: boolean;
154
- /**
155
- * Producer compare-and-set. An **absent** `expected` means "the producer
156
- * must not exist yet" (insert-if-absent) — it does NOT mean "don't check,
157
- * just set". Every implementation must fail the append with reason
158
- * `"producer"` when `expected` is absent but a state already exists.
159
- */
160
- producer?: {
161
- producerId: string;
162
- expected?: ProducerState;
163
- next: ProducerState;
164
- };
165
- };
166
- messages?: StoredMessage[];
167
- recordPatch: StreamRecordPatch;
168
- }
169
- /**
170
- * `reason` is required on `precondition-failed` and names the precondition that
171
- * tripped. When multiple preconditions fail simultaneously, attribute in the
172
- * order **offset → closed → producer**. Backends with opaque conditional writes
173
- * may derive `reason` best-effort from a post-failure re-read under concurrency
174
- * (report `"offset"` when the failure cannot be attributed, e.g. the record was
175
- * concurrently purged); single-writer attribution must be exact — the contract
176
- * kit tests exactly that case. Core's retry loop re-plans from `record` and does
177
- * not branch on `reason`; it exists for adapter diagnostics and kit sharpness.
178
- */
179
- type StorageAppendResult = {
180
- status: "appended";
181
- record: StreamRecord;
182
- } | {
183
- status: "precondition-failed";
184
- record: StreamRecord | null;
185
- reason: "offset" | "closed" | "producer";
186
- };
187
- interface StreamAppender {
188
- append(streamId: StreamId, plan: AppendPlan): Promise<StorageAppendResult>;
189
- }
190
- /**
191
- * `record` is the single source of truth for the created stream, including a
192
- * created-closed stream (`record.lifecycle.closed` / `closedAt` are pre-folded
193
- * by core). Adapters persist the record as given; there is no separate
194
- * close-after step.
195
- */
196
- interface CreatePlan {
197
- record: StreamRecord;
198
- initialMessages?: StoredMessage[];
199
- }
200
- type StorageCreateResult = {
201
- status: "created";
202
- record: StreamRecord;
203
- } | {
204
- status: "exists";
205
- record: StreamRecord;
206
- };
207
- interface ForkPlan {
208
- child: StreamRecord;
209
- sourceId: StreamId;
210
- initialMessages?: StoredMessage[];
211
- /**
212
- * Source liveness check: the fork proceeds only if the source exists, is not
213
- * soft-deleted, and its `currentOffset` is `>=` `sourceLiveAtOffset`
214
- * (lexicographic offset comparison). Its only failure is `fork-source-gone`.
215
- */
216
- precondition: {
217
- sourceLiveAtOffset: Offset;
218
- };
219
- }
220
- /**
221
- * `exists` carries the existing child record so core can run the same
222
- * config-match idempotency it applies to `create` — a byte-identical racing
223
- * fork resolves as idempotent success rather than a bogus conflict.
224
- */
225
- type StorageForkResult = {
226
- status: "created";
227
- record: StreamRecord;
228
- } | {
229
- status: "exists";
230
- record: StreamRecord;
231
- } | {
232
- status: "fork-source-gone";
233
- };
234
- interface DeletePlan {
235
- streamId: StreamId;
236
- reason: "delete" | "expiry";
237
- }
238
- type StorageDeleteResult = {
239
- status: "purged";
240
- } | {
241
- status: "retained-soft-deleted";
242
- } | {
243
- status: "not-found";
244
- } | {
245
- status: "gone";
246
- };
247
- /**
248
- * Per-stream level-triggered live waiter. Serializable in and out: the argument
249
- * and result carry only plain data, so the seam crosses a Durable Object RPC (or
250
- * any future remote adapter) boundary unchanged.
251
- *
252
- * Required: every adapter implements `awaitChange`. A backend that can wake
253
- * cheaply does so directly; one that cannot implements it by polling its own
254
- * durable reads. Core wires no polling fallback in silently, but it exports the
255
- * contract-faithful loop — `runAwaitChangeLoop` — plus the shared
256
- * `buildChangeSnapshot` / `changeSnapshotDiffers` primitives, so an adapter
257
- * supplies only `readRecord` + `waitForWake` (a minimal polling adapter's
258
- * `waitForWake` is a sleep) and stays faithful to the level-triggered contract.
259
- */
260
- interface StreamLiveWaiter {
261
- awaitChange(streamId: StreamId, options: AwaitChangeOptions): Promise<AwaitChangeResult>;
262
- }
263
- /** Per-stream active expiry scheduler. */
264
- interface StreamExpiryScheduler {
265
- scheduleExpiry(streamId: StreamId, at: number): Promise<void> | void;
266
- cancelExpiry(streamId: StreamId): Promise<void> | void;
267
- }
268
- /**
269
- * The storage backend an adapter author implements: one flat, fully serializable
270
- * interface. Per-stream methods take `streamId` first; lifecycle intents carry
271
- * the id in their plan. Adapters keep a private per-stream handle and delegate to
272
- * it internally.
273
- */
274
- interface StorageAdapter extends StreamReader, StreamAppender, StreamLiveWaiter, StreamExpiryScheduler {
275
- create(plan: CreatePlan): Promise<StorageCreateResult>;
276
- fork?(plan: ForkPlan): Promise<StorageForkResult>;
277
- delete(plan: DeletePlan): Promise<StorageDeleteResult>;
278
- }
279
- /**
280
- * Structured "feature not supported" protocol result. Protocol methods map
281
- * typed storage unsupported behavior to this public result shape.
282
- */
283
- interface NotSupportedResult {
284
- status: "not-supported";
285
- feature: string;
286
- message?: string;
287
- }
288
- /** Internal/storage-level unsupported-feature error. */
289
- declare class NotSupportedError extends Error {
290
- readonly feature: string;
291
- constructor(feature: string, message?: string);
292
- }
293
- /** Convenience constructor for a {@link NotSupportedResult}. */
294
- declare function notSupported(feature: string, message?: string): NotSupportedResult;
295
- /** Convenience constructor for a storage-level unsupported-feature error. */
296
- declare function unsupported(feature: string, message?: string): NotSupportedError;
297
- /** Type guard for storage-level unsupported-feature errors. */
298
- declare function isNotSupportedError(value: unknown): value is NotSupportedError;
299
- /** Convert storage-level unsupported-feature errors to public protocol results. */
300
- declare function notSupportedFromError(error: NotSupportedError): NotSupportedResult;
301
- /** Type guard for protocol results that may be a {@link NotSupportedResult}. */
302
- declare function isNotSupported(value: unknown): value is NotSupportedResult;
303
-
304
- //#endregion
305
- //#region src/types/protocol.d.ts
306
- interface CreateOptions {
307
- contentType?: string;
308
- ttlSeconds?: number;
309
- expiresAt?: string;
310
- initialData?: Uint8Array;
311
- closed?: boolean;
312
- forkedFrom?: string;
313
- forkOffset?: string;
314
- /**
315
- * Optional sub-message boundary inside the source message at `forkOffset`.
316
- * `0` is treated as equivalent to an absent header. For binary/text it is a
317
- * byte count within the next source message; for JSON it is a flattened
318
- * message/item count. Requires `forkedFrom`; values `> 0` require
319
- * `forkOffset`.
320
- */
321
- forkSubOffset?: number;
322
- }
323
- interface ProducerOptions {
324
- producerId: string;
325
- producerEpoch: number;
326
- producerSeq: number;
327
- }
328
- interface AppendOptions {
329
- data: Uint8Array;
330
- contentType: string;
331
- seq?: string;
332
- producer?: ProducerOptions;
333
- close?: boolean;
334
- /**
335
- * Optimistic-concurrency precondition: append only if the stream's tail
336
- * offset still equals this offset. On mismatch the append fails with a
337
- * `conflict`/`expected-offset` result carrying the actual tail, and no
338
- * state (messages, close flag, producer state) is changed. `ZERO_OFFSET`
339
- * means "append only if the stream is still empty". Streamsy extension to
340
- * the Durable Streams protocol.
341
- */
342
- expectedOffset?: string;
343
- }
344
- interface ReadOptions {
345
- offset?: string;
346
- }
347
- interface ReadLiveOptions {
348
- offset: string;
349
- mode: "long-poll" | "sse";
350
- cursor?: string;
351
- signal?: AbortSignal;
352
- }
353
- type CreateConflictReason = "config-mismatch" | "soft-deleted" | "fork-content-type" | "fork-source-soft-deleted";
354
- type CreateFailureResult = {
355
- status: "conflict";
356
- nextOffset: string;
357
- contentType: string;
358
- conflictReason?: CreateConflictReason;
359
- errorMessage?: string;
360
- } | {
361
- status: "not-found" | "bad-request";
362
- nextOffset: string;
363
- contentType: string;
364
- errorMessage?: string;
365
- } | NotSupportedResult;
366
- /**
367
- * Create/fork result produced by the protocol services, before the bound
368
- * protocol stream is attached. The protocol factory grafts the resolved
369
- * `stream` onto success outcomes to produce the public {@link CreateResult}.
370
- *
371
- * `created` and `exists` are kept as separate members (rather than a combined
372
- * `"created" | "exists"` discriminant) so callers can narrow either status and
373
- * still eliminate the other union members.
374
- */
375
-
376
- type CreateResult = {
377
- status: "created";
378
- stream: ProtocolStream;
379
- nextOffset: string;
380
- contentType: string;
381
- closed?: boolean;
382
- } | {
383
- status: "exists";
384
- stream: ProtocolStream;
385
- nextOffset: string;
386
- contentType: string;
387
- closed?: boolean;
388
- } | CreateFailureResult;
389
- type AppendConflictReason = "content-type" | "sequence" | "closed" | "expected-offset";
390
- type AppendResult = {
391
- status: "appended";
392
- /**
393
- * Exact stream offset after this append: the offset of the last message
394
- * written by it (for a close-only append with no body, the unchanged
395
- * tail offset). This is the write-acknowledgement token — a reader or
396
- * mirror that has passed `offset` has observed this write. Because reads
397
- * are after-exclusive, it is also the read cursor.
398
- */
399
- offset: string;
400
- producerEpoch?: number;
401
- producerSeq?: number;
402
- closed?: boolean;
403
- } | {
404
- status: "duplicate";
405
- /**
406
- * Current tail offset at acknowledgement time. The originally appended
407
- * message sits at or before `offset`, so it remains a valid
408
- * write-acknowledgement token for sync ("synced once your mirror passes
409
- * offset X").
410
- */
411
- offset: string;
412
- producerEpoch: number;
413
- producerSeq: number;
414
- closed?: boolean;
415
- } | {
416
- status: "not-found";
417
- } | {
418
- status: "gone";
419
- } | {
420
- status: "conflict";
421
- conflictReason: "closed";
422
- offset: string;
423
- closed: true;
424
- } | {
425
- status: "conflict";
426
- conflictReason: "expected-offset";
427
- /**
428
- * Actual tail offset at the time the `expectedOffset` precondition
429
- * failed, so callers can see how far behind they were. Retry loops
430
- * should re-read state and rebuild the append from the new tail.
431
- */
432
- offset: string;
433
- } | {
434
- status: "conflict";
435
- conflictReason: "content-type" | "sequence";
436
- } | {
437
- status: "busy";
438
- } | {
439
- status: "stale-epoch";
440
- currentEpoch: number;
441
- } | {
442
- status: "producer-gap";
443
- expectedSeq: number;
444
- receivedSeq: number;
445
- } | {
446
- status: "invalid-epoch-seq";
447
- } | NotSupportedResult;
448
- type ReadResult = {
449
- status: "ok";
450
- messages: StoredMessage[];
451
- nextOffset: string;
452
- upToDate: boolean;
453
- closed?: boolean;
454
- } | {
455
- status: "not-found";
456
- } | {
457
- status: "gone";
458
- };
459
- type ReadLiveResult = {
460
- status: "ok" | "timeout" | "not-found" | "gone";
461
- messages: StoredMessage[];
462
- nextOffset: string;
463
- upToDate: boolean;
464
- cursor: string;
465
- closed?: boolean;
466
- } | NotSupportedResult;
467
- type MetadataResult = {
468
- status: "ok";
469
- contentType: string;
470
- nextOffset: string;
471
- ttlSeconds?: number;
472
- expiresAt?: string;
473
- closed?: boolean;
474
- } | {
475
- status: "not-found";
476
- } | {
477
- status: "gone";
478
- };
479
- type DeleteResult = {
480
- status: "ok";
481
- } | {
482
- status: "not-found";
483
- } | {
484
- status: "gone";
485
- };
486
- interface ProtocolStream {
487
- readonly id: StreamId;
488
- append(options: AppendOptions): Promise<AppendResult>;
489
- read(options: ReadOptions): Promise<ReadResult>;
490
- readLive(options: ReadLiveOptions): Promise<ReadLiveResult>;
491
- metadata(): Promise<MetadataResult>;
492
- delete(): Promise<DeleteResult>;
493
- }
494
- type ProtocolGetResult = {
495
- status: "ok";
496
- stream: ProtocolStream;
497
- } | {
498
- status: "not-found";
499
- } | {
500
- status: "gone";
501
- } | NotSupportedResult;
502
- interface StreamProtocolFactory {
503
- create(streamId: string, options: CreateOptions): Promise<CreateResult>;
504
- get(streamId: string): Promise<ProtocolGetResult>;
505
- }
506
-
507
- //#endregion
508
- //#region src/protocol/helpers/bind-stream.d.ts
509
- /** The per-stream surface core call sites use (was the seam `Stream`). */
510
- interface BoundStream {
511
- readonly id: StreamId;
512
- getRecord(): Promise<StreamRecord | null>;
513
- listMessages(options?: ListMessagesOptions): Promise<StoredMessage[]>;
514
- getProducerState(producerId: string): Promise<ProducerState | undefined>;
515
- append(plan: AppendPlan): Promise<StorageAppendResult>;
516
- awaitChange(options: AwaitChangeOptions): Promise<AwaitChangeResult>;
517
- scheduleExpiry(at: number): Promise<void> | void;
518
- cancelExpiry(): Promise<void> | void;
519
- }
520
- declare function bindStream(adapter: StorageAdapter, id: StreamId): BoundStream;
521
-
522
- //#endregion
523
- //#region src/protocol/helpers/offset-generator.d.ts
524
- declare const ZERO_OFFSET: Offset;
525
- declare function compareOffsets(a: Offset, b: Offset): number;
526
-
527
- //#endregion
528
- //#region src/protocol.d.ts
529
- interface StreamProtocolOptions {
530
- clock?: Clock;
531
- longPollTimeoutMs?: number;
532
- }
533
- interface StreamProtocolDeps extends StreamProtocolOptions {
534
- storage: {
535
- adapter: StorageAdapter;
536
- };
537
- }
538
- declare function createStreamProtocol(deps: StreamProtocolDeps): StreamProtocolFactory;
539
- declare class StreamProtocol implements StreamProtocolFactory {
540
- private deps;
541
- private clock;
542
- private longPollTimeoutMs;
543
- private expiryPolicy;
544
- private recordFactory;
545
- constructor(deps: StreamProtocolDeps);
546
- create(streamId: string, options: CreateOptions): Promise<CreateResult>;
547
- get(streamId: string): Promise<ProtocolGetResult>;
548
- /** Called by adapter schedulers/alarms; core decides whether expiry applies. */
549
- handleScheduledExpiry(streamId: string): Promise<void>;
550
- private boundProtocolStream;
551
- /** Bind the flat adapter to one id for ergonomic core-side per-stream calls. */
552
- private storageStream;
553
- }
554
-
555
- //#endregion
556
- //#region src/storage/memory/stream.d.ts
557
- /**
558
- * Adapter-internal write engine input. Superset of {@link AppendPlan} with an
559
- * optional `createRecord` — the `create`/`fork` intents reuse the same engine to
560
- * insert the record, while the public `append` never carries `createRecord`.
561
- */
562
- interface WritePlan {
563
- createRecord?: StreamRecord;
564
- preconditions: AppendPlan["preconditions"];
565
- messages?: StoredMessage[];
566
- recordPatch?: StreamRecordPatch;
567
- }
568
- type WriteResult = {
569
- status: "committed";
570
- record: StreamRecord;
571
- } | {
572
- status: "precondition-failed";
573
- record: StreamRecord | null;
574
- reason?: "offset" | "closed" | "producer";
575
- };
576
- /** Adapter-private per-stream handle. Not on the seam — owned by the memory state. */
577
- declare class MemoryStream {
578
- readonly id: StreamId;
579
- private readonly deleteFromState;
580
- private readonly records;
581
- private readonly messages;
582
- private readonly producers;
583
- private readonly notifier;
584
- private readonly timeout;
585
- constructor(id: StreamId, deleteFromState: () => void, onScheduledExpiry?: () => Promise<void> | void);
586
- getRecord(): StreamRecord | null;
587
- /** Public append intent (no `createRecord`). */
588
- append(plan: AppendPlan): StorageAppendResult;
589
- /**
590
- * Adapter-internal write engine shared by `append` (no `createRecord`) and the
591
- * `create`/`fork` intents (with `createRecord`).
592
- */
593
- applyMutation(plan: WritePlan): WriteResult;
594
- listMessages(options?: ListMessagesOptions): StoredMessage[];
595
- getProducerState(producerId: string): ProducerState | undefined;
596
- purgeSelf(): void;
597
- softDelete(): void;
598
- /**
599
- * Level-triggered live wait via the shared exported loop: re-read durable
600
- * state first (so a mutation that landed between the caller's observation and
601
- * this call is never missed), then park on the wake bus until the state
602
- * advances or the budget expires. Read and park are synchronous with the wake
603
- * bus here, so no per-park cap is needed.
604
- */
605
- awaitChange(options: AwaitChangeOptions): Promise<AwaitChangeResult>;
606
- scheduleExpiry(at: number): Promise<void> | void;
607
- cancelExpiry(): Promise<void> | void;
608
- }
609
-
610
- //#endregion
611
- //#region src/storage/memory/state.d.ts
612
- type MemoryExpiryHandler = (streamId: string) => Promise<void> | void;
613
- /** Shared in-memory stream registry. */
614
- declare class MemoryStreamState {
615
- private readonly onScheduledExpiry?;
616
- private readonly streams;
617
- private readonly childEdges;
618
- constructor(onScheduledExpiry?: MemoryExpiryHandler | undefined);
619
- getStream(id: string): MemoryStream;
620
- getExistingStream(id: string): MemoryStream | undefined;
621
- addEdge(parent: string, child: string): void;
622
- dropEdge(parent: string, child: string): void;
623
- countDependents(parent: string): number;
624
- private deleteStream;
625
- }
626
-
627
- //#endregion
628
- //#region src/storage/memory/adapter.d.ts
629
- interface MemoryStorageAdapterOptions {
630
- /**
631
- * Share an existing memory state. Omit to get a fresh, isolated state.
632
- */
633
- state?: MemoryStreamState;
634
- onScheduledExpiry?: (streamId: StreamId) => Promise<void> | void;
635
- }
636
- declare function createMemoryStorageAdapter(options?: MemoryStorageAdapterOptions): StorageAdapter;
637
-
638
- //#endregion
639
- //#region src/http/types.d.ts
640
- interface HttpHandlerOptions {
641
- protocol: StreamProtocolFactory;
642
- pathPrefix?: string;
643
- maxMessageSize?: number;
644
- }
645
- interface ReadOnlyHttpHandlerOptions {
646
- protocol: StreamProtocolFactory;
647
- pathPrefix?: string;
648
- }
649
- interface HttpHandlerInterface {
650
- fetch(request: Request): Promise<Response>;
651
- }
652
-
653
- //#endregion
654
- //#region src/http.d.ts
655
- declare function createHttpHandler(options: HttpHandlerOptions): HttpHandlerInterface;
656
- declare class HttpHandler implements HttpHandlerInterface {
657
- private dispatch;
658
- constructor(options: HttpHandlerOptions);
659
- fetch(request: Request): Promise<Response>;
660
- }
661
-
662
- //#endregion
663
- //#region src/read-only-http.d.ts
664
- declare function createReadOnlyHttpHandler(options: ReadOnlyHttpHandlerOptions): HttpHandlerInterface;
665
- declare class ReadOnlyHttpHandler implements HttpHandlerInterface {
666
- private dispatch;
667
- constructor(options: ReadOnlyHttpHandlerOptions);
668
- fetch(request: Request): Promise<Response>;
669
- }
670
-
671
- //#endregion
672
- //#region src/protocol/helpers/change-snapshot.d.ts
673
- /** Build the serializable, change-relevant snapshot of a (possibly absent) record. */
674
- declare function buildChangeSnapshot(record: StreamRecord | null): StreamChangeSnapshot;
675
- /**
676
- * The level-triggered "differs" predicate. A snapshot differs from what the
677
- * caller observed when the record was purged, transitioned to soft-deleted or
678
- * closed, or its offset is not the parked position. Offset **inequality** — not
679
- * just advance — is the trigger: within one incarnation an offset only ever
680
- * advances, so a *lower* offset means the stream was purged and re-created
681
- * while the waiter was parked, which is also "something happened".
682
- */
683
- declare function changeSnapshotDiffers(snapshot: StreamChangeSnapshot, options: Pick<AwaitChangeOptions, "fromOffset" | "observedClosed" | "observedSoftDeleted">): boolean;
684
-
685
- //#endregion
686
- //#region src/protocol/helpers/await-change-loop.d.ts
687
- interface AwaitChangeLoopDeps {
688
- /** Read the current durable record. May be sync or async. */
689
- readRecord(): StreamRecord | null | Promise<StreamRecord | null>;
690
- /** Park until a wake or the given timeout, whichever comes first. */
691
- waitForWake(timeoutMs: number): Promise<void>;
692
- /** Cap the TOTAL wait budget (early `timeout` return; callers re-park). */
693
- totalCapMs?: number;
694
- /** Cap each individual park so a lost wake is repaired within the cap. */
695
- parkCapMs?: number;
696
- /** Wall clock; overridable for deterministic tests. */
697
- now?: () => number;
698
- }
699
- declare function runAwaitChangeLoop(deps: AwaitChangeLoopDeps, options: AwaitChangeOptions): Promise<AwaitChangeResult>;
700
-
701
- //#endregion
702
- //#region src/http/responses.d.ts
703
- declare class HttpResponseFactory {
704
- secure(response: Response): Response;
705
- text(message: string | null, status: number, headers?: HeadersInit): Response;
706
- empty(status: number, headers?: HeadersInit): Response;
707
- badRequest(message: string): Response;
708
- notFound(message?: string): Response;
709
- gone(message?: string): Response;
710
- conflict(message: string | null, headers?: HeadersInit): Response;
711
- payloadTooLarge(): Response;
712
- invalidJson(): Response;
713
- methodNotAllowed(): Response;
714
- internalError(): Response;
715
- /**
716
- * Wrap a response with the standard security headers used across every
717
- * route. Existing values for the same header names are preserved.
718
- */
719
- withSecurityHeaders(response: Response): Response;
720
- }
721
-
722
- //#endregion
723
- //#region src/http/not-supported.d.ts
724
- declare function notSupportedResponse(result: NotSupportedResult, responses: HttpResponseFactory): Response;
725
- /**
726
- * Convenience for use in `case`-style handlers that may want to short
727
- * circuit on a `not-supported` result before pattern-matching the rest of a
728
- * union.
729
- */
730
- declare function maybeNotSupportedResponse<T>(result: T | NotSupportedResult, responses: HttpResponseFactory): Response | null;
731
-
732
- //#endregion
733
- //#region src/testing/storage-adapter-contract.d.ts
734
- /** Minimal test-runner surface. Satisfied by vitest's and `bun:test`'s `it`. */
735
- interface StorageAdapterContractHarness {
736
- it(name: string, fn: () => void | Promise<void>): void;
737
- }
738
- /** Build a fresh, isolated adapter for one contract case. */
739
- type MakeStorageAdapter = () => StorageAdapter | Promise<StorageAdapter>;
740
- /**
741
- * Register the full storage-adapter contract against `makeAdapter` using the
742
- * provided test harness. Wrap in the caller's own `describe` for grouping:
743
- *
744
- * ```ts
745
- * import { it } from "vitest";
746
- * describe("memory adapter contract", () => {
747
- * runStorageAdapterContract(() => createMemoryStorageAdapter(), { it });
748
- * });
749
- * ```
750
- */
751
- declare function runStorageAdapterContract(makeAdapter: MakeStorageAdapter, harness: StorageAdapterContractHarness): void;
752
-
753
- //#endregion
754
- //#region src/storage/strategies/lineage-store.d.ts
755
- interface LineageStore {
756
- getRecord(id: StreamId): Promise<StreamRecord | null>;
757
- purgeSelf(id: StreamId): Promise<void>;
758
- softDelete(id: StreamId): Promise<void>;
759
- addEdge?(parent: StreamId, child: StreamId): Promise<void>;
760
- dropEdge?(parent: StreamId, child: StreamId): Promise<void>;
761
- countDependents?(parent: StreamId): Promise<number>;
762
- }
763
- interface LineagePolicy {
764
- countDependents(parent: StreamId): Promise<number>;
765
- addEdge(parent: StreamId, child: StreamId): Promise<void>;
766
- dropEdge(parent: StreamId, child: StreamId): Promise<void>;
767
- }
768
- type DependentsQuery = (parent: StreamId) => Promise<number>;
769
-
770
- //#endregion
771
- //#region src/storage/strategies/cascade-reclaim.d.ts
772
- declare function cascadeReclaim(store: LineageStore, plan: DeletePlan, lineage: LineagePolicy): Promise<StorageDeleteResult>;
773
- declare function plainPurge(store: LineageStore, plan: DeletePlan): Promise<StorageDeleteResult>;
774
-
775
- //#endregion
776
- //#region src/storage/strategies/ref-count-lineage.d.ts
777
- declare function refCountLineage(store: LineageStore): LineagePolicy;
778
-
779
- //#endregion
780
- //#region src/storage/strategies/reverse-index-lineage.d.ts
781
- declare function reverseIndexLineage(query: DependentsQuery): LineagePolicy;
782
-
783
- //#endregion
784
- //#region src/storage/strategies/copy-on-fork.d.ts
785
- declare function copyOnForkReclaim(): LineagePolicy;
786
-
787
- //#endregion
788
- //#region src/storage/strategies/ttl-only.d.ts
789
- declare function ttlOnlyReclaim(): LineagePolicy;
790
-
791
- //#endregion
792
- export { AppendConflictReason, AppendOptions, AppendPlan, AppendResult, AwaitChangeLoopDeps, AwaitChangeOptions, AwaitChangeResult, BoundStream, Clock, CreateConflictReason, CreateOptions, CreatePlan, CreateResult, DeletePlan, DeleteResult, DependentsQuery, ForkPlan, HttpHandler, HttpHandlerInterface, HttpHandlerOptions, LineagePolicy, LineageStore, ListMessagesOptions, MakeStorageAdapter, MemoryStorageAdapterOptions, MetadataResult, NotSupportedError, NotSupportedResult, Offset, ProducerOptions, ProducerState, ProtocolGetResult, ProtocolStream, ReadLiveOptions, ReadLiveResult, ReadOnlyHttpHandler, ReadOnlyHttpHandlerOptions, ReadOptions, ReadResult, StorageAdapter, StorageAdapterContractHarness, StorageAppendResult, StorageCreateResult, StorageDeleteResult, StorageForkResult, StoredMessage, StreamAppender, StreamChangeSnapshot, StreamConfig, StreamExpiryScheduler, StreamId, StreamLifecycleState, StreamLiveWaiter, StreamProtocol, StreamProtocolDeps, StreamProtocolFactory, StreamProtocolOptions, StreamReader, StreamRecord, StreamRecordPatch, ZERO_OFFSET, bindStream, buildChangeSnapshot, cascadeReclaim, changeSnapshotDiffers, compareOffsets, copyOnForkReclaim, createHttpHandler, createMemoryStorageAdapter, createReadOnlyHttpHandler, createStreamProtocol, isNotSupported, isNotSupportedError, maybeNotSupportedResponse, notSupported, notSupportedFromError, notSupportedResponse, plainPurge, refCountLineage, reverseIndexLineage, runAwaitChangeLoop, runStorageAdapterContract, ttlOnlyReclaim, unsupported };
1
+ import { $ as ProducerOptions, A as CreateConflictReason, B as ProducerGap, C as ReadNextResult, D as AppendError, E as AppendConflict, F as InvalidEpochSeq, G as StaleEpoch, H as ReadError, I as InvalidForkRequest, J as StreamGone, K as StreamBusy, L as InvalidReadRequest, M as ForkSourceNotFound, N as HeadError, O as AppendErrorFor, P as InvalidAppendRequest, Q as AppendOptions, R as NotSupported, S as ReadMessage, T as AppendBaseError, U as ReadNextError, V as ProtocolError, W as RemoveError, X as isProtocolError, Y as StreamNotFound, Z as AppendCallOptions, _t as StreamsFault, a as Mutation, at as Offset, b as CreateResult, bt as isStreamsFault, c as Mutations, ct as RecordPatch, d as OperationResults, dt as StreamId, et as ReadNextOptions, f as Operations, ft as StreamLifecycle, gt as StorageFault, ht as EncodeFault, i as StorageShape, it as MessageWindow, j as CreateError, k as CreateConflict, l as Operation, lt as StoredMessage, m as StorageCapabilities, mt as DecodeFault, nt as CreateOptions, o as MutationApplied, ot as ProducerId, p as ProducerPrecondition, pt as StreamRecord, q as StreamClosed, r as Storage, rt as ChangeSnapshot, s as MutationRejected, st as ProducerState, tt as ReadOptions, u as OperationResult, ut as StreamConfig, vt as TransportFault, w as ReadResult, x as HeadResult, y as AppendResult, yt as isRetryableFault, z as OffsetMismatch } from "./owner-records-QDlssl__.js";
2
+ import { A as durable_state_d_exports, B as address_d_exports, C as FollowFailure, E as RemoveFailure, F as CommitBoundary, I as CommitBoundaryApi, L as ZERO_OFFSET, O as streamsy_d_exports, R as compare, S as Folded, T as ReadFailure, _ as Collected, b as Decided, g as Batch, h as AppendFailure, j as streams_d_exports, k as producer_d_exports, t as index_d_exports, v as CreateFailure, w as HeadFailure, x as Decision, y as DecideSpec } from "./index-CFv8vZvy.js";
3
+ export { AppendBaseError, type AppendCallOptions, AppendConflict, AppendError, AppendErrorFor, type AppendFailure, type AppendOptions, AppendResult, type Batch, ChangeSnapshot, type Collected, CommitBoundary, type CommitBoundaryApi, CreateConflict, CreateConflictReason, CreateError, type CreateFailure, type CreateOptions, CreateResult, type DecideSpec, type Decided, type Decision, DecodeFault, durable_state_d_exports as DurableState, EncodeFault, type Folded, type FollowFailure, ForkSourceNotFound, HeadError, type HeadFailure, type HeadResult, index_d_exports as Http, InvalidAppendRequest, InvalidEpochSeq, InvalidForkRequest, InvalidReadRequest, streams_d_exports as MemoryStorage, MessageWindow, Mutation, MutationApplied, MutationRejected, Mutations, NotSupported, Offset, OffsetMismatch, Operation, OperationResult, OperationResults, Operations, producer_d_exports as Producer, ProducerGap, ProducerId, type ProducerOptions, ProducerPrecondition, ProducerState, ProtocolError, ReadError, type ReadFailure, type ReadMessage, ReadNextError, type ReadNextOptions, type ReadNextResult, type ReadOptions, type ReadResult, RecordPatch, RemoveError, type RemoveFailure, StaleEpoch, Storage, StorageCapabilities, StorageFault, type StorageShape, StoredMessage, address_d_exports as StreamAddress, StreamBusy, StreamClosed, StreamConfig, StreamGone, StreamId, StreamLifecycle, StreamNotFound, StreamRecord, StreamsFault, streamsy_d_exports as Streamsy, TransportFault, ZERO_OFFSET, compare, isProtocolError, isRetryableFault, isStreamsFault };