@streamsy/core 0.15.0 → 0.16.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.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { $ as ProducerState, A as StreamBusy, C as InvalidEpochSeq, D as OffsetMismatch, E as NotSupported, G as StreamsFault, H as DecodeFault, J as isStreamsFault, K as TransportFault, L as Storage, M as StreamGone, N as StreamNotFound, O as ProducerGap, P as isProtocolError, Q as ProducerId, R as ZERO_OFFSET, S as InvalidCreateRequest, T as InvalidReadRequest, U as EncodeFault, W as StorageFault, X as MessageWindow, Y as ChangeSnapshot, Z as Offset, _ as CreateResult, a as custom, at as StreamRecord, b as ForkSourceNotFound, c as state, d as address_exports, et as RecordPatch, f as isControl, g as AppendResult, h as stateControl, it as StreamLifecycle, j as StreamClosed, k as StaleEpoch, m as stateChange, n as bind, nt as StreamConfig, o as group, p as isUpsert, q as isRetryableFault, r as bytes, rt as StreamId, s as json, t as Wildcard, tt as StoredMessage, v as AppendConflict, w as InvalidForkRequest, x as InvalidAppendRequest, y as CreateConflict, z as compare } from "./streamsy-HKC10a_V.js";
3
- import { p as CommitBoundary } from "./boundary-f1biibJ1.js";
4
- import { a as MutationRejected, c as OperationResult, d as ProducerPrecondition, i as MutationApplied, l as OperationResults, o as Mutations, r as Mutation, s as Operation, t as layer$1, u as Operations } from "./layer-DjKTdIY5.js";
5
- import { t as layer$2 } from "./layer-J6sV3UXD.js";
6
- import { t as http_exports } from "./http-YoA8cUTN.js";
2
+ import { A as StreamBusy, C as InvalidEpochSeq, D as OffsetMismatch, E as NotSupported, G as ProducerId, H as ChangeSnapshot, J as StoredMessage, K as ProducerState, L as Storage, M as StreamGone, N as StreamNotFound, O as ProducerGap, P as isProtocolError, Q as StreamRecord, R as ZERO_OFFSET, S as InvalidCreateRequest, T as InvalidReadRequest, U as MessageWindow, W as Offset, X as StreamId, Y as StreamConfig, Z as StreamLifecycle, _ as CreateResult, a as custom, b as ForkSourceNotFound, c as state, d as address_exports, f as isControl, g as AppendResult, h as stateControl, j as StreamClosed, k as StaleEpoch, m as stateChange, n as bind, o as group, p as isUpsert, q as RecordPatch, r as bytes, s as json, t as Wildcard, v as AppendConflict, w as InvalidForkRequest, x as InvalidAppendRequest, y as CreateConflict, z as compare } from "./streamsy-IBFULoEr.js";
3
+ import { _ as StorageFault, b as isRetryableFault, g as EncodeFault, h as DecodeFault, v as StreamsFault, x as isStreamsFault, y as TransportFault } from "./read-message-CGHhOCMc.js";
4
+ import { p as CommitBoundary } from "./boundary-BTrhL8De.js";
5
+ import { a as MutationRejected, c as OperationResult, d as ProducerPrecondition, i as MutationApplied, l as OperationResults, o as Mutations, r as Mutation, s as Operation, t as layer$1, u as Operations } from "./layer-pomDIajD.js";
6
+ import { t as layer$2 } from "./layer-C-8GAL_W.js";
7
+ import { t as http_exports } from "./http-BNYNMGuk.js";
7
8
  import { Array, Data, Effect, Layer, Option, Predicate, Record, Schema, Stream } from "effect";
8
9
  // src/storage/capabilities.ts
