@mdbase-dev/sdk 0.1.0-beta.187 → 0.1.0-beta.188
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 +188 -953
- package/dist/app-grant/client.js +7 -3
- package/dist/app-grant/client.js.map +1 -1
- package/dist/app-grant/setup.js +2 -2
- package/dist/app-grant/setup.js.map +1 -1
- package/dist/app-host/cloud-copy-host.js +1 -1
- package/dist/app-host/cloud-copy-host.js.map +1 -1
- package/dist/app-host/collection-readiness.js +10 -12
- package/dist/app-host/collection-readiness.js.map +1 -1
- package/dist/app-host/handover.js +1 -1
- package/dist/app-host/handover.js.map +1 -1
- package/dist/app-host/initial-sync.js +4 -4
- package/dist/app-host/initial-sync.js.map +1 -1
- package/dist/application/browser-capabilities.d.ts +1 -1
- package/dist/application/browser-capabilities.js +3 -2
- package/dist/application/browser-capabilities.js.map +1 -1
- package/dist/application/configuration.js +12 -12
- package/dist/application/configuration.js.map +1 -1
- package/dist/application/entry.d.ts +51 -107
- package/dist/application/entry.js +139 -86
- package/dist/application/entry.js.map +1 -1
- package/dist/application/front-door.d.ts +30 -12
- package/dist/application/front-door.js +2 -89
- package/dist/application/front-door.js.map +1 -1
- package/dist/application/phase.d.ts +4 -1
- package/dist/application/phase.js +5 -4
- package/dist/application/phase.js.map +1 -1
- package/dist/application/private-collections.js +2 -1
- package/dist/application/private-collections.js.map +1 -1
- package/dist/application/registration-refusal.d.ts +1 -1
- package/dist/application/registration-refusal.js +1 -3
- package/dist/application/registration-refusal.js.map +1 -1
- package/dist/application/registration.js +1 -4
- package/dist/application/registration.js.map +1 -1
- package/dist/application/setup.d.ts +6 -9
- package/dist/application/setup.js +16 -0
- package/dist/application/setup.js.map +1 -1
- package/dist/application/tabs.d.ts +15 -2
- package/dist/application/tabs.js +35 -13
- package/dist/application/tabs.js.map +1 -1
- package/dist/application/unsynced-transfer.d.ts +1 -1
- package/dist/application/unsynced-transfer.js +3 -3
- package/dist/application/unsynced-transfer.js.map +1 -1
- package/dist/application/worker.js +928 -449
- package/dist/browser/mdbase-sdk.js +21271 -20750
- package/dist/browser/mdbase-sdk.min.js +65 -65
- package/dist/browser.d.ts +1 -0
- package/dist/browser.js +1 -0
- package/dist/browser.js.map +1 -1
- package/dist/client.d.ts +169 -81
- package/dist/client.js +236 -178
- package/dist/client.js.map +1 -1
- package/dist/codec.d.ts +15 -0
- package/dist/codec.js +44 -2
- package/dist/codec.js.map +1 -1
- package/dist/collection-api.d.ts +44 -0
- package/dist/collection-api.js +24 -0
- package/dist/collection-api.js.map +1 -0
- package/dist/collection-availability.js +1 -1
- package/dist/collection-availability.js.map +1 -1
- package/dist/contract-query.d.ts +22 -3
- package/dist/contract-query.js.map +1 -1
- package/dist/contract-records.d.ts +2 -1
- package/dist/contract-records.js.map +1 -1
- package/dist/describe-error.d.ts +1 -1
- package/dist/describe-error.js +7 -6
- package/dist/describe-error.js.map +1 -1
- package/dist/errors.d.ts +3 -5
- package/dist/errors.js +3 -8
- package/dist/errors.js.map +1 -1
- package/dist/files.d.ts +7 -5
- package/dist/files.js +16 -17
- package/dist/files.js.map +1 -1
- package/dist/holds.d.ts +2 -1
- package/dist/holds.js.map +1 -1
- package/dist/index.d.ts +7 -11
- package/dist/index.js +5 -7
- package/dist/index.js.map +1 -1
- package/dist/live.d.ts +2 -1
- package/dist/live.js.map +1 -1
- package/dist/manifest.d.ts +1 -1
- package/dist/manifest.js +1 -1
- package/dist/native/provenance.json +1 -1
- package/dist/people.js +3 -7
- package/dist/people.js.map +1 -1
- package/dist/plain.d.ts +102 -0
- package/dist/plain.js +62 -0
- package/dist/plain.js.map +1 -0
- package/dist/presence.d.ts +2 -1
- package/dist/presence.js +3 -3
- package/dist/presence.js.map +1 -1
- package/dist/read-helpers.d.ts +8 -6
- package/dist/read-helpers.js +20 -13
- package/dist/read-helpers.js.map +1 -1
- package/dist/record-set.d.ts +98 -0
- package/dist/record-set.js +347 -0
- package/dist/record-set.js.map +1 -0
- package/dist/records/session.d.ts +2 -1
- package/dist/records/session.js +22 -20
- package/dist/records/session.js.map +1 -1
- package/dist/records/types.d.ts +5 -3
- package/dist/records/witness.d.ts +7 -4
- package/dist/records/witness.js +13 -8
- package/dist/records/witness.js.map +1 -1
- package/dist/records.js +5 -2
- package/dist/records.js.map +1 -1
- package/dist/saved-views.d.ts +12 -4
- package/dist/saved-views.js +51 -43
- package/dist/saved-views.js.map +1 -1
- package/dist/settle.d.ts +62 -0
- package/dist/settle.js +119 -0
- package/dist/settle.js.map +1 -0
- package/dist/status.d.ts +84 -28
- package/dist/status.js +54 -48
- package/dist/status.js.map +1 -1
- package/dist/testing/application.d.ts +16 -9
- package/dist/testing/application.js +48 -45
- package/dist/testing/application.js.map +1 -1
- package/dist/testing/index.d.ts +2 -2
- package/dist/testing/memory-contracts.d.ts +5 -0
- package/dist/testing/memory-contracts.js.map +1 -1
- package/dist/testing/memory-replica.d.ts +58 -5
- package/dist/testing/memory-replica.js +126 -19
- package/dist/testing/memory-replica.js.map +1 -1
- package/dist/testing/test-app.d.ts +9 -10
- package/dist/testing/test-app.js +8 -17
- package/dist/testing/test-app.js.map +1 -1
- package/dist/thin-client.d.ts +15 -38
- package/dist/thin-client.js +11 -20
- package/dist/thin-client.js.map +1 -1
- package/dist/transport/control-route.js +1 -1
- package/dist/transport/control-route.js.map +1 -1
- package/dist/transport/relay-close.d.ts +0 -1
- package/dist/transport/relay-close.js +4 -2
- package/dist/transport/relay-close.js.map +1 -1
- package/dist/transport/relay-pipe.js +2 -2
- package/dist/transport/relay-pipe.js.map +1 -1
- package/dist/type-packs.js +4 -4
- package/dist/type-packs.js.map +1 -1
- package/dist/validation.d.ts +1 -1
- package/dist/validation.js +2 -2
- package/dist/validation.js.map +1 -1
- package/dist/values.d.ts +4 -20
- package/dist/values.js +3 -49
- package/dist/values.js.map +1 -1
- package/dist/view-sources.d.ts +2 -1
- package/dist/view-sources.js +1 -1
- package/dist/view-sources.js.map +1 -1
- package/dist/wire.d.ts +7 -3
- package/dist/wire.js +4 -4
- package/dist/wire.js.map +1 -1
- package/dist/write-ledger.d.ts +2 -1
- package/dist/write-ledger.js +3 -6
- package/dist/write-ledger.js.map +1 -1
- package/package.json +1 -1
|
@@ -37,9 +37,9 @@ function whenVisible(signal) {
|
|
|
37
37
|
signal.addEventListener("abort", stop, { once: true });
|
|
38
38
|
});
|
|
39
39
|
}
|
|
40
|
-
import { unresolvedSetup } from "./setup.js";
|
|
40
|
+
import { setupResult, unresolvedSetup } from "./setup.js";
|
|
41
41
|
import { applicationPhase, SLOW_OPENING_MS } from "./phase.js";
|
|
42
|
-
import {
|
|
42
|
+
import { BRIEF_PENDING_MS, LONG_PENDING_MS, summarizeSync } from "../status.js";
|
|
43
43
|
import { applicationForgotten } from "./forgotten.js";
|
|
44
44
|
import { applicationSessionHint } from "./session-hint.js";
|
|
45
45
|
import { ApplicationPrivateCollections, withPrivateCollections } from "./private-collections.js";
|
|
@@ -59,7 +59,7 @@ function withoutUnsynced(raw) {
|
|
|
59
59
|
}
|
|
60
60
|
export class MdbaseApplicationUnavailableError extends Error {
|
|
61
61
|
code = "application_not_yet_available";
|
|
62
|
-
constructor() { super("
|
|
62
|
+
constructor() { super("mdbase cannot run in this context"); this.name = "MdbaseApplicationUnavailableError"; }
|
|
63
63
|
}
|
|
64
64
|
const problem = Object.freeze({ code: "application_not_yet_available" });
|
|
65
65
|
const facet = Object.freeze({ checking: false, assessment: null, problem });
|
|
@@ -74,18 +74,28 @@ const noSelection = Object.freeze({ state: "none", problem: null, usable: null,
|
|
|
74
74
|
/** Honest shell where the SDK cannot host its own module Worker (SSR, Node,
|
|
75
75
|
* non-browser tests, non-web origins). Performs no registration, key, Worker,
|
|
76
76
|
* storage, network or popup IO and never returns a fake client/READY state. */
|
|
77
|
-
function unavailableApplication() {
|
|
77
|
+
function unavailableApplication(messages) {
|
|
78
78
|
const base = { status: "blocked", signIn: null, collections: Object.freeze([]), selectedCollectionId: null, problem: problem.code, timing: null, readiness, selection: noSelection };
|
|
79
|
-
const snapshot = Object.freeze({ ...base, phase: applicationPhase(base), sync: null, writes: null, links: null });
|
|
79
|
+
const snapshot = Object.freeze({ ...base, phase: applicationPhase(base, messages ? { messages } : {}), sync: null, writes: null, links: null });
|
|
80
80
|
const refuse = () => Promise.reject(unavailable());
|
|
81
|
-
return Object.freeze({ getSnapshot: () => snapshot, subscribe: () => () => { }, start: refuse,
|
|
82
|
-
assess: refuse, configure: refuse, setup: Object.freeze({ plan: refuse, apply: refuse }),
|
|
81
|
+
return Object.freeze({ getSnapshot: () => snapshot, subscribe: () => () => { }, start: refuse, signIn: refuse, addCollection: refuse, select: refuse, approve: refuse, reauthorize: refuse, refreshCollectionList: refuse, requestAccess: refuse, chooseAnother: refuse,
|
|
82
|
+
assess: refuse, configure: refuse, setup: Object.freeze({ plan: refuse, apply: refuse }), forget: refuse, deleteCollection: refuse, unlock: refuse, connection: () => null, setForeground() { throw unavailable(); }, close: refuse, signOut: refuse,
|
|
83
|
+
unsynced: Object.freeze({ open: refuse, planTransfer: refuse, transfer: refuse, discard: refuse }) });
|
|
83
84
|
}
|
|
84
85
|
/** A host factory's Worker may come from another realm (a parent document's
|
|
85
86
|
* `Worker`), so it is checked by shape rather than `instanceof`. */
|
|
86
87
|
const isWorker = (value) => typeof value === "object" && value !== null &&
|
|
87
88
|
["postMessage", "terminate", "addEventListener", "removeEventListener"].every(name => typeof value[name] === "function");
|
|
88
|
-
const browserHost = (origin) => typeof Worker === "function" && typeof MessageChannel === "function" && currentAppOrigin() !== null && isAppOrigin(origin);
|
|
89
|
+
const browserHost = (origin, runsWorker) => (!runsWorker || typeof Worker === "function") && typeof MessageChannel === "function" && currentAppOrigin() !== null && isAppOrigin(origin);
|
|
90
|
+
function sessionOption(value) {
|
|
91
|
+
if (value === undefined)
|
|
92
|
+
return { build: null, host: true };
|
|
93
|
+
if (!value || typeof value !== "object" || typeof value.build !== "string" || !value.build || value.build.length > 128 || /[\u0000-\u001f\u007f]/.test(value.build))
|
|
94
|
+
throw new TypeError("session.build must be a short non-empty string");
|
|
95
|
+
if (value.host !== undefined && typeof value.host !== "boolean")
|
|
96
|
+
throw new TypeError("session.host must be a boolean");
|
|
97
|
+
return { build: value.build, host: value.host !== false };
|
|
98
|
+
}
|
|
89
99
|
function signInOpener(value, declaration) {
|
|
90
100
|
if (value === undefined)
|
|
91
101
|
return null;
|
|
@@ -138,16 +148,15 @@ function selectionMemory(namespace) {
|
|
|
138
148
|
}
|
|
139
149
|
catch { /* hint storage is optional */ } } });
|
|
140
150
|
}
|
|
141
|
-
/** The
|
|
142
|
-
*
|
|
143
|
-
* Declaration-only public entry. Construction is IO-free; SDK registration,
|
|
151
|
+
/** The entry behind `createMdbase(declaration)`: internal, apps hold its
|
|
152
|
+
* `mdbase`. Declaration-only. Construction is IO-free; SDK registration,
|
|
144
153
|
* same-artifact Worker and original profile/SQL start lazily on the first
|
|
145
154
|
* action. The URL names the requested collection; sign-in approval decides what
|
|
146
155
|
* opens. No private authority hooks, replacement actors or transport-only
|
|
147
156
|
* READY: a host's `worker` factory only constructs the SDK's own Worker, which
|
|
148
157
|
* checks its bootstrap and assets as always. */
|
|
149
|
-
export class
|
|
150
|
-
|
|
158
|
+
export class MdbaseEntry {
|
|
159
|
+
mdbase;
|
|
151
160
|
declaration;
|
|
152
161
|
compiled;
|
|
153
162
|
lifetime = new AbortController();
|
|
@@ -180,6 +189,7 @@ export class MdbaseConnect {
|
|
|
180
189
|
revision = 0;
|
|
181
190
|
links = null;
|
|
182
191
|
cpOrigin = null;
|
|
192
|
+
messages;
|
|
183
193
|
opening = null;
|
|
184
194
|
syncing = null;
|
|
185
195
|
/** On-device storage policy for this origin; null where it cannot be read. */
|
|
@@ -188,6 +198,8 @@ export class MdbaseConnect {
|
|
|
188
198
|
signIn;
|
|
189
199
|
typeIssues;
|
|
190
200
|
createWorker;
|
|
201
|
+
/** The `session` option: the app's own build name, and whether this context may run the Worker. */
|
|
202
|
+
session;
|
|
191
203
|
/** SDK-10: this tab's Private collections (page-side thin clients, never the Worker). */
|
|
192
204
|
privates = null;
|
|
193
205
|
/** Open the unsynced collection when started signed out; tried once per start. */
|
|
@@ -210,9 +222,13 @@ export class MdbaseConnect {
|
|
|
210
222
|
if (options.worker !== undefined && typeof options.worker !== "function")
|
|
211
223
|
throw new TypeError("worker must be a function");
|
|
212
224
|
this.createWorker = options.worker ?? null;
|
|
225
|
+
this.messages = options.messages;
|
|
226
|
+
this.session = sessionOption(options.session);
|
|
227
|
+
if (!this.session.host && this.createWorker)
|
|
228
|
+
throw new TypeError("worker has no effect with session.host: false");
|
|
213
229
|
this.signIn = signInOpener(options.signIn, this.declaration);
|
|
214
|
-
if (!browserHost(this.declaration.origin)) {
|
|
215
|
-
this.
|
|
230
|
+
if (!browserHost(this.declaration.origin, this.session.host)) {
|
|
231
|
+
this.mdbase = unavailableApplication(options.messages);
|
|
216
232
|
return;
|
|
217
233
|
}
|
|
218
234
|
try {
|
|
@@ -228,6 +244,7 @@ export class MdbaseConnect {
|
|
|
228
244
|
this.followPageLifecycle();
|
|
229
245
|
this.followFocus();
|
|
230
246
|
this.followStoragePolicy();
|
|
247
|
+
this.followNetwork();
|
|
231
248
|
this.memory = selectionMemory(this.declaration.storage.applicationNamespace);
|
|
232
249
|
if (options.privateCollections !== false)
|
|
233
250
|
this.privates = new ApplicationPrivateCollections({ declaration: this.declaration, onChange: () => { this.revision++; this.notify(); } });
|
|
@@ -235,7 +252,7 @@ export class MdbaseConnect {
|
|
|
235
252
|
session: this.selectionSession(), memory: this.memory });
|
|
236
253
|
this.selection.subscribe(() => { this.unforgetApproved(); this.notify(false); });
|
|
237
254
|
const view = () => this.getSnapshot();
|
|
238
|
-
this.
|
|
255
|
+
this.mdbase = Object.freeze({ getSnapshot: view, subscribe: (listener) => { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; },
|
|
239
256
|
start: (options) => this.track(() => {
|
|
240
257
|
// Until this start settles, signed out is a step towards work before
|
|
241
258
|
// connecting, so the sign-in screen is not shown and then replaced.
|
|
@@ -275,20 +292,19 @@ export class MdbaseConnect {
|
|
|
275
292
|
this.notify(false);
|
|
276
293
|
} });
|
|
277
294
|
}),
|
|
278
|
-
|
|
295
|
+
signIn: (options) => this.track(() => this.approve(undefined, options)),
|
|
279
296
|
approve: (id, options) => this.track(() => this.approve(id, options)),
|
|
280
297
|
reauthorize: (options) => this.track(() => {
|
|
281
298
|
const selection = this.choose(), snapshot = selection.getSnapshot();
|
|
282
299
|
const id = this.privates?.state()?.collectionId ?? snapshot.usable?.collectionId ?? snapshot.requested.collectionId;
|
|
283
300
|
return id ? this.approve(id, options) : selection.reauthorize(options);
|
|
284
301
|
}),
|
|
285
|
-
|
|
302
|
+
addCollection: (options) => this.track(() => this.approve(null, options)),
|
|
286
303
|
refreshCollectionList: (options) => this.track(() => Promise.all([this.call(runtime => runtime.queue(() => runtime.refreshCollections(options))), this.privates?.refresh(this.account()).catch(() => { })])),
|
|
287
304
|
requestAccess: (request, options) => this.requestAccess(request, options),
|
|
288
305
|
// The person switching collections: a pushed history entry, so Back
|
|
289
306
|
// returns to the previous one. SDK corrections replace the entry.
|
|
290
307
|
select: (id, options) => this.track(() => this.choose().select(id, { ...options, history: "push" })),
|
|
291
|
-
clearSelection: (options) => this.track(() => this.choose().select(null, options)),
|
|
292
308
|
chooseAnother: (options) => this.track(() => this.choose().chooseAnother(options)),
|
|
293
309
|
forget: (id, options) => this.track(async () => {
|
|
294
310
|
// SDK-3: hidden on this device for this account, across reloads; a later
|
|
@@ -327,34 +343,37 @@ export class MdbaseConnect {
|
|
|
327
343
|
setup: Object.freeze({
|
|
328
344
|
plan: (options) => (this.privates?.isOpen() ? this.privates.plan(options) : this.call(runtime => runtime.queue(() => runtime.planSetup(options))))
|
|
329
345
|
.then(plan => unresolvedSetup(plan, this.getSnapshot().readiness)),
|
|
330
|
-
apply: (plan, options) => this.track(() => this.privates?.isOpen() ? this.privates.apply(plan, options) : this.call(runtime => runtime.queue(() => runtime.applySetup(plan, options)))),
|
|
346
|
+
apply: (plan, options) => setupResult(this.track(() => this.privates?.isOpen() ? this.privates.apply(plan, options) : this.call(runtime => runtime.queue(() => runtime.applySetup(plan, options)))), view),
|
|
331
347
|
}),
|
|
348
|
+
connection: (id) => this.connection(id),
|
|
332
349
|
setForeground: (active) => this.setForeground(active), close: () => this.close(),
|
|
333
350
|
signOut: (options) => this.signOut(options),
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
351
|
+
unsynced: Object.freeze({
|
|
352
|
+
planTransfer: (options = {}) => this.call(runtime => {
|
|
353
|
+
const destination = this.transferDestination(null);
|
|
354
|
+
return runtime.withUnsyncedSource((source, signal) => planUnsyncedTransfer(source.records, destination.records, { ...(options.map ? { map: options.map } : {}), ...(options.addTypes ? { addTypes: true } : {}), ledger: this.transferLedger(), signal }), options);
|
|
355
|
+
}),
|
|
356
|
+
transfer: (plan, options = {}) => this.call(async (runtime) => {
|
|
357
|
+
const destination = this.transferDestination(plan?.destination ?? null);
|
|
358
|
+
const result = await runUnsyncedTransfer(plan, destination.records, { ...(options.signal ? { signal: options.signal } : {}), ...(options.onProgress ? { onProgress: options.onProgress } : {}) });
|
|
359
|
+
// A type that could not be added stays only in the unsynced collection's definitions.
|
|
360
|
+
if (result.failed.length || result.failedTypes.length)
|
|
361
|
+
return result;
|
|
362
|
+
// Retire only when planning again finds nothing left: work saved after
|
|
363
|
+
// the plan (here or in another tab) is not left behind.
|
|
364
|
+
const request = options.signal ? { signal: options.signal } : {};
|
|
365
|
+
if (!await runtime.withUnsyncedSource((source, signal) => unsyncedTransferComplete(plan, source.records, destination.records, signal), request))
|
|
366
|
+
return result;
|
|
367
|
+
return Object.freeze({ ...result, retired: await runtime.retireUnsynced(plan.source, plan.destination, request) });
|
|
368
|
+
}),
|
|
369
|
+
discard: (options) => this.track(async () => { await this.call(async (runtime) => { await this.started(runtime, options); return runtime.queue(() => runtime.discardUnsynced(options)); }); }),
|
|
370
|
+
open: (options) => this.track(async () => {
|
|
371
|
+
const selection = this.choose();
|
|
372
|
+
this.privates?.close();
|
|
373
|
+
if (selection.getSnapshot().requested.collectionId !== null)
|
|
374
|
+
await selection.select(null, { ...options, history: "replace" });
|
|
375
|
+
await this.call(async (runtime) => { await this.started(runtime, options); return runtime.queue(() => runtime.openUnsynced(options)); });
|
|
376
|
+
})
|
|
358
377
|
}) });
|
|
359
378
|
}
|
|
360
379
|
/** SDK-10: the session's snapshot with this tab's Private collections listed
|
|
@@ -383,33 +402,42 @@ export class MdbaseConnect {
|
|
|
383
402
|
? Object.freeze({ ...shown, collections: Object.freeze(shown.collections.filter(c => !hidden.has(c.collectionId) || c.collectionId === shown.selectedCollectionId)) }) : shown;
|
|
384
403
|
const id = base.selectedCollectionId, connection = id && !this.closed ? this.privates?.connection(id) ?? this.runtime?.connection(id) ?? null : null;
|
|
385
404
|
const openingUnsynced = this.unsyncedOpening > 0 && !base.unsynced && !base.signOutResult && selection.requested.collectionId === null;
|
|
386
|
-
let phase = applicationPhase({ ...base, selection }, { connection, previous: last?.value.phase ?? null, openingUnsynced, startPending: this.selection?.startPending() ?? false, ...(this.cpOrigin ? { cpOrigin: this.cpOrigin } : {}) });
|
|
405
|
+
let phase = applicationPhase({ ...base, selection }, { connection, previous: last?.value.phase ?? null, openingUnsynced, startPending: this.selection?.startPending() ?? false, ...(this.cpOrigin ? { cpOrigin: this.cpOrigin } : {}), ...(this.messages ? { messages: this.messages } : {}) });
|
|
387
406
|
phase = this.trackOpening(phase);
|
|
388
407
|
this.timing.observe(phase);
|
|
389
|
-
const
|
|
408
|
+
const transport = base.transport ?? null, online = globalThis.navigator?.onLine;
|
|
409
|
+
const status = this.trackSync(phase, transport !== null || online === false);
|
|
390
410
|
const writes = this.syncing?.writes() ?? null;
|
|
391
|
-
const
|
|
392
|
-
const
|
|
411
|
+
const pendingForMs = this.trackPending(Math.max(status?.pending ?? 0, writes?.pending.length ?? 0));
|
|
412
|
+
const saveWarning = status && pendingForMs !== null
|
|
413
|
+
? appSaveState(status.pending, this.storagePolicy ?? { persistent: false, installed: false }, { pendingForMs, connection: status.connection }).warning : null;
|
|
414
|
+
const link = this.syncing?.link();
|
|
415
|
+
const sync = status ? Object.freeze(summarizeSync({ status, writes, problem: base.problem, transport, live: base.live ?? null, storageWarning: saveWarning !== null,
|
|
416
|
+
...(link === undefined ? {} : { link }), ...(typeof online === "boolean" ? { online } : {}), ...(pendingForMs === null ? {} : { pendingForMs }) })) : null;
|
|
417
|
+
const value = Object.freeze({ ...base, selection, phase, sync, storage: this.storagePolicy, saveWarning, links: this.linksFor(id) });
|
|
393
418
|
this.composed = { base: raw, selection, revision: this.revision, hint, value };
|
|
394
419
|
return value;
|
|
395
420
|
}
|
|
396
421
|
linksFor(id) {
|
|
397
422
|
return this.links && id ? Object.freeze({ ...this.links, manageAccess: `${this.cpOrigin}/access?collection=${encodeURIComponent(id)}` }) : this.links;
|
|
398
423
|
}
|
|
399
|
-
/**
|
|
400
|
-
|
|
401
|
-
|
|
424
|
+
/** How long changes have been pending without a break, or null with none:
|
|
425
|
+
* one clock per continuously pending replica, not per edit or request. It
|
|
426
|
+
* wakes the snapshot when a save stops being brief and when it becomes long. */
|
|
427
|
+
trackPending(count) {
|
|
428
|
+
const syncing = this.syncing;
|
|
402
429
|
if (this.pendingSave && (this.closed || this.hidden || !count || this.pendingSave.id !== syncing?.id))
|
|
403
430
|
this.clearPendingSave();
|
|
404
|
-
if (this.closed || this.hidden || !syncing || !
|
|
431
|
+
if (this.closed || this.hidden || !syncing || !count)
|
|
405
432
|
return null;
|
|
406
433
|
if (!this.pendingSave) {
|
|
407
434
|
const pending = { id: syncing.id, since: performance.now(), timer: null };
|
|
408
|
-
|
|
409
|
-
return; pending.timer = null; this.revision++; this.notify(false); }
|
|
435
|
+
const wake = (next) => () => { if (this.pendingSave !== pending)
|
|
436
|
+
return; pending.timer = next === null ? null : setTimeout(wake(null), next); this.revision++; this.notify(false); };
|
|
437
|
+
pending.timer = setTimeout(wake(LONG_PENDING_MS - BRIEF_PENDING_MS), BRIEF_PENDING_MS);
|
|
410
438
|
this.pendingSave = pending;
|
|
411
439
|
}
|
|
412
|
-
return
|
|
440
|
+
return performance.now() - this.pendingSave.since;
|
|
413
441
|
}
|
|
414
442
|
clearPendingSave() {
|
|
415
443
|
if (this.pendingSave?.timer !== null && this.pendingSave?.timer !== undefined)
|
|
@@ -432,8 +460,8 @@ export class MdbaseConnect {
|
|
|
432
460
|
}
|
|
433
461
|
return phase.kind === "opening" && this.opening.slow ? { ...phase, slow: true } : phase;
|
|
434
462
|
}
|
|
435
|
-
/** Follow the open collection's
|
|
436
|
-
trackSync(phase,
|
|
463
|
+
/** Follow the open collection's status, write ledger and link while it is ready. */
|
|
464
|
+
trackSync(phase, deferred) {
|
|
437
465
|
const id = phase.kind === "ready" ? phase.collectionId : null;
|
|
438
466
|
if (this.syncing && this.syncing.id !== id) {
|
|
439
467
|
try {
|
|
@@ -451,10 +479,10 @@ export class MdbaseConnect {
|
|
|
451
479
|
status = records.status;
|
|
452
480
|
}
|
|
453
481
|
catch { /* not yet known */ }
|
|
454
|
-
const syncing = { id: phase.collectionId, stop: () => { }, status, writes: () => null };
|
|
482
|
+
const syncing = { id: phase.collectionId, stop: () => { }, status, writes: () => null, link: () => undefined };
|
|
455
483
|
const changed = () => { if (this.syncing !== syncing)
|
|
456
484
|
return; this.revision++; this.getSnapshot(); this.notify(false); };
|
|
457
|
-
let offStatus = () => { }, offWrites = () => { };
|
|
485
|
+
let offStatus = () => { }, offWrites = () => { }, offLink = () => { };
|
|
458
486
|
try {
|
|
459
487
|
offStatus = records.onStatus(next => { syncing.status = next; changed(); });
|
|
460
488
|
}
|
|
@@ -470,15 +498,25 @@ export class MdbaseConnect {
|
|
|
470
498
|
} };
|
|
471
499
|
}
|
|
472
500
|
catch { /* no ledger */ }
|
|
473
|
-
|
|
501
|
+
try {
|
|
502
|
+
offLink = records.onLink(changed);
|
|
503
|
+
syncing.link = () => { try {
|
|
504
|
+
return records.link;
|
|
505
|
+
}
|
|
506
|
+
catch {
|
|
507
|
+
return undefined;
|
|
508
|
+
} };
|
|
509
|
+
}
|
|
510
|
+
catch { /* link not observable */ }
|
|
511
|
+
syncing.stop = () => { offStatus(); offWrites(); offLink(); };
|
|
474
512
|
this.syncing = syncing;
|
|
475
513
|
}
|
|
476
514
|
// A transport that cannot deliver writes makes pending ones "saved on this device".
|
|
477
515
|
try {
|
|
478
|
-
phase.connection.records.setTransportDeferred(
|
|
516
|
+
phase.connection.records.setTransportDeferred(deferred);
|
|
479
517
|
}
|
|
480
518
|
catch { /* observer only */ }
|
|
481
|
-
return this.syncing.status
|
|
519
|
+
return this.syncing.status;
|
|
482
520
|
}
|
|
483
521
|
nativeAuthorization(call, portal, signal) {
|
|
484
522
|
if (!this.privates || this.closed || this.hidden)
|
|
@@ -623,10 +661,10 @@ export class MdbaseConnect {
|
|
|
623
661
|
const environment = this.environment(), packaged = packagedApplicationAssets(this.declaration.environment, this.declaration.origin);
|
|
624
662
|
// A browser below the SDK's feature floor fails here, once, with a typed
|
|
625
663
|
// problem — before any registration, Worker, key or storage allocation.
|
|
626
|
-
const capabilities = await this.timing.time("capabilities", () => probeBrowserCapabilities());
|
|
664
|
+
const capabilities = await this.timing.time("capabilities", () => probeBrowserCapabilities(undefined, this.session.host));
|
|
627
665
|
this.check();
|
|
628
666
|
if (!capabilities.ok)
|
|
629
|
-
throw mdbaseError("unavailable", "This browser can't run mdbase", { reason: capabilities.problem, details:
|
|
667
|
+
throw mdbaseError("unavailable", "This browser can't run mdbase", { reason: capabilities.problem, details: { missing: capabilities.missing.join(",") } });
|
|
630
668
|
// Registration resolves BEFORE any Worker, key, profile or DB allocation.
|
|
631
669
|
// A first visit registers over the network. Work before connecting opens
|
|
632
670
|
// right after, so the Worker's verified public assets are fetched during
|
|
@@ -673,12 +711,12 @@ export class MdbaseConnect {
|
|
|
673
711
|
const tabs = this.tabsFor(signInScope), election = new AbortController();
|
|
674
712
|
this.election?.abort();
|
|
675
713
|
this.election = election;
|
|
676
|
-
const role =
|
|
714
|
+
const role = await this.timing.time("election", () => tabs.elect(AbortSignal.any([this.lifetime.signal, election.signal])));
|
|
677
715
|
if (this.closed || this.hidden || incarnation !== this.incarnation || election.signal.aborted) {
|
|
678
716
|
if (role.kind === "follower")
|
|
679
717
|
role.leave();
|
|
680
718
|
else
|
|
681
|
-
tabs
|
|
719
|
+
tabs.resign();
|
|
682
720
|
throw mdbaseError("cancelled", "Application entry fenced", "application_entry_fenced");
|
|
683
721
|
}
|
|
684
722
|
if (role.kind === "follower")
|
|
@@ -699,14 +737,14 @@ export class MdbaseConnect {
|
|
|
699
737
|
}
|
|
700
738
|
}
|
|
701
739
|
catch {
|
|
702
|
-
tabs
|
|
740
|
+
tabs.resign();
|
|
703
741
|
channel.port1.close();
|
|
704
742
|
channel.port2.close();
|
|
705
743
|
throw mdbaseError("unavailable", "Application Worker construction unavailable", "application_worker_unavailable");
|
|
706
744
|
}
|
|
707
|
-
const failed = (event) => { event.preventDefault(); channel.port1.dispatchEvent(new MessageEvent("messageerror")); tabs
|
|
745
|
+
const failed = (event) => { event.preventDefault(); channel.port1.dispatchEvent(new MessageEvent("messageerror")); tabs.fault(); };
|
|
708
746
|
worker.addEventListener("error", failed);
|
|
709
|
-
const runtime = new ApplicationRuntime({ declaration, compiledManifest: this.compiled, typeIssues: this.typeIssues, cpOrigin: environment.cpOrigin, port: channel.port1, binding, releaseWorker: () => { worker.removeEventListener("error", failed); worker.terminate(); tabs
|
|
747
|
+
const runtime = new ApplicationRuntime({ declaration, compiledManifest: this.compiled, typeIssues: this.typeIssues, cpOrigin: environment.cpOrigin, port: channel.port1, binding, releaseWorker: () => { worker.removeEventListener("error", failed); worker.terminate(); tabs.resign(); }, nativeAuthorization: (call, portal, signal) => this.nativeAuthorization(call, portal, signal) });
|
|
710
748
|
try {
|
|
711
749
|
worker.postMessage([APPLICATION_WORKER_PROTOCOL, binding, declaration, ...(hosted !== null ? [storageNamespace, hosted] : storageNamespace === null ? [] : [storageNamespace])], [channel.port2]);
|
|
712
750
|
}
|
|
@@ -714,13 +752,13 @@ export class MdbaseConnect {
|
|
|
714
752
|
// No startup request was accepted; the original bootstrap transfer failed.
|
|
715
753
|
worker.removeEventListener("error", failed);
|
|
716
754
|
worker.terminate();
|
|
717
|
-
tabs
|
|
755
|
+
tabs.resign();
|
|
718
756
|
channel.port1.close();
|
|
719
757
|
channel.port2.close();
|
|
720
758
|
throw mdbaseError("unavailable", "Application bootstrap unavailable", "application_worker_binding");
|
|
721
759
|
}
|
|
722
760
|
// Other tabs of this app attach to this Worker through this page.
|
|
723
|
-
tabs
|
|
761
|
+
tabs.lead({ attach: (port, id) => worker.postMessage([APPLICATION_WORKER_PROTOCOL, binding, "attach", id], [port]), detach: id => worker.postMessage([APPLICATION_WORKER_PROTOCOL, binding, "detach", id]) });
|
|
724
762
|
return install(runtime);
|
|
725
763
|
}).catch(error => {
|
|
726
764
|
// Nothing native was allocated (no runtime installed), so a later explicit
|
|
@@ -891,15 +929,12 @@ export class MdbaseConnect {
|
|
|
891
929
|
return;
|
|
892
930
|
void this.signedOut(runtime, result);
|
|
893
931
|
}
|
|
932
|
+
/** This context's tab group. The capability probe has already required Web
|
|
933
|
+
* Locks and BroadcastChannel. */
|
|
894
934
|
tabsFor(scope) {
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
if (!locks || typeof locks.request !== "function" || typeof Channel !== "function")
|
|
899
|
-
return null;
|
|
900
|
-
// The SDK module URL is per build: tabs on different builds never share a Worker.
|
|
901
|
-
this.tabs = new ApplicationTabs({ ...scope, build: import.meta.url }, { locks, BroadcastChannel: Channel }, this.leaderLost, this.signedInElsewhere);
|
|
902
|
-
return this.tabs;
|
|
935
|
+
// The SDK module URL is per build: tabs on different builds never share a
|
|
936
|
+
// Worker. Contexts built separately share one under the app's own build name.
|
|
937
|
+
return this.tabs ??= new ApplicationTabs({ ...scope, build: this.session.build === null ? import.meta.url : `app-build/${this.session.build}` }, { locks: globalThis.navigator.locks, BroadcastChannel: globalThis.BroadcastChannel }, this.leaderLost, this.signedInElsewhere, { lead: this.session.host, wanted: this.hostWanted });
|
|
903
938
|
}
|
|
904
939
|
/** The leader tab went away: start again, as the new leader or a follower of it.
|
|
905
940
|
* If it went because the session signed out, this tab is signed out too: it
|
|
@@ -929,7 +964,15 @@ export class MdbaseConnect {
|
|
|
929
964
|
this.snapshot = Object.freeze({ ...previous, status: "starting", problem: null, selectedCollectionId: null, readiness: emptyReadiness });
|
|
930
965
|
this.notify();
|
|
931
966
|
this.selection?.resync();
|
|
932
|
-
void this.
|
|
967
|
+
void this.mdbase.start().catch(() => { });
|
|
968
|
+
};
|
|
969
|
+
/** A context that cannot run the Worker is waiting, and none runs it: start
|
|
970
|
+
* as this context would on load, unless it is already starting or running. */
|
|
971
|
+
hostWanted = () => {
|
|
972
|
+
if (this.closed || this.hidden || this.signingOut || this.runtime !== null || this.initialization !== null)
|
|
973
|
+
return;
|
|
974
|
+
this.selection?.resync();
|
|
975
|
+
void this.mdbase.start().catch(() => { });
|
|
933
976
|
};
|
|
934
977
|
/** Every tab signed out, then another tab signed in again: follow that
|
|
935
978
|
* session as this tab would on load (no second sign-in or approval). */
|
|
@@ -937,14 +980,14 @@ export class MdbaseConnect {
|
|
|
937
980
|
if (this.closed || this.hidden || this.signingOut || this.runtime !== null || this.initialization !== null || this.snapshot.status !== "signed_out")
|
|
938
981
|
return;
|
|
939
982
|
this.selection?.resync();
|
|
940
|
-
void this.
|
|
983
|
+
void this.mdbase.start().catch(() => { });
|
|
941
984
|
};
|
|
942
985
|
setForeground(active) { this.foreground = active; this.runtime?.setForeground(active); }
|
|
943
986
|
followVisibility() {
|
|
944
987
|
const doc = globalThis.document;
|
|
945
988
|
if (!doc || typeof doc.addEventListener !== "function")
|
|
946
989
|
return;
|
|
947
|
-
// Not through this.
|
|
990
|
+
// Not through this.mdbase: this runs from the constructor, before it exists.
|
|
948
991
|
const sync = () => { if (!this.closed)
|
|
949
992
|
this.setForeground(doc.visibilityState !== "hidden"); };
|
|
950
993
|
const wake = () => { if (doc.visibilityState !== "hidden")
|
|
@@ -957,6 +1000,17 @@ export class MdbaseConnect {
|
|
|
957
1000
|
}
|
|
958
1001
|
sync();
|
|
959
1002
|
}
|
|
1003
|
+
/** `sync.connection` says offline as soon as the browser does, not at the next failed request. */
|
|
1004
|
+
followNetwork() {
|
|
1005
|
+
// `window` in a page; a service worker hears the same events on its own global scope.
|
|
1006
|
+
const scope = typeof window === "undefined" ? globalThis : window;
|
|
1007
|
+
if (typeof scope.addEventListener !== "function")
|
|
1008
|
+
return;
|
|
1009
|
+
const changed = () => { if (this.closed)
|
|
1010
|
+
return; this.revision++; this.notify(false); };
|
|
1011
|
+
scope.addEventListener("online", changed, { signal: this.lifetime.signal });
|
|
1012
|
+
scope.addEventListener("offline", changed, { signal: this.lifetime.signal });
|
|
1013
|
+
}
|
|
960
1014
|
/** Back/forward cache: a page parked there is frozen with its Worker, which
|
|
961
1015
|
* would keep holding the collection lease and block the next document of
|
|
962
1016
|
* this app ("busy"). On pagehide, stop the Worker synchronously (a frozen
|
|
@@ -1007,7 +1061,7 @@ export class MdbaseConnect {
|
|
|
1007
1061
|
// Same path as the app's first start: fresh registration check, Worker and
|
|
1008
1062
|
// session; selection then reopens the requested collection.
|
|
1009
1063
|
this.selection?.resync();
|
|
1010
|
-
void this.
|
|
1064
|
+
void this.mdbase.start().catch(() => { });
|
|
1011
1065
|
};
|
|
1012
1066
|
/** Fallback when tabs cannot share one Worker: another tab of this app on a
|
|
1013
1067
|
* different build (or one still letting go during a leader handover) holds the
|
|
@@ -1028,7 +1082,7 @@ export class MdbaseConnect {
|
|
|
1028
1082
|
if (!current())
|
|
1029
1083
|
return;
|
|
1030
1084
|
this.selection?.resync();
|
|
1031
|
-
void this.
|
|
1085
|
+
void this.mdbase.start().catch(() => { });
|
|
1032
1086
|
}, () => { this.awaitingOtherTab = false; });
|
|
1033
1087
|
}
|
|
1034
1088
|
close() {
|
|
@@ -1068,7 +1122,6 @@ export class MdbaseConnect {
|
|
|
1068
1122
|
});
|
|
1069
1123
|
return this.closing;
|
|
1070
1124
|
}
|
|
1071
|
-
application() { return this.app; }
|
|
1072
1125
|
/** Which revisions of the unsynced collection's records are already in a
|
|
1073
1126
|
* destination, shared by this browser's tabs. */
|
|
1074
1127
|
transferLedger() {
|
|
@@ -1079,7 +1132,7 @@ export class MdbaseConnect {
|
|
|
1079
1132
|
/** The tab's open, ready collection: where an unsynced transfer goes. */
|
|
1080
1133
|
transferDestination(expected) {
|
|
1081
1134
|
const phase = this.getSnapshot().phase;
|
|
1082
|
-
if (phase
|
|
1135
|
+
if (phase.kind !== "ready")
|
|
1083
1136
|
throw mdbaseError("invalid_request", "Open the collection to bring this work into first.", "unsynced_transfer_needs_collection");
|
|
1084
1137
|
if (expected !== null && phase.collectionId !== expected)
|
|
1085
1138
|
throw mdbaseError("invalid_request", "This plan is for another collection. Plan the transfer again.", "unsynced_transfer_plan_stale");
|