@pmate/chat-sdk 0.13.0-profile.1 → 0.13.0-profile.10

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.
Files changed (37) hide show
  1. package/README.md +26 -0
  2. package/lib/profile.d.ts +4 -1
  3. package/lib/profile.js +4 -1
  4. package/lib/runtime/profileChat.d.ts +118 -1
  5. package/lib/runtime/profileChat.js +98 -30
  6. package/lib/runtime/profileCommitQueue.d.ts +2 -1
  7. package/lib/runtime/profileCommitQueue.js +26 -7
  8. package/lib/runtime/profileCoordinator.d.ts +19 -19
  9. package/lib/runtime/profileCoordinator.js +127 -94
  10. package/lib/runtime/profileDatabase.d.ts +7 -7
  11. package/lib/runtime/profileDatabase.js +57 -42
  12. package/lib/runtime/profileGenerationBuilder.d.ts +2 -3
  13. package/lib/runtime/profileGenerationBuilder.js +60 -26
  14. package/lib/runtime/profileInboxFeed.d.ts +1 -0
  15. package/lib/runtime/profileInboxFeed.js +12 -2
  16. package/lib/runtime/profileLegacyInbox.d.ts +8 -0
  17. package/lib/runtime/profileLegacyInbox.js +114 -0
  18. package/lib/runtime/profileLegacyOutbox.d.ts +7 -0
  19. package/lib/runtime/profileLegacyOutbox.js +106 -0
  20. package/lib/runtime/profileLegacyReading.d.ts +7 -0
  21. package/lib/runtime/profileLegacyReading.js +110 -0
  22. package/lib/runtime/profileMemoryStore.d.ts +22 -2
  23. package/lib/runtime/profileMemoryStore.js +140 -12
  24. package/lib/runtime/profileOutboxDispatcher.d.ts +3 -0
  25. package/lib/runtime/profileOutboxDispatcher.js +41 -5
  26. package/lib/runtime/profileOwner.d.ts +11 -6
  27. package/lib/runtime/profileOwner.js +71 -46
  28. package/lib/runtime/profileProjection.d.ts +54 -5
  29. package/lib/runtime/profileProjection.js +336 -51
  30. package/lib/runtime/profileReadingIndex.d.ts +1 -0
  31. package/lib/runtime/profileReadingIndex.js +17 -1
  32. package/lib/runtime/profileStoreTypes.d.ts +15 -9
  33. package/lib/runtime/{profileReplica.d.ts → profileWorkerClient.d.ts} +10 -26
  34. package/lib/runtime/{profileReplica.js → profileWorkerClient.js} +55 -102
  35. package/lib/runtime/profileWorkerHost.d.ts +4 -6
  36. package/lib/runtime/profileWorkerHost.js +58 -21
  37. package/package.json +2 -2
@@ -48,7 +48,13 @@ export type ProfileThread = {
48
48
  pendingControls?: Record<string, unknown[]>;
49
49
  messageRoots?: Record<string, string>;
50
50
  pendingReceipts?: Record<string, string[]>;
51
+ pendingReadingIntents?: Record<string, {
52
+ commandId: string;
53
+ policy: "visible" | "played";
54
+ createdAt: number;
55
+ }[]>;
51
56
  participantCounts?: Record<string, number>;
57
+ unknownReadingCount?: number;
52
58
  };
53
59
  };
