@dxos/feed 0.8.4-main.ef1bc66f44 → 0.8.4-main.fcc0d83b33

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/README.md CHANGED
@@ -260,4 +260,3 @@ All timestamps (e.g., `insertionTimestamp`) are Unix timestamps in milliseconds.
260
260
  ### TODOs
261
261
 
262
262
  - [ ] Sync protocol only works if each namespace is synced separately.
263
-
@@ -1,18 +1,11 @@
1
1
  // src/errors.ts
2
2
  import { BaseError } from "@dxos/errors";
3
- var DuplicateBlockPositionError = class extends BaseError.extend("DuplicateBlockPositionError") {
4
- constructor(args) {
5
- super(`Non-unique block position detected (feedId=${args.feedId} position=${args.position}).`);
6
- }
7
- };
8
- var DuplicateBlockLamportTimestampError = class extends BaseError.extend("DuplicateBlockLamportTimestampError") {
9
- constructor(args) {
10
- super(`Non-unique block Lamport timestamp detected (feedId=${args.feedId} actorId=${args.actorId} sequence=${args.sequence}).`);
11
- }
12
- };
13
3
  var PositionConflictError = class extends BaseError.extend("PositionConflictError") {
14
4
  constructor(args) {
15
- super(`Block already has position ${args.currentPosition}, cannot set to ${args.requestedPosition} (feedId=${args.feedId} actorId=${args.actorId} sequence=${args.sequence}).`);
5
+ super({
6
+ message: `Block already has position ${args.currentPosition}, cannot set to ${args.requestedPosition} (feedId=${args.feedId} actorId=${args.actorId} sequence=${args.sequence}).`,
7
+ context: args
8
+ });
16
9
  }
17
10
  };
18
11
 
@@ -84,7 +77,9 @@ var FeedStore = class {
84
77
  const rows = yield* sql`
85
78
  SELECT feedPrivateId FROM feeds WHERE spaceId = ${spaceId} AND feedId = ${feedId}
86
79
  `;
87
- if (rows.length > 0) return rows[0].feedPrivateId;
80
+ if (rows.length > 0) {
81
+ return rows[0].feedPrivateId;
82
+ }
88
83
  const newRows = yield* sql`
89
84
  INSERT INTO feeds (spaceId, feedId, feedNamespace) VALUES (${spaceId}, ${feedId}, ${namespace}) RETURNING feedPrivateId
90
85
  `;
@@ -96,7 +91,9 @@ var FeedStore = class {
96
91
  #ensureCursorToken = Effect.fn("Feed.ensureCursorToken")((spaceId) => Effect.gen(this, function* () {
97
92
  const sql = yield* SqlClient.SqlClient;
98
93
  const rows = yield* sql`SELECT token FROM cursor_tokens WHERE spaceId = ${spaceId}`;
99
- if (rows.length > 0) return rows[0].token;
94
+ if (rows.length > 0) {
95
+ return rows[0].token;
96
+ }
100
97
  const token = crypto.randomUUID().replace(/-/g, "").slice(0, 6);
101
98
  yield* sql`INSERT INTO cursor_tokens (spaceId, token) VALUES (${spaceId}, ${token})`;
102
99
  return token;
@@ -247,80 +244,51 @@ var FeedStore = class {
247
244
  `;
248
245
  }).pipe(Effect.withSpan("FeedStore.setSyncState"));
249
246
  /**
250
- * Validates that appended blocks do not introduce position or Lamport conflicts.
247
+ * Returns the number of stored blocks for a single feed in a space/namespace.
248
+ * Intended as a low-level primitive for callers (for example Cloudflare Worker code)
249
+ * that need to make retention decisions under constrained storage resources.
251
250
  */
252
- #validateAppendBlocks = Effect.fn("FeedStore.validateAppendBlocks")((blocks, feedPrivateIds) => Effect.gen(this, function* () {
251
+ countBlocks = (opts) => Effect.gen(this, function* () {
253
252
  const sql = yield* SqlClient.SqlClient;
254
- const positionFeedIdByKey = /* @__PURE__ */ new Map();
255
- const lamportFeedIdByKey = /* @__PURE__ */ new Map();
256
- for (const block of blocks) {
257
- const feedPrivateId = feedPrivateIds.get(block.feedId);
258
- if (!this.#options.assignPositions && block.position != null) {
259
- const positionKey = `${feedPrivateId}|${block.position}`;
260
- if (positionFeedIdByKey.has(positionKey)) {
261
- yield* Effect.fail(new DuplicateBlockPositionError({
262
- feedId: block.feedId,
263
- position: block.position
264
- }));
265
- }
266
- positionFeedIdByKey.set(positionKey, block.feedId);
267
- }
268
- const lamportKey = `${feedPrivateId}|${block.actorId}|${block.sequence}`;
269
- if (lamportFeedIdByKey.has(lamportKey)) {
270
- yield* Effect.fail(new DuplicateBlockLamportTimestampError({
271
- feedId: block.feedId,
272
- actorId: block.actorId,
273
- sequence: block.sequence
274
- }));
275
- }
276
- lamportFeedIdByKey.set(lamportKey, block.feedId);
277
- }
278
- const lamportConditions = blocks.map((block) => {
279
- const feedPrivateId = feedPrivateIds.get(block.feedId);
280
- return sql`(feedPrivateId = ${feedPrivateId} AND actorId = ${block.actorId} AND sequence = ${block.sequence})`;
281
- });
282
- if (lamportConditions.length > 0) {
283
- const existingLamports = yield* sql`
284
- SELECT feedPrivateId, actorId, sequence
285
- FROM blocks
286
- WHERE ${sql.or(lamportConditions)}
287
- LIMIT 1
288
- `;
289
- const lamportConflict = existingLamports[0];
290
- if (lamportConflict) {
291
- const key = `${lamportConflict.feedPrivateId}|${lamportConflict.actorId}|${lamportConflict.sequence}`;
292
- yield* Effect.fail(new DuplicateBlockLamportTimestampError({
293
- feedId: lamportFeedIdByKey.get(key),
294
- actorId: lamportConflict.actorId,
295
- sequence: lamportConflict.sequence
296
- }));
297
- }
298
- }
299
- if (!this.#options.assignPositions) {
300
- const positionedBlocks = blocks.filter((block) => block.position != null);
301
- const positionConditions = positionedBlocks.map((block) => {
302
- const feedPrivateId = feedPrivateIds.get(block.feedId);
303
- return sql`(feedPrivateId = ${feedPrivateId} AND position = ${block.position})`;
304
- });
305
- if (positionConditions.length > 0) {
306
- const existingPositions = yield* sql`
307
- SELECT feedPrivateId, position
308
- FROM blocks
309
- WHERE position IS NOT NULL
310
- AND (${sql.or(positionConditions)})
311
- LIMIT 1
312
- `;
313
- const positionConflict = existingPositions[0];
314
- if (positionConflict) {
315
- const key = `${positionConflict.feedPrivateId}|${positionConflict.position}`;
316
- yield* Effect.fail(new DuplicateBlockPositionError({
317
- feedId: positionFeedIdByKey.get(key),
318
- position: positionConflict.position
319
- }));
320
- }
321
- }
253
+ const rows = yield* sql`
254
+ SELECT COUNT(*) AS count
255
+ FROM blocks
256
+ JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId
257
+ WHERE feeds.spaceId = ${opts.spaceId}
258
+ AND feeds.feedNamespace = ${opts.feedNamespace}
259
+ AND feeds.feedId = ${opts.feedId}
260
+ `;
261
+ return rows[0]?.count ?? 0;
262
+ }).pipe(Effect.withSpan("FeedStore.countBlocks"));
263
+ /**
264
+ * Deletes the oldest blocks for a single feed in a space/namespace.
265
+ * This API intentionally does not enforce any retention policy (such as max size);
266
+ * callers decide when and how much to prune, which is useful for constrained
267
+ * environments like Cloudflare Workers.
268
+ *
269
+ * @returns Number of deleted rows.
270
+ */
271
+ deleteOldestBlocks = (opts) => Effect.gen(this, function* () {
272
+ const sql = yield* SqlClient.SqlClient;
273
+ if (opts.count <= 0) {
274
+ return 0;
322
275
  }
323
- }));
276
+ const deletedRows = yield* sql`
277
+ DELETE FROM blocks
278
+ WHERE insertionId IN (
279
+ SELECT blocks.insertionId
280
+ FROM blocks
281
+ JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId
282
+ WHERE feeds.spaceId = ${opts.spaceId}
283
+ AND feeds.feedNamespace = ${opts.feedNamespace}
284
+ AND feeds.feedId = ${opts.feedId}
285
+ ORDER BY blocks.insertionId ASC
286
+ LIMIT ${opts.count}
287
+ )
288
+ RETURNING insertionId
289
+ `;
290
+ return deletedRows.length;
291
+ }).pipe(Effect.withSpan("FeedStore.deleteOldestBlocks"));
324
292
  /**
325
293
  * Appends blocks for a space/namespace and optionally assigns global positions.
326
294
  */
@@ -353,7 +321,6 @@ var FeedStore = class {
353
321
  }), {
354
322
  concurrency: "unbounded"
355
323
  });
356
- yield* this.#validateAppendBlocks(request.blocks, feedPrivateIds);
357
324
  const maxPositions = /* @__PURE__ */ new Map();
358
325
  if (this.#options.assignPositions) {
359
326
  const maxPosResult = yield* sql`
@@ -475,15 +442,22 @@ var FeedStore = class {
475
442
  }
476
443
  blocksBySpaceNamespace.get(spaceNamespaceKey).blocks.push(block);
477
444
  }
478
- for (const { spaceId, feedNamespace, blocks: blocks2 } of blocksBySpaceNamespace.values()) {
479
- yield* this.append({
445
+ const positionByBlock = /* @__PURE__ */ new Map();
446
+ for (const { spaceId, feedNamespace, blocks: batchBlocks } of blocksBySpaceNamespace.values()) {
447
+ const { positions } = yield* this.append({
480
448
  requestId: "local-append",
481
- blocks: blocks2,
449
+ blocks: batchBlocks,
482
450
  spaceId,
483
451
  feedNamespace
484
452
  });
453
+ for (let i = 0; i < batchBlocks.length; i++) {
454
+ positionByBlock.set(batchBlocks[i], positions[i] ?? null);
455
+ }
485
456
  }
486
- return blocks;
457
+ return blocks.map((block) => ({
458
+ ...block,
459
+ position: positionByBlock.get(block) ?? block.position
460
+ }));
487
461
  }).pipe(Effect.withSpan("FeedStore.appendLocal")));
488
462
  /**
489
463
  * Sets positions for existing blocks while preventing conflicting reassignments.
@@ -519,6 +493,37 @@ var FeedStore = class {
519
493
  `;
520
494
  }
521
495
  }).pipe(Effect.withSpan("FeedStore.setPosition"));
496
+ /**
497
+ * Gets all feeds and their blocks for a space, organized by feed ID and namespace.
498
+ * Used for space archive export.
499
+ */
500
+ getAllFeedsForSpace = (opts) => Effect.gen(this, function* () {
501
+ const sql = yield* SqlClient.SqlClient;
502
+ const feeds = yield* sql`
503
+ SELECT DISTINCT feedId, feedNamespace FROM feeds WHERE spaceId = ${opts.spaceId}
504
+ `;
505
+ const result = [];
506
+ for (const feed of feeds) {
507
+ const blocks = yield* sql`
508
+ SELECT blocks.*, feeds.feedId, feeds.feedNamespace
509
+ FROM blocks
510
+ JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId
511
+ WHERE feeds.spaceId = ${opts.spaceId}
512
+ AND feeds.feedId = ${feed.feedId}
513
+ AND feeds.feedNamespace = ${feed.feedNamespace}
514
+ ORDER BY blocks.sequence ASC
515
+ `;
516
+ result.push({
517
+ feedId: feed.feedId,
518
+ feedNamespace: feed.feedNamespace,
519
+ blocks: blocks.map((row) => ({
520
+ ...row,
521
+ data: new Uint8Array(row.data)
522
+ }))
523
+ });
524
+ }
525
+ return result;
526
+ }).pipe(Effect.withSpan("FeedStore.getAllFeedsForSpace"));
522
527
  };
523
528
  var encodeCursor = (token, insertionId) => FeedCursor.make(`${token}|${insertionId}`);
524
529
  var decodeCursor = (cursor) => {
@@ -543,7 +548,7 @@ var SyncServer = class {
543
548
  /**
544
549
  * Receive a message from a client. Handles QueryRequest and AppendRequest; sends response via sendMessage with correct peer ids.
545
550
  */
546
- handleMessage(message) {
551
+ handleMessage(ctx, message) {
547
552
  const self = this;
548
553
  const recipientPeerId = message.senderPeerId;
549
554
  const withPeerIds = (payload) => ({
@@ -556,11 +561,11 @@ var SyncServer = class {
556
561
  const req = message;
557
562
  return Effect2.gen(function* () {
558
563
  const response = yield* self.#feedStore.query(req);
559
- yield* self.#sendMessage(withPeerIds({
564
+ yield* self.#sendMessage(ctx, withPeerIds({
560
565
  _tag: "QueryResponse",
561
566
  ...response
562
567
  }));
563
- }).pipe(Effect2.catchAll((err) => self.#sendMessage(withPeerIds({
568
+ }).pipe(Effect2.catchAll((err) => self.#sendMessage(ctx, withPeerIds({
564
569
  _tag: "Error",
565
570
  message: err instanceof Error ? err.message : String(err)
566
571
  }))));
@@ -569,11 +574,11 @@ var SyncServer = class {
569
574
  const req = message;
570
575
  return Effect2.gen(function* () {
571
576
  const response = yield* self.#feedStore.append(req);
572
- yield* self.#sendMessage(withPeerIds({
577
+ yield* self.#sendMessage(ctx, withPeerIds({
573
578
  _tag: "AppendResponse",
574
579
  ...response
575
580
  }));
576
- }).pipe(Effect2.catchAll((err) => self.#sendMessage(withPeerIds({
581
+ }).pipe(Effect2.catchAll((err) => self.#sendMessage(ctx, withPeerIds({
577
582
  _tag: "Error",
578
583
  message: err instanceof Error ? err.message : String(err)
579
584
  }))));
