@streamsy/core 0.5.0 → 0.6.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,9 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { $ as StreamLifecycle, B as StreamsFault, C as ProducerGap, D as StreamGone, E as StreamClosed, G as MessageWindow, H as isRetryableFault, J as ProducerState, K as Offset, L as DecodeFault, M as Storage, N as ZERO_OFFSET, O as StreamNotFound, P as compare, Q as StreamId, R as EncodeFault, S as OffsetMismatch, T as StreamBusy, U as isStreamsFault, V as TransportFault, W as ChangeSnapshot, X as StoredMessage, Y as RecordPatch, Z as StreamConfig, _ as InvalidAppendRequest, a as custom, b as InvalidReadRequest, c as state, d as address_exports, et as StreamRecord, f as AppendResult, g as ForkSourceNotFound, h as CreateConflict, k as isProtocolError, m as AppendConflict, n as bind, o as group, p as CreateResult, q as ProducerId, r as bytes, s as json, t as Wildcard, v as InvalidEpochSeq, w as StaleEpoch, x as NotSupported, y as InvalidForkRequest, z as StorageFault } from "./streamsy-DJMArv09.js";
3
- import { n as CommitBoundary, t as layer$1 } from "./layer-DJ-c63nY.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$2, u as Operations } from "./layer-DyezIxJT.js";
5
- import { t as http_exports } from "./http-x2IjDHvw.js";
6
- import { Array, Data, Layer, Predicate, Record, Schema } from "effect";
2
+ import { $ as RecordPatch, A as StreamClosed, C as InvalidForkRequest, D as ProducerGap, E as OffsetMismatch, G as TransportFault, H as EncodeFault, I as Storage, J as ChangeSnapshot, K as isRetryableFault, L as ZERO_OFFSET, M as StreamNotFound, N as isProtocolError, O as StaleEpoch, Q as ProducerState, R as compare, S as InvalidEpochSeq, T as NotSupported, U as StorageFault, V as DecodeFault, W as StreamsFault, X as Offset, Y as MessageWindow, Z as ProducerId, _ as CreateResult, a as custom, b as ForkSourceNotFound, c as state, d as address_exports, et as StoredMessage, f as isControl, g as AppendResult, h as stateControl, it as StreamRecord, j as StreamGone, k as StreamBusy, m as stateChange, n as bind, nt as StreamId, o as group, p as isUpsert, q as isStreamsFault, r as bytes, rt as StreamLifecycle, s as json, t as Wildcard, tt as StreamConfig, v as AppendConflict, w as InvalidReadRequest, x as InvalidAppendRequest, y as CreateConflict } from "./streamsy-D9OCCdw0.js";
3
+ import { n as CommitBoundary, t as layer$1 } from "./layer-DQZj5tXr.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$2, u as Operations } from "./layer-8Y1cg6UL.js";
5
+ import { t as http_exports } from "./http-B10ao6xE.js";
6
+ import { Array, Data, Effect, Layer, Option, Predicate, Record, Schema, Stream } from "effect";
7
7
  // src/storage/capabilities.ts