9
10
  const StorageCapabilities = Schema.Struct({
@@ -179,72 +180,87 @@ const next = (position) => ({
179
180
  ...position,
180
181
  producerSeq: position.producerSeq + 1
181
182
  });
182
- // src/toolkit/wake.ts
183
+ // src/toolkit/frontier.ts
184
+ /** "The stream holding this row reflects `stream` up to `offset`." Offsets of one source are fixed-width strings. `closed` is present when the source is closed. */
185
+ const Frontier = Schema.Struct({
186
+ stream: Schema.String,
187
+ offset: Schema.String,
188
+ closed: Schema.optionalKey(Schema.Literal(true))
189
+ });
190
+ /** Spread into a State declaration's collections under any name. */
191
+ const frontier = {
192
+ schema: Frontier,
193
+ key: "stream"
194
+ };
195
+ /**
196
+ * "A reader sees this write once it reflects `stream` up to `offset`." A server answers one after
197
+ * an append. It has the shape of a `Frontier` row, as a separate schema, so a collection declared
198
+ * with `Token` is not taken for a frontier collection.
199
+ */
200
+ const Token = Schema.Struct({
201
+ stream: Schema.String,
202
+ offset: Schema.String
203
+ });
204
+ /** The token of an append to `address`: its stream id and the tail after the write. */
205
+ const token = (address, appended) => Token.make({
206
+ stream: address.id,
207
+ offset: appended.offset
208
+ });
209
+ // src/toolkit/frontier-stream.ts
183
210
  /**
184
- * Wake streams: one Durable State stream that indexes the writes of a family of
211
+ * Frontier streams: one Durable State stream that indexes the writes of a family of
185
212
  * source streams.
186
213
  *
187
- * A wake declaration is a State stream with one `stream` collection. Each row
214
+ * A frontier stream declaration is a State stream with one `stream` collection. Each row
188
215
  * is the latest known state of one source stream. A projection writes the rows:
189
- * `Projection.wake` in `@streamsy/projection` reads one source stream and
216
+ * `Projection.frontier` in `@streamsy/projection` reads one source stream and
190
217
  * appends its row with a producer tuple, on the same owner or another one. A
191
- * wake stream on another owner must exist first: its owner creates it at start.
218
+ * frontier stream on another owner must exist first: its owner creates it at start.
192
219
  * The typed service is the normal State service.
193
220
  */
194
- /** One row of a wake stream: the latest known state of one source stream. */
195
- const WakeRow = Schema.Struct({
196
- /** Canonical id of the source stream. It is also the State key. */
197
- stream: StreamId,
198
- /**
199
- * A position in the source that the row's writer vouches for. The stream
200
- * holding the row says what is vouched: written in a source wake stream,
201
- * or accepted in a projection's accepted stream.
202
- */
203
- offset: Offset,
204
- /** Present when the source stream is closed. */
205
- closed: Schema.optionalKey(Schema.Literal(true))
206
- });
207
- /** The one collection of every wake stream. Its State `type` is `stream`. */
208
- const wakeCollections = { stream: {
209
- schema: WakeRow,
210
- key: "stream"
211
- } };
212
221
  /**
213
- * The codec of one wake stream message: a `stream` change or a State control.
222
+ * The one collection of every frontier stream. Its State `type` is `stream`, and each row is a
223
+ * `Frontier`: the source stream id, a position in the source that the row's writer vouches
224
+ * for, and `closed` when the source is closed. The stream holding the row says what is
225
+ * vouched: written in a source frontier stream, or accepted in a projection's frontier stream.
226
+ */
227
+ const frontierStreamCollections = { stream: frontier };
228
+ /**
229
+ * The codec of one frontier stream message: a `stream` change or a State control.
214
230
  * A client that decodes raw JSON pages uses it in place of a typed service.
215
231
  */
216
- const WakeMessage = Schema.Union([stateChange({
232
+ const FrontierMessage = Schema.Union([stateChange({
217
233
  type: "stream",
218
- schema: WakeRow
234
+ schema: Frontier
219
235
  }), stateControl]);
220
236
  /**
221
- * Declare a wake stream: a State stream of `WakeRow`s at a template.
237
+ * Declare a frontier stream: a State stream of `Frontier` rows at a template.
222
238
  *
223
239
  * ```ts
224
- * class UserWake extends Streamsy.wake<UserWake>()("App/UserWake", "users/:user/wake", {
240
+ * class UserFrontier extends Streamsy.frontierStream<UserFrontier>()("App/UserFrontier", "users/:user/frontier", {
225
241
  * params: { user: UserKey },
226
242
  * }) {}
227
243
  * ```
228
244
  *
229
- * The declaration names no sources. A `Projection.wake` binding links one
230
- * source stream to one wake stream, with params of its own.
245
+ * The declaration names no sources. A `Projection.frontier` binding links one
246
+ * source stream to one frontier stream, with params of its own.
231
247
  */
232
- const wake = () => (name, template, options) => state()(name, template, {
248
+ const frontierStream = () => (name, template, options) => state()(name, template, {
233
249
  params: options.params,
234
- collections: wakeCollections
250
+ collections: frontierStreamCollections
235
251
  });
236
- /** Constructors and matchers for `WakeItem`. */
237
- const WakeItem = Data.taggedEnum();
252
+ /** Constructors and matchers for `FrontierItem`. */
253
+ const FrontierItem = Data.taggedEnum();
238
254
  /**
239
- * The actions for one batch of wake messages. The function is pure: it reads
255
+ * The actions for one batch of frontier stream messages. The function is pure: it reads
240
256
  * no stream and changes none of its inputs. Rows for one stream collapse to one
241
257
  * item; a delete then an upsert of one stream gives `Removed`, then `Dirty` from
242
258
  * `-1`. Pass the returned `snapshot` to the call for the next batch.
243
259
  *
244
- * `followWake` uses it over a typed service. A client with its own HTTP reader
245
- * decodes each page with `WakeMessage` and calls it directly.
260
+ * `followFrontier` uses it over a typed service. A client with its own HTTP reader
261
+ * decodes each page with `FrontierMessage` and calls it directly.
246
262
  */
247
- function wakeActions(events, options) {
263
+ function frontierActions(events, options) {
248
264
  const { cursors } = options;
249
265
  const items = [];
250
266
  let pending = /* @__PURE__ */ new Map();
@@ -252,8 +268,8 @@ function wakeActions(events, options) {
252
268
  let open = options.snapshot === void 0 ? void 0 : new Set(options.snapshot);
253
269
  const flush = () => {
254
270
  for (const [stream, entry] of pending) {
255
- if (entry.removed) items.push(WakeItem.Removed({ stream }));
256
- if (Option.isSome(entry.dirty)) items.push(WakeItem.Dirty({
271
+ if (entry.removed) items.push(FrontierItem.Removed({ stream }));
272
+ if (Option.isSome(entry.dirty)) items.push(FrontierItem.Dirty({
257
273
  stream,
258
274
  ...entry.dirty.value
259
275
  }));
@@ -266,13 +282,13 @@ function wakeActions(events, options) {
266
282
  if (control === "reset") {
267
283
  pending = /* @__PURE__ */ new Map();
268
284
  items.length = 0;
269
- items.push(WakeItem.Reset());
285
+ items.push(FrontierItem.Reset());
270
286
  reset = true;
271
287
  open = void 0;
272
288
  } else if (control === "snapshot-start") open = /* @__PURE__ */ new Set();
273
289
  else if (open !== void 0) {
274
290
  flush();
275
- items.push(WakeItem.Snapshot({ streams: open }));
291
+ items.push(FrontierItem.Snapshot({ streams: open }));
276
292
  open = void 0;
277
293
  }
278
294
  continue;
@@ -309,19 +325,19 @@ function wakeActions(events, options) {
309
325
  };
310
326
  }
311
327
  /**
312
- * Follow one wake stream and give the actions for each batch: which source
328
+ * Follow one frontier stream and give the actions for each batch: which source
313
329
  * streams to read, from which cursor, and which to drop. The helper reads no
314
- * source stream. Save each source cursor first and the wake cursor (`offset`)
330
+ * source stream. Save each source cursor first and the frontier cursor (`offset`)
315
331
  * last; a stop between the two reads the same rows again, and the offset check
316
332
  * skips the streams that were already read.
317
333
  */
318
- function followWake(declaration, params, options) {
334
+ function followFrontier(declaration, params, options) {
319
335
  const { from, cursors, ...follow } = options;
320
336
  return Stream.unwrap(Effect.map(Effect.service(declaration), (service) => service.follow(params, {
321
337
  ...follow,
322
338
  offset: from
323
339
  }).pipe(Stream.mapAccum(() => void 0, (snapshot, batch) => {
324
- const next = wakeActions(batch.items, {
340
+ const next = frontierActions(batch.items, {
325
341
  cursors,
326
342
  snapshot
327
343
  });
@@ -333,36 +349,62 @@ function followWake(declaration, params, options) {
333
349
  return [next.snapshot, [out]];
334
350
  }))));
335
351
  }
352
+ /** The name of the collection declared with `Streamsy.frontier`, found by schema identity. */
353
+ const frontierCollection = (collections) => {
354
+ const names = Array.filter(Record.keys(collections), (name) => collections[name]?.schema === Frontier && collections[name]?.key === "stream");
355
+ const [name] = names;
356
+ if (name === void 0 || names.length > 1) throw new RangeError("awaitFrontier requires a State class with one Streamsy.frontier collection");
357
+ return name;
358
+ };
336
359
  /**
337
- * Wait until a wake row for `stream` reaches `offset`. Works with local and
338
- * remote services. Callers choose their own timeout. Removed source ids must
339
- * not be reused; a new generation needs a new wake stream or a State reset.
340
- * Without `options.from`, each call reads the wake history from the start.
360
+ * Wait until the frontier row for `stream` reaches `offset`. `declaration` is a
361
+ * frontier stream or any State class with one `Streamsy.frontier` collection; the
362
+ * other collections are read and skipped. Works with local and remote
363
+ * services. Callers choose their own timeout. Removed source ids must not be
364
+ * reused; a new generation needs a new stream or a State reset. Without
365
+ * `options.from`, each call reads the history from the start.
341
366
  */
342
- const awaitWake = (declaration, params, target, options = {}) => followWake(declaration, params, {
343
- ...options,
344
- cursors: /* @__PURE__ */ new Map()
345
- }).pipe(Stream.mapAccum(() => Option.none(), (observed, batch) => {
346
- let current = observed;
347
- for (const item of batch.items) if (WakeItem.$is("Reset")(item) || WakeItem.$is("Removed")(item) && item.stream === target.stream || WakeItem.$is("Snapshot")(item) && !item.streams.has(target.stream)) current = Option.none();
348
- else if (WakeItem.$is("Dirty")(item) && item.stream === target.stream) current = Option.some(item.offset);
349
- return [current, [batch.upToDate && Option.isSome(current) && compare(current.value, target.offset) >= 0]];
350
- }), Stream.filter((reached) => reached), Stream.runHead, Effect.flatMap((found) => Option.isSome(found) ? Effect.void : Effect.never));
367
+ const awaitFrontier = (declaration, params, target, options = {}) => {
368
+ const type = frontierCollection(declaration.collections);
369
+ const stream = StreamId.make(target.stream);
370
+ const { from, ...follow } = options;
371
+ return Stream.unwrap(Effect.map(Effect.service(declaration), (service) => service.follow(params, {
372
+ ...follow,
373
+ offset: from
374
+ }).pipe(Stream.mapAccum(() => void 0, (snapshot, batch) => {
375
+ const next = frontierActions(Array.filter(batch.items, (event) => isControl(event) || event.type === type), {
376
+ cursors: /* @__PURE__ */ new Map(),
377
+ snapshot
378
+ });
379
+ return [next.snapshot, [{
380
+ items: next.items,
381
+ upToDate: batch.upToDate
382
+ }]];
383
+ })))).pipe(Stream.mapAccum(() => Option.none(), (observed, batch) => {
384
+ let current = observed;
385
+ for (const item of batch.items) if (FrontierItem.$is("Reset")(item) || FrontierItem.$is("Removed")(item) && item.stream === stream || FrontierItem.$is("Snapshot")(item) && !item.streams.has(stream)) current = Option.none();
386
+ else if (FrontierItem.$is("Dirty")(item) && item.stream === stream) current = Option.some(item.offset);
387
+ return [current, [batch.upToDate && Option.isSome(current) && compare(current.value, target.offset) >= 0]];
388
+ }), Stream.filter((reached) => reached), Stream.runHead, Effect.flatMap((found) => Option.isSome(found) ? Effect.void : Effect.never));
389
+ };
351
390
  // src/streamsy.ts
352
391
  var streamsy_exports = /* @__PURE__ */ __exportAll({
353
- WakeItem: () => WakeItem,
354
- WakeMessage: () => WakeMessage,
355
- WakeRow: () => WakeRow,
392
+ Frontier: () => Frontier,
393
+ FrontierItem: () => FrontierItem,
394
+ FrontierMessage: () => FrontierMessage,
395
+ Token: () => Token,
356
396
  Wildcard: () => Wildcard,
357
- awaitWake: () => awaitWake,
397
+ awaitFrontier: () => awaitFrontier,
358
398
  bytes: () => bytes,
359
399
  custom: () => custom,
360
- followWake: () => followWake,
400
+ followFrontier: () => followFrontier,
401
+ frontier: () => frontier,
402
+ frontierActions: () => frontierActions,
403
+ frontierStream: () => frontierStream,
404
+ frontierStreamCollections: () => frontierStreamCollections,
361
405
  group: () => group,
362
406
  json: () => json,
363
407
  state: () => state,
364
- wake: () => wake,
365
- wakeActions: () => wakeActions,
366
- wakeCollections: () => wakeCollections
408
+ token: () => token
367
409
  });
368
410
  export { AppendConflict, AppendResult, ChangeSnapshot, CommitBoundary, CreateConflict, CreateResult, DecodeFault, durable_state_exports as DurableState, EncodeFault, ForkSourceNotFound, http_exports as Http, InvalidAppendRequest, InvalidCreateRequest, InvalidEpochSeq, InvalidForkRequest, InvalidReadRequest, streams_exports as MemoryStorage, MessageWindow, Mutation, MutationApplied, MutationRejected, Mutations, NotSupported, Offset, OffsetMismatch, Operation, OperationResult, OperationResults, Operations, producer_exports as Producer, ProducerGap, ProducerId, ProducerPrecondition, ProducerState, RecordPatch, StaleEpoch, Storage, StorageCapabilities, StorageFault, StoredMessage, address_exports as StreamAddress, StreamBusy, StreamClosed, StreamConfig, StreamGone, StreamId, StreamLifecycle, StreamNotFound, StreamRecord, StreamsFault, streamsy_exports as Streamsy, TransportFault, ZERO_OFFSET, compare, isProtocolError, isRetryableFault, isStreamsFault };
@@ -1,4 +1,4 @@
1
- import { I as ReadResult, a as ProjectionMarksApi, c as CommitHooksApi, d as OwnerRecords, f as OwnerRecordsApi, i as ProjectionMarks, l as commitHookRegistry, n as PendingMark, o as CommitHook, r as ProjectionMarkSummary, s as CommitHooks, t as MarkFailure, u as OWNER_RECORDS_LIST_UNSUPPORTED } from "../projection-marks-BEZv8qDJ.js";
1
+ import { K as ReadResult, Lt as DecodeFault, P as StreamAddress, W as ReadMessage, a as ProjectionMarksApi, c as CommitHooksApi, d as OwnerRecords, f as OwnerRecordsApi, i as ProjectionMarks, l as commitHookRegistry, n as PendingMark, o as CommitHook, r as ProjectionMarkSummary, s as CommitHooks, t as MarkFailure, u as OWNER_RECORDS_LIST_UNSUPPORTED } from "../projection-marks-DcO_5VNd.js";
2
2
  import { Cause, Context, Effect, Option, Schema } from "effect";
3
3
  /** Private bridge: a stream guard dies with this sentinel; the atomic runner translates it. */
4
4
  declare const ForeignOwnerType: unique symbol;
@@ -75,4 +75,35 @@ declare class MemoryEnlistFault extends MemoryEnlistFault_base {}
75
75
  export declare function enlist(owner: object, participant: TransactionParticipant): Effect.Effect<void, MemoryEnlistFault>;
76
76
  export declare const attachOffsets: <A extends object>(result: A, offsets: ReadonlyArray<string>) => A;
77
77
  export declare const offsetsOf: (result: Pick<ReadResult, "messages">) => ReadonlyArray<string> | undefined;
78
+ /** A decoded message, or None for a change outside a non-strict State address's collections. */
79
+ export declare const decodeMessage: <A, RD, RE>(address: StreamAddress<A, RD, RE>, message: ReadMessage, index: number) => Effect.Effect<Option.Option<A>, DecodeFault, RD>;
80
+ /** Decode the State envelope while keeping row values in their wire form. */
81
+ export declare const decodeStateWire: (input: string, options?: import("effect/SchemaAST").ParseOptions) => import("effect/Effect").Effect<{
82
+ readonly headers: {
83
+ readonly control: "reset" | "snapshot-end" | "snapshot-start";
84
+ readonly offset?: string | undefined;
85
+ };
86
+ } | {
87
+ readonly type: string;
88
+ readonly key: string;
89
+ readonly value: unknown;
90
+ readonly headers: {
91
+ readonly offset?: string | undefined;
92
+ readonly txid?: string | undefined;
93
+ readonly timestamp?: string | undefined;
94
+ readonly from?: string | undefined;
95
+ readonly operation: "upsert";
96
+ };
97
+ } | {
98
+ readonly type: string;
99
+ readonly key: string;
100
+ readonly old_value?: unknown;
101
+ readonly headers: {
102
+ readonly offset?: string | undefined;
103
+ readonly txid?: string | undefined;
104
+ readonly timestamp?: string | undefined;
105
+ readonly from?: string | undefined;
106
+ readonly operation: "delete";
107
+ };
108
+ }, Schema.SchemaError, never>;
78
109
  export { type CommitHook, CommitHooks, type CommitHooksApi, type MarkFailure, OWNER_RECORDS_LIST_UNSUPPORTED, OwnerRecords, type OwnerRecordsApi, type PendingMark, type ProjectionMarkSummary, ProjectionMarks, type ProjectionMarksApi, type TransactionParticipant, commitHookRegistry };
@@ -1,5 +1,5 @@
1
- import { a as CommitHooks, c as OwnerRecords, i as ProjectionMarks, o as commitHookRegistry, r as memoryProjectionMarks, s as OWNER_RECORDS_LIST_UNSUPPORTED, t as enlist } from "../boundary-f1biibJ1.js";
2
- import { a as attachOwner, c as isForeignOwner, i as CurrentOwner, l as ownerOf, t as compileSegments } from "../route-internal-DNL0oGTN.js";
1
+ import { a as compileSegments, c as CurrentOwner, f as isForeignOwner, i as decodeStateWire, l as attachOwner, p as ownerOf, t as decodeMessage } from "../read-message-CGHhOCMc.js";
2
+ import { a as CommitHooks, c as OwnerRecords, i as ProjectionMarks, o as commitHookRegistry, r as memoryProjectionMarks, s as OWNER_RECORDS_LIST_UNSUPPORTED, t as enlist } from "../boundary-BTrhL8De.js";
3
3
  import { n as offsetsOf, t as attachOffsets } from "../read-offsets-CQ4VkAs8.js";
4
4
  import { Array, Effect } from "effect";
5
5
  // src/internal/limits.ts
@@ -26,4 +26,4 @@ const fitKey = (key, limit, readable = key) => {
26
26
  const prefix = Array.join(Array.take(codePoints(readable), limit - DIGEST_LENGTH), "");
27
27
  return Effect.map(sha256Hex(key), (digest) => `${prefix}#${digest}`);
28
28
  };
29
- export { CommitHooks, CurrentOwner, MAX_PRODUCER_ID_LENGTH, OWNER_RECORDS_LIST_UNSUPPORTED, OwnerRecords, ProjectionMarks, attachOffsets, attachOwner, commitHookRegistry, compileSegments, enlist, fitKey, isForeignOwner, memoryProjectionMarks, offsetsOf, ownerOf };
29
+ export { CommitHooks, CurrentOwner, MAX_PRODUCER_ID_LENGTH, OWNER_RECORDS_LIST_UNSUPPORTED, OwnerRecords, ProjectionMarks, attachOffsets, attachOwner, commitHookRegistry, compileSegments, decodeMessage, decodeStateWire, enlist, fitKey, isForeignOwner, memoryProjectionMarks, offsetsOf, ownerOf };
@@ -1,7 +1,7 @@
1
- import { L as Storage, R as ZERO_OFFSET } from "./streamsy-HKC10a_V.js";
2
- import { a as CommitHooks, c as OwnerRecords, d as indexDeadlines, f as patchRecord, i as ProjectionMarks, l as copyMessage, n as makeBoundary, p as CommitBoundary, u as copyRecord } from "./boundary-f1biibJ1.js";
3
- import { a as MutationRejected, l as OperationResults, o as Mutations, u as Operations } from "./layer-DjKTdIY5.js";
4
- import { a as attachOwner, l as ownerOf } from "./route-internal-DNL0oGTN.js";
1
+ import { L as Storage, R as ZERO_OFFSET } from "./streamsy-IBFULoEr.js";
2
+ import { l as attachOwner, p as ownerOf } from "./read-message-CGHhOCMc.js";
3
+ import { a as CommitHooks, c as OwnerRecords, d as indexDeadlines, f as patchRecord, i as ProjectionMarks, l as copyMessage, n as makeBoundary, p as CommitBoundary, u as copyRecord } from "./boundary-BTrhL8De.js";
4
+ import { a as MutationRejected, l as OperationResults, o as Mutations, u as Operations } from "./layer-pomDIajD.js";
5
5
  import { Array, Context, Effect, Layer, Option, Order, Predicate, PubSub, Queue, Schedule, Stream } from "effect";
6
6
  // src/storage/memory/lineage.ts
7
7
  /** Synchronous port of cascade-reclaim and chained message composition.
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { $ as ProducerState, A as StreamBusy, B as isValid, C as InvalidEpochSeq, D as OffsetMismatch, E as NotSupported, F as StreamsReader, I as StreamsWriter, L as Storage, M as StreamGone, N as StreamNotFound, O as ProducerGap, Q as ProducerId, R as ZERO_OFFSET, T as InvalidReadRequest, V as next, Z as Offset, _ as CreateResult, at as StreamRecord, b as ForkSourceNotFound, et as RecordPatch, g as AppendResult, j as StreamClosed, k as StaleEpoch, n as bind, rt as StreamId, tt as StoredMessage, v as AppendConflict, w as InvalidForkRequest, x as InvalidAppendRequest, y as CreateConflict, z as compare } from "./streamsy-HKC10a_V.js";
3
- import { o as attachStorage } from "./route-internal-DNL0oGTN.js";
4
- import { n as validateCreateOptions, r as frameMessages, t as frameCreateMessages } from "./create-validation-DzLxKiux.js";
2
+ import { A as StreamBusy, B as isValid, C as InvalidEpochSeq, D as OffsetMismatch, E as NotSupported, F as StreamsReader, G as ProducerId, I as StreamsWriter, J as StoredMessage, K as ProducerState, L as Storage, M as StreamGone, N as StreamNotFound, O as ProducerGap, Q as StreamRecord, R as ZERO_OFFSET, T as InvalidReadRequest, V as next, W as Offset, X as StreamId, _ as CreateResult, b as ForkSourceNotFound, g as AppendResult, j as StreamClosed, k as StaleEpoch, n as bind, q as RecordPatch, v as AppendConflict, w as InvalidForkRequest, x as InvalidAppendRequest, y as CreateConflict, z as compare } from "./streamsy-IBFULoEr.js";
3
+ import { u as attachStorage } from "./read-message-CGHhOCMc.js";
4
+ import { n as validateCreateOptions, r as frameMessages, t as frameCreateMessages } from "./create-validation-C_aJJm5u.js";
5
5
  import { t as attachOffsets } from "./read-offsets-CQ4VkAs8.js";
6
6
  import { t as generateCursor } from "./cursor-generator-DySXZ93b.js";
7
7
  import { Array, Clock, Context, Data, Effect, Layer, Match, Option, Predicate, Random, Result, Schema, Stream } from "effect";
@@ -447,10 +447,12 @@ const append = Effect.fn("Protocol.append")(function* (storage, id, options) {
447
447
  });
448
448
  if (!closeOnly && !contentTypeMatches(record.config.contentType, options.contentType)) return yield* new AppendConflict({
449
449
  id,
450
+ reason: "content-type",
450
451
  message: "Content-Type mismatch"
451
452
  });
452
453
  if (!closeOnly && options.seq && record.lifecycle.lastSeq && options.seq <= record.lifecycle.lastSeq) return yield* new AppendConflict({
453
454
  id,
455
+ reason: "sequence",
454
456
  message: "Sequence conflict"
455
457
  });
456
458
  if (options.expectedOffset !== void 0 && options.expectedOffset !== record.currentOffset) return yield* new OffsetMismatch({
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { B as isValid, F as StreamsReader, I as StreamsWriter, P as isProtocolError, _ as CreateResult, g as AppendResult, rt as StreamId } from "./streamsy-HKC10a_V.js";
2
+ import { B as isValid, F as StreamsReader, I as StreamsWriter, P as isProtocolError, X as StreamId, _ as CreateResult, g as AppendResult } from "./streamsy-IBFULoEr.js";
3
3
  import { t as generateCursor } from "./cursor-generator-DySXZ93b.js";
4
4
  import { Array, Clock, Context, DateTime, Deferred, Effect, Layer, Match, Option, Random, Record, Ref, Schedule, Stream } from "effect";
5
5
  import { HttpServerRequest, HttpServerResponse } from "effect/http";
@@ -441,7 +441,10 @@ function dataEvent(messages, options) {
441
441
  chunks.push(encode("data:]\n"));
442
442
  } else {
443
443
  const text = Array.join(Array.map(messages, (msg) => decoder.decode(msg.data)), "");
444
- for (const line of text.split(/\r\n|\r|\n/)) chunks.push(encode(`data:${line}\n`));
444
+ for (const line of text.split(/\r\n|\r|\n/)) {
445
+ const separator = line.startsWith(" ") ? " " : "";
446
+ chunks.push(encode(`data:${separator}${line}\n`));
447
+ }
445
448
  }
446
449
  chunks.push(encode("\n"));
447
450
  return chunks;
@@ -756,7 +759,7 @@ function protocolErrorResponse(error, context) {
756
759
  StreamGone: () => context.method === "HEAD" ? responses$1.noStore(responses$1.gone()) : responses$1.gone(),
757
760
  ForkSourceNotFound: ({ source }) => responses$1.notFound(`Source stream not found: ${source}`),
758
761
  CreateConflict: conflict,
759
- AppendConflict: conflict,
762
+ AppendConflict: ({ message, reason }) => responses$1.conflict(message, reason === void 0 ? void 0 : { "stream-conflict-reason": reason }),
760
763
  InvalidReadRequest: badRequest,
761
764
  InvalidForkRequest: badRequest,
762
765
  InvalidCreateRequest: badRequest,
@@ -201,6 +201,12 @@ declare class OffsetMismatch extends OffsetMismatch_base {
201
201
  }
202
202
  declare const AppendConflict_base: Schema.Class<AppendConflict, Schema.TaggedStruct<"AppendConflict", {
203
203
  readonly id: Schema.brand<Schema.String, "StreamId">;
204
+ /**
205
+ * `sequence` when the `Stream-Seq` does not sort after the last one, `content-type` when the
206
+ * content type differs. Absent when the cause is unknown, for example from a server that does
207
+ * not send `stream-conflict-reason`.
208
+ */
209
+ readonly reason: Schema.optionalKey<Schema.Literals<readonly ["sequence", "content-type"]>>;
204
210
  readonly message: Schema.String;
205
211
  }>, import("effect/Cause").YieldableError>;
206
212
  declare class AppendConflict extends AppendConflict_base {}
@@ -361,6 +367,140 @@ declare const StreamsReader_base: Context.ServiceClass<StreamsReader, "@streamsy
361
367
  declare class StreamsReader extends StreamsReader_base {}
362
368
  declare const StreamsWriter_base: Context.ServiceClass<StreamsWriter, "@streamsy/core/StreamsWriter", Writer<StorageFault | TransportFault>>;
363
369
  declare class StreamsWriter extends StreamsWriter_base {}
370
+ declare namespace address_d_exports {
371
+ export { Collection, Collections, CollectionsChange, CollectionsDecodingServices, CollectionsEncodedChange, CollectionsEncodedEvent, CollectionsEncodingServices, CollectionsEvent, StateAddress, StateChange, StateControl, StateControlName, StateDelete, StateEvent, StateHeaders, StateKey, StateUpsert, StreamAddress, ValidCollections, bytes, isChange, isControl, isUpsert, json, reset, snapshotEnd, snapshotStart, state, stateChange, stateControl };
372
+ }
373
+ /** Omit `offset` and `txid` rather than setting them to `undefined`. */
374
+ interface StateHeaders {
375
+ readonly operation: "upsert" | "delete";
376
+ readonly offset?: string;
377
+ readonly txid?: string;
378
+ readonly timestamp?: string;
379
+ readonly from?: string;
380
+ }
381
+ interface StateUpsert<A, Type extends string = string> {
382
+ readonly type: Type;
383
+ readonly key: string;
384
+ readonly value: A;
385
+ readonly headers: StateHeaders & {
386
+ readonly operation: "upsert";
387
+ };
388
+ }
389
+ interface StateDelete<A, Type extends string = string> {
390
+ readonly type: Type;
391
+ readonly key: string;
392
+ readonly old_value?: A;
393
+ readonly headers: StateHeaders & {
394
+ readonly operation: "delete";
395
+ };
396
+ }
397
+ /** A change event consumed by `@durable-streams/state`, narrowed by its `type`. */
398
+ type StateChange<A, Type extends string = string> = StateUpsert<A, Type> | StateDelete<A, Type>;
399
+ type StateEncodedChange<A, Type extends string = string> = (Omit<StateUpsert<A, Type>, "headers"> & {
400
+ readonly headers: Omit<StateHeaders, "operation"> & {
401
+ readonly operation: "insert" | "update" | "upsert";
402
+ };
403
+ }) | StateDelete<A, Type>;
404
+ /** The control signals of the Durable State protocol (STATE-PROTOCOL.md section 4.2). */
405
+ type StateControlName = "snapshot-start" | "snapshot-end" | "reset";
406
+ /**
407
+ * A control message of a Durable State stream. It has no `type` or `key`.
408
+ * `snapshot-start` and `snapshot-end` mark a run of changes that is a complete
409
+ * snapshot. `reset` tells a reader to clear its materialized state. Omit
410
+ * `offset` rather than setting it to `undefined`.
411
+ */
412
+ interface StateControl {
413
+ readonly headers: {
414
+ readonly control: StateControlName;
415
+ readonly offset?: string;
416
+ };
417
+ }
418
+ /** One item of a Durable State stream: a change of one collection or a control. */
419
+ type StateEvent<A, Type extends string = string> = StateChange<A, Type> | StateControl;
420
+ /** The value fields that may serve as a Durable State key. */
421
+ type StateKey<A> = { [K in keyof A]-?: A[K] extends string | number ? K : never; }[keyof A];
422
+ /** One collection of a Durable State stream: its value schema and the value field used as the key. */
423
+ interface Collection<A, I, RD, RE, Key extends StateKey<A> = StateKey<A>> {
424
+ readonly schema: Schema.Codec<A, I, RD, RE>;
425
+ readonly key: Key;
426
+ }
427
+ /** Collections keyed by the `type` that names them on the wire. */
428
+ type Collections = Record<string, Collection<any, any, any, any, any>>;
429
+ /**
430
+ * Each `key` must name a string or number field of its own collection's value.
431
+ * A mismatch reports on the `key` property of the offending collection.
432
+ */
433
+ type ValidCollections<C extends Collections> = { readonly [K in keyof C]: C[K]["key"] extends StateKey<C[K]["schema"]["Type"]> ? C[K] : {
434
+ readonly key: StateKey<C[K]["schema"]["Type"]>;
435
+ }; };
436
+ /** The union of change events across every collection, discriminated by `type`. */
437
+ type CollectionsChange<C extends Collections> = { [K in keyof C & string]: StateChange<C[K]["schema"]["Type"], K>; }[keyof C & string];
438
+ type CollectionsEncodedChange<C extends Collections> = { [K in keyof C & string]: StateEncodedChange<C[K]["schema"]["Encoded"], K>; }[keyof C & string];
439
+ /** The items of a State address: the change events of its collections, plus controls. */
440
+ type CollectionsEvent<C extends Collections> = CollectionsChange<C> | StateControl;
441
+ type CollectionsEncodedEvent<C extends Collections> = CollectionsEncodedChange<C> | StateControl;
442
+ type CollectionsDecodingServices<C extends Collections> = C[keyof C]["schema"]["DecodingServices"];
443
+ type CollectionsEncodingServices<C extends Collections> = C[keyof C]["schema"]["EncodingServices"];
444
+ /** Inert identity and codec. Constructing an address acquires no service or resource. */
445
+ interface StreamAddress<A, RD = never, RE = never> {
446
+ readonly _tag: "Json" | "Bytes";
447
+ readonly id: StreamId;
448
+ readonly contentType: string;
449
+ readonly codec: Schema.Codec<A, string | Uint8Array, RD, RE>;
450
+ }
451
+ /** A JSON address whose items are the change events of its collections and State controls. */
452
+ interface StateAddress<C extends Collections, RD = CollectionsDecodingServices<C>, RE = CollectionsEncodingServices<C>> extends StreamAddress<CollectionsEvent<C>, RD, RE> {
453
+ readonly collections: C;
454
+ /** Fail typed reads on changes to undeclared collections. */
455
+ readonly strict?: boolean;
456
+ }
457
+ declare function json<A, I, RD, RE>(id: string, options: {
458
+ readonly schema: Schema.Codec<A, I, RD, RE>;
459
+ }): StreamAddress<A, RD, RE>;
460
+ /**
461
+ * A codec for the upsert and delete change events of one collection.
462
+ * `state` composes one of these per collection. Omit optional headers instead
463
+ * of setting them to `undefined`.
464
+ */
465
+ declare function stateChange<A, I, RD, RE, const Type extends string>(options: {
466
+ readonly schema: Schema.Codec<A, I, RD, RE>;
467
+ readonly type: Type;
468
+ }): Schema.Codec<StateChange<A, Type>, StateEncodedChange<I, Type>, RD, RE>;
469
+ /** The codec for a State control message. It needs no services. */
470
+ declare const stateControl: Schema.Codec<StateControl>;
471
+ /** True for a control message. A change has `headers.operation` and no `headers.control`. */
472
+ declare const isControl: <E extends StateEvent<unknown>>(event: E) => event is Extract<E, StateControl>;
473
+ /** True for an upsert or delete change. */
474
+ declare const isChange: <E extends StateEvent<unknown>>(event: E) => event is Exclude<E, StateControl>;
475
+ /** True for an upsert change, with its value available. */
476
+ declare const isUpsert: <E extends StateEvent<unknown>>(event: E) => event is Extract<E, StateUpsert<unknown>>;
477
+ /** A `reset` control. A reader should clear its materialized state and apply what follows. */
478
+ declare const reset: (options?: {
479
+ readonly offset?: string;
480
+ }) => StateControl;
481
+ /** A `snapshot-start` control. The changes up to `snapshot-end` form a complete snapshot. */
482
+ declare const snapshotStart: (options?: {
483
+ readonly offset?: string;
484
+ }) => StateControl;
485
+ /** A `snapshot-end` control. It closes the snapshot that `snapshot-start` opened. */
486
+ declare const snapshotEnd: (options?: {
487
+ readonly offset?: string;
488
+ }) => StateControl;
489
+ /**
490
+ * A stream of Durable State events for several collections. Each record
491
+ * key is the `type` on the wire; each entry gives the value schema and the value
492
+ * field that becomes the event `key`. The codec also decodes and encodes the
493
+ * State control messages `snapshot-start`, `snapshot-end` and `reset`.
494
+ * Typed reads skip changes to undeclared collections unless `strict` is true.
495
+ */
496
+ declare function state<const C extends Collections>(id: string, options: {
497
+ readonly collections: C & ValidCollections<C>;
498
+ readonly strict?: boolean;
499
+ }): StateAddress<C>;
500
+ /** Items from one bytes append are joined into one stored message. */
501
+ declare function bytes(id: string, options?: {
502
+ readonly contentType?: string;
503
+ }): StreamAddress<Uint8Array>;
364
504
  declare const StorageCapabilities: Schema.Struct<{
365
505
  readonly fork: Schema.Literals<readonly ["none", "copy", "chain"]>;
366
506
  readonly atomicScope: Schema.Literals<readonly ["stream", "store"]>;
@@ -1253,4 +1393,4 @@ interface ProjectionMarksApi {
1253
1393
  }
1254
1394
  declare const ProjectionMarks_base: Context.ServiceClass<ProjectionMarks, "@streamsy/core/internal/ProjectionMarks", ProjectionMarksApi>;
1255
1395
  declare class ProjectionMarks extends ProjectionMarks_base {}
1256
- export { ProducerGap as $, Writer as A, StreamsFault as At, AppendErrorFor as B, OperationResults as C, StreamConfig as Ct, Reader as D, DecodeFault as Dt, StorageCapabilities as E, StreamRecord as Et, ReadNextResult as F, HeadError as G, CreateConflictReason as H, ReadResult as I, InvalidEpochSeq as J, InvalidAppendRequest as K, AppendBaseError as L, CreateResult as M, isRetryableFault as Mt, HeadResult as N, isStreamsFault as Nt, StreamsReader as O, EncodeFault as Ot, ReadMessage as P, OffsetMismatch as Q, AppendConflict as R, OperationResult as S, StoredMessage as St, ProducerPrecondition as T, StreamLifecycle as Tt, CreateError as U, CreateConflict as V, ForkSourceNotFound as W, InvalidReadRequest as X, InvalidForkRequest as Y, NotSupported as Z, Mutation as _, MessageWindow as _t, ProjectionMarksApi as a, StreamBusy as at, Mutations as b, ProducerState as bt, CommitHooksApi as c, StreamNotFound as ct, OwnerRecords as d, AppendOptions as dt, ProtocolError as et, OwnerRecordsApi as f, ProducerOptions as ft, StorageShape as g, ChangeSnapshot as gt, Storage as h, CreateOptions as ht, ProjectionMarks as i, StaleEpoch as it, AppendResult as j, TransportFault as jt, StreamsWriter as k, StorageFault as kt, commitHookRegistry as l, isProtocolError as lt, CommitBoundaryApi as m, ReadOptions as mt, PendingMark as n, ReadNextError as nt, CommitHook as o, StreamClosed as ot, CommitBoundary as p, ReadNextOptions as pt, InvalidCreateRequest as q, ProjectionMarkSummary as r, RemoveError as rt, CommitHooks as s, StreamGone as st, MarkFailure as t, ReadError as tt, OWNER_RECORDS_LIST_UNSUPPORTED as u, AppendCallOptions as ut, MutationApplied as v, Offset as vt, Operations as w, StreamId as wt, Operation as x, RecordPatch as xt, MutationRejected as y, ProducerId as yt, AppendError as z };
1396
+ export { CreateError as $, CollectionsEncodingServices as A, ProducerState as At, Writer as B, StreamsFault as Bt, OperationResults as C, ReadNextOptions as Ct, Collections as D, MessageWindow as Dt, StorageCapabilities as E, ChangeSnapshot as Et, ValidCollections as F, StreamLifecycle as Ft, ReadNextResult as G, CreateResult as H, isRetryableFault as Ht, address_d_exports as I, StreamRecord as It, AppendConflict as J, ReadResult as K, Reader as L, DecodeFault as Lt, StateAddress as M, StoredMessage as Mt, StateControl as N, StreamConfig as Nt, CollectionsDecodingServices as O, Offset as Ot, StreamAddress as P, StreamId as Pt, CreateConflictReason as Q, StreamsReader as R, EncodeFault as Rt, OperationResult as S, ProducerOptions as St, ProducerPrecondition as T, CreateOptions as Tt, HeadResult as U, isStreamsFault as Ut, AppendResult as V, TransportFault as Vt, ReadMessage as W, AppendErrorFor as X, AppendError as Y, CreateConflict as Z, Mutation as _, StreamGone as _t, ProjectionMarksApi as a, InvalidForkRequest as at, Mutations as b, AppendCallOptions as bt, CommitHooksApi as c, OffsetMismatch as ct, OwnerRecords as d, ReadError as dt, ForkSourceNotFound as et, OwnerRecordsApi as f, ReadNextError as ft, StorageShape as g, StreamClosed as gt, Storage as h, StreamBusy as ht, ProjectionMarks as i, InvalidEpochSeq as it, CollectionsEvent as j, RecordPatch as jt, CollectionsEncodedEvent as k, ProducerId as kt, commitHookRegistry as l, ProducerGap as lt, CommitBoundaryApi as m, StaleEpoch as mt, PendingMark as n, InvalidAppendRequest as nt, CommitHook as o, InvalidReadRequest as ot, CommitBoundary as p, RemoveError as pt, AppendBaseError as q, ProjectionMarkSummary as r, InvalidCreateRequest as rt, CommitHooks as s, NotSupported as st, MarkFailure as t, HeadError as tt, OWNER_RECORDS_LIST_UNSUPPORTED as u, ProtocolError as ut, MutationApplied as v, StreamNotFound as vt, Operations as w, ReadOptions as wt, Operation as x, AppendOptions as xt, MutationRejected as y, isProtocolError as yt, StreamsWriter as z, StorageFault as zt };
@@ -1,5 +1,5 @@
1
- import { A as Writer, D as Reader, O as StreamsReader, k as StreamsWriter } from "../projection-marks-BEZv8qDJ.js";
2
- import { J as layer_d_exports, V as streams_d_exports, Z as route_d_exports, w as RoutesOptions } from "../index-BtVxu6VJ.js";
1
+ import { B as Writer, L as Reader, R as StreamsReader, z as StreamsWriter } from "../projection-marks-DcO_5VNd.js";
2
+ import { J as layer_d_exports, V as streams_d_exports, Z as route_d_exports, w as RoutesOptions } from "../index-D-n48qXe.js";
3
3
  import { HttpRouter } from "effect/http";
4
4
  /** Raw protocol route for adapters and wire conformance tests. */
5
5
  export declare const routes: (options?: Omit<RoutesOptions, "access">) => import("effect/Layer").Layer<never, never, HttpRouter.HttpRouter | HttpRouter.Request<"Requires", StreamsReader> | HttpRouter.Request<"Requires", StreamsWriter>>;
@@ -1,6 +1,6 @@
1
- import { F as StreamsReader, I as StreamsWriter, l as streams_exports, u as route_exports } from "../streamsy-HKC10a_V.js";
2
- import { n as layer_exports } from "../layer-DjKTdIY5.js";
3
- import { t as app } from "../program-BlfAJNlD.js";
1
+ import { F as StreamsReader, I as StreamsWriter, l as streams_exports, u as route_exports } from "../streamsy-IBFULoEr.js";
2
+ import { n as layer_exports } from "../layer-pomDIajD.js";
3
+ import { t as app } from "../program-DhW5In9U.js";
4
4
  import { HttpRouter } from "effect/http";
5
5
  // src/protocol/routes.ts
6
6
  /** Raw protocol route for adapters and wire conformance tests. */