54
60
  export type ProfileMessageRef = {
@@ -109,16 +115,14 @@ export type ProfileCurrentState = {
109
115
  key: "current";
110
116
  epoch: string;
111
117
  committedSeq: string;
118
+ windowStart?: number;
112
119
  activeGeneration: string;
113
120
  projectionVersion: number;
114
121
  commitRevision: number;
115
122
  receiptsReady?: boolean;
116
- };
117
- export type ProfileWriterLease = {
118
- key: "lease";
119
- ownerId: string;
120
- fence: number;
121
- expiresAt: number;
123
+ localMigrations?: string[];
124
+ revokedTeamIds?: string[];
125
+ teamAccessRevision?: number;
122
126
  };
123
127
  export type ProfileGenerationState = {
124
128
  key: `build:${string}`;
@@ -134,7 +138,7 @@ export type ProfileGenerationState = {
134
138
  windowStart?: number;
135
139
  receiptsReady?: boolean;
136
140
  };
137
- export type ProfileStateRecord = ProfileCurrentState | ProfileWriterLease | ProfileGenerationState;
141
+ export type ProfileStateRecord = ProfileCurrentState | ProfileGenerationState;
138
142
  export type ProfileOutboxCommand = {
139
143
  commandId: string;
140
144
  kind: "message" | "reading" | "played";
@@ -146,13 +150,15 @@ export type ProfileOutboxCommand = {
146
150
  attempts: number;
147
151
  };
148
152
  export type ProfileWriteBatch = {
149
- ownerId: string;
150
- fence: number;
151
153
  expectedRevision: number;
152
154
  generation: string;
153
155
  epoch: string;
154
156
  committedSeq: string;
157
+ windowStart?: number;
155
158
  receiptsReady?: boolean;
159
+ localMigrations?: string[];
160
+ revokedTeamIds?: string[];
161
+ teamAccessRevision?: number;
156
162
  threads?: ProfileThread[];
157
163
  windows?: ProfileWindow[];
158
164
  messages?: ProfileMessage[];
@@ -1,4 +1,4 @@
1
- import { ProfileMemoryStore, type ProfileDelta } from "./profileMemoryStore.js";
1
+ import { ProfileMemoryStore } from "./profileMemoryStore.js";
2
2
  import type { ProfileOperation } from "./profileProjection.js";
3
3
  import type { ProfileOwner } from "./profileOwner.js";
4
4
  export type ProfileMessagePort = {
@@ -7,25 +7,11 @@ export type ProfileMessagePort = {
7
7
  removeEventListener(type: "message", listener: (event: MessageEvent) => void): void;
8
8
  start?(): void;
9
9
  };
10
- /** A bounded, volatile history: no extra persistence or full-team snapshot write.
11
- * A producer restart intentionally falls back to a prepared snapshot. */
12
- export declare class ProfileDeltaJournal {
13
- private maxEntries;
14
- private maxBytes;
15
- private rows;
16
- private bytes;
17
- constructor(maxEntries?: number, maxBytes?: number);
18
- append(delta: ProfileDelta): void;
19
- since(generation: string | undefined, revision: number | undefined, current: {
20
- activeGeneration: string;
21
- commitRevision: number;
22
- }): ProfileDelta[] | undefined;
23
- }
24
- /** Same adapter accepts a Dedicated Worker's message port or BroadcastChannel. */
25
- export declare function serveProfileOwner(owner: ProfileOwner, port: ProfileMessagePort, scope: string, onError?: (error: unknown) => void): () => void;
26
- /** UI/WebView replica. Reads and subscriptions use memory; only commands and
27
- * revision repair cross the message boundary. Normal deltas never read disk. */
28
- export declare class ProfileReplica {
10
+ /** Direct Dedicated Worker port; the rendering document is its only consumer. */
11
+ export declare function serveProfileWorker(owner: ProfileOwner, port: ProfileMessagePort, scope: string, onError?: (error: unknown) => void): () => void;
12
+ /** One rendering document consumes committed projections from its own Worker.
13
+ * Ordered port delivery needs no journal, polling or distributed repair. */
14
+ export declare class ProfileWorkerClient {
29
15
  private port;
30
16
  private scope;
31
17
  private onError;
@@ -33,20 +19,18 @@ export declare class ProfileReplica {
33
19
  readonly memory: ProfileMemoryStore;
34
20
  private clientId;
35
21
  private requests;
36
- private repairing?;
22
+ private restoring;
37
23
  private closed;
38
24
  private buffered;
39
- private timer?;
40
25
  private lastError?;
41
- constructor(port: ProfileMessagePort, scope: string, onError?: (error: unknown) => void, timeoutMs?: number, profileId?: string);
26
+ constructor(port: ProfileMessagePort, scope: string, onError?: (error: unknown) => void, timeoutMs?: number, profileId?: string, memory?: ProfileMemoryStore);
42
27
  private receive;
43
28
  private fail;
44
29
  private request;
45
- start(poll?: boolean): Promise<void>;
46
- check(): Promise<void>;
47
- repair(): Promise<void>;
30
+ start(): Promise<void>;
48
31
  submit(operation: ProfileOperation, immediate?: boolean): Promise<void>;
49
32
  synchronize(): Promise<void>;
33
+ updateCredentials(token: string): Promise<void>;
50
34
  waitForCommand(commandId: string): Promise<void>;
51
35
  voiceAttachment(messageId: string): Promise<Blob | null>;
52
36
  getStatus(): {
@@ -1,67 +1,38 @@
1
1
  import { ProfileMemoryStore, PROFILE_PROTOCOL_VERSION } from "./profileMemoryStore.js";
2
- /** A bounded, volatile history: no extra persistence or full-team snapshot write.
3
- * A producer restart intentionally falls back to a prepared snapshot. */
4
- export class ProfileDeltaJournal {
5
- maxEntries;
6
- maxBytes;
7
- rows = [];
8
- bytes = 0;
9
- constructor(maxEntries = 256, maxBytes = 8 * 1024 * 1024) {
10
- this.maxEntries = maxEntries;
11
- this.maxBytes = maxBytes;
12
- }
13
- append(delta) {
14
- if (this.rows.length && (this.rows.at(-1).delta.generation !== delta.generation || this.rows.at(-1).delta.toRevision !== delta.fromRevision)) {
15
- this.rows = [];
16
- this.bytes = 0;
17
- }
18
- const bytes = new TextEncoder().encode(JSON.stringify(delta)).byteLength;
19
- this.rows.push({ delta, bytes });
20
- this.bytes += bytes;
21
- while (this.rows.length && (this.rows.length > this.maxEntries || this.bytes > this.maxBytes))
22
- this.bytes -= this.rows.shift().bytes;
23
- }
24
- since(generation, revision, current) {
25
- if (generation !== current.activeGeneration || revision === undefined || revision > current.commitRevision)
26
- return;
27
- if (revision === current.commitRevision)
28
- return [];
29
- const start = this.rows.findIndex(row => row.delta.fromRevision === revision && row.delta.generation === generation);
30
- if (start < 0 || this.rows.at(-1)?.delta.toRevision !== current.commitRevision)
31
- return;
32
- return this.rows.slice(start).map(row => row.delta);
33
- }
34
- }
35
- /** Same adapter accepts a Dedicated Worker's message port or BroadcastChannel. */
36
- export function serveProfileOwner(owner, port, scope, onError = () => { }) {
37
- const journal = new ProfileDeltaJournal();
2
+ /** Direct Dedicated Worker port; the rendering document is its only consumer. */
3
+ export function serveProfileWorker(owner, port, scope, onError = () => { }) {
38
4
  const send = (response) => port.postMessage({ ...response, profileProtocol: PROFILE_PROTOCOL_VERSION, scope });
5
+ let generation = owner.current.activeGeneration;
39
6
  const off = owner.subscribeCommitted(delta => {
40
- journal.append(delta);
41
- send({ clientId: "*", delta });
7
+ if (delta.generation !== generation) {
8
+ generation = delta.generation;
9
+ send({ clientId: "*", snapshot: owner.snapshot() });
10
+ }
11
+ else
12
+ send({ clientId: "*", delta });
42
13
  });
43
14
  let active = true;
44
15
  const controller = new AbortController();
45
16
  const listener = (event) => {
46
17
  const request = event.data;
47
- if (!request || request.scope !== scope || !request.requestId || !request.action)
18
+ if (!request || request.scope !== scope || !request.requestId || !request.action || !owner.active)
48
19
  return;
49
20
  void (async () => {
50
21
  if (request.profileProtocol !== PROFILE_PROTOCOL_VERSION)
51
22
  throw Error("PROFILE_PROTOCOL_INCOMPATIBLE");
52
- if (!owner.active)
53
- throw Error("PROFILE_OWNER_UNAVAILABLE");
54
23
  let result;
55
- if (request.action === "catchUp") {
56
- const deltas = journal.since(request.generation, request.revision, owner.current);
57
- result = deltas ? { deltas } : { snapshot: owner.snapshot() };
58
- }
59
- else if (request.action === "status")
60
- result = { generation: owner.current.activeGeneration, revision: owner.current.commitRevision };
24
+ if (request.action === "snapshot")
25
+ result = { snapshot: owner.snapshot() };
61
26
  else if (request.action === "synchronize") {
62
27
  await owner.synchronize();
63
28
  result = null;
64
29
  }
30
+ else if (request.action === "credentials") {
31
+ if (typeof request.token !== "string" || !request.token || request.token.length > 65536)
32
+ throw Error("INVALID_PROFILE_CREDENTIALS");
33
+ owner.updateCredentials(request.token);
34
+ result = null;
35
+ }
65
36
  else if (request.action === "waitCommand") {
66
37
  if (typeof request.commandId !== "string" || !request.commandId)
67
38
  throw Error("INVALID_PROFILE_COMMAND");
@@ -81,10 +52,10 @@ export function serveProfileOwner(owner, port, scope, onError = () => { }) {
81
52
  }
82
53
  else
83
54
  throw Error("INVALID_PROFILE_REQUEST");
84
- if (active)
55
+ if (active && owner.active)
85
56
  send({ clientId: request.clientId, requestId: request.requestId, result });
86
57
  })().catch(error => {
87
- if (!active)
58
+ if (!active || !owner.active)
88
59
  return;
89
60
  try {
90
61
  send({ clientId: request.clientId, requestId: request.requestId, error: error instanceof Error ? error.message : "PROFILE_REQUEST_FAILED" });
@@ -98,9 +69,9 @@ export function serveProfileOwner(owner, port, scope, onError = () => { }) {
98
69
  port.start?.();
99
70
  return () => { active = false; controller.abort(); off(); port.removeEventListener("message", listener); };
100
71
  }
101
- /** UI/WebView replica. Reads and subscriptions use memory; only commands and
102
- * revision repair cross the message boundary. Normal deltas never read disk. */
103
- export class ProfileReplica {
72
+ /** One rendering document consumes committed projections from its own Worker.
73
+ * Ordered port delivery needs no journal, polling or distributed repair. */
74
+ export class ProfileWorkerClient {
104
75
  port;
105
76
  scope;
106
77
  onError;
@@ -108,17 +79,16 @@ export class ProfileReplica {
108
79
  memory;
109
80
  clientId = crypto.randomUUID();
110
81
  requests = new Map();
111
- repairing;
82
+ restoring = true;
112
83
  closed = false;
113
84
  buffered = [];
114
- timer;
115
85
  lastError;
116
- constructor(port, scope, onError = () => { }, timeoutMs = 30000, profileId = "") {
86
+ constructor(port, scope, onError = () => { }, timeoutMs = 30000, profileId = "", memory) {
117
87
  this.port = port;
118
88
  this.scope = scope;
119
89
  this.onError = onError;
120
90
  this.timeoutMs = timeoutMs;
121
- this.memory = new ProfileMemoryStore(onError, profileId);
91
+ this.memory = memory ?? new ProfileMemoryStore(onError, profileId);
122
92
  port.addEventListener("message", this.receive);
123
93
  port.start?.();
124
94
  }
@@ -141,36 +111,39 @@ export class ProfileReplica {
141
111
  else
142
112
  request.resolve(response.result);
143
113
  }
114
+ if (response.snapshot) {
115
+ if (this.restoring)
116
+ return; // The requested startup snapshot follows this message.
117
+ try {
118
+ this.memory.restore(response.snapshot);
119
+ }
120
+ catch (error) {
121
+ this.fail(error);
122
+ }
123
+ }
144
124
  if (response.delta) {
145
- if (this.repairing || this.memory.getStatus().phase === "restoring") {
125
+ if (this.restoring)
146
126
  this.buffered.push(response.delta);
147
- if (!this.repairing)
148
- void this.repair().catch(failure => this.fail(failure));
149
- }
150
- else {
127
+ else
151
128
  try {
152
129
  this.memory.apply(response.delta);
153
130
  }
154
131
  catch (error) {
155
- this.buffered.push(response.delta);
156
- void this.repair().catch(failure => this.fail(failure));
132
+ this.fail(error);
157
133
  }
158
- }
159
- if (this.buffered.length > 256)
160
- this.buffered = this.buffered.slice(-256);
161
134
  }
162
135
  };
163
- fail(error) { this.lastError = error instanceof Error ? error : Error("PROFILE_REPLICA_FAILED"); try {
136
+ fail(error) { this.lastError = error instanceof Error ? error : Error("PROFILE_WORKER_PROTOCOL_FAILED"); try {
164
137
  this.onError(this.lastError);
165
138
  }
166
139
  catch { } }
167
140
  request(action, fields = {}) {
168
141
  if (this.closed)
169
- return Promise.reject(Error("PROFILE_REPLICA_CLOSED"));
142
+ return Promise.reject(Error("PROFILE_WORKER_CLIENT_CLOSED"));
170
143
  const requestId = crypto.randomUUID();
171
144
  return new Promise((resolve, reject) => {
172
- const timeout = action === "status" || action === "catchUp" ? this.timeoutMs : Math.max(this.timeoutMs, 30000);
173
- const timer = setTimeout(() => { this.requests.delete(requestId); reject(Error("PROFILE_OWNER_TIMEOUT")); }, timeout);
145
+ const timeout = action === "snapshot" ? this.timeoutMs : Math.max(this.timeoutMs, 30000);
146
+ const timer = action === "waitCommand" ? undefined : setTimeout(() => { this.requests.delete(requestId); reject(Error("PROFILE_WORKER_TIMEOUT")); }, timeout);
174
147
  this.requests.set(requestId, { resolve, reject, timer });
175
148
  try {
176
149
  this.port.postMessage({ ...fields, profileProtocol: PROFILE_PROTOCOL_VERSION, scope: this.scope, clientId: this.clientId, requestId, action });
@@ -182,37 +155,17 @@ export class ProfileReplica {
182
155
  }
183
156
  });
184
157
  }
185
- async start(poll = true) {
186
- await this.repair();
187
- if (poll && !this.timer)
188
- this.timer = setInterval(() => { void this.check().catch(error => this.fail(error)); }, 10000);
189
- }
190
- async check() {
191
- const remote = await this.request("status"), local = this.memory.getStatus();
192
- if (remote.generation !== local.generation || remote.revision !== local.revision)
193
- await this.repair();
194
- }
195
- repair() {
196
- if (this.repairing)
197
- return this.repairing;
198
- const task = Promise.resolve().then(async () => {
199
- const local = this.memory.getStatus();
200
- const result = await this.request("catchUp", { generation: local.generation, revision: local.revision });
201
- if ("snapshot" in result)
202
- this.memory.restore(result.snapshot);
203
- else
204
- for (const delta of result.deltas)
205
- this.memory.apply(delta);
206
- const buffered = this.buffered;
207
- this.buffered = [];
208
- for (const delta of buffered)
158
+ async start() {
159
+ const result = await this.request("snapshot");
160
+ this.memory.restore(result.snapshot);
161
+ for (const delta of this.buffered) {
162
+ const status = this.memory.getStatus();
163
+ if (delta.generation === status.generation && delta.toRevision > (status.revision ?? -1))
209
164
  this.memory.apply(delta);
210
- this.lastError = undefined;
211
- });
212
- this.repairing = task;
213
- void task.finally(() => { if (this.repairing === task)
214
- this.repairing = undefined; }).catch(() => { });
215
- return task;
165
+ }
166
+ this.buffered = [];
167
+ this.restoring = false;
168
+ this.lastError = undefined;
216
169
  }
217
170
  submit(operation, immediate = false) {
218
171
  const payload = "type" in operation && operation.type === "send" ? operation.command.payload : undefined;
@@ -220,16 +173,16 @@ export class ProfileReplica {
220
173
  return this.request("operation", { operation, bytes: new TextEncoder().encode(JSON.stringify(operation)).byteLength + binaryBytes, immediate });
221
174
  }
222
175
  synchronize() { return this.request("synchronize"); }
176
+ updateCredentials(token) { return this.request("credentials", { token }); }
223
177
  waitForCommand(commandId) { return this.request("waitCommand", { commandId }); }
224
178
  voiceAttachment(messageId) { return this.request("voiceAttachment", { commandId: messageId }); }
225
179
  getStatus() { return { ...this.memory.getStatus(), error: this.lastError }; }
226
180
  close() {
227
181
  this.closed = true;
228
- clearInterval(this.timer);
229
182
  this.port.removeEventListener("message", this.receive);
230
183
  for (const request of this.requests.values()) {
231
184
  clearTimeout(request.timer);
232
- request.reject(Error("PROFILE_REPLICA_CLOSED"));
185
+ request.reject(Error("PROFILE_WORKER_CLIENT_CLOSED"));
233
186
  }
234
187
  this.requests.clear();
235
188
  }
@@ -1,5 +1,5 @@
1
1
  import { ProfileDatabase } from "./profileDatabase.js";
2
- import { ProfileReplica, type ProfileMessagePort } from "./profileReplica.js";
2
+ import { ProfileWorkerClient, type ProfileMessagePort } from "./profileWorkerClient.js";
3
3
  import type { ProfileIdentity } from "./profileStoreTypes.js";
4
4
  export type ProfileWorkerConfiguration = {
5
5
  identity: ProfileIdentity;
@@ -16,18 +16,16 @@ export declare const profileChannelName: (identity: ProfileIdentity) => string;
16
16
  * Identity cannot change within a host; a Profile switch creates another host. */
17
17
  export declare function installProfileWorker(port: ProfileMessagePort, options?: {
18
18
  database?: (identity: ProfileIdentity) => ProfileDatabase;
19
- channel?: (name: string) => ProfileMessagePort & {
20
- close(): void;
21
- };
22
19
  fetch?: typeof fetch;
20
+ locks?: Pick<LockManager, "request"> | null;
23
21
  }): () => Promise<void>;
24
22
  /** The application passes its bundler-created Worker. Worker code and main-page
25
23
  * code ship together, so protocol negotiation precedes any snapshot handoff. */
26
- export declare function openProfileWorker(worker: ProfileMessagePort, configuration: ProfileWorkerConfiguration, timeoutMs?: number): Promise<{
24
+ export declare function openProfileWorker(worker: ProfileMessagePort, configuration: ProfileWorkerConfiguration, timeoutMs?: number, signal?: AbortSignal): Promise<{
27
25
  close: () => Promise<void>;
28
26
  update: (config: ProfileWorkerConfiguration) => Promise<void>;
29
27
  }>;
30
28
  export declare function connectProfileWorker(worker: ProfileMessagePort, configuration: ProfileWorkerConfiguration, timeoutMs?: number): Promise<{
31
- replica: ProfileReplica;
29
+ client: ProfileWorkerClient;
32
30
  close: () => Promise<void>;
33
31
  }>;
@@ -1,17 +1,20 @@
1
1
  import { ProfileDatabase } from "./profileDatabase.js";
2
2
  import { ProfileOwner } from "./profileOwner.js";
3
- import { ProfileReplica, serveProfileOwner } from "./profileReplica.js";
3
+ import { ProfileWorkerClient, serveProfileWorker } from "./profileWorkerClient.js";
4
4
  import { PROFILE_PROTOCOL_VERSION } from "./profileMemoryStore.js";
5
5
  import { ProfileInboxFeed } from "./profileInboxFeed.js";
6
6
  import { ProfileOutboxDispatcher } from "./profileOutboxDispatcher.js";
7
7
  import { ChatClient } from "./chatClient.js";
8
+ import { migrateLegacyInbox } from "./profileLegacyInbox.js";
9
+ import { migrateLegacyOutbox } from "./profileLegacyOutbox.js";
10
+ import { migrateLegacyReading } from "./profileLegacyReading.js";
8
11
  export const profileChannelName = (identity) => `pmate-profile:${JSON.stringify([identity.accountId, identity.appId, identity.profileId])}`;
9
12
  /** Installs the SDK host in a Dedicated Worker, not on the rendering thread.
10
13
  * Identity cannot change within a host; a Profile switch creates another host. */
11
14
  export function installProfileWorker(port, options = {}) {
12
15
  let owner, database;
13
- let channel;
14
16
  let scope, opening;
17
+ let releaseWriterLock;
15
18
  let disposers = [];
16
19
  let feed, dispatcher, connection;
17
20
  let network;
@@ -28,12 +31,12 @@ export function installProfileWorker(port, options = {}) {
28
31
  await opening;
29
32
  await stopNetwork();
30
33
  await owner?.close();
34
+ await releaseWriterLock?.();
35
+ releaseWriterLock = undefined;
31
36
  for (const off of disposers.splice(0))
32
37
  off();
33
38
  owner = undefined;
34
39
  opening = undefined;
35
- channel?.close();
36
- channel = undefined;
37
40
  database?.close();
38
41
  database = undefined;
39
42
  reply(request.requestId, null);
@@ -52,21 +55,36 @@ export function installProfileWorker(port, options = {}) {
52
55
  network = config.network;
53
56
  if (!opening) {
54
57
  opening = (async () => {
58
+ // Lifetime browser admission only: no persisted lease, expiry,
59
+ // renewal, election or handoff. Also excludes older lock-based clients.
60
+ const locks = options.locks === undefined ? globalThis.navigator?.locks : options.locks;
61
+ if (locks)
62
+ releaseWriterLock = await holdProfileWriterLock(locks, `${nextScope}:writer`);
63
+ else if (options.locks !== null)
64
+ throw Error("PROFILE_LOCKS_UNAVAILABLE");
55
65
  database = options.database?.(config.identity) ?? new ProfileDatabase(config.identity);
56
66
  const stored = await database.inboxState.get("current");
57
67
  owner = await ProfileOwner.open({ database, epoch: stored?.epoch ?? config.epoch ?? "uninitialized", windowStart: config.windowStart,
58
68
  onError: error => port.postMessage({ profileControl: "error", error: error instanceof Error ? error.message : "PROFILE_OWNER_FAILED" }) });
59
- channel = options.channel?.(nextScope) ?? new BroadcastChannel(nextScope);
60
- disposers.push(serveProfileOwner(owner, port, nextScope), serveProfileOwner(owner, channel, nextScope));
69
+ disposers.push(serveProfileWorker(owner, port, nextScope));
61
70
  if (network) {
62
71
  const report = (error) => port.postMessage({ profileControl: "error", error: error instanceof Error ? error.message : "PROFILE_NETWORK_FAILED" });
63
72
  const endpoint = network.hubHttpUrl.replace(/\/$/, "").replace(/^ws/, "http");
64
73
  const token = () => network.token;
74
+ owner.setCredentialUpdater(value => {
75
+ network = { ...network, token: value };
76
+ const message = { profileControl: "credentials", token: value };
77
+ port.postMessage(message);
78
+ });
65
79
  connection = new ChatClient({ appId: config.identity.appId, profileId: config.identity.profileId,
66
80
  hubUrl: endpoint.replace(/^http/, "ws"), fetchImpl: options.fetch, getToken: async () => token(),
67
81
  session: { token: token(), identity: { accountId: config.identity.accountId, app: config.identity.appId, profileId: config.identity.profileId } } });
68
- feed = new ProfileInboxFeed({ owner, hubHttpUrl: endpoint, getToken: token, fetch: options.fetch, onError: report,
69
- onProgress: progress => { const message = { profileControl: "progress", progress }; port.postMessage(message); channel?.postMessage(message); } });
82
+ feed = new ProfileInboxFeed({ owner, hubHttpUrl: endpoint, getToken: token, fetch: options.fetch, onError: report, prepare: async () => {
83
+ await migrateLegacyInbox(owner);
84
+ await migrateLegacyOutbox(owner);
85
+ await migrateLegacyReading(owner);
86
+ },
87
+ onProgress: progress => { const message = { profileControl: "progress", progress }; port.postMessage(message); } });
70
88
  owner.setSynchronizer(() => feed.synchronize());
71
89
  dispatcher = new ProfileOutboxDispatcher({ owner, hubHttpUrl: endpoint, getToken: token, fetch: options.fetch,
72
90
  uploadEndpoint: network.uploadEndpoint,
@@ -78,10 +96,10 @@ export function installProfileWorker(port, options = {}) {
78
96
  await stopNetwork();
79
97
  for (const off of disposers.splice(0))
80
98
  off();
81
- channel?.close();
82
- channel = undefined;
83
99
  await owner?.close();
84
100
  owner = undefined;
101
+ await releaseWriterLock?.();
102
+ releaseWriterLock = undefined;
85
103
  database?.close();
86
104
  database = undefined;
87
105
  opening = undefined;
@@ -98,26 +116,29 @@ export function installProfileWorker(port, options = {}) {
98
116
  await opening;
99
117
  await stopNetwork();
100
118
  await owner?.close();
119
+ await releaseWriterLock?.();
120
+ releaseWriterLock = undefined;
101
121
  port.removeEventListener("message", listener);
102
122
  for (const off of disposers.splice(0))
103
123
  off();
104
- channel?.close();
105
124
  database?.close();
106
125
  };
107
126
  }
108
127
  /** The application passes its bundler-created Worker. Worker code and main-page
109
128
  * code ship together, so protocol negotiation precedes any snapshot handoff. */
110
- export async function openProfileWorker(worker, configuration, timeoutMs = 30000) {
129
+ export async function openProfileWorker(worker, configuration, timeoutMs = 30000, signal) {
111
130
  async function control(action, config = configuration) {
131
+ signal?.throwIfAborted();
112
132
  const requestId = crypto.randomUUID();
113
133
  return new Promise((resolve, reject) => {
114
- const timer = setTimeout(() => { worker.removeEventListener("message", receive); reject(Error("PROFILE_WORKER_TIMEOUT")); }, timeoutMs);
134
+ const cleanup = () => { clearTimeout(timer); worker.removeEventListener("message", receive); signal?.removeEventListener("abort", abort); };
135
+ const abort = () => { cleanup(); reject(signal.reason); };
136
+ const timer = setTimeout(() => { cleanup(); reject(Error("PROFILE_WORKER_TIMEOUT")); }, timeoutMs);
115
137
  const receive = (event) => {
116
138
  const response = event.data;
117
139
  if (response?.profileControl !== "result" || response.requestId !== requestId)
118
140
  return;
119
- clearTimeout(timer);
120
- worker.removeEventListener("message", receive);
141
+ cleanup();
121
142
  if (response.protocolVersion !== PROFILE_PROTOCOL_VERSION)
122
143
  reject(Error("PROFILE_PROTOCOL_INCOMPATIBLE"));
123
144
  else if (response.error)
@@ -126,13 +147,13 @@ export async function openProfileWorker(worker, configuration, timeoutMs = 30000
126
147
  resolve();
127
148
  };
128
149
  worker.addEventListener("message", receive);
150
+ signal?.addEventListener("abort", abort, { once: true });
129
151
  worker.start?.();
130
152
  try {
131
153
  worker.postMessage({ profileControl: action, requestId, configuration: config, protocolVersion: PROFILE_PROTOCOL_VERSION });
132
154
  }
133
155
  catch (error) {
134
- clearTimeout(timer);
135
- worker.removeEventListener("message", receive);
156
+ cleanup();
136
157
  reject(error);
137
158
  }
138
159
  });
@@ -143,14 +164,30 @@ export async function openProfileWorker(worker, configuration, timeoutMs = 30000
143
164
  export async function connectProfileWorker(worker, configuration, timeoutMs = 30000) {
144
165
  const scope = profileChannelName(configuration.identity);
145
166
  const host = await openProfileWorker(worker, configuration, timeoutMs);
146
- const replica = new ProfileReplica(worker, scope, undefined, timeoutMs, configuration.identity.profileId);
167
+ const client = new ProfileWorkerClient(worker, scope, undefined, timeoutMs, configuration.identity.profileId);
147
168
  try {
148
- await replica.start();
169
+ await client.start();
149
170
  }
150
171
  catch (error) {
151
- replica.close();
172
+ client.close();
152
173
  await host.close();
153
174
  throw error;
154
175
  }
155
- return { replica, close: async () => { replica.close(); await host.close(); } };
176
+ return { client, close: async () => { client.close(); await host.close(); } };
177
+ }
178
+ /** Refuse a second document instead of creating a distributed replica. */
179
+ async function holdProfileWriterLock(locks, name) {
180
+ return new Promise((resolve, reject) => {
181
+ let release;
182
+ const held = new Promise(done => { release = done; });
183
+ const request = locks.request(name, { mode: "exclusive", ifAvailable: true }, lock => {
184
+ if (!lock) {
185
+ reject(Error("PROFILE_ALREADY_OPEN"));
186
+ return;
187
+ }
188
+ resolve(async () => { release(); await request; });
189
+ return held;
190
+ });
191
+ void request.catch(reject);
192
+ });
156
193
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pmate/chat-sdk",
3
- "version": "0.13.0-profile.1",
3
+ "version": "0.13.0-profile.10",
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",
@@ -98,7 +98,7 @@
98
98
  "scripts": {
99
99
  "clean": "rimraf lib",
100
100
  "build": "pnpm run clean && tsc -p tsconfig.build.json && cp src/voice/recorder-processor.js lib/voice/recorder-processor.js",
101
- "npm:publish": "pnpm run build && npm publish --access public --registry https://registry.npmjs.org/",
101
+ "npm:publish": "pnpm publish --access public --registry https://registry.npmjs.org/",
102
102
  "test": "vitest run",
103
103
  "storybook": "storybook dev -p 6009",
104
104
  "build-storybook": "storybook build --output-dir dist"