@@ -619,16 +624,20 @@ var SyncClient = class {
619
624
  */
620
625
  handleMessage(message) {
621
626
  const requestId = "requestId" in message && message.requestId != null ? String(message.requestId) : void 0;
622
- if (requestId == null) return Effect3.void;
627
+ if (requestId == null) {
628
+ return Effect3.void;
629
+ }
623
630
  const deferred = this.#handlers.get(requestId);
624
- if (deferred == null) return Effect3.void;
631
+ if (deferred == null) {
632
+ return Effect3.void;
633
+ }
625
634
  this.#handlers.delete(requestId);
626
635
  if (message._tag === "Error") {
627
636
  return Effect3.andThen(Deferred.fail(deferred, new Error(message.message)), () => Effect3.void);
628
637
  }
629
638
  return Effect3.andThen(Deferred.succeed(deferred, message), () => Effect3.void);
630
639
  }
631
- pull(opts) {
640
+ pull(ctx, opts) {
632
641
  const self = this;
633
642
  return Effect3.gen(function* () {
634
643
  const lastPulledPosition = yield* self.#feedStore.getSyncState({
@@ -646,7 +655,7 @@ var SyncClient = class {
646
655
  position: lastPulledPosition,
647
656
  limit: opts.limit
648
657
  };
649
- yield* self.#sendMessage(self.#withPeerIds(request));
658
+ yield* self.#sendMessage(ctx, self.#withPeerIds(request));
650
659
  const message = yield* Deferred.await(deferred);
651
660
  const response = yield* self.#expectResponse(requestId, message, "QueryResponse");
652
661
  if (response.blocks.length === 0) {
@@ -670,7 +679,7 @@ var SyncClient = class {
670
679
  };
671
680
  });
672
681
  }
673
- push(opts) {
682
+ push(ctx, opts) {
674
683
  const self = this;
675
684
  return Effect3.gen(function* () {
676
685
  const unpositioned = yield* self.#feedStore.query({
@@ -694,7 +703,7 @@ var SyncClient = class {
694
703
  feedNamespace: opts.feedNamespace,
695
704
  blocks: unpositioned.blocks
696
705
  };
697
- yield* self.#sendMessage(self.#withPeerIds(request));
706
+ yield* self.#sendMessage(ctx, self.#withPeerIds(request));
698
707
  const message = yield* Deferred.await(deferred);
699
708
  const response = yield* self.#expectResponse(requestId, message, "AppendResponse");
700
709
  yield* self.#feedStore.setPosition({
@@ -725,11 +734,9 @@ var SyncClient = class {
725
734
  };
726
735
 
727
736
  export {
728
- DuplicateBlockPositionError,
729
- DuplicateBlockLamportTimestampError,
730
737
  PositionConflictError,
731
738
  FeedStore,
732
739
  SyncServer,
733
740
  SyncClient
734
741
  };
735
- //# sourceMappingURL=chunk-Q5PE2Q5P.mjs.map
742
+ //# sourceMappingURL=chunk-PENEKCN2.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../src/errors.ts", "../../../src/feed-store.ts", "../../../src/sync-server.ts", "../../../src/sync-client.ts"],
4
+ "sourcesContent": ["//\n// Copyright 2026 DXOS.org\n//\n\nimport { BaseError } from '@dxos/errors';\n\nexport class PositionConflictError extends BaseError.extend('PositionConflictError') {\n constructor(args: {\n feedId?: string;\n actorId: string;\n sequence: number;\n currentPosition: number;\n requestedPosition: number | null;\n }) {\n super({\n message: `Block already has position ${args.currentPosition}, cannot set to ${args.requestedPosition} (feedId=${args.feedId} actorId=${args.actorId} sequence=${args.sequence}).`,\n context: args,\n });\n }\n}\n", "//\n// Copyright 2026 DXOS.org\n//\n\nimport * as SqlClient from '@effect/sql/SqlClient';\nimport type * as SqlError from '@effect/sql/SqlError';\nimport * as Effect from 'effect/Effect';\n\nimport { Event } from '@dxos/async';\nimport { assertArgument } from '@dxos/invariant';\nimport { type SpaceId } from '@dxos/keys';\nimport { FeedProtocol } from '@dxos/protocols';\nimport { SqlTransaction } from '@dxos/sql-sqlite';\n\nimport { PositionConflictError } from './errors';\n\ntype AppendRequest = FeedProtocol.AppendRequest;\ntype AppendResponse = FeedProtocol.AppendResponse;\ntype Block = FeedProtocol.Block;\nconst FeedCursor = FeedProtocol.FeedCursor;\ntype FeedCursor = FeedProtocol.FeedCursor;\nconst isWellKnownNamespace = FeedProtocol.isWellKnownNamespace;\ntype QueryRequest = FeedProtocol.QueryRequest;\ntype QueryResponse = FeedProtocol.QueryResponse;\ntype SubscribeRequest = FeedProtocol.SubscribeRequest;\ntype SubscribeResponse = FeedProtocol.SubscribeResponse;\n\nexport interface FeedStoreOptions {\n /**\n * The actor ID of the local user.\n */\n localActorId: string;\n\n /**\n * Whether to assign positions to appended blocks.\n * Only a single peer (usually the server) can assign positions.\n */\n assignPositions: boolean;\n}\n\n/**\n * Persistent storage for feed metadata, blocks, subscriptions, and sync state.\n *\n */\nexport class FeedStore {\n readonly #options: FeedStoreOptions;\n\n constructor(options: FeedStoreOptions) {\n this.#options = options;\n }\n\n /**\n * Emits after successful block append operations.\n */\n readonly onNewBlocks = new Event<void>();\n\n /**\n * Creates required feed store tables and indexes if they do not exist.\n */\n migrate = Effect.fn('FeedStore.migrate')(() =>\n Effect.gen(function* () {\n const sql = yield* SqlClient.SqlClient;\n\n // Feeds Table\n yield* sql`CREATE TABLE IF NOT EXISTS feeds (\n feedPrivateId INTEGER PRIMARY KEY AUTOINCREMENT,\n spaceId TEXT NOT NULL,\n feedId TEXT NOT NULL,\n feedNamespace TEXT\n )`;\n yield* sql`CREATE UNIQUE INDEX IF NOT EXISTS idx_feeds_spaceId_feedId ON feeds(spaceId, feedId)`;\n\n // Blocks Table\n yield* sql`CREATE TABLE IF NOT EXISTS blocks (\n insertionId INTEGER PRIMARY KEY AUTOINCREMENT,\n feedPrivateId INTEGER NOT NULL,\n position INTEGER,\n sequence INTEGER NOT NULL,\n actorId TEXT NOT NULL,\n prevSequence INTEGER,\n prevActorId TEXT,\n timestamp INTEGER NOT NULL,\n data BLOB NOT NULL,\n FOREIGN KEY(feedPrivateId) REFERENCES feeds(feedPrivateId)\n )`;\n yield* sql`CREATE UNIQUE INDEX IF NOT EXISTS idx_blocks_feedPrivateId_position ON blocks(feedPrivateId, position)`;\n yield* sql`CREATE UNIQUE INDEX IF NOT EXISTS idx_blocks_feedPrivateId_sequence_actorId ON blocks(feedPrivateId, sequence, actorId)`;\n\n // Subscriptions Table\n yield* sql`CREATE TABLE IF NOT EXISTS subscriptions (\n subscriptionId TEXT PRIMARY KEY,\n expiresAt INTEGER NOT NULL,\n feedPrivateIds TEXT NOT NULL -- JSON array\n )`;\n\n // Cursor Tokens Table\n yield* sql`CREATE TABLE IF NOT EXISTS cursor_tokens (\n spaceId TEXT PRIMARY KEY,\n token TEXT NOT NULL\n )`;\n\n // Sync State Table.\n yield* sql`CREATE TABLE IF NOT EXISTS sync_state (\n spaceId TEXT NOT NULL,\n feedNamespace TEXT NOT NULL,\n lastPulledPosition INTEGER NOT NULL DEFAULT -1,\n PRIMARY KEY (spaceId, feedNamespace)\n )`;\n }).pipe(Effect.withSpan('FeedStore.migrate')),\n );\n\n /**\n * Ensures a feed row exists and returns its internal feed ID.\n */\n #ensureFeed = Effect.fn('Feed.ensureFeed')(\n (\n spaceId: string,\n feedId: string,\n namespace?: string,\n ): Effect.Effect<number, SqlError.SqlError, SqlClient.SqlClient> =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n\n const rows = yield* sql<{ feedPrivateId: number }>`\n SELECT feedPrivateId FROM feeds WHERE spaceId = ${spaceId} AND feedId = ${feedId}\n `;\n if (rows.length > 0) {\n return rows[0].feedPrivateId;\n }\n\n const newRows = yield* sql<{ feedPrivateId: number }>`\n INSERT INTO feeds (spaceId, feedId, feedNamespace) VALUES (${spaceId}, ${feedId}, ${namespace}) RETURNING feedPrivateId\n `;\n return newRows[0].feedPrivateId;\n }).pipe(Effect.withSpan('FeedStore.ensureFeed')),\n );\n\n /**\n * Ensures cursor token exists for a space and returns it.\n */\n #ensureCursorToken = Effect.fn('Feed.ensureCursorToken')(\n (spaceId: string): Effect.Effect<string, SqlError.SqlError, SqlClient.SqlClient> =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n const rows = yield* sql<{ token: string }>`SELECT token FROM cursor_tokens WHERE spaceId = ${spaceId}`;\n if (rows.length > 0) {\n return rows[0].token;\n }\n\n const token = crypto.randomUUID().replace(/-/g, '').slice(0, 6);\n yield* sql`INSERT INTO cursor_tokens (spaceId, token) VALUES (${spaceId}, ${token})`;\n return token;\n }).pipe(Effect.withSpan('FeedStore.ensureCursorToken')),\n );\n\n /**\n * Queries feed blocks by feed IDs or subscription with cursor/position pagination.\n */\n query = Effect.fn('Feed.query')(\n (request: QueryRequest): Effect.Effect<QueryResponse, SqlError.SqlError, SqlClient.SqlClient> =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n let feedIds: string[] | undefined = [];\n let cursorInsertionId = -1;\n let cursorToken: string | undefined;\n\n if (!request.spaceId) {\n return yield* Effect.die(new Error('spaceId is required'));\n }\n\n if (\n (request.position !== undefined ? 1 : 0) +\n (request.cursor !== undefined ? 1 : 0) +\n (request.unpositionedOnly === true ? 1 : 0) >\n 1\n ) {\n return yield* Effect.die(new Error('Only one of position, cursor, or unpositionedOnly can be used'));\n }\n\n if (request.cursor) {\n const { token, insertionId } = decodeCursor(request.cursor as FeedCursor);\n if (!token || insertionId === undefined || isNaN(insertionId)) {\n return yield* Effect.die(new Error(`Invalid cursor format`));\n }\n cursorToken = token;\n cursorInsertionId = insertionId;\n }\n\n // Validate Token if cursor used.\n const validCursorToken = yield* this.#ensureCursorToken(request.spaceId);\n if (request.cursor && cursorToken !== validCursorToken) {\n return yield* Effect.die(new Error(`Cursor token mismatch`));\n }\n\n // If cursor is provided, we must validate it against the space token.\n // If spaceId is not provided in request (e.g. feedIds query), we can't easily validate token unless we look up spaceId for feedIds.\n // Ideally spaceId should be required for token validation.\n\n /*\n Logic:\n 1. If `cursor` is present, it's `token|insertionId`.\n 2. If `position` is present, it's `position` (legacy/manual).\n \n We prioritize `cursor`.\n */\n\n const position = request.position ?? -1;\n\n // Resolve subscriptions or feed IDs.\n if (request.query && 'subscriptionId' in request.query) {\n const rows = yield* sql<{ feedPrivateIds: string; expiresAt: number }>`\n SELECT feedPrivateIds, expiresAt FROM subscriptions WHERE subscriptionId = ${request.query.subscriptionId}\n `;\n if (rows.length > 0) {\n const { feedPrivateIds, expiresAt } = rows[0];\n if (Date.now() <= expiresAt) {\n const privateIds = JSON.parse(feedPrivateIds) as number[];\n if (privateIds.length > 0) {\n const feedRows = yield* sql<{ feedId: string }>`\n SELECT feedId FROM feeds WHERE feedPrivateId IN ${sql.in(privateIds)}\n `;\n feedIds = feedRows.map((r) => r.feedId);\n }\n }\n }\n } else if (request.query && 'feedIds' in request.query) {\n feedIds = [...request.query.feedIds];\n } else {\n feedIds = undefined;\n }\n\n if (feedIds !== undefined && feedIds.length === 0) {\n return {\n requestId: request.requestId,\n blocks: [],\n nextCursor: encodeCursor(validCursorToken, -1),\n hasMore: false,\n };\n }\n\n // Fetch blocks.\n const query = sql<Block>`\n SELECT blocks.*, feeds.feedId, feeds.feedNamespace\n FROM blocks\n JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId\n WHERE 1=1\n ${feedIds !== undefined ? sql`AND feeds.feedId IN ${sql.in(feedIds)}` : sql``}\n ${request.spaceId ? sql`AND feeds.spaceId = ${request.spaceId}` : sql``}\n ${sql`AND feeds.feedNamespace = ${request.feedNamespace}`}\n `;\n\n // Add filter based on cursor or position.\n const filter = request.cursor\n ? sql`AND blocks.insertionId > ${cursorInsertionId}`\n : request.unpositionedOnly\n ? sql`AND blocks.position IS NULL`\n : sql`AND (blocks.position > ${position} OR blocks.position IS NULL)`;\n\n const orderBy = request.cursor\n ? sql`ORDER BY blocks.insertionId ASC`\n : sql`ORDER BY blocks.position ASC NULLS LAST`;\n\n const requestLimit = request.limit;\n const queryLimit = requestLimit != null ? requestLimit + 1 : undefined;\n const rows = yield* sql<Block>`\n ${query}\n ${filter}\n ${orderBy}\n ${queryLimit != null ? sql`LIMIT ${queryLimit}` : sql``}\n `;\n\n const hasMore = requestLimit != null && rows.length > requestLimit;\n const slice = hasMore ? rows.slice(0, requestLimit) : rows;\n const blocks = slice.map((row) => ({\n ...row,\n // Have to clone buffer otherwise we get empty Uint8Array.\n data: new Uint8Array(row.data),\n }));\n\n let nextCursor: FeedCursor = request.cursor ?? encodeCursor(validCursorToken, -1);\n if (blocks.length > 0 && request.spaceId) {\n const lastBlock = blocks[blocks.length - 1];\n if (lastBlock.insertionId !== undefined) {\n nextCursor = encodeCursor(validCursorToken, lastBlock.insertionId);\n }\n }\n\n return { requestId: request.requestId, blocks, nextCursor, hasMore } satisfies QueryResponse;\n }).pipe(Effect.withSpan('FeedStore.query')),\n );\n\n /**\n * Creates a subscription and stores the resolved internal feed IDs.\n */\n subscribe = Effect.fn('Feed.subscribe')(\n (request: SubscribeRequest): Effect.Effect<SubscribeResponse, SqlError.SqlError, SqlClient.SqlClient> =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n const ttl = 60 * 60 * 1000;\n const subscriptionId = crypto.randomUUID();\n const expiresAt = Date.now() + ttl;\n\n if (!request.spaceId) {\n // TODO(dmaretskyi): Define error type.\n return yield* Effect.die(new Error('spaceId required for subscribe'));\n }\n\n const feedPrivateIds = yield* Effect.forEach(\n request.feedIds,\n (feedId) => this.#ensureFeed(request.spaceId!, feedId),\n { concurrency: 'unbounded' },\n );\n\n yield* sql`\n INSERT INTO subscriptions (subscriptionId, expiresAt, feedPrivateIds)\n VALUES (${subscriptionId}, ${expiresAt}, ${JSON.stringify(feedPrivateIds)})\n `;\n\n return {\n requestId: request.requestId,\n subscriptionId,\n expiresAt,\n };\n }).pipe(Effect.withSpan('FeedStore.subscribe')),\n );\n\n /**\n * Get the last pulled position for the given space and namespace.\n * Returns -1 if no sync state exists yet.\n */\n getSyncState = (opts: {\n spaceId: SpaceId;\n feedNamespace: string;\n }): Effect.Effect<number, SqlError.SqlError, SqlClient.SqlClient> =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n const rows = yield* sql<{ lastPulledPosition: number }>`\n SELECT lastPulledPosition FROM sync_state\n WHERE spaceId = ${opts.spaceId} AND feedNamespace = ${opts.feedNamespace}\n `;\n return rows[0]?.lastPulledPosition ?? -1;\n }).pipe(Effect.withSpan('FeedStore.getSyncState'));\n\n /**\n * Update the last pulled position for the given space and namespace.\n */\n setSyncState = (opts: {\n spaceId: SpaceId;\n feedNamespace: string;\n lastPulledPosition: number;\n }): Effect.Effect<void, SqlError.SqlError, SqlClient.SqlClient> =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n yield* sql`\n INSERT INTO sync_state (spaceId, feedNamespace, lastPulledPosition)\n VALUES (${opts.spaceId}, ${opts.feedNamespace}, ${opts.lastPulledPosition})\n ON CONFLICT (spaceId, feedNamespace) DO UPDATE SET lastPulledPosition = ${opts.lastPulledPosition}\n `;\n }).pipe(Effect.withSpan('FeedStore.setSyncState'));\n\n /**\n * Returns the number of stored blocks for a single feed in a space/namespace.\n * Intended as a low-level primitive for callers (for example Cloudflare Worker code)\n * that need to make retention decisions under constrained storage resources.\n */\n countBlocks = (opts: {\n spaceId: SpaceId;\n feedNamespace: string;\n feedId: string;\n }): Effect.Effect<number, SqlError.SqlError, SqlClient.SqlClient> =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n const rows = yield* sql<{ count: number }>`\n SELECT COUNT(*) AS count\n FROM blocks\n JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId\n WHERE feeds.spaceId = ${opts.spaceId}\n AND feeds.feedNamespace = ${opts.feedNamespace}\n AND feeds.feedId = ${opts.feedId}\n `;\n return rows[0]?.count ?? 0;\n }).pipe(Effect.withSpan('FeedStore.countBlocks'));\n\n /**\n * Deletes the oldest blocks for a single feed in a space/namespace.\n * This API intentionally does not enforce any retention policy (such as max size);\n * callers decide when and how much to prune, which is useful for constrained\n * environments like Cloudflare Workers.\n *\n * @returns Number of deleted rows.\n */\n deleteOldestBlocks = (opts: {\n spaceId: SpaceId;\n feedNamespace: string;\n feedId: string;\n count: number;\n }): Effect.Effect<number, SqlError.SqlError, SqlClient.SqlClient> =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n if (opts.count <= 0) {\n return 0;\n }\n\n const deletedRows = yield* sql<{ insertionId: number }>`\n DELETE FROM blocks\n WHERE insertionId IN (\n SELECT blocks.insertionId\n FROM blocks\n JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId\n WHERE feeds.spaceId = ${opts.spaceId}\n AND feeds.feedNamespace = ${opts.feedNamespace}\n AND feeds.feedId = ${opts.feedId}\n ORDER BY blocks.insertionId ASC\n LIMIT ${opts.count}\n )\n RETURNING insertionId\n `;\n\n return deletedRows.length;\n }).pipe(Effect.withSpan('FeedStore.deleteOldestBlocks'));\n\n /**\n * Appends blocks for a space/namespace and optionally assigns global positions.\n */\n append = (\n request: AppendRequest,\n ): Effect.Effect<AppendResponse, SqlError.SqlError, SqlClient.SqlClient | SqlTransaction.SqlTransaction> =>\n Effect.gen(this, function* () {\n if (!request.spaceId) {\n return yield* Effect.die(new Error('spaceId required for append'));\n }\n\n assertArgument(\n isWellKnownNamespace(request.feedNamespace),\n 'request.feedNamespace',\n 'specified well-known namespace',\n );\n\n // Validate all blocks upfront.\n for (const block of request.blocks) {\n assertArgument(block.feedId, 'block.feedId', 'feedId is required');\n }\n\n // Wrap in transaction to ensure atomicity when assigning positions.\n const sqlTransaction = yield* SqlTransaction.SqlTransaction;\n const positions = yield* sqlTransaction.withTransaction(\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n\n // 1. Collect unique feed IDs and batch #ensureFeed calls.\n const feedKeys = new Map<string, { feedId: string }>();\n for (const block of request.blocks) {\n const key = block.feedId!;\n if (!feedKeys.has(key)) {\n feedKeys.set(key, { feedId: block.feedId! });\n }\n }\n\n const feedPrivateIds = new Map<string, number>();\n yield* Effect.forEach(\n [...feedKeys.entries()],\n ([key, { feedId }]) =>\n Effect.gen(this, function* () {\n const id = yield* this.#ensureFeed(request.spaceId!, feedId, request.feedNamespace);\n feedPrivateIds.set(key, id);\n }),\n { concurrency: 'unbounded' },\n );\n\n // 2. Get max position per namespace ONCE (not per block).\n const maxPositions = new Map<string, number>();\n if (this.#options.assignPositions) {\n const maxPosResult = yield* sql<{ maxPos: number | null }>`\n SELECT MAX(position) as maxPos \n FROM blocks \n JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId\n WHERE feeds.spaceId = ${request.spaceId} AND feeds.feedNamespace = ${request.feedNamespace}\n `;\n maxPositions.set(request.feedNamespace, maxPosResult[0]?.maxPos ?? -1);\n }\n\n // 3. Insert all blocks and compute positions.\n const positions: number[] = [];\n for (const block of request.blocks) {\n const key = block.feedId!;\n const feedPrivateId = feedPrivateIds.get(key)!;\n\n let positionToInsert: number | null = null;\n if (this.#options.assignPositions) {\n const currentMax = maxPositions.get(request.feedNamespace)!;\n positionToInsert = currentMax + 1;\n maxPositions.set(request.feedNamespace, positionToInsert); // Increment for next block in same namespace.\n positions.push(positionToInsert);\n } else if (block.position != null) {\n positionToInsert = block.position;\n }\n\n yield* sql`\n INSERT INTO blocks (\n feedPrivateId, position, sequence, actorId, \n prevSequence, prevActorId, timestamp, data\n ) VALUES (\n ${feedPrivateId}, ${positionToInsert}, ${block.sequence}, ${block.actorId},\n ${block.prevSequence}, ${block.prevActorId}, ${block.timestamp}, ${block.data}\n ) ON CONFLICT DO NOTHING\n `;\n }\n\n return positions;\n }),\n );\n\n this.onNewBlocks.emit();\n\n return { requestId: request.requestId, positions };\n }).pipe(Effect.withSpan('FeedStore.append'));\n\n /**\n * Creates local blocks with sequential predecessors and appends grouped batches.\n */\n appendLocal = Effect.fn('Feed.appendLocal')(\n (\n messages: { spaceId: string; feedId: string; feedNamespace: string; data: Uint8Array }[],\n ): Effect.Effect<Block[], SqlError.SqlError, SqlClient.SqlClient | SqlTransaction.SqlTransaction> =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n\n // 1. Collect unique feeds and ensure they exist.\n type FeedKey = string; // `${spaceId}|${feedNamespace}|${feedId}`\n const feedKeys = new Map<FeedKey, { spaceId: string; feedId: string; feedNamespace: string }>();\n for (const msg of messages) {\n const key = `${msg.spaceId}|${msg.feedNamespace}|${msg.feedId}`;\n if (!feedKeys.has(key)) {\n feedKeys.set(key, { spaceId: msg.spaceId, feedId: msg.feedId, feedNamespace: msg.feedNamespace });\n }\n }\n\n // Batch ensure feeds and get their private IDs.\n const feedPrivateIds = new Map<FeedKey, number>();\n yield* Effect.forEach(\n [...feedKeys.entries()],\n ([key, { spaceId, feedId, feedNamespace }]) =>\n Effect.gen(this, function* () {\n const id = yield* this.#ensureFeed(spaceId, feedId, feedNamespace);\n feedPrivateIds.set(key, id);\n }),\n { concurrency: 'unbounded' },\n );\n\n // 2. Get last sequence for each unique feed (batch query).\n const lastSeqs = new Map<FeedKey, { sequence: number; actorId: string } | null>();\n for (const [key] of feedKeys) {\n const feedPrivateId = feedPrivateIds.get(key)!;\n const lastBlockResult = yield* sql<{ sequence: number; actorId: string }>`\n SELECT sequence, actorId FROM blocks \n WHERE feedPrivateId = ${feedPrivateId} \n ORDER BY sequence DESC \n LIMIT 1\n `;\n lastSeqs.set(key, lastBlockResult[0] ?? null);\n }\n\n // 3. Build all blocks with correct sequences.\n // Track in-flight sequences per feed to handle multiple messages to same feed.\n const currentSeqs = new Map<FeedKey, { sequence: number; actorId: string }>();\n const blocks: Block[] = [];\n const blocksBySpaceNamespace = new Map<string, { spaceId: string; feedNamespace: string; blocks: Block[] }>();\n\n for (const msg of messages) {\n const key = `${msg.spaceId}|${msg.feedNamespace}|${msg.feedId}`;\n\n // Determine predecessor: either from in-flight blocks or from DB.\n let sequence: number;\n let prevSequence: number | null;\n let prevActorId: string | null;\n\n const inFlight = currentSeqs.get(key);\n if (inFlight) {\n // We've already added blocks for this feed - continue from last in-flight.\n sequence = inFlight.sequence + 1;\n prevSequence = inFlight.sequence;\n prevActorId = inFlight.actorId;\n } else {\n // First block for this feed - use DB state.\n const lastBlock = lastSeqs.get(key);\n sequence = (lastBlock?.sequence ?? -1) + 1;\n prevSequence = lastBlock?.sequence ?? null;\n prevActorId = lastBlock?.actorId ?? null;\n }\n\n const block: Block = {\n feedId: msg.feedId,\n actorId: this.#options.localActorId,\n sequence,\n prevActorId,\n prevSequence,\n timestamp: Date.now(),\n data: msg.data,\n position: null, // Assigned by append.\n };\n\n blocks.push(block);\n\n // Update in-flight tracking.\n currentSeqs.set(key, { sequence, actorId: this.#options.localActorId });\n\n // Group by (spaceId, feedNamespace).\n const spaceNamespaceKey = `${msg.spaceId}|${msg.feedNamespace}`;\n if (!blocksBySpaceNamespace.has(spaceNamespaceKey)) {\n blocksBySpaceNamespace.set(spaceNamespaceKey, {\n spaceId: msg.spaceId,\n feedNamespace: msg.feedNamespace,\n blocks: [],\n });\n }\n blocksBySpaceNamespace.get(spaceNamespaceKey)!.blocks.push(block);\n }\n\n // 4. Call append once per (spaceId, namespace) batch and assign returned positions.\n const positionByBlock = new Map<Block, number | null>();\n for (const { spaceId, feedNamespace, blocks: batchBlocks } of blocksBySpaceNamespace.values()) {\n const { positions } = yield* this.append({\n requestId: 'local-append',\n blocks: batchBlocks,\n spaceId,\n feedNamespace,\n });\n for (let i = 0; i < batchBlocks.length; i++) {\n positionByBlock.set(batchBlocks[i], positions[i] ?? null);\n }\n }\n\n return blocks.map((block) => ({\n ...block,\n position: positionByBlock.get(block) ?? block.position,\n }));\n }).pipe(Effect.withSpan('FeedStore.appendLocal')),\n );\n\n /**\n * Sets positions for existing blocks while preventing conflicting reassignments.\n */\n setPosition = (request: {\n spaceId: string;\n blocks: (Pick<Block, 'feedId' | 'actorId' | 'sequence' | 'position'> & { feedNamespace: string })[];\n }): Effect.Effect<void, SqlError.SqlError | PositionConflictError, SqlClient.SqlClient> =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n for (const block of request.blocks) {\n const existing = yield* sql<{ position: number | null }>`\n SELECT position FROM blocks\n WHERE feedPrivateId = (\n SELECT feedPrivateId FROM feeds\n WHERE spaceId = ${request.spaceId} AND feedId = ${block.feedId} AND feedNamespace = ${block.feedNamespace}\n )\n AND actorId = ${block.actorId} AND sequence = ${block.sequence}\n `;\n const current = existing[0];\n if (current?.position != null && current.position !== block.position) {\n yield* Effect.fail(\n new PositionConflictError({\n feedId: block.feedId,\n actorId: block.actorId,\n sequence: block.sequence,\n currentPosition: current.position,\n requestedPosition: block.position,\n }),\n );\n }\n yield* sql`\n UPDATE blocks SET position = ${block.position}\n WHERE feedPrivateId = (\n SELECT feedPrivateId FROM feeds\n WHERE spaceId = ${request.spaceId} AND feedId = ${block.feedId} AND feedNamespace = ${block.feedNamespace}\n )\n AND actorId = ${block.actorId} AND sequence = ${block.sequence}\n `;\n }\n }).pipe(Effect.withSpan('FeedStore.setPosition'));\n\n /**\n * Gets all feeds and their blocks for a space, organized by feed ID and namespace.\n * Used for space archive export.\n */\n getAllFeedsForSpace = (opts: {\n spaceId: SpaceId;\n }): Effect.Effect<\n Array<{\n feedId: string;\n feedNamespace: string;\n blocks: Block[];\n }>,\n SqlError.SqlError,\n SqlClient.SqlClient\n > =>\n Effect.gen(this, function* () {\n const sql = yield* SqlClient.SqlClient;\n\n const feeds = yield* sql<{ feedId: string; feedNamespace: string }>`\n SELECT DISTINCT feedId, feedNamespace FROM feeds WHERE spaceId = ${opts.spaceId}\n `;\n\n const result: Array<{ feedId: string; feedNamespace: string; blocks: Block[] }> = [];\n\n for (const feed of feeds) {\n const blocks = yield* sql<Block>`\n SELECT blocks.*, feeds.feedId, feeds.feedNamespace\n FROM blocks\n JOIN feeds ON blocks.feedPrivateId = feeds.feedPrivateId\n WHERE feeds.spaceId = ${opts.spaceId}\n AND feeds.feedId = ${feed.feedId}\n AND feeds.feedNamespace = ${feed.feedNamespace}\n ORDER BY blocks.sequence ASC\n `;\n\n result.push({\n feedId: feed.feedId,\n feedNamespace: feed.feedNamespace,\n blocks: blocks.map((row) => ({\n ...row,\n data: new Uint8Array(row.data),\n })),\n });\n }\n\n return result;\n }).pipe(Effect.withSpan('FeedStore.getAllFeedsForSpace'));\n}\n\nconst encodeCursor = (token: string, insertionId: number) => FeedCursor.make(`${token}|${insertionId}`);\nconst decodeCursor = (cursor: FeedCursor) => {\n const [token, insertionId] = cursor.split('|');\n return { token, insertionId: Number(insertionId) };\n};\n", "//\n// Copyright 2026 DXOS.org\n//\n\nimport type * as SqlClient from '@effect/sql/SqlClient';\nimport * as Effect from 'effect/Effect';\n\nimport { Context } from '@dxos/context';\nimport { type FeedProtocol } from '@dxos/protocols';\nimport type { SqlTransaction } from '@dxos/sql-sqlite';\n\nimport type { FeedStore } from './feed-store';\n\ntype AppendRequest = FeedProtocol.AppendRequest;\ntype ProtocolMessage = FeedProtocol.ProtocolMessage;\ntype QueryRequest = FeedProtocol.QueryRequest;\ntype QueryResponse = FeedProtocol.QueryResponse;\n\nexport type SyncServerOptions = {\n /** This server's peer id. Set as senderPeerId on all replies. */\n peerId: string;\n feedStore: FeedStore;\n /** Send a protocol message to a client. Receives full message (recipient is set by server). Returns Effect. */\n sendMessage: (ctx: Context, message: ProtocolMessage) => Effect.Effect<void, unknown, never>;\n};\n\n/**\n * Server-side sync: receives protocol messages, runs query/append against the store, sends responses.\n * Reusable for many peers: sets senderPeerId = peerId and recipientPeerId = incoming message's senderPeerId on replies.\n */\nexport class SyncServer {\n readonly #peerId: string;\n readonly #feedStore: FeedStore;\n readonly #sendMessage: SyncServerOptions['sendMessage'];\n\n constructor(options: SyncServerOptions) {\n this.#peerId = options.peerId;\n this.#feedStore = options.feedStore;\n this.#sendMessage = options.sendMessage;\n }\n\n /**\n * Receive a message from a client. Handles QueryRequest and AppendRequest; sends response via sendMessage with correct peer ids.\n */\n handleMessage(\n ctx: Context,\n message: ProtocolMessage,\n ): Effect.Effect<void, unknown, SqlClient.SqlClient | SqlTransaction.SqlTransaction> {\n const self = this;\n const recipientPeerId = message.senderPeerId;\n const withPeerIds = (payload: Omit<ProtocolMessage, 'senderPeerId' | 'recipientPeerId'>): ProtocolMessage =>\n ({\n ...payload,\n senderPeerId: self.#peerId,\n recipientPeerId,\n }) as ProtocolMessage;\n switch (message._tag) {\n case 'QueryRequest': {\n const req = message as QueryRequest;\n return Effect.gen(function* () {\n const response: QueryResponse = yield* self.#feedStore.query(req);\n yield* self.#sendMessage(ctx, withPeerIds({ _tag: 'QueryResponse', ...response }));\n }).pipe(\n Effect.catchAll((err: unknown) =>\n self.#sendMessage(\n ctx,\n withPeerIds({\n _tag: 'Error',\n message: err instanceof Error ? err.message : String(err),\n } as Omit<ProtocolMessage, 'senderPeerId' | 'recipientPeerId'>),\n ),\n ),\n );\n }\n case 'AppendRequest': {\n const req = message as AppendRequest;\n return Effect.gen(function* () {\n const response = yield* self.#feedStore.append(req);\n yield* self.#sendMessage(ctx, withPeerIds({ _tag: 'AppendResponse', ...response }));\n }).pipe(\n Effect.catchAll((err: unknown) =>\n self.#sendMessage(\n ctx,\n withPeerIds({\n _tag: 'Error',\n message: err instanceof Error ? err.message : String(err),\n } as Omit<ProtocolMessage, 'senderPeerId' | 'recipientPeerId'>),\n ),\n ),\n );\n }\n default:\n return Effect.void;\n }\n }\n}\n", "//\n// Copyright 2026 DXOS.org\n//\n\nimport type * as SqlClient from '@effect/sql/SqlClient';\nimport * as Array from 'effect/Array';\nimport * as Deferred from 'effect/Deferred';\nimport * as Effect from 'effect/Effect';\n\nimport { Context } from '@dxos/context';\nimport type { SpaceId } from '@dxos/keys';\nimport { type FeedProtocol } from '@dxos/protocols';\nimport type { SqlTransaction } from '@dxos/sql-sqlite';\n\nimport type { FeedStore } from './feed-store';\n\ntype AppendResponse = FeedProtocol.AppendResponse;\ntype ProtocolMessage = FeedProtocol.ProtocolMessage;\ntype QueryResponse = FeedProtocol.QueryResponse;\ntype QueryRequestMessage = Extract<ProtocolMessage, { _tag: 'QueryRequest' }>;\ntype AppendRequestMessage = Extract<ProtocolMessage, { _tag: 'AppendRequest' }>;\ntype RequestMessage = QueryRequestMessage | AppendRequestMessage;\ntype RequestPayload =\n | Omit<QueryRequestMessage, 'senderPeerId' | 'recipientPeerId'>\n | Omit<AppendRequestMessage, 'senderPeerId' | 'recipientPeerId'>;\n\nexport type SyncClientOptions = {\n /** This client's peer id. Set as senderPeerId on all requests. */\n peerId: string;\n /** The server's peer id. Set as recipientPeerId on all requests. */\n serverPeerId?: string;\n feedStore: FeedStore;\n /** Send a protocol message to the server. Returns Effect. */\n sendMessage: (ctx: Context, message: RequestMessage) => Effect.Effect<void, unknown, never>;\n};\n\n/**\n * Client-side sync: pull/push by sending protocol messages and handling responses.\n * Sets senderPeerId = peerId and recipientPeerId = serverPeerId on all requests.\n * Uses a map of requestId -> Deferred to match responses to in-flight requests.\n * handleMessage completes the Deferred for the requestId (if any) and removes the handler; no handler = noop.\n */\nexport class SyncClient {\n readonly #peerId: string;\n readonly #serverPeerId: string | undefined;\n readonly #feedStore: FeedStore;\n readonly #sendMessage: SyncClientOptions['sendMessage'];\n readonly #handlers = new Map<string, Deferred.Deferred<ProtocolMessage, Error>>();\n\n constructor(options: SyncClientOptions) {\n this.#peerId = options.peerId;\n this.#serverPeerId = options.serverPeerId;\n this.#feedStore = options.feedStore;\n this.#sendMessage = options.sendMessage;\n }\n\n #withPeerIds(payload: RequestPayload): RequestMessage {\n if (payload._tag === 'QueryRequest') {\n return {\n ...payload,\n senderPeerId: this.#peerId,\n recipientPeerId: this.#serverPeerId,\n };\n }\n return {\n ...payload,\n senderPeerId: this.#peerId,\n recipientPeerId: this.#serverPeerId,\n };\n }\n\n /**\n * Receive a message from the server. If a handler is registered for the message's requestId, complete it and remove; else noop.\n */\n handleMessage(message: ProtocolMessage): Effect.Effect<void, never, never> {\n const requestId = 'requestId' in message && message.requestId != null ? String(message.requestId) : undefined;\n if (requestId == null) {\n return Effect.void;\n }\n const deferred = this.#handlers.get(requestId);\n if (deferred == null) {\n return Effect.void;\n }\n this.#handlers.delete(requestId);\n if (message._tag === 'Error') {\n return Effect.andThen(Deferred.fail(deferred, new Error(message.message)), () => Effect.void);\n }\n return Effect.andThen(Deferred.succeed(deferred, message), () => Effect.void);\n }\n\n pull(\n ctx: Context,\n opts: {\n spaceId: SpaceId;\n feedNamespace: string;\n limit?: number;\n },\n ): Effect.Effect<{ done: boolean }, unknown, SqlClient.SqlClient | SqlTransaction.SqlTransaction> {\n const self = this;\n return Effect.gen(function* () {\n const lastPulledPosition = yield* self.#feedStore.getSyncState({\n spaceId: opts.spaceId,\n feedNamespace: opts.feedNamespace,\n });\n const requestId = crypto.randomUUID();\n const deferred = yield* Deferred.make<ProtocolMessage, Error>();\n self.#handlers.set(requestId, deferred);\n const request: RequestPayload = {\n _tag: 'QueryRequest',\n requestId,\n spaceId: opts.spaceId,\n feedNamespace: opts.feedNamespace,\n position: lastPulledPosition,\n limit: opts.limit,\n };\n yield* self.#sendMessage(ctx, self.#withPeerIds(request));\n const message = yield* Deferred.await(deferred);\n const response = yield* self.#expectResponse<QueryResponse>(requestId, message, 'QueryResponse');\n if (response.blocks.length === 0) {\n return { done: true };\n }\n yield* self.#feedStore.append({\n spaceId: opts.spaceId,\n feedNamespace: opts.feedNamespace,\n blocks: response.blocks,\n });\n\n // Update sync state with the max position from the pulled batch.\n const maxPulledPosition = response.blocks.reduce(\n (max, block) => (block.position != null && block.position > max ? block.position : max),\n lastPulledPosition,\n );\n yield* self.#feedStore.setSyncState({\n spaceId: opts.spaceId,\n feedNamespace: opts.feedNamespace,\n lastPulledPosition: maxPulledPosition,\n });\n\n return { done: false };\n });\n }\n\n push(\n ctx: Context,\n opts: {\n spaceId: SpaceId;\n feedNamespace: string;\n limit?: number;\n },\n ): Effect.Effect<{ done: boolean }, unknown, SqlClient.SqlClient | SqlTransaction.SqlTransaction> {\n const self = this;\n return Effect.gen(function* () {\n const unpositioned = yield* self.#feedStore.query({\n spaceId: opts.spaceId,\n feedNamespace: opts.feedNamespace,\n unpositionedOnly: true,\n limit: opts.limit,\n });\n if (unpositioned.blocks.length === 0) {\n return { done: true };\n }\n const requestId = crypto.randomUUID();\n const deferred = yield* Deferred.make<ProtocolMessage, Error>();\n self.#handlers.set(requestId, deferred);\n const request: RequestPayload = {\n _tag: 'AppendRequest',\n requestId,\n spaceId: opts.spaceId,\n feedNamespace: opts.feedNamespace,\n blocks: unpositioned.blocks,\n };\n yield* self.#sendMessage(ctx, self.#withPeerIds(request));\n const message = yield* Deferred.await(deferred);\n const response = yield* self.#expectResponse<AppendResponse>(requestId, message, 'AppendResponse');\n yield* self.#feedStore.setPosition({\n spaceId: opts.spaceId,\n blocks: Array.zipWith(response.positions, unpositioned.blocks, (position, block) => ({\n feedId: block.feedId,\n feedNamespace: opts.feedNamespace,\n actorId: block.actorId,\n sequence: block.sequence,\n position,\n })),\n });\n return { done: false };\n });\n }\n\n #expectResponse<T>(requestId: string, message: ProtocolMessage, expectedTag: string): Effect.Effect<T, Error, never> {\n if (message._tag === 'Error') {\n return Effect.fail(new Error(message.message));\n }\n const requestIdMsg = 'requestId' in message ? String(message.requestId) : undefined;\n if (message._tag !== expectedTag || requestIdMsg !== requestId) {\n return Effect.fail(new Error(`Unexpected message: expected ${expectedTag} with requestId ${requestId}`));\n }\n return Effect.succeed(message as T);\n }\n}\n"],
5
+ "mappings": ";AAIA,SAASA,iBAAiB;AAEnB,IAAMC,wBAAN,cAAoCD,UAAUE,OAAO,uBAAA,EAAA;EAC1D,YAAYC,MAMT;AACD,UAAM;MACJC,SAAS,8BAA8BD,KAAKE,eAAe,mBAAmBF,KAAKG,iBAAiB,YAAYH,KAAKI,MAAM,YAAYJ,KAAKK,OAAO,aAAaL,KAAKM,QAAQ;MAC7KC,SAASP;IACX,CAAA;EACF;AACF;;;ACfA,YAAYQ,eAAe;AAE3B,YAAYC,YAAY;AAExB,SAASC,aAAa;AACtB,SAASC,sBAAsB;AAE/B,SAASC,oBAAoB;AAC7B,SAASC,sBAAsB;AAO/B,IAAMC,aAAaC,aAAaD;AAEhC,IAAME,uBAAuBD,aAAaC;AAuBnC,IAAMC,YAAN,MAAMA;EACF;EAET,YAAYC,SAA2B;AACrC,SAAK,WAAWA;EAClB;;;;EAKSC,cAAc,IAAIC,MAAAA;;;;EAK3BC,UAAiBC,UAAG,mBAAA,EAAqB,MAChCC,WAAI,aAAA;AACT,UAAMC,MAAM,OAAiBC;AAG7B,WAAOD;;;;;;AAMP,WAAOA;AAGP,WAAOA;;;;;;;;;;;;AAYP,WAAOA;AACP,WAAOA;AAGP,WAAOA;;;;;AAOP,WAAOA;;;;AAMP,WAAOA;;;;;;EAMT,CAAA,EAAGE,KAAYC,gBAAS,mBAAA,CAAA,CAAA;;;;EAM1B,cAAqBL,UAAG,iBAAA,EACtB,CACEM,SACAC,QACAC,cAEOP,WAAI,MAAM,aAAA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M,gCAAgCuC,WAAAA,mBAA8BhD,SAAAA,EAAW,CAAA;IACxG;AACA,WAAcU,gBAAQX,OAAAA;EACxB;AACF;",
6
+ "names": ["BaseError", "PositionConflictError", "extend", "args", "message", "currentPosition", "requestedPosition", "feedId", "actorId", "sequence", "context", "SqlClient", "Effect", "Event", "assertArgument", "FeedProtocol", "SqlTransaction", "FeedCursor", "FeedProtocol", "isWellKnownNamespace", "FeedStore", "options", "onNewBlocks", "Event", "migrate", "fn", "gen", "sql", "SqlClient", "pipe", "withSpan", "spaceId", "feedId", "namespace", "rows", "length", "feedPrivateId", "newRows", "token", "crypto", "randomUUID", "replace", "slice", "query", "request", "feedIds", "cursorInsertionId", "cursorToken", "die", "Error", "position", "undefined", "cursor", "unpositionedOnly", "insertionId", "decodeCursor", "isNaN", "validCursorToken", "subscriptionId", "feedPrivateIds", "expiresAt", "Date", "now", "privateIds", "JSON", "parse", "feedRows", "in", "map", "r", "requestId", "blocks", "nextCursor", "encodeCursor", "hasMore", "feedNamespace", "filter", "orderBy", "requestLimit", "limit", "queryLimit", "row", "data", "Uint8Array", "lastBlock", "subscribe", "ttl", "forEach", "concurrency", "stringify", "getSyncState", "opts", "lastPulledPosition", "setSyncState", "countBlocks", "count", "deleteOldestBlocks", "deletedRows", "append", "assertArgument", "block", "sqlTransaction", "SqlTransaction", "positions", "withTransaction", "feedKeys", "Map", "key", "has", "set", "entries", "id", "maxPositions", "assignPositions", "maxPosResult", "maxPos", "get", "positionToInsert", "currentMax", "push", "sequence", "actorId", "prevSequence", "prevActorId", "timestamp", "emit", "appendLocal", "messages", "msg", "lastSeqs", "lastBlockResult", "currentSeqs", "blocksBySpaceNamespace", "inFlight", "localActorId", "spaceNamespaceKey", "positionByBlock", "batchBlocks", "values", "i", "setPosition", "existing", "current", "fail", "PositionConflictError", "currentPosition", "requestedPosition", "getAllFeedsForSpace", "feeds", "result", "feed", "make", "split", "Number", "Effect", "SyncServer", "options", "peerId", "feedStore", "sendMessage", "handleMessage", "ctx", "message", "self", "recipientPeerId", "senderPeerId", "withPeerIds", "payload", "_tag", "req", "gen", "response", "query", "pipe", "catchAll", "err", "Error", "String", "append", "void", "Array", "Deferred", "Effect", "SyncClient", "Map", "options", "peerId", "serverPeerId", "feedStore", "sendMessage", "payload", "_tag", "senderPeerId", "recipientPeerId", "handleMessage", "message", "requestId", "String", "undefined", "void", "deferred", "get", "delete", "andThen", "fail", "Error", "succeed", "pull", "ctx", "opts", "self", "gen", "lastPulledPosition", "getSyncState", "spaceId", "feedNamespace", "crypto", "randomUUID", "make", "set", "request", "position", "limit", "await", "response", "blocks", "length", "done", "append", "maxPulledPosition", "reduce", "max", "block", "setSyncState", "push", "unpositioned", "query", "unpositionedOnly", "setPosition", "zipWith", "positions", "feedId", "actorId", "sequence", "expectedTag", "requestIdMsg"]
7
+ }
@@ -1,14 +1,10 @@
1
1
  import {
2
- DuplicateBlockLamportTimestampError,
3
- DuplicateBlockPositionError,
4
2
  FeedStore,
5
3
  PositionConflictError,
6
4
  SyncClient,
7
5
  SyncServer
8
- } from "./chunk-Q5PE2Q5P.mjs";
6
+ } from "./chunk-PENEKCN2.mjs";
9
7
  export {
10
- DuplicateBlockLamportTimestampError,
11
- DuplicateBlockPositionError,
12
8
  FeedStore,
13
9
  PositionConflictError,
14
10
  SyncClient,
@@ -1 +1 @@
1
- {"inputs":{"src/errors.ts":{"bytes":3825,"imports":[{"path":"@dxos/errors","kind":"import-statement","external":true}],"format":"esm"},"src/feed-store.ts":{"bytes":86983,"imports":[{"path":"@effect/sql/SqlClient","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite","kind":"import-statement","external":true},{"path":"src/errors.ts","kind":"import-statement","original":"./errors"}],"format":"esm"},"src/sync-server.ts":{"bytes":9233,"imports":[{"path":"effect/Effect","kind":"import-statement","external":true}],"format":"esm"},"src/sync-client.ts":{"bytes":21805,"imports":[{"path":"effect/Array","kind":"import-statement","external":true},{"path":"effect/Deferred","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true}],"format":"esm"},"src/index.ts":{"bytes":736,"imports":[{"path":"src/feed-store.ts","kind":"import-statement","original":"./feed-store"},{"path":"src/errors.ts","kind":"import-statement","original":"./errors"},{"path":"src/sync-server.ts","kind":"import-statement","original":"./sync-server"},{"path":"src/sync-client.ts","kind":"import-statement","original":"./sync-client"}],"format":"esm"},"src/testing/test-builder.ts":{"bytes":23497,"imports":[{"path":"@effect/sql/Statement","kind":"import-statement","external":true},{"path":"effect/Array","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Layer","kind":"import-statement","external":true},{"path":"effect/ManagedRuntime","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/effect","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite/platform","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite/SqlExport","kind":"import-statement","external":true},{"path":"src/feed-store.ts","kind":"import-statement","original":"../feed-store"},{"path":"src/sync-client.ts","kind":"import-statement","original":"../sync-client"},{"path":"src/sync-server.ts","kind":"import-statement","original":"../sync-server"}],"format":"esm"},"src/testing/index.ts":{"bytes":470,"imports":[{"path":"src/testing/test-builder.ts","kind":"import-statement","original":"./test-builder"}],"format":"esm"}},"outputs":{"dist/lib/neutral/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":93},"dist/lib/neutral/index.mjs":{"imports":[{"path":"dist/lib/neutral/chunk-Q5PE2Q5P.mjs","kind":"import-statement"}],"exports":["DuplicateBlockLamportTimestampError","DuplicateBlockPositionError","FeedStore","PositionConflictError","SyncClient","SyncServer"],"entryPoint":"src/index.ts","inputs":{"src/index.ts":{"bytesInOutput":0}},"bytes":357},"dist/lib/neutral/testing/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":11998},"dist/lib/neutral/testing/index.mjs":{"imports":[{"path":"dist/lib/neutral/chunk-Q5PE2Q5P.mjs","kind":"import-statement"},{"path":"@effect/sql/Statement","kind":"import-statement","external":true},{"path":"effect/Array","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Layer","kind":"import-statement","external":true},{"path":"effect/ManagedRuntime","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/effect","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite/platform","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite/SqlExport","kind":"import-statement","external":true}],"exports":["TestBuilder","TestPeer"],"entryPoint":"src/testing/index.ts","inputs":{"src/testing/test-builder.ts":{"bytesInOutput":5173},"src/testing/index.ts":{"bytesInOutput":0}},"bytes":5359},"dist/lib/neutral/chunk-Q5PE2Q5P.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":59597},"dist/lib/neutral/chunk-Q5PE2Q5P.mjs":{"imports":[{"path":"@dxos/errors","kind":"import-statement","external":true},{"path":"@effect/sql/SqlClient","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Array","kind":"import-statement","external":true},{"path":"effect/Deferred","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true}],"exports":["DuplicateBlockLamportTimestampError","DuplicateBlockPositionError","FeedStore","PositionConflictError","SyncClient","SyncServer"],"inputs":{"src/errors.ts":{"bytesInOutput":841},"src/feed-store.ts":{"bytesInOutput":20888},"src/sync-server.ts":{"bytesInOutput":1660},"src/sync-client.ts":{"bytesInOutput":4700}},"bytes":28366}}}
1
+ {"inputs":{"src/errors.ts":{"bytes":1997,"imports":[{"path":"@dxos/errors","kind":"import-statement","external":true}],"format":"esm"},"src/feed-store.ts":{"bytes":84904,"imports":[{"path":"@effect/sql/SqlClient","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite","kind":"import-statement","external":true},{"path":"src/errors.ts","kind":"import-statement","original":"./errors"}],"format":"esm"},"src/sync-server.ts":{"bytes":9358,"imports":[{"path":"effect/Effect","kind":"import-statement","external":true}],"format":"esm"},"src/sync-client.ts":{"bytes":22105,"imports":[{"path":"effect/Array","kind":"import-statement","external":true},{"path":"effect/Deferred","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true}],"format":"esm"},"src/index.ts":{"bytes":658,"imports":[{"path":"src/feed-store.ts","kind":"import-statement","original":"./feed-store"},{"path":"src/errors.ts","kind":"import-statement","original":"./errors"},{"path":"src/sync-server.ts","kind":"import-statement","original":"./sync-server"},{"path":"src/sync-client.ts","kind":"import-statement","original":"./sync-client"}],"format":"esm"},"src/testing/test-builder.ts":{"bytes":23925,"imports":[{"path":"@effect/sql/Statement","kind":"import-statement","external":true},{"path":"effect/Array","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Layer","kind":"import-statement","external":true},{"path":"effect/ManagedRuntime","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/effect","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite/platform","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite/SqlExport","kind":"import-statement","external":true},{"path":"src/feed-store.ts","kind":"import-statement","original":"../feed-store"},{"path":"src/sync-client.ts","kind":"import-statement","original":"../sync-client"},{"path":"src/sync-server.ts","kind":"import-statement","original":"../sync-server"}],"format":"esm"},"src/testing/index.ts":{"bytes":388,"imports":[{"path":"src/testing/test-builder.ts","kind":"import-statement","original":"./test-builder"}],"format":"esm"}},"outputs":{"dist/lib/neutral/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":93},"dist/lib/neutral/index.mjs":{"imports":[{"path":"dist/lib/neutral/chunk-PENEKCN2.mjs","kind":"import-statement"}],"exports":["FeedStore","PositionConflictError","SyncClient","SyncServer"],"entryPoint":"src/index.ts","inputs":{"src/index.ts":{"bytesInOutput":0}},"bytes":217},"dist/lib/neutral/testing/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":11479},"dist/lib/neutral/testing/index.mjs":{"imports":[{"path":"dist/lib/neutral/chunk-PENEKCN2.mjs","kind":"import-statement"},{"path":"@effect/sql/Statement","kind":"import-statement","external":true},{"path":"effect/Array","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Layer","kind":"import-statement","external":true},{"path":"effect/ManagedRuntime","kind":"import-statement","external":true},{"path":"@dxos/context","kind":"import-statement","external":true},{"path":"@dxos/effect","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite/platform","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite/SqlExport","kind":"import-statement","external":true}],"exports":["TestBuilder","TestPeer"],"entryPoint":"src/testing/index.ts","inputs":{"src/testing/test-builder.ts":{"bytesInOutput":5447},"src/testing/index.ts":{"bytesInOutput":0}},"bytes":5633},"dist/lib/neutral/chunk-PENEKCN2.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":57960},"dist/lib/neutral/chunk-PENEKCN2.mjs":{"imports":[{"path":"@dxos/errors","kind":"import-statement","external":true},{"path":"@effect/sql/SqlClient","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"@dxos/async","kind":"import-statement","external":true},{"path":"@dxos/invariant","kind":"import-statement","external":true},{"path":"@dxos/protocols","kind":"import-statement","external":true},{"path":"@dxos/sql-sqlite","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true},{"path":"effect/Array","kind":"import-statement","external":true},{"path":"effect/Deferred","kind":"import-statement","external":true},{"path":"effect/Effect","kind":"import-statement","external":true}],"exports":["FeedStore","PositionConflictError","SyncClient","SyncServer"],"inputs":{"src/errors.ts":{"bytesInOutput":382},"src/feed-store.ts":{"bytesInOutput":20881},"src/sync-server.ts":{"bytesInOutput":1685},"src/sync-client.ts":{"bytesInOutput":4748}},"bytes":27903}}}
@@ -2,7 +2,7 @@ import {
2
2
  FeedStore,
3
3
  SyncClient,
4
4
  SyncServer
5
- } from "../chunk-Q5PE2Q5P.mjs";
5
+ } from "../chunk-PENEKCN2.mjs";
6
6
 
7
7
  // src/testing/test-builder.ts
8
8
  import * as Statement from "@effect/sql/Statement";
@@ -10,12 +10,13 @@ import * as Array from "effect/Array";
10
10
  import * as Effect from "effect/Effect";
11
11
  import * as Layer from "effect/Layer";
12
12
  import * as ManagedRuntime from "effect/ManagedRuntime";
13
- import { Resource } from "@dxos/context";
13
+ import { Context, Resource } from "@dxos/context";
14
14
  import { RuntimeProvider } from "@dxos/effect";
15
15
  import { FeedProtocol } from "@dxos/protocols";
16
16
  import { SqlTransaction } from "@dxos/sql-sqlite";
17
17
  import { layerMemory } from "@dxos/sql-sqlite/platform";
18
18
  import * as SqlExport from "@dxos/sql-sqlite/SqlExport";
19
+ var __dxlog_file = "/__w/dxos/dxos/packages/core/echo/feed/src/testing/test-builder.ts";
19
20
  var WellKnownNamespaces = FeedProtocol.WellKnownNamespaces;
20
21
  var TestBuilder = class extends Resource {
21
22
  #peers = [];
@@ -29,7 +30,7 @@ var TestBuilder = class extends Resource {
29
30
  isServer: i === 0,
30
31
  actorId: `peer-${i}`,
31
32
  serverPeerId: i === 0 ? void 0 : "peer-0",
32
- sendMessage: (msg) => this.#routeMessage(msg),
33
+ sendMessage: (ctx, msg) => this.#routeMessage(ctx, msg),
33
34
  logSql
34
35
  }));
35
36
  }
@@ -60,12 +61,12 @@ var TestBuilder = class extends Resource {
60
61
  });
61
62
  }
62
63
  /** Route a message to the peer identified by recipientPeerId. Runs the recipient's handleMessage with that peer's runtime. */
63
- #routeMessage(msg) {
64
+ #routeMessage(ctx, msg) {
64
65
  const peer = this.#peers.find((p) => p.peerId === msg.recipientPeerId);
65
66
  if (peer == null) {
66
67
  return Effect.die(new Error(`TestPeer not found: ${msg.recipientPeerId}`));
67
68
  }
68
- const handleEffect = peer.syncServer != null ? peer.syncServer.handleMessage(msg) : peer.syncClient != null ? peer.syncClient.handleMessage(msg) : null;
69
+ const handleEffect = peer.syncServer != null ? peer.syncServer.handleMessage(ctx, msg) : peer.syncClient != null ? peer.syncClient.handleMessage(msg) : null;
69
70
  if (handleEffect == null) {
70
71
  return Effect.die(new Error(`TestPeer has no handler: ${msg.recipientPeerId}`));
71
72
  }
@@ -152,14 +153,14 @@ var TestPeer = class extends Resource {
152
153
  return this.#feedStore.appendLocal(req).pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));
153
154
  }
154
155
  pull({ spaceId, feedNamespace, limit = 10 }) {
155
- return this.#client.pull({
156
+ return this.#client.pull(Context.default(void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 153 }), {
156
157
  spaceId,
157
158
  feedNamespace,
158
159
  limit
159
160
  }).pipe(RuntimeProvider.runPromise(this.#runtime.runtimeEffect));
160
161
  }
161
162
  push({ spaceId, feedNamespace, limit = 10 }) {
162
- return this.#client.push({
163
+ return this.#client.push(Context.default(void 0, { "~LogMeta": "~LogMeta", F: __dxlog_file, L: 160 }), {
163
164
  spaceId,
164
165
  feedNamespace,
165
166
  limit