mindoodb-app-sdk 0.0.41 → 0.0.42

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.
@@ -0,0 +1,1303 @@
1
+ // src/client/createMindooDBAppBridge.ts
2
+ import { parseMindooDBFormulaBooleanExpression } from "mindoodb-view-language";
3
+
4
+ // src/client/portRpcClient.ts
5
+ var PROTOCOL = "mindoodb-app-bridge";
6
+ function normalizeRpcValue(value, seen = /* @__PURE__ */ new WeakMap()) {
7
+ if (typeof value === "function") {
8
+ throw new Error("Bridge RPC params cannot include functions.");
9
+ }
10
+ if (typeof value === "symbol") {
11
+ throw new Error("Bridge RPC params cannot include symbols.");
12
+ }
13
+ if (value === null || typeof value !== "object") {
14
+ return value;
15
+ }
16
+ if (value instanceof Date) {
17
+ return new Date(value.getTime());
18
+ }
19
+ if (value instanceof ArrayBuffer) {
20
+ return value.slice(0);
21
+ }
22
+ if (ArrayBuffer.isView(value)) {
23
+ return new Uint8Array(value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength));
24
+ }
25
+ if (seen.has(value)) {
26
+ return seen.get(value);
27
+ }
28
+ if (Array.isArray(value)) {
29
+ const copy2 = [];
30
+ seen.set(value, copy2);
31
+ for (const entry of value) {
32
+ copy2.push(normalizeRpcValue(entry, seen));
33
+ }
34
+ return copy2;
35
+ }
36
+ const copy = {};
37
+ seen.set(value, copy);
38
+ for (const [key, entry] of Object.entries(value)) {
39
+ copy[key] = normalizeRpcValue(entry, seen);
40
+ }
41
+ return copy;
42
+ }
43
+ function toBridgeError(error) {
44
+ const wrapped = new Error(error.message);
45
+ wrapped.name = error.code || "MindooDBAppBridgeError";
46
+ return wrapped;
47
+ }
48
+ function isRpcMessage(message) {
49
+ if (!isProtocolMessage(message)) {
50
+ return false;
51
+ }
52
+ return "id" in message && typeof message.id === "string";
53
+ }
54
+ function isProtocolMessage(message) {
55
+ return Boolean(
56
+ message && typeof message === "object" && "protocol" in message && message.protocol === PROTOCOL
57
+ );
58
+ }
59
+ var PortRpcClient = class {
60
+ constructor(port) {
61
+ this.port = port;
62
+ this.handleMessage = this.handleMessage.bind(this);
63
+ this.port.addEventListener("message", this.handleMessage);
64
+ this.port.start();
65
+ }
66
+ port;
67
+ pending = /* @__PURE__ */ new Map();
68
+ listeners = /* @__PURE__ */ new Set();
69
+ requestCounter = 0;
70
+ disposed = false;
71
+ /** Sends one RPC request and resolves with the typed response payload. */
72
+ async call(method, params) {
73
+ if (this.disposed) {
74
+ throw new Error("The bridge connection has already been closed.");
75
+ }
76
+ const normalizedParams = normalizeRpcValue(params);
77
+ const id = `${Date.now()}-${this.requestCounter += 1}`;
78
+ const message = {
79
+ protocol: PROTOCOL,
80
+ kind: "request",
81
+ id,
82
+ method,
83
+ params: normalizedParams
84
+ };
85
+ return await new Promise((resolve, reject) => {
86
+ this.pending.set(id, { resolve, reject });
87
+ try {
88
+ this.port.postMessage(message);
89
+ } catch (error) {
90
+ this.pending.delete(id);
91
+ console.error("MindooDB app bridge RPC postMessage failed.", { method, params: normalizedParams, error });
92
+ reject(error instanceof Error ? error : new Error(String(error)));
93
+ }
94
+ });
95
+ }
96
+ /** Closes the port and rejects any requests that are still waiting for a response. */
97
+ dispose() {
98
+ if (this.disposed) {
99
+ return;
100
+ }
101
+ this.disposed = true;
102
+ this.port.removeEventListener("message", this.handleMessage);
103
+ this.port.close();
104
+ this.pending.forEach(({ reject }) => reject(new Error("The bridge connection was closed.")));
105
+ this.pending.clear();
106
+ this.listeners.clear();
107
+ }
108
+ /** Subscribes to all protocol messages, including attachment stream traffic. */
109
+ addMessageListener(listener) {
110
+ this.listeners.add(listener);
111
+ return () => {
112
+ this.listeners.delete(listener);
113
+ };
114
+ }
115
+ /** Posts a raw protocol message over the port, optionally with transferables. */
116
+ postMessage(message, transfer = []) {
117
+ if (this.disposed) {
118
+ throw new Error("The bridge connection has already been closed.");
119
+ }
120
+ try {
121
+ this.port.postMessage(message, transfer);
122
+ } catch (error) {
123
+ console.error("MindooDB app bridge raw postMessage failed.", { message, transferCount: transfer.length, error });
124
+ throw error;
125
+ }
126
+ }
127
+ /** Dispatches incoming messages to listeners and resolves matching RPC requests. */
128
+ handleMessage(event) {
129
+ if (!isProtocolMessage(event.data)) {
130
+ return;
131
+ }
132
+ const message = event.data;
133
+ this.listeners.forEach((listener) => listener(message));
134
+ if (!isRpcMessage(message)) {
135
+ return;
136
+ }
137
+ if (message.kind !== "success" && message.kind !== "error") {
138
+ return;
139
+ }
140
+ const pending = this.pending.get(message.id);
141
+ if (!pending) {
142
+ return;
143
+ }
144
+ this.pending.delete(message.id);
145
+ if (message.kind === "success") {
146
+ pending.resolve(message.result);
147
+ return;
148
+ }
149
+ pending.reject(toBridgeError(message.error));
150
+ }
151
+ };
152
+
153
+ // src/client/createMindooDBAppBridge.ts
154
+ var PROTOCOL2 = "mindoodb-app-bridge";
155
+ var DEFAULT_CONNECT_TIMEOUT_MS = 1e4;
156
+ function isMethodNotFoundError(error) {
157
+ return error instanceof Error && error.name === "method-not-found";
158
+ }
159
+ function toTransferableArrayBuffer(chunk) {
160
+ return chunk.buffer.slice(
161
+ chunk.byteOffset,
162
+ chunk.byteOffset + chunk.byteLength
163
+ );
164
+ }
165
+ function isStreamChunkFor(streamId, message) {
166
+ return message.kind === "stream-chunk" && message.streamId === streamId;
167
+ }
168
+ function isStreamAckFor(streamId, message) {
169
+ return message.kind === "stream-ack" && message.streamId === streamId;
170
+ }
171
+ function isStreamErrorFor(streamId, message) {
172
+ return message.kind === "stream-error" && message.streamId === streamId;
173
+ }
174
+ function isQueryResultFor(subscriptionId, message) {
175
+ return message.kind === "query-result" && message.subscriptionId === subscriptionId;
176
+ }
177
+ function isViewChangedFor(navigatorId, message) {
178
+ return message.kind === "view-changed" && message.navigatorId === navigatorId;
179
+ }
180
+ function normalizeDocumentQuery(query) {
181
+ if (!query) {
182
+ return {};
183
+ }
184
+ const { filter, ...rest } = query;
185
+ return {
186
+ ...rest,
187
+ ...filter !== void 0 ? {
188
+ filter: typeof filter === "string" ? parseMindooDBFormulaBooleanExpression(filter) : filter
189
+ } : {}
190
+ };
191
+ }
192
+ function isThemeChangedMessage(message) {
193
+ return message.kind === "theme-changed";
194
+ }
195
+ function isViewportChangedMessage(message) {
196
+ return message.kind === "viewport-changed";
197
+ }
198
+ function isUiPreferencesChangedMessage(message) {
199
+ return message.kind === "ui-preferences-changed";
200
+ }
201
+ function isLocaleChangedMessage(message) {
202
+ return message.kind === "locale-changed";
203
+ }
204
+ function toStreamError(message) {
205
+ const error = new Error(message.error.message);
206
+ error.name = message.error.code || "MindooDBAppBridgeStreamError";
207
+ return error;
208
+ }
209
+ function resolveLaunchId(options) {
210
+ if (options?.launchId) {
211
+ return options.launchId;
212
+ }
213
+ if (typeof window === "undefined") {
214
+ throw new Error(
215
+ "A launchId must be provided when connecting outside the browser."
216
+ );
217
+ }
218
+ const search = new URLSearchParams(window.location.search);
219
+ const launchId = search.get("mindoodbAppLaunchId");
220
+ if (!launchId) {
221
+ throw new Error("Missing mindoodbAppLaunchId in the current URL.");
222
+ }
223
+ return launchId;
224
+ }
225
+ function shouldUseWindowedHostTab() {
226
+ if (typeof window === "undefined") {
227
+ return false;
228
+ }
229
+ return window.parent === window && Boolean(window.opener);
230
+ }
231
+ function resolveTargetWindow() {
232
+ if (typeof window === "undefined") {
233
+ throw new Error(
234
+ "The MindooDB app bridge is only available in the browser."
235
+ );
236
+ }
237
+ if (window.parent && window.parent !== window) {
238
+ return window.parent;
239
+ }
240
+ if (window.opener) {
241
+ return window.opener;
242
+ }
243
+ throw new Error("Could not find a MindooDB Haven host window.");
244
+ }
245
+ function waitForConnectedPort(options, launchId) {
246
+ const targetWindow = resolveTargetWindow();
247
+ const targetOrigin = options?.targetOrigin ?? "*";
248
+ const channel = new MessageChannel();
249
+ const timeoutMs = options?.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
250
+ return new Promise((resolve, reject) => {
251
+ let timeoutId = null;
252
+ const cleanup = () => {
253
+ if (timeoutId !== null) {
254
+ window.clearTimeout(timeoutId);
255
+ }
256
+ channel.port1.removeEventListener(
257
+ "message",
258
+ handleMessage
259
+ );
260
+ };
261
+ const handleMessage = (event) => {
262
+ const payload = event.data;
263
+ if (!payload || payload.protocol !== PROTOCOL2) {
264
+ return;
265
+ }
266
+ if (payload.type === "mindoodb-app:connected") {
267
+ cleanup();
268
+ resolve(channel.port1);
269
+ return;
270
+ }
271
+ if (payload.type === "mindoodb-app:error") {
272
+ cleanup();
273
+ channel.port1.close();
274
+ const message2 = typeof payload.error === "string" && payload.error.trim() ? payload.error : "MindooDB Haven bridge connection failed.";
275
+ reject(new Error(message2));
276
+ }
277
+ };
278
+ timeoutId = window.setTimeout(() => {
279
+ cleanup();
280
+ channel.port1.close();
281
+ reject(
282
+ new Error(
283
+ `Timed out while connecting to the MindooDB Haven bridge for launch ${launchId}.`
284
+ )
285
+ );
286
+ }, timeoutMs);
287
+ channel.port1.addEventListener("message", handleMessage);
288
+ channel.port1.start();
289
+ const message = {
290
+ protocol: PROTOCOL2,
291
+ type: "mindoodb-app:connect",
292
+ launchId
293
+ };
294
+ targetWindow.postMessage(message, targetOrigin, [channel.port2]);
295
+ });
296
+ }
297
+ var MindooDBAppViewNavigatorImpl = class {
298
+ constructor(rpc, navigatorId, viewCursor) {
299
+ this.rpc = rpc;
300
+ this.navigatorId = navigatorId;
301
+ this.viewCursor = viewCursor;
302
+ }
303
+ rpc;
304
+ navigatorId;
305
+ viewCursor;
306
+ /** Shorthand: call an RPC method with the navigator ID automatically injected. */
307
+ async call(method, params = {}) {
308
+ return await this.rpc.call(method, {
309
+ navigatorId: this.navigatorId,
310
+ ...params
311
+ });
312
+ }
313
+ async getDefinition() {
314
+ return await this.call("viewNavigators.getDefinition");
315
+ }
316
+ async getViewCursor() {
317
+ return this.viewCursor;
318
+ }
319
+ async refresh() {
320
+ const result = await this.call(
321
+ "viewNavigators.refresh"
322
+ );
323
+ this.viewCursor = result.viewCursor;
324
+ return this.viewCursor;
325
+ }
326
+ onDidUpdate(listener) {
327
+ return this.rpc.addMessageListener((message) => {
328
+ if (isViewChangedFor(this.navigatorId, message)) {
329
+ listener(message.stats);
330
+ }
331
+ });
332
+ }
333
+ async getCurrentEntry() {
334
+ return await this.call("viewNavigators.current.get");
335
+ }
336
+ async gotoFirst() {
337
+ return await this.call("viewNavigators.goto.first");
338
+ }
339
+ async gotoLast() {
340
+ return await this.call("viewNavigators.goto.last");
341
+ }
342
+ async gotoNext() {
343
+ return await this.call("viewNavigators.goto.next");
344
+ }
345
+ async gotoPrev() {
346
+ return await this.call("viewNavigators.goto.prev");
347
+ }
348
+ async gotoNextSibling() {
349
+ return await this.call("viewNavigators.goto.nextSibling");
350
+ }
351
+ async gotoPrevSibling() {
352
+ return await this.call("viewNavigators.goto.prevSibling");
353
+ }
354
+ async gotoParent() {
355
+ return await this.call("viewNavigators.goto.parent");
356
+ }
357
+ async gotoFirstChild() {
358
+ return await this.call("viewNavigators.goto.firstChild");
359
+ }
360
+ async gotoLastChild() {
361
+ return await this.call("viewNavigators.goto.lastChild");
362
+ }
363
+ async gotoPos(position) {
364
+ return await this.call("viewNavigators.goto.pos", { position });
365
+ }
366
+ async getPos(position) {
367
+ return await this.call("viewNavigators.pos.get", { position });
368
+ }
369
+ async findCategoryEntryByParts(parts) {
370
+ return await this.call("viewNavigators.category.findByParts", { parts });
371
+ }
372
+ async entriesForward(options) {
373
+ return await this.call("viewNavigators.entries.forward", {
374
+ options: options ?? {}
375
+ });
376
+ }
377
+ async entriesBackward(options) {
378
+ return await this.call("viewNavigators.entries.backward", {
379
+ options: options ?? {}
380
+ });
381
+ }
382
+ async gotoNextSelected() {
383
+ return await this.call("viewNavigators.goto.nextSelected");
384
+ }
385
+ async gotoPrevSelected() {
386
+ return await this.call("viewNavigators.goto.prevSelected");
387
+ }
388
+ async select(origin, docId, selectParentCategories) {
389
+ await this.call("viewNavigators.selection.select", {
390
+ origin,
391
+ docId,
392
+ selectParentCategories
393
+ });
394
+ }
395
+ async deselect(origin, docId) {
396
+ await this.call("viewNavigators.selection.deselect", { origin, docId });
397
+ }
398
+ async selectAllEntries() {
399
+ await this.call("viewNavigators.selection.selectAll");
400
+ }
401
+ async deselectAllEntries() {
402
+ await this.call("viewNavigators.selection.deselectAll");
403
+ }
404
+ async isSelected(origin, docId) {
405
+ return await this.call("viewNavigators.selection.isSelected", {
406
+ origin,
407
+ docId
408
+ });
409
+ }
410
+ async getSelectionState() {
411
+ return await this.call("viewNavigators.selection.get");
412
+ }
413
+ async setSelectionState(state) {
414
+ await this.call("viewNavigators.selection.set", { state });
415
+ }
416
+ async expand(origin, docId) {
417
+ await this.call("viewNavigators.expansion.expand", { origin, docId });
418
+ }
419
+ async collapse(origin, docId) {
420
+ await this.call("viewNavigators.expansion.collapse", { origin, docId });
421
+ }
422
+ async expandAll() {
423
+ await this.call("viewNavigators.expansion.expandAll");
424
+ }
425
+ async collapseAll() {
426
+ await this.call("viewNavigators.expansion.collapseAll");
427
+ }
428
+ async expandToLevel(level) {
429
+ await this.call("viewNavigators.expansion.expandToLevel", { level });
430
+ }
431
+ async isExpanded(entryKey) {
432
+ return await this.call("viewNavigators.expansion.isExpanded", { entryKey });
433
+ }
434
+ async getExpansionState() {
435
+ return await this.call("viewNavigators.expansion.get");
436
+ }
437
+ async setExpansionState(state) {
438
+ await this.call("viewNavigators.expansion.set", { state });
439
+ }
440
+ async childEntries(entryKey, descending) {
441
+ return await this.call("viewNavigators.children.entries", {
442
+ entryKey,
443
+ descending
444
+ });
445
+ }
446
+ async childCategories(entryKey, descending) {
447
+ return await this.call("viewNavigators.children.categories", {
448
+ entryKey,
449
+ descending
450
+ });
451
+ }
452
+ async childDocuments(entryKey, descending) {
453
+ return await this.call("viewNavigators.children.documents", {
454
+ entryKey,
455
+ descending
456
+ });
457
+ }
458
+ async childCategoriesByKey(entryKey, key, exact, descending) {
459
+ return await this.call("viewNavigators.children.categoriesByKey", {
460
+ entryKey,
461
+ key,
462
+ exact,
463
+ descending
464
+ });
465
+ }
466
+ async childDocumentsByKey(entryKey, key, exact, descending) {
467
+ return await this.call("viewNavigators.children.documentsByKey", {
468
+ entryKey,
469
+ key,
470
+ exact,
471
+ descending
472
+ });
473
+ }
474
+ async childCategoriesBetween(entryKey, range) {
475
+ return await this.call("viewNavigators.children.categoriesBetween", {
476
+ entryKey,
477
+ range
478
+ });
479
+ }
480
+ async childDocumentsBetween(entryKey, range) {
481
+ return await this.call("viewNavigators.children.documentsBetween", {
482
+ entryKey,
483
+ range
484
+ });
485
+ }
486
+ async getSortedDocIds(descending) {
487
+ return await this.call(
488
+ "viewNavigators.sortedDocIds.get",
489
+ { descending }
490
+ );
491
+ }
492
+ async getSortedDocIdsScoped(entryKey, descending) {
493
+ return await this.call(
494
+ "viewNavigators.sortedDocIds.scoped",
495
+ { entryKey, descending }
496
+ );
497
+ }
498
+ async dispose() {
499
+ await this.call("viewNavigators.dispose");
500
+ }
501
+ };
502
+ var MindooDBAppReadableAttachmentStreamImpl = class {
503
+ constructor(rpc, streamId) {
504
+ this.rpc = rpc;
505
+ this.streamId = streamId;
506
+ this.unsubscribe = this.rpc.addMessageListener((message) => {
507
+ if (isStreamChunkFor(this.streamId, message)) {
508
+ const pending = this.pendingRead;
509
+ this.pendingRead = null;
510
+ if (!pending) {
511
+ return;
512
+ }
513
+ pending.resolve(
514
+ message.done ? null : new Uint8Array(message.chunk ?? new ArrayBuffer(0))
515
+ );
516
+ if (message.done) {
517
+ this.closed = true;
518
+ this.unsubscribe();
519
+ }
520
+ return;
521
+ }
522
+ if (isStreamErrorFor(this.streamId, message)) {
523
+ const pending = this.pendingRead;
524
+ this.pendingRead = null;
525
+ pending?.reject(toStreamError(message));
526
+ this.closed = true;
527
+ this.unsubscribe();
528
+ }
529
+ });
530
+ }
531
+ rpc;
532
+ streamId;
533
+ unsubscribe;
534
+ closed = false;
535
+ pendingRead = null;
536
+ /** Requests and returns the next attachment chunk, or `null` when the stream ends. */
537
+ async read() {
538
+ if (this.closed) {
539
+ return null;
540
+ }
541
+ if (this.pendingRead) {
542
+ throw new Error(
543
+ "A read() call is already in progress for this attachment stream."
544
+ );
545
+ }
546
+ return await new Promise((resolve, reject) => {
547
+ this.pendingRead = { resolve, reject };
548
+ this.rpc.postMessage({
549
+ protocol: PROTOCOL2,
550
+ kind: "stream-read",
551
+ streamId: this.streamId
552
+ });
553
+ });
554
+ }
555
+ /** Closes the read stream and releases any pending read waiter. */
556
+ async close() {
557
+ if (this.closed) {
558
+ return;
559
+ }
560
+ this.closed = true;
561
+ this.pendingRead?.resolve(null);
562
+ this.pendingRead = null;
563
+ this.rpc.postMessage({
564
+ protocol: PROTOCOL2,
565
+ kind: "stream-close",
566
+ streamId: this.streamId
567
+ });
568
+ this.unsubscribe();
569
+ }
570
+ };
571
+ var MindooDBAppWritableAttachmentStreamImpl = class {
572
+ constructor(rpc, streamId) {
573
+ this.rpc = rpc;
574
+ this.streamId = streamId;
575
+ this.unsubscribe = this.rpc.addMessageListener((message) => {
576
+ if (isStreamAckFor(this.streamId, message)) {
577
+ const inflight = this.inflight;
578
+ this.inflight = null;
579
+ inflight?.resolve();
580
+ return;
581
+ }
582
+ if (isStreamErrorFor(this.streamId, message)) {
583
+ const inflight = this.inflight;
584
+ this.inflight = null;
585
+ inflight?.reject(toStreamError(message));
586
+ this.closed = true;
587
+ this.unsubscribe();
588
+ }
589
+ });
590
+ }
591
+ rpc;
592
+ streamId;
593
+ unsubscribe;
594
+ closed = false;
595
+ inflight = null;
596
+ queue = Promise.resolve();
597
+ /** Ensures write/close/abort operations run strictly in order. */
598
+ enqueue(operation) {
599
+ const next = this.queue.then(operation);
600
+ this.queue = next.catch(() => void 0);
601
+ return next;
602
+ }
603
+ /** Sends one stream operation and waits for its ack/error response. */
604
+ async waitForAck(send) {
605
+ return await new Promise((resolve, reject) => {
606
+ this.inflight = { resolve, reject };
607
+ send();
608
+ });
609
+ }
610
+ /** Writes one binary chunk to the host-managed attachment stream. */
611
+ async write(chunk) {
612
+ if (this.closed) {
613
+ throw new Error("The attachment write stream is already closed.");
614
+ }
615
+ return await this.enqueue(async () => {
616
+ const buffer = toTransferableArrayBuffer(chunk);
617
+ await this.waitForAck(() => {
618
+ this.rpc.postMessage(
619
+ {
620
+ protocol: PROTOCOL2,
621
+ kind: "stream-write",
622
+ streamId: this.streamId,
623
+ chunk: buffer
624
+ },
625
+ [buffer]
626
+ );
627
+ });
628
+ });
629
+ }
630
+ /** Gracefully closes the write stream after any queued writes complete. */
631
+ async close() {
632
+ if (this.closed) {
633
+ return;
634
+ }
635
+ this.closed = true;
636
+ await this.enqueue(async () => {
637
+ await this.waitForAck(() => {
638
+ this.rpc.postMessage({
639
+ protocol: PROTOCOL2,
640
+ kind: "stream-close",
641
+ streamId: this.streamId
642
+ });
643
+ });
644
+ });
645
+ this.unsubscribe();
646
+ }
647
+ /** Aborts the write stream after any in-flight work has settled. */
648
+ async abort() {
649
+ if (this.closed) {
650
+ return;
651
+ }
652
+ this.closed = true;
653
+ await this.enqueue(async () => {
654
+ await this.waitForAck(() => {
655
+ this.rpc.postMessage({
656
+ protocol: PROTOCOL2,
657
+ kind: "stream-abort",
658
+ streamId: this.streamId
659
+ });
660
+ });
661
+ });
662
+ this.unsubscribe();
663
+ }
664
+ };
665
+ var MindooDBAppDatabaseImpl = class {
666
+ constructor(rpc, databaseId) {
667
+ this.rpc = rpc;
668
+ this.databaseId = databaseId;
669
+ this.documents = {
670
+ list: async (query) => await this.rpc.call("documents.list", {
671
+ databaseId: this.databaseId,
672
+ query: query ?? {}
673
+ }),
674
+ listInaccessible: async (query) => await this.rpc.call("documents.listInaccessible", {
675
+ databaseId: this.databaseId,
676
+ query: query ?? {}
677
+ }),
678
+ query: async (query) => await this.rpc.call("documents.query", {
679
+ databaseId: this.databaseId,
680
+ query: normalizeDocumentQuery(query)
681
+ }),
682
+ liveQuery: async (query, onResult) => {
683
+ const { subscriptionId, result } = await this.rpc.call("documents.liveQuery.subscribe", {
684
+ databaseId: this.databaseId,
685
+ query: normalizeDocumentQuery(query)
686
+ });
687
+ let disposed = false;
688
+ const unsubscribe = this.rpc.addMessageListener((message) => {
689
+ if (!disposed && isQueryResultFor(subscriptionId, message)) {
690
+ onResult(message.result);
691
+ }
692
+ });
693
+ onResult(result);
694
+ const subscription = {
695
+ refresh: async () => {
696
+ if (disposed) {
697
+ return;
698
+ }
699
+ await this.rpc.call("documents.liveQuery.refresh", {
700
+ subscriptionId
701
+ });
702
+ },
703
+ dispose: async () => {
704
+ if (disposed) {
705
+ return;
706
+ }
707
+ disposed = true;
708
+ unsubscribe();
709
+ await this.rpc.call("documents.liveQuery.unsubscribe", {
710
+ subscriptionId
711
+ });
712
+ }
713
+ };
714
+ return subscription;
715
+ },
716
+ getHeadCursor: async () => await this.rpc.call("documents.getHeadCursor", {
717
+ databaseId: this.databaseId
718
+ }),
719
+ get: async (docId) => await this.rpc.call("documents.get", {
720
+ databaseId: this.databaseId,
721
+ docId
722
+ }),
723
+ getRichText: async (docId, path, options) => await this.rpc.call("documents.richText.get", {
724
+ databaseId: this.databaseId,
725
+ docId,
726
+ path,
727
+ revisionId: options?.revisionId
728
+ }),
729
+ getAutomergeSnapshot: async (docId, options) => await this.rpc.call("documents.automerge.getSnapshot", {
730
+ databaseId: this.databaseId,
731
+ docId,
732
+ revisionId: options?.revisionId
733
+ }),
734
+ applyAutomergeChanges: async (docId, patch) => await this.rpc.call("documents.automerge.applyChanges", {
735
+ databaseId: this.databaseId,
736
+ docId,
737
+ patch
738
+ }),
739
+ create: async (input) => await this.rpc.call("documents.create", {
740
+ databaseId: this.databaseId,
741
+ input
742
+ }),
743
+ createMany: async (inputs) => {
744
+ if (inputs.length === 0) {
745
+ return { ids: [] };
746
+ }
747
+ try {
748
+ return await this.rpc.call("documents.createMany", {
749
+ databaseId: this.databaseId,
750
+ inputs
751
+ });
752
+ } catch (error) {
753
+ if (!isMethodNotFoundError(error)) {
754
+ throw error;
755
+ }
756
+ const ids = [];
757
+ for (const input of inputs) {
758
+ const document = await this.rpc.call("documents.create", {
759
+ databaseId: this.databaseId,
760
+ input
761
+ });
762
+ ids.push(document.id);
763
+ }
764
+ return { ids };
765
+ }
766
+ },
767
+ update: async (docId, patch) => await this.rpc.call("documents.update", {
768
+ databaseId: this.databaseId,
769
+ docId,
770
+ patch
771
+ }),
772
+ addRecipients: async (docId, recipients) => await this.rpc.call("documents.addRecipients", {
773
+ databaseId: this.databaseId,
774
+ docId,
775
+ recipients
776
+ }),
777
+ removeRecipients: async (docId, recipients) => await this.rpc.call("documents.removeRecipients", {
778
+ databaseId: this.databaseId,
779
+ docId,
780
+ recipients
781
+ }),
782
+ setRecipients: async (docId, recipients, options) => await this.rpc.call("documents.setRecipients", {
783
+ databaseId: this.databaseId,
784
+ docId,
785
+ recipients,
786
+ recipientOptions: options
787
+ }),
788
+ delete: async (docId) => await this.rpc.call("documents.delete", {
789
+ databaseId: this.databaseId,
790
+ docId
791
+ }),
792
+ deleteMany: async (docIds) => {
793
+ if (docIds.length === 0) {
794
+ return { ok: true };
795
+ }
796
+ try {
797
+ return await this.rpc.call("documents.deleteMany", {
798
+ databaseId: this.databaseId,
799
+ docIds
800
+ });
801
+ } catch (error) {
802
+ if (!isMethodNotFoundError(error)) {
803
+ throw error;
804
+ }
805
+ for (const docId of docIds) {
806
+ await this.rpc.call("documents.delete", {
807
+ databaseId: this.databaseId,
808
+ docId
809
+ });
810
+ }
811
+ return { ok: true };
812
+ }
813
+ },
814
+ undelete: async (docId) => await this.rpc.call("documents.undelete", {
815
+ databaseId: this.databaseId,
816
+ docId
817
+ }),
818
+ canCreate: async (input) => await this.rpc.call("documents.canCreate", {
819
+ databaseId: this.databaseId,
820
+ input: input ?? {}
821
+ }),
822
+ canChange: async (docId) => await this.rpc.call("documents.canChange", {
823
+ databaseId: this.databaseId,
824
+ docId
825
+ }),
826
+ canDelete: async (docId) => await this.rpc.call("documents.canDelete", {
827
+ databaseId: this.databaseId,
828
+ docId
829
+ }),
830
+ canUndelete: async (docId) => await this.rpc.call("documents.canUndelete", {
831
+ databaseId: this.databaseId,
832
+ docId
833
+ }),
834
+ getDefaultCreateKeyId: async () => await this.rpc.call("documents.getDefaultCreateKeyId", {
835
+ databaseId: this.databaseId
836
+ }),
837
+ listCreateKeys: async () => {
838
+ try {
839
+ return await this.rpc.call("documents.listCreateKeys", {
840
+ databaseId: this.databaseId
841
+ });
842
+ } catch (error) {
843
+ if (!isMethodNotFoundError(error)) {
844
+ throw error;
845
+ }
846
+ const keyId = await this.rpc.call("documents.getDefaultCreateKeyId", {
847
+ databaseId: this.databaseId
848
+ });
849
+ return [{ keyId, isDefault: true }];
850
+ }
851
+ },
852
+ listHistory: async (docId) => await this.rpc.call("documents.history.list", {
853
+ databaseId: this.databaseId,
854
+ docId
855
+ }),
856
+ getAtTimestamp: async (docId, timestamp) => await this.rpc.call("documents.history.getAtTimestamp", {
857
+ databaseId: this.databaseId,
858
+ docId,
859
+ timestamp
860
+ }),
861
+ getAtRevision: async (docId, revisionId, options) => await this.rpc.call("documents.history.getAtRevision", {
862
+ databaseId: this.databaseId,
863
+ docId,
864
+ revisionId,
865
+ phase: options?.phase
866
+ }),
867
+ getAtHeads: async (docId, headIds) => await this.rpc.call("documents.history.getAtHeads", {
868
+ databaseId: this.databaseId,
869
+ docId,
870
+ headIds
871
+ }),
872
+ listVerification: async (docId, revisionIds) => await this.rpc.call("documents.history.listVerification", {
873
+ databaseId: this.databaseId,
874
+ docId,
875
+ revisionIds
876
+ })
877
+ };
878
+ this.identity = {
879
+ signStatement: async (input) => await this.rpc.call("identity.signStatement", {
880
+ databaseId: this.databaseId,
881
+ ...input
882
+ })
883
+ };
884
+ this.timestamps = {
885
+ rfc3161: async (input) => await this.rpc.call("timestamps.rfc3161", {
886
+ databaseId: this.databaseId,
887
+ ...input
888
+ }),
889
+ listProviders: async () => await this.rpc.call("timestamps.listProviders", {
890
+ databaseId: this.databaseId
891
+ })
892
+ };
893
+ this.directory = {
894
+ excerpt: async (publicKeys) => await this.rpc.call("directory.excerpt", {
895
+ databaseId: this.databaseId,
896
+ publicKeys
897
+ }),
898
+ listUsers: async () => {
899
+ try {
900
+ return await this.rpc.call("directory.listUsers", {
901
+ databaseId: this.databaseId
902
+ });
903
+ } catch (error) {
904
+ if (!isMethodNotFoundError(error)) {
905
+ throw error;
906
+ }
907
+ return [];
908
+ }
909
+ }
910
+ };
911
+ this.attachments = {
912
+ list: async (docId, options) => await this.rpc.call("attachments.list", {
913
+ databaseId: this.databaseId,
914
+ docId,
915
+ timestamp: options?.timestamp,
916
+ revisionId: options?.revisionId
917
+ }),
918
+ remove: async (docId, attachmentName) => await this.rpc.call("attachments.remove", {
919
+ databaseId: this.databaseId,
920
+ docId,
921
+ attachmentName
922
+ }),
923
+ openReadStream: async (docId, attachmentName, options) => {
924
+ const result = await this.rpc.call(
925
+ "attachments.openReadStream",
926
+ {
927
+ databaseId: this.databaseId,
928
+ docId,
929
+ attachmentName,
930
+ timestamp: options?.timestamp,
931
+ revisionId: options?.revisionId
932
+ }
933
+ );
934
+ return new MindooDBAppReadableAttachmentStreamImpl(
935
+ this.rpc,
936
+ result.streamId
937
+ );
938
+ },
939
+ openWriteStream: async (docId, attachmentName, contentType) => {
940
+ const result = await this.rpc.call(
941
+ "attachments.openWriteStream",
942
+ {
943
+ databaseId: this.databaseId,
944
+ docId,
945
+ attachmentName,
946
+ contentType
947
+ }
948
+ );
949
+ return new MindooDBAppWritableAttachmentStreamImpl(
950
+ this.rpc,
951
+ result.streamId
952
+ );
953
+ },
954
+ scan: async (docId, options) => {
955
+ const scannerTab = shouldUseWindowedHostTab() ? window.open("", "_blank") : null;
956
+ if (scannerTab) {
957
+ try {
958
+ scannerTab.document.title = "Opening document scanner...";
959
+ const preparedSession = await this.rpc.call("attachments.prepareScanSession", {
960
+ databaseId: this.databaseId,
961
+ docId,
962
+ defaultFileName: options?.defaultFileName,
963
+ preset: options?.preset,
964
+ mimeType: options?.mimeType
965
+ });
966
+ scannerTab.location.href = preparedSession.scanUrl;
967
+ return await this.rpc.call(
968
+ "attachments.awaitScanSession",
969
+ {
970
+ databaseId: this.databaseId,
971
+ sessionId: preparedSession.sessionId
972
+ }
973
+ );
974
+ } catch (error) {
975
+ scannerTab.close();
976
+ throw error;
977
+ }
978
+ }
979
+ return await this.rpc.call(
980
+ "attachments.scanAndWrite",
981
+ {
982
+ databaseId: this.databaseId,
983
+ docId,
984
+ defaultFileName: options?.defaultFileName,
985
+ preset: options?.preset,
986
+ mimeType: options?.mimeType
987
+ }
988
+ );
989
+ },
990
+ preparePreviewSession: async (docId, attachmentName, options) => await this.rpc.call("attachments.preparePreviewSession", {
991
+ databaseId: this.databaseId,
992
+ docId,
993
+ attachmentName,
994
+ timestamp: options?.timestamp,
995
+ revisionId: options?.revisionId
996
+ }),
997
+ openPreview: async (docId, attachmentName, options) => {
998
+ const previewTab = shouldUseWindowedHostTab() ? window.open("", "_blank") : null;
999
+ if (previewTab) {
1000
+ try {
1001
+ previewTab.document.title = "Opening attachment preview...";
1002
+ const previewSession = await this.rpc.call("attachments.preparePreviewSession", {
1003
+ databaseId: this.databaseId,
1004
+ docId,
1005
+ attachmentName,
1006
+ timestamp: options?.timestamp,
1007
+ revisionId: options?.revisionId
1008
+ });
1009
+ previewTab.location.href = previewSession.previewUrl;
1010
+ return { ok: true };
1011
+ } catch (error) {
1012
+ previewTab.close();
1013
+ throw error;
1014
+ }
1015
+ }
1016
+ return await this.rpc.call("attachments.openPreview", {
1017
+ databaseId: this.databaseId,
1018
+ docId,
1019
+ attachmentName,
1020
+ timestamp: options?.timestamp,
1021
+ revisionId: options?.revisionId
1022
+ });
1023
+ },
1024
+ extractText: async (input) => {
1025
+ return await this.rpc.call("attachments.extractText", {
1026
+ databaseId: this.databaseId,
1027
+ bytes: input.bytes,
1028
+ mimeType: input.mimeType,
1029
+ fileName: input.fileName,
1030
+ format: input.format,
1031
+ languages: input.languages
1032
+ });
1033
+ }
1034
+ };
1035
+ }
1036
+ rpc;
1037
+ databaseId;
1038
+ documents;
1039
+ attachments;
1040
+ identity;
1041
+ timestamps;
1042
+ directory;
1043
+ /** Returns database metadata for the currently opened binding. */
1044
+ async info() {
1045
+ return await this.rpc.call("databases.info", {
1046
+ databaseId: this.databaseId
1047
+ });
1048
+ }
1049
+ /** Reads the full-text configuration from the synced `dbsetup` document. */
1050
+ async getFulltextSetup() {
1051
+ const result = await this.rpc.call(
1052
+ "database.getFulltextSetup",
1053
+ { databaseId: this.databaseId }
1054
+ );
1055
+ return result.config;
1056
+ }
1057
+ /** Writes (or removes, with `null`) the full-text configuration. */
1058
+ async setFulltextSetup(config) {
1059
+ await this.rpc.call("database.setFulltextSetup", {
1060
+ databaseId: this.databaseId,
1061
+ config
1062
+ });
1063
+ }
1064
+ /** Reads the attachment extraction configuration from the synced `dbsetup` document. */
1065
+ async getExtractionSetup() {
1066
+ const result = await this.rpc.call(
1067
+ "database.getExtractionSetup",
1068
+ { databaseId: this.databaseId }
1069
+ );
1070
+ return result.config;
1071
+ }
1072
+ /** Writes (or removes, with `null`) the attachment extraction configuration. */
1073
+ async setExtractionSetup(config) {
1074
+ await this.rpc.call("database.setExtractionSetup", {
1075
+ databaseId: this.databaseId,
1076
+ config
1077
+ });
1078
+ }
1079
+ };
1080
+ var MindooDBAppSessionImpl = class {
1081
+ constructor(rpc, onDisconnect) {
1082
+ this.rpc = rpc;
1083
+ this.onDisconnect = onDisconnect;
1084
+ this.menus = {
1085
+ show: async (input) => await this.rpc.call("menus.show", input),
1086
+ hide: async () => {
1087
+ await this.rpc.call("menus.hide", {});
1088
+ }
1089
+ };
1090
+ this.storage = {
1091
+ snapshot: async (options) => await this.rpc.call("appStorage.snapshot", {
1092
+ prefixes: options?.prefixes
1093
+ }),
1094
+ get: async (key) => await this.rpc.call("appStorage.get", { key }),
1095
+ set: async (key, value) => {
1096
+ await this.rpc.call("appStorage.set", { key, value });
1097
+ },
1098
+ remove: async (key) => {
1099
+ await this.rpc.call("appStorage.remove", { key });
1100
+ },
1101
+ keys: async (options) => await this.rpc.call("appStorage.keys", { prefix: options?.prefix }),
1102
+ clear: async (options) => {
1103
+ await this.rpc.call("appStorage.clear", { prefix: options?.prefix });
1104
+ }
1105
+ };
1106
+ this.rpc.addMessageListener((message) => {
1107
+ if (message.kind === "before-close") {
1108
+ void this.handleBeforeClose(message.closeId);
1109
+ }
1110
+ });
1111
+ }
1112
+ rpc;
1113
+ onDisconnect;
1114
+ menus;
1115
+ storage;
1116
+ beforeCloseListeners = /* @__PURE__ */ new Set();
1117
+ /**
1118
+ * Lets every listener finish, then tells the host it may proceed.
1119
+ *
1120
+ * The ack is sent even when a listener fails: the host is going to tear the launch down
1121
+ * either way once its grace period elapses, and answering late only wastes that time.
1122
+ */
1123
+ async handleBeforeClose(closeId) {
1124
+ try {
1125
+ await Promise.all(
1126
+ [...this.beforeCloseListeners].map(async (listener) => {
1127
+ try {
1128
+ await listener();
1129
+ } catch (error) {
1130
+ console.warn("[mindoodb-app-sdk] A before-close listener failed.", error);
1131
+ }
1132
+ })
1133
+ );
1134
+ } finally {
1135
+ try {
1136
+ this.rpc.postMessage({
1137
+ protocol: PROTOCOL2,
1138
+ kind: "before-close-ack",
1139
+ closeId
1140
+ });
1141
+ } catch (error) {
1142
+ console.warn("[mindoodb-app-sdk] Could not acknowledge before-close.", error);
1143
+ }
1144
+ }
1145
+ }
1146
+ /** Returns the launch context provided by the Haven host. */
1147
+ async getLaunchContext() {
1148
+ return await this.rpc.call("session.getLaunchContext", {});
1149
+ }
1150
+ /**
1151
+ * Asks the host to open an encrypted channel to a tenant-joined service.
1152
+ * The host owns the key exchange and the resulting session key; nothing
1153
+ * secret crosses back into the app.
1154
+ */
1155
+ async openSealedChannel(input) {
1156
+ return await this.rpc.call("sealedChannel.open", input);
1157
+ }
1158
+ /** Sends one request through an open channel; the host seals and opens it. */
1159
+ async sealedChannelRequest(input) {
1160
+ return await this.rpc.call("sealedChannel.request", input);
1161
+ }
1162
+ /** Discards a channel host-side. */
1163
+ async closeSealedChannel(channelId) {
1164
+ await this.rpc.call("sealedChannel.close", { channelId });
1165
+ }
1166
+ /** Returns the product names currently licensed in the Haven host. */
1167
+ async getLicensedProducts() {
1168
+ return await this.rpc.call("session.getLicensedProducts", {});
1169
+ }
1170
+ /** Lists the databases that the host has made available for this app session. */
1171
+ async listDatabases() {
1172
+ return await this.rpc.call("session.listDatabases", {});
1173
+ }
1174
+ /** Opens one database binding and returns a client facade for it. */
1175
+ async openDatabase(databaseId) {
1176
+ await this.rpc.call("session.openDatabase", { databaseId });
1177
+ return new MindooDBAppDatabaseImpl(this.rpc, databaseId);
1178
+ }
1179
+ async listDocumentsSinceViewCursor(cursor) {
1180
+ return await this.rpc.call("session.listDocumentsSinceViewCursor", {
1181
+ cursor
1182
+ });
1183
+ }
1184
+ /**
1185
+ * Create a navigator from an ad-hoc view definition and one or more database bindings.
1186
+ *
1187
+ * The host builds a `VirtualView` from `input.definition`, optionally applying
1188
+ * open options (root scoping, category filtering), and returns a `navigatorId`
1189
+ * that all subsequent navigator RPCs reference.
1190
+ */
1191
+ async createViewNavigator(input) {
1192
+ const result = await this.rpc.call("session.createViewNavigator", input);
1193
+ return new MindooDBAppViewNavigatorImpl(
1194
+ this.rpc,
1195
+ result.navigatorId,
1196
+ result.viewCursor
1197
+ );
1198
+ }
1199
+ /**
1200
+ * Open a navigator for a preconfigured view that the host already knows about.
1201
+ *
1202
+ * `viewId` must match one of the views declared in the launch context. The
1203
+ * host resolves the full view definition and database bindings automatically.
1204
+ */
1205
+ async openViewNavigator(viewId, options) {
1206
+ const result = await this.rpc.call("session.openViewNavigator", { viewId, options: options ?? {} });
1207
+ return new MindooDBAppViewNavigatorImpl(
1208
+ this.rpc,
1209
+ result.navigatorId,
1210
+ result.viewCursor
1211
+ );
1212
+ }
1213
+ /** Subscribe to host-pushed theme changes (dark/light mode, color tokens). */
1214
+ onThemeChange(listener) {
1215
+ return this.rpc.addMessageListener((message) => {
1216
+ if (isThemeChangedMessage(message)) {
1217
+ listener(message.theme);
1218
+ }
1219
+ });
1220
+ }
1221
+ /** Subscribe to host-pushed viewport dimension changes (resize, orientation). */
1222
+ onViewportChange(listener) {
1223
+ return this.rpc.addMessageListener((message) => {
1224
+ if (isViewportChangedMessage(message)) {
1225
+ listener(message.viewport);
1226
+ }
1227
+ });
1228
+ }
1229
+ /** Subscribe to host-pushed embedded UI preference changes. */
1230
+ onUiPreferencesChange(listener) {
1231
+ return this.rpc.addMessageListener((message) => {
1232
+ if (isUiPreferencesChangedMessage(message)) {
1233
+ listener(message.uiPreferences);
1234
+ }
1235
+ });
1236
+ }
1237
+ /** Subscribe to host-pushed UI language changes. */
1238
+ onLocaleChange(listener) {
1239
+ return this.rpc.addMessageListener((message) => {
1240
+ if (isLocaleChangedMessage(message)) {
1241
+ listener(message.locale);
1242
+ }
1243
+ });
1244
+ }
1245
+ /** Register work to run before the host tears this launch down. */
1246
+ onBeforeClose(listener) {
1247
+ this.beforeCloseListeners.add(listener);
1248
+ return () => {
1249
+ this.beforeCloseListeners.delete(listener);
1250
+ };
1251
+ }
1252
+ /** Disconnects from the host and always disposes the underlying port client. */
1253
+ async disconnect() {
1254
+ try {
1255
+ await this.rpc.call("session.disconnect", {});
1256
+ } finally {
1257
+ this.rpc.dispose();
1258
+ this.onDisconnect?.();
1259
+ }
1260
+ }
1261
+ };
1262
+ var sessionsByLaunchId = /* @__PURE__ */ new Map();
1263
+ function releaseMindooDBAppBridgeSessions(launchId) {
1264
+ if (launchId === void 0) {
1265
+ sessionsByLaunchId.clear();
1266
+ return;
1267
+ }
1268
+ sessionsByLaunchId.delete(launchId);
1269
+ }
1270
+ function createMindooDBAppBridge() {
1271
+ return {
1272
+ async connect(options) {
1273
+ const launchId = resolveLaunchId(options);
1274
+ const existing = sessionsByLaunchId.get(launchId);
1275
+ if (existing) {
1276
+ return await existing;
1277
+ }
1278
+ const pending = (async () => {
1279
+ const port = await waitForConnectedPort(options, launchId);
1280
+ const rpc = new PortRpcClient(port);
1281
+ return new MindooDBAppSessionImpl(rpc, () => {
1282
+ if (sessionsByLaunchId.get(launchId) === pending) {
1283
+ sessionsByLaunchId.delete(launchId);
1284
+ }
1285
+ });
1286
+ })();
1287
+ sessionsByLaunchId.set(launchId, pending);
1288
+ try {
1289
+ return await pending;
1290
+ } catch (error) {
1291
+ if (sessionsByLaunchId.get(launchId) === pending) {
1292
+ sessionsByLaunchId.delete(launchId);
1293
+ }
1294
+ throw error;
1295
+ }
1296
+ }
1297
+ };
1298
+ }
1299
+
1300
+ export {
1301
+ releaseMindooDBAppBridgeSessions,
1302
+ createMindooDBAppBridge
1303
+ };