@streamsy/core 0.4.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.
@@ -1,13 +1,12 @@
1
- import { M as Storage, N as ZERO_OFFSET } from "./streamsy-OjRubIPC.js";
2
- import { a as MutationRejected, l as OperationResults, o as Mutations, u as Operations } from "./layer-KvknRFUT.js";
3
- import { n as attachOwner, o as ownerOf } from "./owner-BQzMpfC1.js";
4
- import { t as OwnerRecords } from "./owner-records-CX6yU28i.js";
5
- import { Context, Effect, Layer, Option, Predicate, Queue, Schedule, Semaphore, Stream } from "effect";
6
- //#region src/storage/commit-boundary.ts
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
+ import { t as OwnerRecords } from "./owner-records-C0p8jeC1.js";
5
+ import { Array, Context, Effect, Layer, Option, Order, Predicate, PubSub, Queue, Schedule, Semaphore, Stream } from "effect";
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") {};
9
- //#endregion
10
- //#region src/storage/memory/state.ts
9
+ // src/storage/memory/state.ts
11
10
  const copyRecord = (record) => ({
12
11
  id: record.id,
13
12
  currentOffset: record.currentOffset,
@@ -48,26 +47,31 @@ function patchRecord(record, patch) {
48
47
  };
49
48
  }
50
49
  function indexDeadlines(state) {
51
- state.deadlines = [...state.entries.values()].flatMap(({ record }) => record.lifecycle.softDeleted || record.lifecycle.expiresAtMs === void 0 ? [] : [{
50
+ state.deadlines = Array.sort(Array.flatMap([...state.entries.values()], ({ record }) => record.lifecycle.softDeleted || record.lifecycle.expiresAtMs === void 0 ? [] : [{
52
51
  at: record.lifecycle.expiresAtMs,
53
52
  streamId: record.id
54
- }]).toSorted((a, b) => a.at - b.at || a.streamId.localeCompare(b.streamId));
53
+ }]), Order.make((a, b) => {
54
+ const compared = a.at - b.at || a.streamId.localeCompare(b.streamId);
55
+ return compared < 0 ? -1 : compared > 0 ? 1 : 0;
56
+ }));
55
57
  }
56
58
  /** A private transaction draft; no mutable stream data aliases the committed state. */
57
59
  const copyState = (state) => ({
58
- entries: new Map([...state.entries].map(([id, entry]) => [id, {
60
+ entries: new Map(Array.map([...state.entries], ([id, entry]) => [id, {
59
61
  record: copyRecord(entry.record),
60
- messages: entry.messages.map(copyMessage),
61
- producers: new Map([...entry.producers].map(([producerId, producer]) => [producerId, {
62
+ messages: Array.map(entry.messages, copyMessage),
63
+ producers: new Map(Array.map([...entry.producers], ([producerId, producer]) => [producerId, {
62
64
  epoch: producer.epoch,
63
65
  lastSeq: producer.lastSeq
64
66
  }]))
65
67
  }])),
66
- children: new Map([...state.children].map(([id, children]) => [id, new Set(children)])),
67
- deadlines: state.deadlines.map((deadline) => ({ ...deadline }))
68
+ children: new Map(Array.map([...state.children], ([id, children]) => [id, new Set(children)])),
69
+ deadlines: Array.map(state.deadlines, (deadline) => ({ ...deadline }))
68
70
  });
69
- //#endregion
70
- //#region src/storage/memory/lineage.ts
71
+ // src/storage/memory/lineage.ts
72
+ /** Synchronous port of cascade-reclaim and chained message composition.
73
+ * Called only inside the memory mutation lock or synchronous read snapshot.
74
+ */
71
75
  function addEdge(state, parent, child) {
72
76
  const children = state.children.get(parent) ?? /* @__PURE__ */ new Set();
73
77
  children.add(child);
@@ -95,10 +99,10 @@ function composeMessages(state, id, chain) {
95
99
  const entry = state.entries.get(id);
96
100
  if (!entry) return [];
97
101
  const { forkedFrom, forkOffset } = entry.record.lifecycle;
98
- return [...chain && forkedFrom !== void 0 && forkOffset !== void 0 ? composeMessages(state, forkedFrom, true).filter((message) => message.offset <= forkOffset) : [], ...entry.messages].toSorted((a, b) => a.offset < b.offset ? -1 : a.offset > b.offset ? 1 : 0);
102
+ const inherited = chain && forkedFrom !== void 0 && forkOffset !== void 0 ? Array.filter(composeMessages(state, forkedFrom, true), (message) => message.offset <= forkOffset) : [];
103
+ return Array.sort([...inherited, ...entry.messages], Order.mapInput(Order.String, (message) => message.offset));
99
104
  }
100
- //#endregion
101
- //#region src/storage/memory/notifier.ts
105
+ // src/storage/memory/notifier.ts
102
106
  /** Private store-wide wakes, with retention isolated to each active subscription. */
103
107
  const createNotifier = Effect.gen(function* () {
104
108
  const queues = /* @__PURE__ */ new Set();
@@ -138,8 +142,7 @@ const createNotifier = Effect.gen(function* () {
138
142
  })
139
143
  };
140
144
  });
141
- //#endregion
142
- //#region src/storage/memory/boundary.ts
145
+ // src/storage/memory/boundary.ts
143
146
  var ActiveDraft = class extends Context.Service()("@streamsy/core/internal/MemoryActiveDraft") {};
144
147
  const makeBoundary = (committed, publish) => Effect.gen(function* () {
145
148
  const owner = {};
@@ -157,21 +160,23 @@ const makeBoundary = (committed, publish) => Effect.gen(function* () {
157
160
  fiberId: fiber.id,
158
161
  state: copyState(committed),
159
162
  records: new Map(committedRecords),
163
+ ids: /* @__PURE__ */ new Set(),
160
164
  active: true,
161
165
  changed: false
162
166
  };
163
167
  return Effect.uninterruptibleMask((restore) => restore(body.pipe(Effect.provideService(ActiveDraft, draft))).pipe(Effect.tap(() => Effect.sync(() => {
164
168
  Object.assign(committed, draft.state);
165
169
  committedRecords = draft.records;
166
- }).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(() => {
167
171
  draft.active = false;
168
172
  }))));
169
173
  }).pipe(Semaphore.withPermit(lock)));
170
174
  });
171
175
  const access = (f) => Effect.map(current, (draft) => f(Option.isSome(draft) ? draft.value.state : committed));
172
- const changed = Effect.map(current, (draft) => {
176
+ const changed = (ids) => Effect.map(current, (draft) => {
173
177
  if (Option.isNone(draft)) throw new Error("Memory mutation requires an owner");
174
178
  draft.value.changed = true;
179
+ for (const id of ids) draft.value.ids.add(id);
175
180
  });
176
181
  const boundary = CommitBoundary.of({ withTransaction });
177
182
  const records = OwnerRecords.of({
@@ -193,8 +198,7 @@ const makeBoundary = (committed, publish) => Effect.gen(function* () {
193
198
  changed
194
199
  };
195
200
  });
196
- //#endregion
197
- //#region src/storage/memory/changes.ts
201
+ // src/storage/memory/changes.ts
198
202
  function snapshot(state, id) {
199
203
  const record = state.entries.get(id)?.record;
200
204
  return {
@@ -212,8 +216,7 @@ function changes(state, bus, id, push, interval) {
212
216
  return Stream.concat(Stream.fromEffect(read), Stream.fromQueue(subscription).pipe(Stream.mapEffect(() => read)));
213
217
  }));
214
218
  }
215
- //#endregion
216
- //#region src/storage/memory/layer.ts
219
+ // src/storage/memory/layer.ts
217
220
  function reject(state, operation, index) {
218
221
  const id = Predicate.isTagged(operation, "Create") ? operation.record.id : operation.streamId;
219
222
  const entry = state.entries.get(id);
@@ -255,7 +258,8 @@ const layer = (options = {}) => Layer.effectContext(Effect.gen(function* () {
255
258
  deadlines: []
256
259
  };
257
260
  const bus = yield* createNotifier;
258
- 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)));
259
263
  const commit = (state, mutation) => {
260
264
  const changed = /* @__PURE__ */ new Set();
261
265
  for (const [index, operation] of mutation.operations.entries()) {
@@ -268,7 +272,7 @@ const layer = (options = {}) => Layer.effectContext(Effect.gen(function* () {
268
272
  const record = copyRecord(operation.record);
269
273
  state.entries.set(record.id, {
270
274
  record,
271
- messages: operation.initialMessages.map(copyMessage),
275
+ messages: Array.map(operation.initialMessages, copyMessage),
272
276
  producers: /* @__PURE__ */ new Map()
273
277
  });
274
278
  if (chain && record.lifecycle.forkedFrom !== void 0) addEdge(state, record.lifecycle.forkedFrom, record.id);
@@ -283,7 +287,7 @@ const layer = (options = {}) => Layer.effectContext(Effect.gen(function* () {
283
287
  results.push(OperationResults.Created({ record: copyRecord(entry.record) }));
284
288
  },
285
289
  Append: (append) => {
286
- entry.messages.push(...append.messages.map(copyMessage));
290
+ entry.messages.push(...Array.map(append.messages, copyMessage));
287
291
  entry.record = patchRecord(entry.record, append.patch);
288
292
  if (append.producer) entry.producers.set(append.producer.producerId, { ...append.producer.next });
289
293
  results.push(OperationResults.Appended({ record: copyRecord(entry.record) }));
@@ -315,26 +319,26 @@ const layer = (options = {}) => Layer.effectContext(Effect.gen(function* () {
315
319
  expiryIndex: chain ? "indexed" : "lazy"
316
320
  },
317
321
  record: Effect.fn("Memory.record")((id) => owner.access((state) => Option.fromUndefinedOr(state.entries.get(id)?.record).pipe(Option.map(copyRecord)))),
318
- messages: Effect.fn("Memory.messages")((id, window) => owner.access((state) => composeMessages(state, id, chain).filter((message) => (window.after === void 0 || message.offset > window.after) && (window.until === void 0 || message.offset <= window.until)).slice(0, window.limit === void 0 ? void 0 : Math.max(0, window.limit)).map(copyMessage))),
322
+ messages: Effect.fn("Memory.messages")((id, window) => owner.access((state) => Array.map(Array.filter(composeMessages(state, id, chain), (message) => (window.after === void 0 || message.offset > window.after) && (window.until === void 0 || message.offset <= window.until)).slice(0, window.limit === void 0 ? void 0 : Math.max(0, window.limit)), copyMessage))),
319
323
  producer: Effect.fn("Memory.producer")((id, producerId) => owner.access((state) => Option.fromUndefinedOr(state.entries.get(id)?.producers.get(producerId)).pipe(Option.map((value) => ({
320
324
  epoch: value.epoch,
321
325
  lastSeq: value.lastSeq
322
326
  }))))),
323
327
  mutate: Effect.fn("Memory.mutate")(function* (mutation) {
324
- const ids = mutation.operations.map((operation) => Predicate.isTagged(operation, "Create") ? operation.record.id : operation.streamId);
328
+ const ids = Array.map(mutation.operations, (operation) => Predicate.isTagged(operation, "Create") ? operation.record.id : operation.streamId);
325
329
  if (ids.length === 0 || new Set(ids).size !== ids.length || !chain && ids.length > 1) return yield* Effect.die(/* @__PURE__ */ new Error("Mutation requires distinct streams within atomicScope"));
326
330
  return yield* Effect.gen(function* () {
327
331
  const result = yield* owner.access((state) => commit(state, mutation));
328
332
  if (Predicate.isTagged(result, "MutationRejected")) return yield* result;
329
333
  const { outcome, changed } = result;
330
- if (changed.size > 0) yield* owner.changed;
334
+ if (changed.size > 0) yield* owner.changed(ids);
331
335
  return outcome;
332
336
  }).pipe(owner.withTransaction, Effect.uninterruptible);
333
337
  }),
334
338
  changes: (id) => changes(committed, bus, id, chain, interval),
339
+ committed: PubSub.subscribe(feed),
335
340
  nextExpiry: owner.access((state) => Option.fromUndefinedOr(state.deadlines[0]).pipe(Option.map((deadline) => ({ ...deadline }))))
336
341
  });
337
342
  return Context.make(Storage, attachOwner(storage, ownerOf(owner.boundary))).pipe(Context.add(CommitBoundary, owner.boundary), Context.add(OwnerRecords, owner.records));
338
343
  }));
339
- //#endregion
340
344
  export { CommitBoundary as n, layer as t };
@@ -1,5 +1,4 @@
1
1
  import { Context } from "effect";
2
- //#region src/internal/owner-records.ts
2
+ // src/internal/owner-records.ts
3
3
  var OwnerRecords = class extends Context.Service()("@streamsy/core/internal/OwnerRecords") {};
4
- //#endregion
5
4
  export { OwnerRecords as t };
@@ -1,5 +1,4 @@
1
- import { Context, Data, Effect, Option, Schema, Stream } from "effect";
2
- //#region src/fault.d.ts
1
+ import { Context, Data, Effect, Option, PubSub, Schema, Scope, Stream } from "effect";
3
2
  declare const StorageFault_base: Schema.Class<StorageFault, Schema.TaggedStruct<"StorageFault", {
4
3
  readonly operation: Schema.String;
5
4
  readonly message: Schema.String;
@@ -36,8 +35,6 @@ type StreamsFault = typeof StreamsFault.Type;
36
35
  declare const isStreamsFault: <I>(input: I) => input is I & (StorageFault | TransportFault);
37
36
  /** A storage or transport failure that can succeed later. */
38
37
  declare const isRetryableFault: (error: unknown) => error is StreamsFault;
39
- //#endregion
40
- //#region src/schema/index.d.ts
41
38
  declare const StreamId: Schema.brand<Schema.String, "StreamId">;
42
39
  declare const Offset: Schema.brand<Schema.String, "Offset">;
43
40
  declare const ProducerId: Schema.brand<Schema.String, "ProducerId">;
@@ -126,8 +123,6 @@ declare const RecordPatch: Schema.Struct<{
126
123
  readonly clear: Schema.optionalKey<Schema.$Array<Schema.Literals<readonly ["ttlSeconds", "expiresAt", "expiresAtMs", "lastSeq"]>>>;
127
124
  }>;
128
125
  interface RecordPatch extends Schema.Schema.Type<typeof RecordPatch> {}
129
- //#endregion
130
- //#region src/policy/options.d.ts
131
126
  /** Private pure-policy input, promoted to protocol options in Batch 3. */
132
127
  interface CreateOptions {
133
128
  readonly contentType?: string;
@@ -139,8 +134,6 @@ interface CreateOptions {
139
134
  readonly forkSubOffset?: number;
140
135
  readonly initialData?: Uint8Array;
141
136
  }
142
- //#endregion
143
- //#region src/protocol/options.d.ts
144
137
  interface ProducerOptions {
145
138
  readonly producerId: string;
146
139
  readonly producerEpoch: number;
@@ -177,8 +170,6 @@ interface ReadNextOptions {
177
170
  offset: string;
178
171
  cursor?: string;
179
172
  }
180
- //#endregion
181
- //#region src/protocol/errors.d.ts
182
173
  declare const StreamNotFound_base: Schema.Class<StreamNotFound, Schema.TaggedStruct<"StreamNotFound", {
183
174
  readonly id: Schema.brand<Schema.String, "StreamId">;
184
175
  }>, import("effect/Cause").YieldableError>;
@@ -300,8 +291,6 @@ type ProtocolError = HeadError | ReadNextError | CreateError | AppendError | Rem
300
291
  declare const isProtocolError: (error: {
301
292
  readonly _tag: string;
302
293
  }) => error is ProtocolError;
303
- //#endregion
304
- //#region src/protocol/results.d.ts
305
294
  /** Payload-only messages exposed by the public protocol; storage owns offsets and timestamps. */
306
295
  interface ReadMessage {
307
296
  readonly data: Uint8Array;
@@ -427,8 +416,6 @@ interface HeadResult {
427
416
  readonly expiresAt?: string;
428
417
  readonly closed: boolean;
429
418
  }
430
- //#endregion
431
- //#region src/protocol/tags.d.ts
432
419
  interface Reader<E = StorageFault> {
433
420
  readonly head: (id: StreamId) => Effect.Effect<HeadResult, HeadError | E>;
434
421
  readonly read: (id: StreamId, options?: ReadOptions) => Effect.Effect<ReadResult, ReadError | E>;
@@ -444,8 +431,6 @@ declare const StreamsReader_base: Context.ServiceClass<StreamsReader, "@streamsy
444
431
  declare class StreamsReader extends StreamsReader_base {}
445
432
  declare const StreamsWriter_base: Context.ServiceClass<StreamsWriter, "@streamsy/core/StreamsWriter", Writer<StorageFault | TransportFault>>;
446
433
  declare class StreamsWriter extends StreamsWriter_base {}
447
- //#endregion
448
- //#region src/storage/capabilities.d.ts
449
434
  declare const StorageCapabilities: Schema.Struct<{
450
435
  readonly fork: Schema.Literals<readonly ["none", "copy", "chain"]>;
451
436
  readonly atomicScope: Schema.Literals<readonly ["stream", "store"]>;
@@ -453,8 +438,6 @@ declare const StorageCapabilities: Schema.Struct<{
453
438
  readonly expiryIndex: Schema.Literals<readonly ["lazy", "indexed"]>;
454
439
  }>;
455
440
  interface StorageCapabilities extends Schema.Schema.Type<typeof StorageCapabilities> {}
456
- //#endregion
457
- //#region src/storage/mutation.d.ts
458
441
  declare const ProducerPrecondition: Schema.Struct<{
459
442
  readonly producerId: Schema.brand<Schema.String, "ProducerId">;
460
443
  readonly expected: Schema.Option<Schema.Struct<{
@@ -2930,8 +2913,6 @@ declare const Mutations: {
2930
2913
  })[]];
2931
2914
  }, "_tag">;
2932
2915
  };
2933
- //#endregion
2934
- //#region src/storage/storage.d.ts
2935
2916
  interface StorageShape {
2936
2917
  readonly capabilities: StorageCapabilities;
2937
2918
  readonly record: (id: StreamId) => Effect.Effect<Option.Option<StreamRecord>, StorageFault>;
@@ -2939,6 +2920,15 @@ interface StorageShape {
2939
2920
  readonly producer: (id: StreamId, producerId: ProducerId) => Effect.Effect<Option.Option<ProducerState>, StorageFault>;
2940
2921
  readonly mutate: (mutation: Mutation) => Effect.Effect<MutationApplied, MutationRejected | StorageFault>;
2941
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>;
2942
2932
  readonly nextExpiry: Effect.Effect<Option.Option<{
2943
2933
  readonly at: number;
2944
2934
  readonly streamId: StreamId;
@@ -2946,8 +2936,6 @@ interface StorageShape {
2946
2936
  }
2947
2937
  declare const Storage_base: Context.ServiceClass<Storage, "@streamsy/core/Storage", StorageShape>;
2948
2938
  declare class Storage extends Storage_base {}
2949
- //#endregion
2950
- //#region src/internal/owner-records.d.ts
2951
2939
  /**
2952
2940
  * Encoded records on the storage owner, for the projection checkpoint store.
2953
2941
  * Calls inside `CommitBoundary.withTransaction` join that transaction.
@@ -2959,5 +2947,4 @@ interface OwnerRecordsApi {
2959
2947
  }
2960
2948
  declare const OwnerRecords_base: Context.ServiceClass<OwnerRecords, "@streamsy/core/internal/OwnerRecords", OwnerRecordsApi>;
2961
2949
  declare class OwnerRecords extends OwnerRecords_base {}
2962
- //#endregion
2963
2950
  export { ProducerOptions as $, CreateConflictReason as A, ProducerGap as B, ReadNextResult as C, AppendError as D, AppendConflict as E, InvalidEpochSeq as F, StaleEpoch as G, ReadError as H, InvalidForkRequest as I, StreamGone as J, StreamBusy as K, InvalidReadRequest as L, ForkSourceNotFound as M, HeadError as N, AppendErrorFor as O, InvalidAppendRequest as P, AppendOptions as Q, NotSupported as R, ReadMessage as S, AppendBaseError as T, ReadNextError as U, ProtocolError as V, RemoveError as W, isProtocolError as X, StreamNotFound as Y, AppendCallOptions as Z, StreamsWriter as _, StreamsFault as _t, Mutation as a, Offset as at, CreateResult as b, isStreamsFault as bt, Mutations as c, RecordPatch as ct, OperationResults as d, StreamId as dt, ReadNextOptions as et, Operations as f, StreamLifecycle as ft, StreamsReader as g, StorageFault as gt, Reader as h, EncodeFault as ht, StorageShape as i, MessageWindow as it, CreateError as j, CreateConflict as k, Operation as l, StoredMessage as lt, StorageCapabilities as m, DecodeFault as mt, OwnerRecordsApi as n, CreateOptions as nt, MutationApplied as o, ProducerId as ot, ProducerPrecondition as p, StreamRecord as pt, StreamClosed as q, Storage as r, ChangeSnapshot as rt, MutationRejected as s, ProducerState as st, OwnerRecords as t, ReadOptions as tt, OperationResult as u, StreamConfig as ut, Writer as v, TransportFault as vt, ReadResult as w, HeadResult as x, AppendResult as y, isRetryableFault as yt, OffsetMismatch as z };
@@ -1,9 +1,9 @@
1
- import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.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-OjRubIPC.js";
3
- import { t as generateCursor } from "./cursor-generator-CGz1TO_N.js";
4
- import { Clock, Context, DateTime, Deferred, Effect, Layer, Match, Option, Random, Ref, Schedule, Stream } from "effect";
1
+ import { t as __exportAll } from "./rolldown-runtime-D8jQpDG7.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
+ import { t as generateCursor } from "./cursor-generator-DySXZ93b.js";
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";
6
- //#region src/http/responses.ts
6
+ // src/http/responses.ts
7
7
  var responses_exports = /* @__PURE__ */ __exportAll({
8
8
  badRequest: () => badRequest$1,
9
9
  cacheControlForVisibility: () => cacheControlForVisibility,
@@ -86,18 +86,16 @@ function fromWeb(response) {
86
86
  return HttpServerResponse.raw(response, {
87
87
  status: response.status,
88
88
  statusText: response.statusText,
89
- headers: Object.fromEntries(response.headers)
89
+ headers: Record.fromEntries(response.headers)
90
90
  });
91
91
  }
92
- //#endregion
93
- //#region src/http/security-headers.ts
92
+ // src/http/security-headers.ts
94
93
  /** Shared protocol and host security headers. */
95
94
  const securityHeaders = Object.freeze({
96
95
  "x-content-type-options": "nosniff",
97
96
  "cross-origin-resource-policy": "cross-origin"
98
97
  });
99
- //#endregion
100
- //#region src/http/stream-path-service.ts
98
+ // src/http/stream-path-service.ts
101
99
  /** Prefix helpers shared by protocol and host routers. */
102
100
  const streamPath = (pathPrefix = "/") => {
103
101
  const prefix = pathPrefix.endsWith("/") ? pathPrefix : `${pathPrefix}/`;
@@ -109,8 +107,7 @@ const streamPath = (pathPrefix = "/") => {
109
107
  canonicalizeForkSource: (source) => regex.test(source) ? strip(source) : source.replace(/^\//, "")
110
108
  };
111
109
  };
112
- //#endregion
113
- //#region src/http/request-body-reader.ts
110
+ // src/http/request-body-reader.ts
114
111
  const requestBodyReader = (maxMessageSize) => ({ read: Effect.fn("Http.readBody")(function* (request) {
115
112
  return yield* request.arrayBuffer.pipe(Effect.map((data) => data.byteLength > maxMessageSize ? {
116
113
  ok: false,
@@ -124,8 +121,7 @@ const requestBodyReader = (maxMessageSize) => ({ read: Effect.fn("Http.readBody"
124
121
  response: payloadTooLarge()
125
122
  })));
126
123
  }) });
127
- //#endregion
128
- //#region src/http/request-body-discard.ts
124
+ // src/http/request-body-discard.ts
129
125
  /**
130
126
  * Consumes an unread request body before an early rejection.
131
127
  *
@@ -141,8 +137,7 @@ const requestBodyReader = (maxMessageSize) => ({ read: Effect.fn("Http.readBody"
141
137
  * the outcome that matters.
142
138
  */
143
139
  const discardRequestBody = (request) => Stream.runDrain(request.stream).pipe(Effect.ignoreCause);
144
- //#endregion
145
- //#region src/http/create.ts
140
+ // src/http/create.ts
146
141
  const responses$4 = responses_exports;
147
142
  function parseHeaders$1(request, path) {
148
143
  const rawContentType = request.headers.get("content-type");
@@ -219,8 +214,7 @@ function toResponse$1(result, location) {
219
214
  if (result.closed) headers.set("stream-closed", "true");
220
215
  return responses$4.empty(created ? 201 : 200, headers);
221
216
  }
222
- //#endregion
223
- //#region src/http/producer-header-parser.ts
217
+ // src/http/producer-header-parser.ts
224
218
  var producer_header_parser_exports = /* @__PURE__ */ __exportAll({ parse: () => parse });
225
219
  const MAX_SAFE_PRODUCER_INT = Number.MAX_SAFE_INTEGER;
226
220
  const NON_NEGATIVE_INT_RE = /^(0|[1-9]\d*)$/;
@@ -228,11 +222,11 @@ function parse(request) {
228
222
  const id = request.headers.get("producer-id");
229
223
  const epoch = request.headers.get("producer-epoch");
230
224
  const seq = request.headers.get("producer-seq");
231
- const present = [
225
+ const present = Array.filter([
232
226
  id,
233
227
  epoch,
234
228
  seq
235
- ].filter((v) => v !== null).length;
229
+ ], (v) => v !== null).length;
236
230
  if (present === 0) return { kind: "absent" };
237
231
  if (present !== 3 || id === null || epoch === null || seq === null) return { kind: "invalid" };
238
232
  if (id.length === 0) return { kind: "invalid" };
@@ -254,8 +248,7 @@ function parseInt$1(raw) {
254
248
  if (!Number.isFinite(n) || n > MAX_SAFE_PRODUCER_INT) return null;
255
249
  return n;
256
250
  }
257
- //#endregion
258
- //#region src/http/append.ts
251
+ // src/http/append.ts
259
252
  const producerParser = producer_header_parser_exports;
260
253
  const responses$3 = responses_exports;
261
254
  function parseHeaders(request) {
@@ -298,15 +291,13 @@ function toResponse(result, producerHeaders, isEmpty) {
298
291
  }
299
292
  });
300
293
  }
301
- //#endregion
302
- //#region src/http/etag-builder.ts
294
+ // src/http/etag-builder.ts
303
295
  var etag_builder_exports = /* @__PURE__ */ __exportAll({ forCatchUp: () => forCatchUp });
304
296
  function forCatchUp(pathname, startOffset, nextOffset, closed) {
305
297
  const closedSuffix = closed ? ":c" : "";
306
298
  return `"${btoa(pathname)}:${startOffset}:${nextOffset}${closedSuffix}"`;
307
299
  }
308
- //#endregion
309
- //#region src/http/bytes.ts
300
+ // src/http/bytes.ts
310
301
  /**
311
302
  * Cross-runtime byte normalization for HTTP bodies.
312
303
  *
@@ -369,8 +360,7 @@ function nodeBufferBase64(bytes) {
369
360
  if (encoded === null || encoded === void 0 || isReferenceValue(encoded) || Object.getPrototypeOf(Object(encoded)) !== String.prototype) return;
370
361
  return String.prototype.valueOf.call(encoded);
371
362
  }
372
- //#endregion
373
- //#region src/http/message-body-codec.ts
363
+ // src/http/message-body-codec.ts
374
364
  var message_body_codec_exports = /* @__PURE__ */ __exportAll({
375
365
  bytesToBase64: () => bytesToBase64,
376
366
  concatBytes: () => concatBytes,
@@ -380,15 +370,18 @@ var message_body_codec_exports = /* @__PURE__ */ __exportAll({
380
370
  const decoder$1 = new TextDecoder();
381
371
  function encodeHttpBody(messages, contentType) {
382
372
  const lower = contentType.toLowerCase();
383
- if (lower.startsWith("application/json")) return `[${messages.map((msg) => decoder$1.decode(msg.data)).join(",")}]`;
384
- if (lower.startsWith("text/")) return messages.map((msg) => decoder$1.decode(msg.data)).join("");
373
+ if (lower.startsWith("application/json")) {
374
+ const items = Array.map(messages, (msg) => decoder$1.decode(msg.data));
375
+ return `[${Array.join(items, ",")}]`;
376
+ }
377
+ if (lower.startsWith("text/")) return Array.join(Array.map(messages, (msg) => decoder$1.decode(msg.data)), "");
385
378
  return toArrayBuffer(concatBytes(messages));
386
379
  }
387
380
  function emptyBodyForContentType(contentType) {
388
381
  return contentType.toLowerCase().startsWith("application/json") ? "[]" : "";
389
382
  }
390
383
  function concatBytes(messages) {
391
- const totalLength = messages.reduce((acc, msg) => acc + msg.data.length, 0);
384
+ const totalLength = Array.reduce(messages, 0, (acc, msg) => acc + msg.data.length);
392
385
  const combined = new Uint8Array(totalLength);
393
386
  let pos = 0;
394
387
  for (const msg of messages) {
@@ -405,8 +398,7 @@ function bytesToBase64(bytes) {
405
398
  for (let i = 0; i < bytes.length; i += chunk) binary += String.fromCharCode(...bytes.subarray(i, i + chunk));
406
399
  return btoa(binary);
407
400
  }
408
- //#endregion
409
- //#region src/http/read-query-parser.ts
401
+ // src/http/read-query-parser.ts
410
402
  const readQueryParser = (isValidOffset) => ({ parse(url) {
411
403
  const offset = url.searchParams.get("offset") ?? void 0;
412
404
  const liveParam = url.searchParams.get("live");
@@ -427,8 +419,7 @@ const readQueryParser = (isValidOffset) => ({ parse(url) {
427
419
  cursor
428
420
  };
429
421
  } });
430
- //#endregion
431
- //#region src/http/sse-event-encoder.ts
422
+ // src/http/sse-event-encoder.ts
432
423
  var sse_event_encoder_exports = /* @__PURE__ */ __exportAll({
433
424
  controlEvent: () => controlEvent,
434
425
  dataEvent: () => dataEvent
@@ -441,7 +432,7 @@ function dataEvent(messages, options) {
441
432
  const combined = concatBytes(messages);
442
433
  chunks.push(encode(`data:${bytesToBase64(combined)}\n`));
443
434
  } else if (options.isJson) {
444
- const items = messages.map((msg) => decoder.decode(msg.data));
435
+ const items = Array.map(messages, (msg) => decoder.decode(msg.data));
445
436
  chunks.push(encode("data:[\n"));
446
437
  for (let i = 0; i < items.length; i++) {
447
438
  const suffix = i < items.length - 1 ? "," : "";
@@ -449,7 +440,7 @@ function dataEvent(messages, options) {
449
440
  }
450
441
  chunks.push(encode("data:]\n"));
451
442
  } else {
452
- const text = messages.map((msg) => decoder.decode(msg.data)).join("");
443
+ const text = Array.join(Array.map(messages, (msg) => decoder.decode(msg.data)), "");
453
444
  for (const line of text.split(/\r\n|\r|\n/)) chunks.push(encode(`data:${line}\n`));
454
445
  }
455
446
  chunks.push(encode("\n"));
@@ -461,8 +452,7 @@ function controlEvent(data) {
461
452
  function encode(value) {
462
453
  return encoder.encode(value);
463
454
  }
464
- //#endregion
465
- //#region src/http/sse.ts
455
+ // src/http/sse.ts
466
456
  const events = sse_event_encoder_exports;
467
457
  /** Each connection's deadline is `deadlineMs` scaled by a factor from 0.9 to 1.1. */
468
458
  const DEADLINE_JITTER = .1;
@@ -511,7 +501,7 @@ function sse(reader, id, contentType, offset, cursor, deadlineMs = 6e4, signal)
511
501
  if (!result.closed && result.upToDate) control.upToDate = true;
512
502
  chunks.push(events.controlEvent(control));
513
503
  return {
514
- frames: [concatBytes(chunks.map((data) => ({ data })))],
504
+ frames: [concatBytes(Array.map(chunks, (data) => ({ data })))],
515
505
  done: result.closed
516
506
  };
517
507
  }).pipe(Effect.catchTags({
@@ -536,10 +526,9 @@ function sse(reader, id, contentType, offset, cursor, deadlineMs = 6e4, signal)
536
526
  });
537
527
  if (encoding.useBase64) headers.set("stream-sse-data-encoding", "base64");
538
528
  const body = signal === void 0 ? frames : signal.trackStream(frames);
539
- return HttpServerResponse.stream(body, { headers: Object.fromEntries(headers) });
529
+ return HttpServerResponse.stream(body, { headers: Record.fromEntries(headers) });
540
530
  }
541
- //#endregion
542
- //#region src/http/shutdown-signal.ts
531
+ // src/http/shutdown-signal.ts
543
532
  var ShutdownSignal = class extends Context.Service()("@streamsy/core/ShutdownSignal") {};
544
533
  /** How often `drain` checks the live-read count. */
545
534
  const POLL = Schedule.spaced("5 millis");
@@ -561,8 +550,7 @@ const makeShutdownSignal = Effect.gen(function* () {
561
550
  });
562
551
  /** A fresh signal. Provide it to the routes and call `drain` before they close. */
563
552
  const layerShutdownSignal = Layer.effect(ShutdownSignal, makeShutdownSignal);
564
- //#endregion
565
- //#region src/http/read.ts
553
+ // src/http/read.ts
566
554
  const responses$2 = responses_exports;
567
555
  const bodyCodec = message_body_codec_exports;
568
556
  const etags = etag_builder_exports;
@@ -644,14 +632,12 @@ const read$1 = Effect.fn("Http.read")(function* (reader, id, url, requestHeaders
644
632
  headers.set("content-type", result.contentType);
645
633
  return new Response(bodyCodec.encodeHttpBody(result.messages, result.contentType), { headers });
646
634
  });
647
- //#endregion
648
- //#region src/http/route.ts
635
+ // src/http/route.ts
649
636
  /** Preserve the Web request origin; Effect 4.0.1 toURL otherwise reconstructs it from Host. */
650
637
  function requestUrl(request) {
651
638
  return URL.parse(request.originalUrl) ?? Option.getOrUndefined(HttpServerRequest.toURL(request));
652
639
  }
653
- //#endregion
654
- //#region src/http/read-program.ts
640
+ // src/http/read-program.ts
655
641
  /** @internal Shared construction-time validation for HTTP read routes. */
656
642
  function checkReadOptions(options) {
657
643
  if (options.sseDeadlineMs !== void 0 && (!Number.isFinite(options.sseDeadlineMs) || options.sseDeadlineMs <= 0)) throw new RangeError("sseDeadlineMs must be positive");
@@ -676,15 +662,14 @@ function read(id, options = {}) {
676
662
  if (meta.expiresAt) headers.set("stream-expires-at", meta.expiresAt);
677
663
  return HttpServerResponse.empty({
678
664
  status: 200,
679
- headers: Object.fromEntries(headers)
665
+ headers: Record.fromEntries(headers)
680
666
  });
681
667
  }
682
668
  const response = yield* read$1(reader, id, url, new Headers(request.headers), cacheControlForVisibility(options.cacheVisibility ?? "private"), options.sseDeadlineMs);
683
669
  return response instanceof Response ? fromWeb(response) : response;
684
670
  }).pipe(Effect.map(HttpServerResponse.setHeaders(securityHeaders)));
685
671
  }
686
- //#endregion
687
- //#region src/http/protocol-error-response.ts
672
+ // src/http/protocol-error-response.ts
688
673
  const responses$1 = responses_exports;
689
674
  const conflict = ({ message }) => responses$1.conflict(message);
690
675
  const badRequest = ({ message }) => responses$1.badRequest(message);
@@ -717,8 +702,7 @@ function protocolErrorResponse(error, context) {
717
702
  })
718
703
  });
719
704
  }
720
- //#endregion
721
- //#region src/http/program.ts
705
+ // src/http/program.ts
722
706
  const responses = responses_exports;
723
707
  const failure = (error) => Effect.map(HttpServerRequest.HttpServerRequest, (request) => protocolErrorResponse(error, { method: request.method }));
724
708
  /**
@@ -810,5 +794,4 @@ function app(options = {}) {
810
794
  return HttpServerResponse.setHeaders(result, securityHeaders);
811
795
  }));
812
796
  }
813
- //#endregion
814
797
  export { ShutdownSignal as a, streamPath as c, requestUrl as i, securityHeaders as l, checkReadOptions as n, layerShutdownSignal as o, read as r, discardRequestBody as s, app as t };
@@ -1,8 +1,6 @@
1
- import { _ as StreamsWriter, g as StreamsReader, h as Reader, v as Writer } from "../owner-records-QDlssl__.js";
2
- import { D as streams_d_exports, P as layer_d_exports, u as RoutesOptions, z as route_d_exports } from "../index-CFv8vZvy.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
- //#region src/protocol/routes.d.ts
5
4
  /** Raw protocol route for adapters and wire conformance tests. */
6
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>>;
7
- //#endregion
8
6
  export { layer_d_exports as Protocol, type Reader, route_d_exports as StreamRoute, streams_d_exports as Streams, StreamsReader, StreamsWriter, type Writer };
@@ -1,8 +1,8 @@
1
- import { A as StreamsReader, j as StreamsWriter, l as streams_exports, u as route_exports } from "../streamsy-OjRubIPC.js";
2
- import { n as layer_exports } from "../layer-KvknRFUT.js";
3
- import { t as app } from "../program-DJ8NpHIf.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
- //#region src/protocol/routes.ts
5
+ // src/protocol/routes.ts
6
6
  /** Raw protocol route for adapters and wire conformance tests. */
7
7
  const routes = (options = {}) => {
8
8
  const prefix = options.prefix?.replace(/\/$/, "") || "/";
@@ -12,5 +12,4 @@ const routes = (options = {}) => {
12
12
  pathPrefix: prefix
13
13
  }));
14
14
  };
15
- //#endregion
16
15
  export { layer_exports as Protocol, route_exports as StreamRoute, streams_exports as Streams, StreamsReader, StreamsWriter, routes };
@@ -1,8 +1,7 @@
1
- import { _ as StreamsWriter, g as StreamsReader, vt as TransportFault } from "../owner-records-QDlssl__.js";
2
- import { f as Any, m as Identifiers, p as Group } from "../index-CFv8vZvy.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
- //#region src/remote/request.d.ts
6
5
  interface Options {
7
6
  readonly baseUrl: string;
8
7
  readonly headers?: Readonly<Record<string, string>>;
@@ -19,5 +18,4 @@ declare namespace streams_d_exports {
19
18
  declare const layerProtocol: (options: Options) => Layer.Layer<StreamsReader | StreamsWriter, TransportFault, HttpClient.HttpClient>;
20
19
  /** Remote streams have no local change feed. */
21
20
  declare function layer<const Keys extends ReadonlyArray<Any>>(group: Group<Keys>, options: Options): Layer.Layer<Identifiers<Keys>, TransportFault, HttpClient.HttpClient>;
22
- //#endregion
23
21
  export { streams_d_exports as RemoteStreams };