@pmate/chat-sdk 0.13.0-profile.7 → 0.13.0-profile.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
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";
@@ -13,8 +13,8 @@ export const profileChannelName = (identity) => `pmate-profile:${JSON.stringify(
13
13
  * Identity cannot change within a host; a Profile switch creates another host. */
14
14
  export function installProfileWorker(port, options = {}) {
15
15
  let owner, database;
16
- let channel;
17
16
  let scope, opening;
17
+ let releaseWriterLock;
18
18
  let disposers = [];
19
19
  let feed, dispatcher, connection;
20
20
  let network;
@@ -31,12 +31,12 @@ export function installProfileWorker(port, options = {}) {
31
31
  await opening;
32
32
  await stopNetwork();
33
33
  await owner?.close();
34
+ await releaseWriterLock?.();
35
+ releaseWriterLock = undefined;
34
36
  for (const off of disposers.splice(0))
35
37
  off();
36
38
  owner = undefined;
37
39
  opening = undefined;
38
- channel?.close();
39
- channel = undefined;
40
40
  database?.close();
41
41
  database = undefined;
42
42
  reply(request.requestId, null);
@@ -55,12 +55,18 @@ export function installProfileWorker(port, options = {}) {
55
55
  network = config.network;
56
56
  if (!opening) {
57
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");
58
65
  database = options.database?.(config.identity) ?? new ProfileDatabase(config.identity);
59
66
  const stored = await database.inboxState.get("current");
60
67
  owner = await ProfileOwner.open({ database, epoch: stored?.epoch ?? config.epoch ?? "uninitialized", windowStart: config.windowStart,
61
68
  onError: error => port.postMessage({ profileControl: "error", error: error instanceof Error ? error.message : "PROFILE_OWNER_FAILED" }) });
62
- channel = options.channel?.(nextScope) ?? new BroadcastChannel(nextScope);
63
- disposers.push(serveProfileOwner(owner, port, nextScope), serveProfileOwner(owner, channel, nextScope));
69
+ disposers.push(serveProfileWorker(owner, port, nextScope));
64
70
  if (network) {
65
71
  const report = (error) => port.postMessage({ profileControl: "error", error: error instanceof Error ? error.message : "PROFILE_NETWORK_FAILED" });
66
72
  const endpoint = network.hubHttpUrl.replace(/\/$/, "").replace(/^ws/, "http");
@@ -69,7 +75,6 @@ export function installProfileWorker(port, options = {}) {
69
75
  network = { ...network, token: value };
70
76
  const message = { profileControl: "credentials", token: value };
71
77
  port.postMessage(message);
72
- channel?.postMessage(message);
73
78
  });
74
79
  connection = new ChatClient({ appId: config.identity.appId, profileId: config.identity.profileId,
75
80
  hubUrl: endpoint.replace(/^http/, "ws"), fetchImpl: options.fetch, getToken: async () => token(),
@@ -79,7 +84,7 @@ export function installProfileWorker(port, options = {}) {
79
84
  await migrateLegacyOutbox(owner);
80
85
  await migrateLegacyReading(owner);
81
86
  },
82
- onProgress: progress => { const message = { profileControl: "progress", progress }; port.postMessage(message); channel?.postMessage(message); } });
87
+ onProgress: progress => { const message = { profileControl: "progress", progress }; port.postMessage(message); } });
83
88
  owner.setSynchronizer(() => feed.synchronize());
84
89
  dispatcher = new ProfileOutboxDispatcher({ owner, hubHttpUrl: endpoint, getToken: token, fetch: options.fetch,
85
90
  uploadEndpoint: network.uploadEndpoint,
@@ -91,10 +96,10 @@ export function installProfileWorker(port, options = {}) {
91
96
  await stopNetwork();
92
97
  for (const off of disposers.splice(0))
93
98
  off();
94
- channel?.close();
95
- channel = undefined;
96
99
  await owner?.close();
97
100
  owner = undefined;
101
+ await releaseWriterLock?.();
102
+ releaseWriterLock = undefined;
98
103
  database?.close();
99
104
  database = undefined;
100
105
  opening = undefined;
@@ -111,26 +116,29 @@ export function installProfileWorker(port, options = {}) {
111
116
  await opening;
112
117
  await stopNetwork();
113
118
  await owner?.close();
119
+ await releaseWriterLock?.();
120
+ releaseWriterLock = undefined;
114
121
  port.removeEventListener("message", listener);
115
122
  for (const off of disposers.splice(0))
116
123
  off();
117
- channel?.close();
118
124
  database?.close();
119
125
  };
120
126
  }
121
127
  /** The application passes its bundler-created Worker. Worker code and main-page
122
128
  * code ship together, so protocol negotiation precedes any snapshot handoff. */
123
- export async function openProfileWorker(worker, configuration, timeoutMs = 30000) {
129
+ export async function openProfileWorker(worker, configuration, timeoutMs = 30000, signal) {
124
130
  async function control(action, config = configuration) {
131
+ signal?.throwIfAborted();
125
132
  const requestId = crypto.randomUUID();
126
133
  return new Promise((resolve, reject) => {
127
- 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);
128
137
  const receive = (event) => {
129
138
  const response = event.data;
130
139
  if (response?.profileControl !== "result" || response.requestId !== requestId)
131
140
  return;
132
- clearTimeout(timer);
133
- worker.removeEventListener("message", receive);
141
+ cleanup();
134
142
  if (response.protocolVersion !== PROFILE_PROTOCOL_VERSION)
135
143
  reject(Error("PROFILE_PROTOCOL_INCOMPATIBLE"));
136
144
  else if (response.error)
@@ -139,13 +147,13 @@ export async function openProfileWorker(worker, configuration, timeoutMs = 30000
139
147
  resolve();
140
148
  };
141
149
  worker.addEventListener("message", receive);
150
+ signal?.addEventListener("abort", abort, { once: true });
142
151
  worker.start?.();
143
152
  try {
144
153
  worker.postMessage({ profileControl: action, requestId, configuration: config, protocolVersion: PROFILE_PROTOCOL_VERSION });
145
154
  }
146
155
  catch (error) {
147
- clearTimeout(timer);
148
- worker.removeEventListener("message", receive);
156
+ cleanup();
149
157
  reject(error);
150
158
  }
151
159
  });
@@ -156,14 +164,30 @@ export async function openProfileWorker(worker, configuration, timeoutMs = 30000
156
164
  export async function connectProfileWorker(worker, configuration, timeoutMs = 30000) {
157
165
  const scope = profileChannelName(configuration.identity);
158
166
  const host = await openProfileWorker(worker, configuration, timeoutMs);
159
- const replica = new ProfileReplica(worker, scope, undefined, timeoutMs, configuration.identity.profileId);
167
+ const client = new ProfileWorkerClient(worker, scope, undefined, timeoutMs, configuration.identity.profileId);
160
168
  try {
161
- await replica.start();
169
+ await client.start();
162
170
  }
163
171
  catch (error) {
164
- replica.close();
172
+ client.close();
165
173
  await host.close();
166
174
  throw error;
167
175
  }
168
- 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
+ });
169
193
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pmate/chat-sdk",
3
- "version": "0.13.0-profile.7",
3
+ "version": "0.13.0-profile.9",
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"