@pmate/chat-sdk 0.13.0-profile.6 → 0.13.0-profile.8

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.
@@ -14,7 +14,7 @@ export declare class ProfileDatabase extends Dexie {
14
14
  indexedDB?: IDBFactory;
15
15
  name?: string;
16
16
  });
17
- claimWriter(ownerId: string, now?: number, ttlMs?: number): Promise<ProfileWriterLease | undefined>;
17
+ claimWriter(ownerId: string, now?: number, ttlMs?: number, writerLock?: string): Promise<ProfileWriterLease | undefined>;
18
18
  private assertWriter;
19
19
  releaseWriter(ownerId: string, fence: number): Promise<void>;
20
20
  initialize(ownerId: string, fence: number, state: Omit<ProfileCurrentState, "key" | "commitRevision">): Promise<ProfileCurrentState>;
@@ -24,17 +24,17 @@ export class ProfileDatabase extends Dexie {
24
24
  });
25
25
  this.on("versionchange", () => { this.close(); return false; });
26
26
  }
27
- async claimWriter(ownerId, now = Date.now(), ttlMs = 30000) {
27
+ async claimWriter(ownerId, now = Date.now(), ttlMs = 30000, writerLock) {
28
28
  if (!ownerId || !Number.isSafeInteger(ttlMs) || ttlMs < 1)
29
29
  throw Error("INVALID_PROFILE_LEASE");
30
30
  return this.transaction("rw", this.inboxState, async () => {
31
31
  const old = await this.inboxState.get("lease");
32
- if (old && old.ownerId !== ownerId && old.expiresAt > now)
32
+ if (old && old.ownerId !== ownerId && old.expiresAt > now && (!writerLock || old.writerLock !== writerLock))
33
33
  return undefined;
34
34
  const fence = old ? old.ownerId === ownerId && old.expiresAt > now ? old.fence : old.fence + 1 : 1;
35
35
  if (!Number.isSafeInteger(fence))
36
36
  throw Error("PROFILE_FENCE_EXHAUSTED");
37
- const lease = { key: "lease", ownerId, fence, expiresAt: now + ttlMs };
37
+ const lease = { key: "lease", ownerId, fence, expiresAt: now + ttlMs, ...(writerLock ? { writerLock } : {}) };
38
38
  await this.inboxState.put(lease);
39
39
  return lease;
40
40
  });
@@ -81,7 +81,7 @@ export class ProfileDatabase extends Dexie {
81
81
  throw Error("PROFILE_CURSOR_REGRESSION");
82
82
  const changed = [batch.threads, batch.windows, batch.messages, batch.outbox, batch.deleteMessages, batch.deleteWindows, batch.deleteOutbox].some(rows => rows?.length);
83
83
  const localMigrations = batch.localMigrations ? [...new Set([...(current.localMigrations ?? []), ...batch.localMigrations])] : current.localMigrations;
84
- if (!changed && batch.committedSeq === current.committedSeq && (batch.receiptsReady === undefined || batch.receiptsReady === current.receiptsReady) && JSON.stringify(localMigrations) === JSON.stringify(current.localMigrations) && JSON.stringify(batch.revokedTeamIds ?? current.revokedTeamIds) === JSON.stringify(current.revokedTeamIds) && (batch.teamAccessRevision ?? current.teamAccessRevision) === current.teamAccessRevision)
84
+ if (!changed && batch.committedSeq === current.committedSeq && (batch.receiptsReady === undefined || batch.receiptsReady === current.receiptsReady) && JSON.stringify(localMigrations) === JSON.stringify(current.localMigrations) && JSON.stringify(batch.revokedTeamIds ?? current.revokedTeamIds) === JSON.stringify(current.revokedTeamIds) && (batch.teamAccessRevision ?? current.teamAccessRevision) === current.teamAccessRevision && (batch.windowStart ?? current.windowStart) === current.windowStart)
85
85
  return current;
86
86
  if (batch.messages?.length)
87
87
  await this.messages.bulkPut(batch.messages);
@@ -99,7 +99,7 @@ export class ProfileDatabase extends Dexie {
99
99
  await this.outbox.bulkDelete(batch.deleteOutbox);
100
100
  if (!Number.isSafeInteger(current.commitRevision + 1))
101
101
  throw Error("PROFILE_REVISION_EXHAUSTED");
102
- const next = { ...current, ...(batch.receiptsReady === undefined ? {} : { receiptsReady: batch.receiptsReady }), localMigrations, revokedTeamIds: batch.revokedTeamIds ?? current.revokedTeamIds, teamAccessRevision: batch.teamAccessRevision ?? current.teamAccessRevision, committedSeq: batch.committedSeq, commitRevision: current.commitRevision + 1 };
102
+ const next = { ...current, ...(batch.receiptsReady === undefined ? {} : { receiptsReady: batch.receiptsReady }), localMigrations, windowStart: batch.windowStart ?? current.windowStart, revokedTeamIds: batch.revokedTeamIds ?? current.revokedTeamIds, teamAccessRevision: batch.teamAccessRevision ?? current.teamAccessRevision, committedSeq: batch.committedSeq, commitRevision: current.commitRevision + 1 };
103
103
  await this.inboxState.put(next);
104
104
  return next;
105
105
  });
@@ -107,10 +107,18 @@ export class ProfileDatabase extends Dexie {
107
107
  /** Restore from one consistent transaction, never mix data across a switch. */
108
108
  async restore() {
109
109
  return this.transaction("r", [this.threads, this.windows, this.messages, this.inboxState, this.outbox], async () => {
110
- const current = await this.inboxState.get("current");
110
+ let current = await this.inboxState.get("current");
111
111
  const generation = current?.activeGeneration;
112
- return { current,
113
- threads: generation ? await this.threads.where("generation").equals(generation).toArray() : [],
112
+ const threads = generation ? await this.threads.where("generation").equals(generation).toArray() : [];
113
+ if (current && current.windowStart === undefined) {
114
+ // Additive migration for early Profile caches. Restoration already reads
115
+ // these records; never replace a committed range with a startup default.
116
+ const build = await this.inboxState.get(`build:${generation}`);
117
+ const inferred = build?.windowStart ?? (threads.length ? threads.reduce((start, row) => Math.max(start, row.coverage.windowStart), threads[0].coverage.windowStart) : undefined);
118
+ if (inferred !== undefined)
119
+ current = { ...current, windowStart: inferred };
120
+ }
121
+ return { current, threads,
114
122
  windows: generation ? await this.windows.where("generation").equals(generation).toArray() : [],
115
123
  messages: generation ? await this.messages.where("generation").equals(generation).toArray() : [],
116
124
  outbox: await this.outbox.toArray(),
@@ -191,7 +199,7 @@ export class ProfileDatabase extends Dexie {
191
199
  if (build.status !== "validated")
192
200
  throw Error("PROFILE_BUILD_NOT_VALIDATED");
193
201
  const next = { ...current, key: "current", activeGeneration: generation, epoch: build.epoch,
194
- committedSeq: build.committedSeq, projectionVersion: build.projectionVersion, commitRevision: current.commitRevision + 1, receiptsReady: build.receiptsReady };
202
+ committedSeq: build.committedSeq, windowStart: build.windowStart ?? current.windowStart, projectionVersion: build.projectionVersion, commitRevision: current.commitRevision + 1, receiptsReady: build.receiptsReady };
195
203
  await this.inboxState.put({ ...build, status: "active" });
196
204
  await this.inboxState.put(next);
197
205
  return next;
@@ -49,7 +49,7 @@ export class ProfileGenerationBuilder {
49
49
  committedSeq: (start - 1n).toString(), projectionVersion: 1, sourceRevision, status: "building", throughSeq: bootstrap.headSeq,
50
50
  windowStart: bootstrap.windowStart, buildRevision: 0 };
51
51
  const projection = new ProfileProjection(this.database.identity, { current: { key: "current", activeGeneration: generation,
52
- epoch: build.epoch, committedSeq: build.committedSeq, projectionVersion: 1, commitRevision: 0 }, threads: [], windows: [], messages: [] }, bootstrap.windowStart);
52
+ epoch: build.epoch, committedSeq: build.committedSeq, windowStart: build.windowStart, projectionVersion: 1, commitRevision: 0 }, threads: [], windows: [], messages: [] }, bootstrap.windowStart);
53
53
  const prepared = projection.prepareBasis(bootstrap), lease = this.lease();
54
54
  const next = { ...build, buildRevision: prepared.current.commitRevision };
55
55
  await this.database.saveGeneration(lease.ownerId, lease.fence, next, prepared);
@@ -8,6 +8,8 @@ export type ProfileOwnerOptions = {
8
8
  epoch: string;
9
9
  windowStart: number;
10
10
  ownerId?: string;
11
+ /** Set only while the Worker holds the matching exclusive browser lock. */
12
+ writerLock?: string;
11
13
  onCommitted?: (delta: ProfileDelta) => void;
12
14
  onError?: (error: unknown) => void;
13
15
  windowMs?: number;
@@ -29,18 +29,18 @@ export class ProfileOwner {
29
29
  static async open(options) {
30
30
  const owner = new ProfileOwner(options);
31
31
  const ownerId = options.ownerId ?? crypto.randomUUID();
32
- const lease = await options.database.claimWriter(ownerId);
32
+ const lease = await options.database.claimWriter(ownerId, undefined, undefined, options.writerLock);
33
33
  if (!lease)
34
34
  throw Error("PROFILE_OWNER_UNAVAILABLE");
35
35
  owner.lease = lease;
36
36
  try {
37
37
  await options.database.initialize(ownerId, lease.fence, { activeGeneration: crypto.randomUUID(), epoch: options.epoch,
38
- committedSeq: "0", projectionVersion: 1 });
38
+ committedSeq: "0", projectionVersion: 1, windowStart: options.windowStart });
39
39
  const restored = await options.database.restore();
40
40
  if (!restored.current || restored.current.epoch !== options.epoch)
41
41
  throw Error("PROFILE_EPOCH_REBUILD_REQUIRED");
42
42
  const snapshot = { ...restored, current: restored.current };
43
- owner.projection = new ProfileProjection(options.database.identity, snapshot, options.windowStart);
43
+ owner.projection = new ProfileProjection(options.database.identity, snapshot, restored.current.windowStart ?? options.windowStart);
44
44
  owner.builder = new ProfileGenerationBuilder(options.database, () => owner.lease);
45
45
  owner.memory.restore(snapshot);
46
46
  owner.queue = new ProfileCommitQueue({ commit: events => owner.commit(events), windowMs: options.windowMs,
@@ -163,7 +163,7 @@ export class ProfileOwner {
163
163
  if (this.closed || this.lost)
164
164
  return;
165
165
  try {
166
- const next = await this.options.database.claimWriter(this.lease.ownerId);
166
+ const next = await this.options.database.claimWriter(this.lease.ownerId, undefined, undefined, this.lease.writerLock);
167
167
  if (!next || next.fence !== this.lease.fence) {
168
168
  this.lost = true;
169
169
  this.report(Error("PROFILE_WRITER_FENCED"));
@@ -218,7 +218,7 @@ export class ProfileOwner {
218
218
  const prepared = this.projection.prepare(events);
219
219
  const committed = await this.options.database.commit({ ...prepared, ownerId: this.lease.ownerId, fence: this.lease.fence,
220
220
  generation: this.current.activeGeneration, expectedRevision: fromRevision, epoch: this.current.epoch,
221
- committedSeq: prepared.current.committedSeq, receiptsReady: prepared.current.receiptsReady, localMigrations: prepared.current.localMigrations, revokedTeamIds: prepared.current.revokedTeamIds, teamAccessRevision: prepared.current.teamAccessRevision });
221
+ committedSeq: prepared.current.committedSeq, windowStart: prepared.current.windowStart, receiptsReady: prepared.current.receiptsReady, localMigrations: prepared.current.localMigrations, revokedTeamIds: prepared.current.revokedTeamIds, teamAccessRevision: prepared.current.teamAccessRevision });
222
222
  if (committed.commitRevision === fromRevision)
223
223
  return prepared.rejected;
224
224
  prepared.current = committed;
@@ -115,6 +115,7 @@ export type ProfileCurrentState = {
115
115
  key: "current";
116
116
  epoch: string;
117
117
  committedSeq: string;
118
+ windowStart?: number;
118
119
  activeGeneration: string;
119
120
  projectionVersion: number;
120
121
  commitRevision: number;
@@ -128,6 +129,7 @@ export type ProfileWriterLease = {
128
129
  ownerId: string;
129
130
  fence: number;
130
131
  expiresAt: number;
132
+ writerLock?: string;
131
133
  };
132
134
  export type ProfileGenerationState = {
133
135
  key: `build:${string}`;
@@ -161,6 +163,7 @@ export type ProfileWriteBatch = {
161
163
  generation: string;
162
164
  epoch: string;
163
165
  committedSeq: string;
166
+ windowStart?: number;
164
167
  receiptsReady?: boolean;
165
168
  localMigrations?: string[];
166
169
  revokedTeamIds?: string[];
@@ -20,6 +20,7 @@ export declare function installProfileWorker(port: ProfileMessagePort, options?:
20
20
  close(): void;
21
21
  };
22
22
  fetch?: typeof fetch;
23
+ locks?: Pick<LockManager, "request"> | null;
23
24
  }): () => Promise<void>;
24
25
  /** The application passes its bundler-created Worker. Worker code and main-page
25
26
  * code ship together, so protocol negotiation precedes any snapshot handoff. */
@@ -15,6 +15,7 @@ export function installProfileWorker(port, options = {}) {
15
15
  let owner, database;
16
16
  let channel;
17
17
  let scope, opening;
18
+ let releaseWriterLock;
18
19
  let disposers = [];
19
20
  let feed, dispatcher, connection;
20
21
  let network;
@@ -31,6 +32,8 @@ export function installProfileWorker(port, options = {}) {
31
32
  await opening;
32
33
  await stopNetwork();
33
34
  await owner?.close();
35
+ await releaseWriterLock?.();
36
+ releaseWriterLock = undefined;
34
37
  for (const off of disposers.splice(0))
35
38
  off();
36
39
  owner = undefined;
@@ -55,9 +58,16 @@ export function installProfileWorker(port, options = {}) {
55
58
  network = config.network;
56
59
  if (!opening) {
57
60
  opening = (async () => {
61
+ // Browser-managed locks disappear with a terminated Worker. Only a
62
+ // lease tagged with this same lock can bypass its old TTL; legacy or
63
+ // lockless owners retain the normal expiry/fencing rules.
64
+ const locks = options.locks === undefined ? globalThis.navigator?.locks : options.locks;
65
+ const writerLock = `${nextScope}:writer`;
66
+ if (locks)
67
+ releaseWriterLock = await holdProfileWriterLock(locks, writerLock);
58
68
  database = options.database?.(config.identity) ?? new ProfileDatabase(config.identity);
59
69
  const stored = await database.inboxState.get("current");
60
- owner = await ProfileOwner.open({ database, epoch: stored?.epoch ?? config.epoch ?? "uninitialized", windowStart: config.windowStart,
70
+ owner = await ProfileOwner.open({ database, writerLock: releaseWriterLock ? writerLock : undefined, epoch: stored?.epoch ?? config.epoch ?? "uninitialized", windowStart: config.windowStart,
61
71
  onError: error => port.postMessage({ profileControl: "error", error: error instanceof Error ? error.message : "PROFILE_OWNER_FAILED" }) });
62
72
  channel = options.channel?.(nextScope) ?? new BroadcastChannel(nextScope);
63
73
  disposers.push(serveProfileOwner(owner, port, nextScope), serveProfileOwner(owner, channel, nextScope));
@@ -95,6 +105,8 @@ export function installProfileWorker(port, options = {}) {
95
105
  channel = undefined;
96
106
  await owner?.close();
97
107
  owner = undefined;
108
+ await releaseWriterLock?.();
109
+ releaseWriterLock = undefined;
98
110
  database?.close();
99
111
  database = undefined;
100
112
  opening = undefined;
@@ -111,6 +123,8 @@ export function installProfileWorker(port, options = {}) {
111
123
  await opening;
112
124
  await stopNetwork();
113
125
  await owner?.close();
126
+ await releaseWriterLock?.();
127
+ releaseWriterLock = undefined;
114
128
  port.removeEventListener("message", listener);
115
129
  for (const off of disposers.splice(0))
116
130
  off();
@@ -167,3 +181,20 @@ export async function connectProfileWorker(worker, configuration, timeoutMs = 30
167
181
  }
168
182
  return { replica, close: async () => { replica.close(); await host.close(); } };
169
183
  }
184
+ /** A null result preserves TTL takeover when a frozen context still holds the
185
+ * browser lock. It never authorizes bypassing an unexpired database lease. */
186
+ async function holdProfileWriterLock(locks, name) {
187
+ return new Promise((resolve, reject) => {
188
+ let release;
189
+ const held = new Promise(done => { release = done; });
190
+ const request = locks.request(name, { mode: "exclusive", ifAvailable: true }, lock => {
191
+ if (!lock) {
192
+ resolve(undefined);
193
+ return;
194
+ }
195
+ resolve(async () => { release(); await request; });
196
+ return held;
197
+ });
198
+ void request.catch(reject);
199
+ });
200
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pmate/chat-sdk",
3
- "version": "0.13.0-profile.6",
3
+ "version": "0.13.0-profile.8",
4
4
  "description": "Local-first chat SDK, message subscriptions, reading state, and shared chat UI primitives",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",