8
8
  const StorageCapabilities = Schema.Struct({
9
9
  fork: Schema.Literals([
@@ -30,6 +30,8 @@ function layer(group, options = {}) {
30
30
  // src/toolkit/durable-state.ts
31
31
  var durable_state_exports = /* @__PURE__ */ __exportAll({
32
32
  changes: () => changes,
33
+ materialize: () => materialize,
34
+ materialized: () => materialized,
33
35
  remove: () => remove,
34
36
  upsert: () => upsert
35
37
  });
@@ -102,6 +104,73 @@ const stampControl = (entry, offset) => offset === void 0 || entry.headers.offse
102
104
  control: entry.headers.control,
103
105
  offset
104
106
  } };
107
+ /** A row key that is unique across collections, for snapshot bookkeeping. */
108
+ const snapshotKey = (type, key) => `${type}\u0000${key}`;
109
+ /** Empty materialized state for the collections of `address`. */
110
+ function materialized(address) {
111
+ const rows = {};
112
+ for (const type of Record.keys(address.collections)) rows[type] = /* @__PURE__ */ new Map();
113
+ return {
114
+ rows,
115
+ snapshot: void 0
116
+ };
117
+ }
118
+ /**
119
+ * Fold State events into materialized state, with the State protocol rules:
120
+ *
121
+ * - `upsert` sets the row of its key, and `delete` removes it.
122
+ * - `reset` clears every collection.
123
+ * - `snapshot-end` removes each row that no change since `snapshot-start` named.
124
+ * A snapshot may span several calls.
125
+ *
126
+ * The input state is not changed. Only the collections that `events` touch are copied.
127
+ */
128
+ function materialize(state, events) {
129
+ const rows = /* @__PURE__ */ new Map();
130
+ let cleared = false;
131
+ let snapshot = state.snapshot === void 0 ? void 0 : new Set(state.snapshot);
132
+ const source = (type) => cleared ? void 0 : Record.has(state.rows, type) ? state.rows[type] : void 0;
133
+ const writable = (type) => {
134
+ const existing = rows.get(type);
135
+ if (existing !== void 0) return existing;
136
+ const copy = new Map(source(type));
137
+ rows.set(type, copy);
138
+ return copy;
139
+ };
140
+ for (const event of events) {
141
+ if (isControl(event)) {
142
+ const control = event.headers.control;
143
+ if (control === "reset") {
144
+ cleared = true;
145
+ rows.clear();
146
+ snapshot = void 0;
147
+ } else if (control === "snapshot-start") snapshot = /* @__PURE__ */ new Set();
148
+ else if (snapshot !== void 0) {
149
+ const seen = snapshot;
150
+ for (const type of Record.keys(state.rows)) {
151
+ const table = writable(type);
152
+ for (const key of Array.fromIterable(table.keys())) if (!seen.has(snapshotKey(type, key))) table.delete(key);
153
+ }
154
+ snapshot = void 0;
155
+ }
156
+ continue;
157
+ }
158
+ const table = writable(event.type);
159
+ if (isUpsert(event)) {
160
+ table.set(event.key, event.value);
161
+ snapshot?.add(snapshotKey(event.type, event.key));
162
+ } else {
163
+ table.delete(event.key);
164
+ snapshot?.delete(snapshotKey(event.type, event.key));
165
+ }
166
+ }
167
+ const next = {};
168
+ for (const type of Record.keys(state.rows)) next[type] = rows.get(type) ?? (cleared ? /* @__PURE__ */ new Map() : state.rows[type]);
169
+ return {
170
+ rows: next,
171
+ snapshot
172
+ };
173
+ }
105
174
  // src/toolkit/producer.ts
106
175
  var producer_exports = /* @__PURE__ */ __exportAll({ next: () => next });
107
176
  /** Advance only after the caller has acknowledged appended or duplicate. Persist this tuple at the owning edge. */
@@ -109,13 +178,170 @@ const next = (position) => ({
109
178
  ...position,
110
179
  producerSeq: position.producerSeq + 1
111
180
  });
181
+ // src/toolkit/wake.ts
182
+ /**
183
+ * Wake streams: one Durable State stream that indexes the writes of a family of
184
+ * source streams.
185
+ *
186
+ * A wake declaration is a State stream with one `stream` collection. Each row
187
+ * is the latest known state of one source stream. A projection writes the rows:
188
+ * `Projection.wake` in `@streamsy/projection` reads one source stream and
189
+ * appends its row with a producer tuple, on the same owner or another one. A
190
+ * wake stream on another owner must exist first: its owner creates it at start.
191
+ * The typed service is the normal State service.
192
+ */
193
+ /** One row of a wake stream: the latest known state of one source stream. */
194
+ const WakeRow = Schema.Struct({
195
+ /** Canonical id of the source stream. It is also the State key. */
196
+ stream: StreamId,
197
+ /** Source tail after the write. The same value as a reader's saved cursor. */
198
+ offset: Offset,
199
+ /** Present when the source stream is closed. */
200
+ closed: Schema.optionalKey(Schema.Literal(true))
201
+ });
202
+ /** The one collection of every wake stream. Its State `type` is `stream`. */
203
+ const wakeCollections = { stream: {
204
+ schema: WakeRow,
205
+ key: "stream"
206
+ } };
207
+ /**
208
+ * The codec of one wake stream message: a `stream` change or a State control.
209
+ * A client that decodes raw JSON pages uses it in place of a typed service.
210
+ */
211
+ const WakeMessage = Schema.Union([stateChange({
212
+ type: "stream",
213
+ schema: WakeRow
214
+ }), stateControl]);
215
+ /**
216
+ * Declare a wake stream: a State stream of `WakeRow`s at a template.
217
+ *
218
+ * ```ts
219
+ * class UserWake extends Streamsy.wake<UserWake>()("App/UserWake", "users/:user/wake", {
220
+ * params: { user: UserKey },
221
+ * }) {}
222
+ * ```
223
+ *
224
+ * The declaration names no sources. A `Projection.wake` binding links one
225
+ * source stream to one wake stream, with params of its own.
226
+ */
227
+ const wake = () => (name, template, options) => state()(name, template, {
228
+ params: options.params,
229
+ collections: wakeCollections
230
+ });
231
+ /** Constructors and matchers for `WakeItem`. */
232
+ const WakeItem = Data.taggedEnum();
233
+ /**
234
+ * The actions for one batch of wake messages. The function is pure: it reads
235
+ * no stream and changes none of its inputs. Rows for one stream collapse to one
236
+ * item; a delete then an upsert of one stream gives `Removed`, then `Dirty` from
237
+ * `-1`. Pass the returned `snapshot` to the call for the next batch.
238
+ *
239
+ * `followWake` uses it over a typed service. A client with its own HTTP reader
240
+ * decodes each page with `WakeMessage` and calls it directly.
241
+ */
242
+ function wakeActions(events, options) {
243
+ const { cursors } = options;
244
+ const items = [];
245
+ let pending = /* @__PURE__ */ new Map();
246
+ let reset = false;
247
+ let open = options.snapshot === void 0 ? void 0 : new Set(options.snapshot);
248
+ const flush = () => {
249
+ for (const [stream, entry] of pending) {
250
+ if (entry.removed) items.push(WakeItem.Removed({ stream }));
251
+ if (Option.isSome(entry.dirty)) items.push(WakeItem.Dirty({
252
+ stream,
253
+ ...entry.dirty.value
254
+ }));
255
+ }
256
+ pending = /* @__PURE__ */ new Map();
257
+ };
258
+ for (const event of events) {
259
+ if (isControl(event)) {
260
+ const control = event.headers.control;
261
+ if (control === "reset") {
262
+ pending = /* @__PURE__ */ new Map();
263
+ items.length = 0;
264
+ items.push(WakeItem.Reset());
265
+ reset = true;
266
+ open = void 0;
267
+ } else if (control === "snapshot-start") open = /* @__PURE__ */ new Set();
268
+ else if (open !== void 0) {
269
+ flush();
270
+ items.push(WakeItem.Snapshot({ streams: open }));
271
+ open = void 0;
272
+ }
273
+ continue;
274
+ }
275
+ const stream = StreamId.make(event.key);
276
+ const prior = pending.get(stream);
277
+ pending.delete(stream);
278
+ if (!isUpsert(event)) {
279
+ pending.set(stream, {
280
+ removed: true,
281
+ dirty: Option.none()
282
+ });
283
+ open?.delete(stream);
284
+ continue;
285
+ }
286
+ const row = event.value;
287
+ const removed = prior?.removed ?? false;
288
+ const base = removed || reset ? "-1" : cursors.get(stream) ?? "-1";
289
+ const dirty = compare(row.offset, base) > 0 || row.closed === true;
290
+ pending.set(stream, {
291
+ removed,
292
+ dirty: dirty ? Option.some({
293
+ from: base,
294
+ offset: row.offset,
295
+ closed: row.closed === true
296
+ }) : Option.none()
297
+ });
298
+ open?.add(stream);
299
+ }
300
+ flush();
301
+ return {
302
+ items,
303
+ snapshot: open
304
+ };
305
+ }
306
+ /**
307
+ * Follow one wake stream and give the actions for each batch: which source
308
+ * streams to read, from which cursor, and which to drop. The helper reads no
309
+ * source stream. Save each source cursor first and the wake cursor (`offset`)
310
+ * last; a stop between the two reads the same rows again, and the offset check
311
+ * skips the streams that were already read.
312
+ */
313
+ function followWake(declaration, params, options) {
314
+ const { from, cursors, ...follow } = options;
315
+ return Stream.unwrap(Effect.map(Effect.service(declaration), (service) => service.follow(params, {
316
+ ...follow,
317
+ offset: from
318
+ }).pipe(Stream.mapAccum(() => void 0, (snapshot, batch) => {
319
+ const next = wakeActions(batch.items, {
320
+ cursors,
321
+ snapshot
322
+ });
323
+ const out = {
324
+ items: next.items,
325
+ offset: batch.nextOffset,
326
+ upToDate: batch.upToDate
327
+ };
328
+ return [next.snapshot, [out]];
329
+ }))));
330
+ }
112
331
  // src/streamsy.ts
113
332
  var streamsy_exports = /* @__PURE__ */ __exportAll({
333
+ WakeItem: () => WakeItem,
334
+ WakeMessage: () => WakeMessage,
335
+ WakeRow: () => WakeRow,
114
336
  Wildcard: () => Wildcard,
115
337
  bytes: () => bytes,
116
338
  custom: () => custom,
339
+ followWake: () => followWake,
117
340
  group: () => group,
118
341
  json: () => json,
119
- state: () => state
342
+ state: () => state,
343
+ wake: () => wake,
344
+ wakeActions: () => wakeActions,
345
+ wakeCollections: () => wakeCollections
120
346
  });
121
347
  export { AppendConflict, AppendResult, ChangeSnapshot, CommitBoundary, CreateConflict, CreateResult, DecodeFault, durable_state_exports as DurableState, EncodeFault, ForkSourceNotFound, http_exports as Http, InvalidAppendRequest, 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 { n as OwnerRecordsApi, t as OwnerRecords } from "../owner-records-BV5Un5R0.js";
1
+ import { n as OwnerRecordsApi, t as OwnerRecords } from "../owner-records-H7VEuBpy.js";
2
2
  import { Context, Effect } 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;
@@ -17,4 +17,27 @@ type Owner = object;
17
17
  export declare const attachOwner: <A extends object>(value: A, owner: Owner) => A;
18
18
  export declare const ownerOf: (value: object) => Owner;
19
19
  export declare const CurrentOwner: Context.Reference<object | undefined>;
20
+ /**
21
+ * Compile output shared by `StreamRoute` and stream validation.
22
+ *
23
+ * The public route value carries an id grammar, a typed `parse`, and an address
24
+ * constructor. Stream validation also needs the compiled grammar, so it can
25
+ * reject two templates that can both match one id. This module owns that
26
+ * compilation and the static overlap check.
27
+ */
28
+ interface LiteralSegment {
29
+ readonly kind: "literal";
30
+ readonly value: string;
31
+ }
32
+ interface ParameterSegment {
33
+ readonly kind: "parameter";
34
+ readonly name: string;
35
+ }
36
+ type Segment = LiteralSegment | ParameterSegment;
37
+ interface TemplateGrammar<Template extends string = string> {
38
+ readonly template: Template;
39
+ readonly segments: ReadonlyArray<Segment>;
40
+ readonly names: ReadonlyArray<string>;
41
+ }
42
+ export declare function compileSegments<const Template extends string>(template: Template): TemplateGrammar<Template>;
20
43
  export { OwnerRecords, type OwnerRecordsApi };
@@ -1,3 +1,3 @@
1
- import { a as isForeignOwner, n as attachOwner, o as ownerOf, t as CurrentOwner } from "../owner-BWQ2KvC_.js";
1
+ import { a as attachOwner, c as isForeignOwner, i as CurrentOwner, l as ownerOf, t as compileSegments } from "../route-internal-DNL0oGTN.js";
2
2
  import { t as OwnerRecords } from "../owner-records-C0p8jeC1.js";
3
- export { CurrentOwner, OwnerRecords, attachOwner, isForeignOwner, ownerOf };
3
+ export { CurrentOwner, OwnerRecords, attachOwner, compileSegments, isForeignOwner, ownerOf };
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { A as StreamsReader, C as ProducerGap, D as StreamGone, E as StreamClosed, F as isValid, I as next, J as ProducerState, K as Offset, M as Storage, N as ZERO_OFFSET, O as StreamNotFound, P as compare, Q as StreamId, S as OffsetMismatch, T as StreamBusy, X as StoredMessage, Y as RecordPatch, _ as InvalidAppendRequest, b as InvalidReadRequest, et as StreamRecord, f as AppendResult, g as ForkSourceNotFound, h as CreateConflict, j as StreamsWriter, m as AppendConflict, n as bind, p as CreateResult, q as ProducerId, v as InvalidEpochSeq, w as StaleEpoch, x as NotSupported, y as InvalidForkRequest } from "./streamsy-DJMArv09.js";
3
- import { r as attachStorage } from "./owner-BWQ2KvC_.js";
2
+ import { $ as RecordPatch, A as StreamClosed, B as next, C as InvalidForkRequest, D as ProducerGap, E as OffsetMismatch, F as StreamsWriter, I as Storage, L as ZERO_OFFSET, M as StreamNotFound, O as StaleEpoch, P as StreamsReader, Q as ProducerState, R as compare, S as InvalidEpochSeq, T as NotSupported, X as Offset, Z as ProducerId, _ as CreateResult, b as ForkSourceNotFound, et as StoredMessage, g as AppendResult, it as StreamRecord, j as StreamGone, k as StreamBusy, n as bind, nt as StreamId, v as AppendConflict, w as InvalidReadRequest, x as InvalidAppendRequest, y as CreateConflict, z as isValid } from "./streamsy-D9OCCdw0.js";
3
+ import { o as attachStorage } from "./route-internal-DNL0oGTN.js";
4
4
  import { t as generateCursor } from "./cursor-generator-DySXZ93b.js";
5
5
  import { Array, Clock, Context, Data, Effect, Layer, Match, Option, Predicate, Random, Schema, Stream } from "effect";
6
6
  // src/storage/mutation.ts
@@ -1,8 +1,8 @@
1
- import { M as Storage, N as ZERO_OFFSET } from "./streamsy-DJMArv09.js";
2
- import { a as MutationRejected, l as OperationResults, o as Mutations, u as Operations } from "./layer-DyezIxJT.js";
3
- import { n as attachOwner, o as ownerOf } from "./owner-BWQ2KvC_.js";
1
+ import { I as Storage, L as ZERO_OFFSET } from "./streamsy-D9OCCdw0.js";
2
+ import { a as MutationRejected, l as OperationResults, o as Mutations, u as Operations } from "./layer-8Y1cg6UL.js";
3
+ import { a as attachOwner, l as ownerOf } from "./route-internal-DNL0oGTN.js";
4
4
  import { t as OwnerRecords } from "./owner-records-C0p8jeC1.js";
5
- import { Array, Context, Effect, Layer, Option, Order, Predicate, Queue, Schedule, Semaphore, Stream } from "effect";
5
+ import { Array, Context, Effect, Layer, Option, Order, Predicate, PubSub, Queue, Schedule, Semaphore, Stream } from "effect";
6
6
  // src/storage/commit-boundary.ts
7
7
  /** The transaction of the storage owner. Every Streamsy storage host provides it. */
8
8
  var CommitBoundary = class extends Context.Service()("@streamsy/core/CommitBoundary") {};
@@ -160,21 +160,23 @@ const makeBoundary = (committed, publish) => Effect.gen(function* () {
160
160
  fiberId: fiber.id,
161
161
  state: copyState(committed),
162
162
  records: new Map(committedRecords),
163
+ ids: /* @__PURE__ */ new Set(),
163
164
  active: true,
164
165
  changed: false
165
166
  };
166
167
  return Effect.uninterruptibleMask((restore) => restore(body.pipe(Effect.provideService(ActiveDraft, draft))).pipe(Effect.tap(() => Effect.sync(() => {
167
168
  Object.assign(committed, draft.state);
168
169
  committedRecords = draft.records;
169
- }).pipe(Effect.andThen(Effect.suspend(() => draft.changed ? publish : Effect.void)))), Effect.ensuring(Effect.sync(() => {
170
+ }).pipe(Effect.andThen(Effect.suspend(() => draft.changed ? publish(draft.ids) : Effect.void)))), Effect.ensuring(Effect.sync(() => {
170
171
  draft.active = false;
171
172
  }))));
172
173
  }).pipe(Semaphore.withPermit(lock)));
173
174
  });
174
175
  const access = (f) => Effect.map(current, (draft) => f(Option.isSome(draft) ? draft.value.state : committed));
175
- const changed = Effect.map(current, (draft) => {
176
+ const changed = (ids) => Effect.map(current, (draft) => {
176
177
  if (Option.isNone(draft)) throw new Error("Memory mutation requires an owner");
177
178
  draft.value.changed = true;
179
+ for (const id of ids) draft.value.ids.add(id);
178
180
  });
179
181
  const boundary = CommitBoundary.of({ withTransaction });
180
182
  const records = OwnerRecords.of({
@@ -256,7 +258,8 @@ const layer = (options = {}) => Layer.effectContext(Effect.gen(function* () {
256
258
  deadlines: []
257
259
  };
258
260
  const bus = yield* createNotifier;
259
- const owner = yield* makeBoundary(committed, bus.publish);
261
+ const feed = yield* Effect.acquireRelease(PubSub.unbounded(), PubSub.shutdown);
262
+ const owner = yield* makeBoundary(committed, (ids) => Effect.andThen(bus.publish, ids.size === 0 ? Effect.void : PubSub.publish(feed, [...ids]).pipe(Effect.asVoid)));
260
263
  const commit = (state, mutation) => {
261
264
  const changed = /* @__PURE__ */ new Set();
262
265
  for (const [index, operation] of mutation.operations.entries()) {
@@ -328,11 +331,12 @@ const layer = (options = {}) => Layer.effectContext(Effect.gen(function* () {
328
331
  const result = yield* owner.access((state) => commit(state, mutation));
329
332
  if (Predicate.isTagged(result, "MutationRejected")) return yield* result;
330
333
  const { outcome, changed } = result;
331
- if (changed.size > 0) yield* owner.changed;
334
+ if (changed.size > 0) yield* owner.changed(ids);
332
335
  return outcome;
333
336
  }).pipe(owner.withTransaction, Effect.uninterruptible);
334
337
  }),
335
338
  changes: (id) => changes(committed, bus, id, chain, interval),
339
+ committed: PubSub.subscribe(feed),
336
340
  nextExpiry: owner.access((state) => Option.fromUndefinedOr(state.deadlines[0]).pipe(Option.map((deadline) => ({ ...deadline }))))
337
341
  });
338
342
  return Context.make(Storage, attachOwner(storage, ownerOf(owner.boundary))).pipe(Context.add(CommitBoundary, owner.boundary), Context.add(OwnerRecords, owner.records));
@@ -1,4 +1,4 @@
1
- import { Context, Data, Effect, Option, Schema, Stream } from "effect";
1
+ import { Context, Data, Effect, Option, PubSub, Schema, Scope, Stream } from "effect";
2
2
  declare const StorageFault_base: Schema.Class<StorageFault, Schema.TaggedStruct<"StorageFault", {
3
3
  readonly operation: Schema.String;
4
4
  readonly message: Schema.String;
@@ -2920,6 +2920,15 @@ interface StorageShape {
2920
2920
  readonly producer: (id: StreamId, producerId: ProducerId) => Effect.Effect<Option.Option<ProducerState>, StorageFault>;
2921
2921
  readonly mutate: (mutation: Mutation) => Effect.Effect<MutationApplied, MutationRejected | StorageFault>;
2922
2922
  readonly changes: (id: StreamId) => Stream.Stream<ChangeSnapshot, StorageFault>;
2923
+ /**
2924
+ * Subscribe to the stream ids of later local commits. The subscription exists when
2925
+ * this effect returns, so a commit after that point always lands in it. Each item
2926
+ * holds the ids that one commit created, appended to or deleted, after that commit.
2927
+ * A rolled-back mutation reports nothing. In process and best effort: a commit by
2928
+ * another process on the same database does not show, and nothing replays after a
2929
+ * restart. The scope releases the subscription.
2930
+ */
2931
+ readonly committed: Effect.Effect<PubSub.Subscription<ReadonlyArray<StreamId>>, never, Scope.Scope>;
2923
2932
  readonly nextExpiry: Effect.Effect<Option.Option<{
2924
2933
  readonly at: number;
2925
2934
  readonly streamId: StreamId;
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { A as StreamsReader, F as isValid, Q as StreamId, f as AppendResult, j as StreamsWriter, k as isProtocolError, p as CreateResult } from "./streamsy-DJMArv09.js";
2
+ import { F as StreamsWriter, N as isProtocolError, P as StreamsReader, _ as CreateResult, g as AppendResult, nt as StreamId, z as isValid } from "./streamsy-D9OCCdw0.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";
@@ -1,5 +1,5 @@
1
- import { _ as StreamsWriter, g as StreamsReader, h as Reader, v as Writer } from "../owner-records-BV5Un5R0.js";
2
- import { D as streams_d_exports, P as layer_d_exports, u as RoutesOptions, z as route_d_exports } from "../index-C26ncp7Y.js";
1
+ import { _ as StreamsWriter, g as StreamsReader, h as Reader, v as Writer } from "../owner-records-H7VEuBpy.js";
2
+ import { D as streams_d_exports, P as layer_d_exports, u as RoutesOptions, z as route_d_exports } from "../index-p68har8W.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 { A as StreamsReader, j as StreamsWriter, l as streams_exports, u as route_exports } from "../streamsy-DJMArv09.js";
2
- import { n as layer_exports } from "../layer-DyezIxJT.js";
3
- import { t as app } from "../program-DXUjw5B2.js";
1
+ import { F as StreamsWriter, P as StreamsReader, l as streams_exports, u as route_exports } from "../streamsy-D9OCCdw0.js";
2
+ import { n as layer_exports } from "../layer-8Y1cg6UL.js";
3
+ import { t as app } from "../program-CYtMjdvD.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. */
@@ -1,5 +1,5 @@
1
- import { _ as StreamsWriter, g as StreamsReader, vt as TransportFault } from "../owner-records-BV5Un5R0.js";
2
- import { f as Any, m as Identifiers, p as Group } from "../index-C26ncp7Y.js";
1
+ import { _ as StreamsWriter, g as StreamsReader, vt as TransportFault } from "../owner-records-H7VEuBpy.js";
2
+ import { f as Any, m as Identifiers, p as Group } from "../index-p68har8W.js";
3
3
  import { Layer } from "effect";
4
4
  import { HttpClient, HttpClientRequest } from "effect/http";
5
5
  interface Options {
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "../rolldown-runtime-D8jQpDG7.js";
2
- import { A as StreamsReader, C as ProducerGap, D as StreamGone, E as StreamClosed, O as StreamNotFound, Q as StreamId, S as OffsetMismatch, T as StreamBusy, V as TransportFault, _ as InvalidAppendRequest, b as InvalidReadRequest, f as AppendResult, g as ForkSourceNotFound, h as CreateConflict, j as StreamsWriter, m as AppendConflict, n as bind, p as CreateResult, w as StaleEpoch, x as NotSupported, y as InvalidForkRequest } from "../streamsy-DJMArv09.js";
2
+ import { A as StreamClosed, C as InvalidForkRequest, D as ProducerGap, E as OffsetMismatch, F as StreamsWriter, G as TransportFault, M as StreamNotFound, O as StaleEpoch, P as StreamsReader, T as NotSupported, _ as CreateResult, b as ForkSourceNotFound, g as AppendResult, j as StreamGone, k as StreamBusy, n as bind, nt as StreamId, v as AppendConflict, w as InvalidReadRequest, x as InvalidAppendRequest, y as CreateConflict } from "../streamsy-D9OCCdw0.js";
3
3
  import { Array, Context, DateTime, Effect, Fiber, Layer, Option, Schema, Scope, Stream } from "effect";
4
4
  import { HttpClient, HttpClientRequest } from "effect/http";
5
5
  // src/remote/request.ts
@@ -0,0 +1,93 @@
1
+ import { Context, Data, Effect, Predicate } from "effect";
2
+ // src/internal/owner.ts
3
+ /** Private bridge: a stream guard dies with this sentinel; the atomic runner translates it. */
4
+ const ForeignOwnerType = Symbol.for("@streamsy/core/internal/ForeignOwner");
5
+ var ForeignOwner = class extends Data.TaggedError("ForeignOwner") {
6
+ stream;
7
+ [ForeignOwnerType] = true;
8
+ constructor(stream, knownOwner) {
9
+ super({ message: knownOwner ? `Stream write to ${stream} does not share the checkpoint owner` : `Cannot establish a storage owner for ${stream}; the exposed Storage does not own the protocol wires` });
10
+ this.stream = stream;
11
+ }
12
+ };
13
+ const isForeignOwner = (value) => Predicate.hasProperty(value, ForeignOwnerType) && value[ForeignOwnerType] === true;
14
+ const OwnerMetadata = Symbol.for("@streamsy/core/internal/CommitOwner");
15
+ const attachOwner = (value, owner) => Object.defineProperty(value, OwnerMetadata, {
16
+ value: owner,
17
+ enumerable: false
18
+ });
19
+ const ownerOf = (value) => {
20
+ if (!(OwnerMetadata in value)) return value;
21
+ const owner = value[OwnerMetadata];
22
+ return Predicate.isObjectKeyword(owner) ? owner : value;
23
+ };
24
+ const CurrentOwner = Context.Reference("@streamsy/core/internal/CurrentOwner", { defaultValue: () => void 0 });
25
+ const checkWriteOwner = (owner, id, knownOwner) => Effect.flatMap(CurrentOwner, (expected) => expected === void 0 || expected === owner ? Effect.void : Effect.die(new ForeignOwner(id, knownOwner)));
26
+ const Metadata = Symbol.for("@streamsy/core/internal/StorageOwner");
27
+ const attachStorage = (wire, storage) => Object.defineProperty(wire, Metadata, {
28
+ value: storage,
29
+ enumerable: false
30
+ });
31
+ const storageOf = (wire) => {
32
+ if (!(Metadata in wire)) return void 0;
33
+ return wire[Metadata];
34
+ };
35
+ // src/toolkit/route-internal.ts
36
+ /** Ids are canonical relative paths, the same rule the remote Layer enforces. */
37
+ function isCanonicalIdSegment(value) {
38
+ if (value.length === 0 || value === "." || value === "..") return false;
39
+ return !/[%?#/\\]/.test(value);
40
+ }
41
+ function compileSegments(template) {
42
+ if (template.length === 0) throw new RangeError("a stream route template must name at least one segment");
43
+ if (template.startsWith("/")) throw new RangeError("a stream route template is relative and cannot start with a slash");
44
+ if (/[?#*]/.test(template)) throw new RangeError("a stream route template cannot contain a query, fragment, or wildcard");
45
+ const names = [];
46
+ const segments = [];
47
+ for (const part of template.split("/")) {
48
+ if (part.length === 0) throw new RangeError("a stream route template cannot contain an empty segment");
49
+ if (!part.startsWith(":")) {
50
+ if (!isCanonicalIdSegment(part)) throw new RangeError(`a stream route literal segment is not a canonical id segment: ${part}`);
51
+ segments.push({
52
+ kind: "literal",
53
+ value: part
54
+ });
55
+ continue;
56
+ }
57
+ const name = part.slice(1);
58
+ if (name.length === 0) throw new RangeError("a stream route parameter needs a name");
59
+ if (names.includes(name)) throw new RangeError(`duplicate stream route parameter: ${name}`);
60
+ names.push(name);
61
+ segments.push({
62
+ kind: "parameter",
63
+ name
64
+ });
65
+ }
66
+ return {
67
+ template,
68
+ segments: Object.freeze(segments),
69
+ names: Object.freeze(names)
70
+ };
71
+ }
72
+ /**
73
+ * True when two template routes can both match one id.
74
+ *
75
+ * Lengths must agree, and every position must be either an equal literal pair
76
+ * or a parameter on at least one side. A parameter is treated as matching any
77
+ * segment, so a codec-constrained parameter can report an overlap it would
78
+ * never actually match. A custom route carries no template and is never
79
+ * checked; HTTP dispatch uses declaration order and the first match wins.
80
+ */
81
+ function templatesOverlap(left, right) {
82
+ if (left.length === 0 || right.length === 0) return false;
83
+ const a = compileSegments(left).segments;
84
+ const b = compileSegments(right).segments;
85
+ if (a.length !== b.length) return false;
86
+ for (const [index, segment] of a.entries()) {
87
+ const other = b[index];
88
+ if (!other || segment.kind === "parameter" || other.kind === "parameter") continue;
89
+ if (segment.value !== other.value) return false;
90
+ }
91
+ return true;
92
+ }
93
+ export { attachOwner as a, isForeignOwner as c, CurrentOwner as i, ownerOf as l, isCanonicalIdSegment as n, attachStorage as o, templatesOverlap as r, checkWriteOwner as s, compileSegments as t, storageOf as u };
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.js";
2
- import { i as checkWriteOwner, o as ownerOf, s as storageOf } from "./owner-BWQ2KvC_.js";
2
+ import { l as ownerOf, n as isCanonicalIdSegment, r as templatesOverlap, s as checkWriteOwner, t as compileSegments, u as storageOf } from "./route-internal-DNL0oGTN.js";
3
3
  import { Array, Context, Data, Duration, Effect, Layer, Option, Predicate, Record, Result, Schedule, Schema, Stream } from "effect";
4
4
  // src/schema/index.ts
5
5
  const StreamId = Schema.String.pipe(Schema.brand("StreamId"));
@@ -242,69 +242,12 @@ const isProtocolError = (error) => Record.has(protocolErrorTags, error._tag);
242
242
  /** Constructors and matchers for the protocol results above. */
243
243
  const CreateResult = Data.taggedEnum();
244
244
  const AppendResult = Data.taggedEnum();
245
- // src/toolkit/route-internal.ts
246
- /** Ids are canonical relative paths, the same rule the remote Layer enforces. */
247
- function isCanonicalIdSegment(value) {
248
- if (value.length === 0 || value === "." || value === "..") return false;
249
- return !/[%?#/\\]/.test(value);
250
- }
251
- function compileSegments(template) {
252
- if (template.length === 0) throw new RangeError("a stream route template must name at least one segment");
253
- if (template.startsWith("/")) throw new RangeError("a stream route template is relative and cannot start with a slash");
254
- if (/[?#*]/.test(template)) throw new RangeError("a stream route template cannot contain a query, fragment, or wildcard");
255
- const names = [];
256
- const segments = [];
257
- for (const part of template.split("/")) {
258
- if (part.length === 0) throw new RangeError("a stream route template cannot contain an empty segment");
259
- if (!part.startsWith(":")) {
260
- if (!isCanonicalIdSegment(part)) throw new RangeError(`a stream route literal segment is not a canonical id segment: ${part}`);
261
- segments.push({
262
- kind: "literal",
263
- value: part
264
- });
265
- continue;
266
- }
267
- const name = part.slice(1);
268
- if (name.length === 0) throw new RangeError("a stream route parameter needs a name");
269
- if (names.includes(name)) throw new RangeError(`duplicate stream route parameter: ${name}`);
270
- names.push(name);
271
- segments.push({
272
- kind: "parameter",
273
- name
274
- });
275
- }
276
- return {
277
- template,
278
- segments: Object.freeze(segments),
279
- names: Object.freeze(names)
280
- };
281
- }
282
- /**
283
- * True when two template routes can both match one id.
284
- *
285
- * Lengths must agree, and every position must be either an equal literal pair
286
- * or a parameter on at least one side. A parameter is treated as matching any
287
- * segment, so a codec-constrained parameter can report an overlap it would
288
- * never actually match. A custom route carries no template and is never
289
- * checked; HTTP dispatch uses declaration order and the first match wins.
290
- */
291
- function templatesOverlap(left, right) {
292
- if (left.length === 0 || right.length === 0) return false;
293
- const a = compileSegments(left).segments;
294
- const b = compileSegments(right).segments;
295
- if (a.length !== b.length) return false;
296
- for (const [index, segment] of a.entries()) {
297
- const other = b[index];
298
- if (!other || segment.kind === "parameter" || other.kind === "parameter") continue;
299
- if (segment.value !== other.value) return false;
300
- }
301
- return true;
302
- }
303
245
  // src/toolkit/address.ts
304
246
  var address_exports = /* @__PURE__ */ __exportAll({
305
247
  bytes: () => bytes$2,
306
248
  isChange: () => isChange,
307
249
  isControl: () => isControl,
250
+ isUpsert: () => isUpsert,
308
251
  json: () => json$2,
309
252
  reset: () => reset,
310
253
  snapshotEnd: () => snapshotEnd,
@@ -371,6 +314,8 @@ const stateControl = Schema.Struct({ headers: Schema.Struct({
371
314
  const isControl = (event) => Predicate.hasProperty(event.headers, "control");
372
315
  /** True for an upsert or delete change. */
373
316
  const isChange = (event) => !isControl(event);
317
+ /** True for an upsert change, with its value available. */
318
+ const isUpsert = (event) => isChange(event) && event.headers.operation === "upsert";
374
319
  const control = (name, options) => ({ headers: options.offset === void 0 ? { control: name } : {
375
320
  control: name,
376
321
  offset: options.offset
@@ -843,4 +788,4 @@ function group(...keys) {
843
788
  checkStreams(keys);
844
789
  return Object.freeze({ streams: Object.freeze(keys) });
845
790
  }
846
- export { StreamLifecycle as $, StreamsReader as A, StreamsFault as B, ProducerGap as C, StreamGone as D, StreamClosed as E, isValid as F, MessageWindow as G, isRetryableFault as H, next as I, ProducerState as J, Offset as K, DecodeFault as L, Storage as M, ZERO_OFFSET as N, StreamNotFound as O, compare as P, StreamId as Q, EncodeFault as R, OffsetMismatch as S, StreamBusy as T, isStreamsFault as U, TransportFault as V, ChangeSnapshot as W, StoredMessage as X, RecordPatch as Y, StreamConfig as Z, InvalidAppendRequest as _, custom as a, InvalidReadRequest as b, state as c, address_exports as d, StreamRecord as et, AppendResult as f, ForkSourceNotFound as g, CreateConflict as h, checkStreams as i, StreamsWriter as j, isProtocolError as k, streams_exports as l, AppendConflict as m, bind as n, group as o, CreateResult as p, ProducerId as q, bytes as r, json as s, Wildcard as t, route_exports as u, InvalidEpochSeq as v, StaleEpoch as w, NotSupported as x, InvalidForkRequest as y, StorageFault as z };
791
+ export { RecordPatch as $, StreamClosed as A, next as B, InvalidForkRequest as C, ProducerGap as D, OffsetMismatch as E, StreamsWriter as F, TransportFault as G, EncodeFault as H, Storage as I, ChangeSnapshot as J, isRetryableFault as K, ZERO_OFFSET as L, StreamNotFound as M, isProtocolError as N, StaleEpoch as O, StreamsReader as P, ProducerState as Q, compare as R, InvalidEpochSeq as S, NotSupported as T, StorageFault as U, DecodeFault as V, StreamsFault as W, Offset as X, MessageWindow as Y, ProducerId as Z, CreateResult as _, custom as a, ForkSourceNotFound as b, state as c, address_exports as d, StoredMessage as et, isControl as f, AppendResult as g, stateControl as h, checkStreams as i, StreamRecord as it, StreamGone as j, StreamBusy as k, streams_exports as l, stateChange as m, bind as n, StreamId as nt, group as o, isUpsert as p, isStreamsFault as q, bytes as r, StreamLifecycle as rt, json as s, Wildcard as t, StreamConfig as tt, route_exports as u, AppendConflict as v, InvalidReadRequest as w, InvalidAppendRequest as x, CreateConflict as y, isValid as z };