mindoodb 0.2.8 → 0.2.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.
@@ -0,0 +1,902 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/core/automerge-adapter.ts
9
+ import * as AutomergeWasm from "@automerge/automerge";
10
+ var Automerge;
11
+ var isNative = false;
12
+ function isReactNativeRuntime() {
13
+ return typeof navigator !== "undefined" && navigator.product === "ReactNative";
14
+ }
15
+ if (isReactNativeRuntime()) {
16
+ try {
17
+ const nativeModuleName = "react-native-automerge-generated";
18
+ const nativeRequire = typeof __require === "function" ? __require : void 0;
19
+ const nativeModule = nativeRequire?.(nativeModuleName);
20
+ if (nativeModule?.Automerge) {
21
+ Automerge = nativeModule.Automerge;
22
+ isNative = true;
23
+ console.log("[MindooDB] \u2713 Using native Rust Automerge (react-native-automerge-generated)");
24
+ } else {
25
+ Automerge = AutomergeWasm;
26
+ console.log("[MindooDB] \u26A0 Native module loaded but Automerge API unavailable, using WASM");
27
+ }
28
+ } catch (error) {
29
+ Automerge = AutomergeWasm;
30
+ isNative = false;
31
+ console.log("[MindooDB] \u2139 Using WASM Automerge (Browser/Node.js mode)");
32
+ }
33
+ } else {
34
+ Automerge = AutomergeWasm;
35
+ isNative = false;
36
+ console.log("[MindooDB] \u2139 Using WASM Automerge (Browser/Node.js mode)");
37
+ }
38
+
39
+ // src/core/documentLoadGuard.ts
40
+ var SNAPSHOT_BYTES_PER_OP = 130;
41
+ var RETAINED_BYTES_PER_OP = 8;
42
+ var RETAINED_BYTES_PER_CHANGE = 300;
43
+ var STEP_BYTES_PER_OP = 500;
44
+ var STEP_BYTES_PER_CHANGE = 1500;
45
+ var APPLY_CHANGES_SLICE_OPS = 5e5;
46
+ var APPLY_CHANGES_SLICE_BYTES = 2 * 1024 * 1024;
47
+ var MAGIC = [133, 111, 74, 131];
48
+ var CHUNK_DOCUMENT = 0;
49
+ var CHUNK_CHANGE = 1;
50
+ var CHUNK_COMPRESSED_CHANGE = 2;
51
+ var ACTION_COLUMN_ID = 4;
52
+ var ACTION_COLUMN_TYPE = 2;
53
+ var DocumentTooLargeError = class extends Error {
54
+ constructor(docId, estimate, budgetBytes2) {
55
+ super(
56
+ `Document ${docId} is too large to load here: about ${Math.round(estimate.bytes / 1048576)} MB of Automerge memory for ${estimate.ops} operations, budget ${Math.round(budgetBytes2 / 1048576)} MB`
57
+ );
58
+ this.name = "DocumentTooLargeError";
59
+ this.docId = docId;
60
+ this.estimatedBytes = estimate.bytes;
61
+ this.budgetBytes = budgetBytes2;
62
+ this.ops = estimate.ops;
63
+ }
64
+ };
65
+ var budgetBytes = null;
66
+ function setDocumentLoadBudget(bytes) {
67
+ if (bytes !== null && (!Number.isFinite(bytes) || bytes <= 0)) {
68
+ throw new Error("Document load budget must be a positive number of bytes or null");
69
+ }
70
+ budgetBytes = bytes;
71
+ }
72
+ function getDocumentLoadBudget() {
73
+ return budgetBytes;
74
+ }
75
+ function estimateDocumentLoad(snapshot, changes) {
76
+ let snapshotOps = 0;
77
+ if (snapshot) {
78
+ const ops = countChunkOps(snapshot);
79
+ if (ops === null) return null;
80
+ snapshotOps = ops;
81
+ }
82
+ let changeOps = 0;
83
+ let largestStepBytes = 0;
84
+ let largestStepOps = 0;
85
+ let stepOps = 0;
86
+ let stepChanges = 0;
87
+ let stepBytes = 0;
88
+ const closeStep = () => {
89
+ const cost = stepOps * STEP_BYTES_PER_OP + stepChanges * STEP_BYTES_PER_CHANGE;
90
+ if (cost > largestStepBytes) {
91
+ largestStepBytes = cost;
92
+ largestStepOps = stepOps;
93
+ }
94
+ stepOps = 0;
95
+ stepChanges = 0;
96
+ stepBytes = 0;
97
+ };
98
+ for (const change of changes) {
99
+ const ops = countChunkOps(change);
100
+ if (ops === null) return null;
101
+ changeOps += ops;
102
+ if (stepChanges > 0 && (stepBytes + change.byteLength > APPLY_CHANGES_SLICE_BYTES || stepOps + ops > APPLY_CHANGES_SLICE_OPS)) {
103
+ closeStep();
104
+ }
105
+ stepOps += ops;
106
+ stepChanges += 1;
107
+ stepBytes += change.byteLength;
108
+ }
109
+ if (stepChanges > 0) closeStep();
110
+ return {
111
+ ops: snapshotOps + changeOps,
112
+ bytes: snapshotOps * SNAPSHOT_BYTES_PER_OP + changeOps * RETAINED_BYTES_PER_OP + changes.length * RETAINED_BYTES_PER_CHANGE + largestStepBytes,
113
+ largestStepOps
114
+ };
115
+ }
116
+ function assertDocumentLoadWithinBudget(docId, snapshot, changes) {
117
+ if (budgetBytes === null) return;
118
+ const estimate = estimateDocumentLoad(snapshot, changes);
119
+ if (estimate && estimate.bytes > budgetBytes) {
120
+ throw new DocumentTooLargeError(docId, estimate, budgetBytes);
121
+ }
122
+ }
123
+ function countChunkOps(bytes) {
124
+ try {
125
+ if (bytes.length < 9) return null;
126
+ for (let i = 0; i < 4; i++) if (bytes[i] !== MAGIC[i]) return null;
127
+ let offset = 8;
128
+ const type = bytes[offset++];
129
+ const [length, bodyStart] = readUleb(bytes, offset);
130
+ if (type === CHUNK_COMPRESSED_CHANGE) return null;
131
+ const body = bytes.subarray(bodyStart, bodyStart + length);
132
+ if (type === CHUNK_CHANGE) return countChangeOps(body);
133
+ if (type === CHUNK_DOCUMENT) return countDocumentOps(body);
134
+ return null;
135
+ } catch {
136
+ return null;
137
+ }
138
+ }
139
+ function countChangeOps(body) {
140
+ let p = 0;
141
+ let n;
142
+ [n, p] = readUleb(body, p);
143
+ p += 32 * n;
144
+ let actorLength;
145
+ [actorLength, p] = readUleb(body, p);
146
+ p += actorLength;
147
+ [, p] = readUleb(body, p);
148
+ [, p] = readUleb(body, p);
149
+ [, p] = readSleb(body, p);
150
+ let messageLength;
151
+ [messageLength, p] = readUleb(body, p);
152
+ p += messageLength;
153
+ [n, p] = readUleb(body, p);
154
+ for (let i = 0; i < n; i++) {
155
+ let otherLength;
156
+ [otherLength, p] = readUleb(body, p);
157
+ p += otherLength;
158
+ }
159
+ let columns;
160
+ [columns, p] = readColumns(body, p);
161
+ return countActionRows(body, columns, p);
162
+ }
163
+ function countDocumentOps(body) {
164
+ let p = 0;
165
+ let n;
166
+ [n, p] = readUleb(body, p);
167
+ for (let i = 0; i < n; i++) {
168
+ let actorLength;
169
+ [actorLength, p] = readUleb(body, p);
170
+ p += actorLength;
171
+ }
172
+ [n, p] = readUleb(body, p);
173
+ p += 32 * n;
174
+ let changeColumns;
175
+ let opColumns;
176
+ [changeColumns, p] = readColumns(body, p);
177
+ [opColumns, p] = readColumns(body, p);
178
+ const opDataStart = p + changeColumns.reduce((sum, column) => sum + column.length, 0);
179
+ return countActionRows(body, opColumns, opDataStart);
180
+ }
181
+ function readColumns(body, offset) {
182
+ let p = offset;
183
+ let count;
184
+ [count, p] = readUleb(body, p);
185
+ const columns = [];
186
+ for (let i = 0; i < count; i++) {
187
+ let spec;
188
+ let length;
189
+ [spec, p] = readUleb(body, p);
190
+ [length, p] = readUleb(body, p);
191
+ columns.push({ spec, length });
192
+ }
193
+ return [columns, p];
194
+ }
195
+ function countActionRows(body, columns, dataStart) {
196
+ let p = dataStart;
197
+ for (const column of columns) {
198
+ if (column.spec >> 4 === ACTION_COLUMN_ID && (column.spec & 7) === ACTION_COLUMN_TYPE) {
199
+ if (column.spec >> 3 & 1) return null;
200
+ return countRleRows(body.subarray(p, p + column.length));
201
+ }
202
+ p += column.length;
203
+ }
204
+ return 0;
205
+ }
206
+ function countRleRows(data) {
207
+ let p = 0;
208
+ let rows = 0;
209
+ while (p < data.length) {
210
+ let count;
211
+ [count, p] = readSleb(data, p);
212
+ if (count > 0) {
213
+ [, p] = readUleb(data, p);
214
+ rows += count;
215
+ } else if (count < 0) {
216
+ for (let i = 0; i < -count; i++) [, p] = readUleb(data, p);
217
+ rows += -count;
218
+ } else {
219
+ let nulls;
220
+ [nulls, p] = readUleb(data, p);
221
+ rows += nulls;
222
+ }
223
+ }
224
+ return rows;
225
+ }
226
+ function readUleb(bytes, offset) {
227
+ let result = 0;
228
+ let shift = 0;
229
+ let p = offset;
230
+ for (; ; ) {
231
+ if (p >= bytes.length) throw new Error("truncated LEB128");
232
+ const byte = bytes[p++];
233
+ result += (byte & 127) * 2 ** shift;
234
+ shift += 7;
235
+ if ((byte & 128) === 0) return [result, p];
236
+ if (shift > 63) throw new Error("LEB128 too long");
237
+ }
238
+ }
239
+ function readSleb(bytes, offset) {
240
+ let result = 0;
241
+ let shift = 0;
242
+ let p = offset;
243
+ for (; ; ) {
244
+ if (p >= bytes.length) throw new Error("truncated LEB128");
245
+ const byte = bytes[p++];
246
+ result += (byte & 127) * 2 ** shift;
247
+ shift += 7;
248
+ if ((byte & 128) === 0) {
249
+ if (byte & 64) result -= 2 ** shift;
250
+ return [result, p];
251
+ }
252
+ if (shift > 63) throw new Error("LEB128 too long");
253
+ }
254
+ }
255
+
256
+ // src/core/applyChangesInSlices.ts
257
+ function planChangeSlices(changes, maxSliceBytes = APPLY_CHANGES_SLICE_BYTES, maxSliceOps = APPLY_CHANGES_SLICE_OPS) {
258
+ const slices = [];
259
+ let slice = [];
260
+ let sliceBytes = 0;
261
+ let sliceOps = 0;
262
+ for (const change of changes) {
263
+ const ops = countChunkOps(change) ?? 0;
264
+ if (slice.length > 0 && (sliceBytes + change.byteLength > maxSliceBytes || sliceOps + ops > maxSliceOps)) {
265
+ slices.push(slice);
266
+ slice = [];
267
+ sliceBytes = 0;
268
+ sliceOps = 0;
269
+ }
270
+ slice.push(change);
271
+ sliceBytes += change.byteLength;
272
+ sliceOps += ops;
273
+ }
274
+ if (slice.length > 0) slices.push(slice);
275
+ return slices;
276
+ }
277
+ function applyChangesInSlices(doc, changes, maxSliceBytes = APPLY_CHANGES_SLICE_BYTES, maxSliceOps = APPLY_CHANGES_SLICE_OPS) {
278
+ let current = doc;
279
+ for (const slice of planChangeSlices(changes, maxSliceBytes, maxSliceOps)) {
280
+ [current] = Automerge.applyChanges(current, slice);
281
+ }
282
+ return current;
283
+ }
284
+
285
+ // src/core/crypto/EntrySignature.ts
286
+ var ENTRY_SIGNATURE_LAYOUT_VERSION = 1;
287
+ var ENTRY_PROVENANCE_BLOCK_TAG = 2;
288
+ var ENTRY_RECIPIENTS_BLOCK_TAG = 3;
289
+ var textEncoder = new TextEncoder();
290
+ function base64ToBytes(base64) {
291
+ const binary = atob(base64);
292
+ const bytes = new Uint8Array(binary.length);
293
+ for (let i = 0; i < binary.length; i++) {
294
+ bytes[i] = binary.charCodeAt(i);
295
+ }
296
+ return bytes;
297
+ }
298
+ function pushLengthPrefixed(parts, bytes) {
299
+ const lengthPrefix = new Uint8Array(4);
300
+ new DataView(lengthPrefix.buffer).setUint32(
301
+ 0,
302
+ bytes.length,
303
+ false
304
+ /* big-endian */
305
+ );
306
+ parts.push(lengthPrefix, bytes);
307
+ }
308
+ function pushString(parts, value) {
309
+ pushLengthPrefixed(parts, textEncoder.encode(value));
310
+ }
311
+ function pushUint32BE(parts, value) {
312
+ const buf = new Uint8Array(4);
313
+ new DataView(buf.buffer).setUint32(
314
+ 0,
315
+ value >>> 0,
316
+ false
317
+ /* big-endian */
318
+ );
319
+ parts.push(buf);
320
+ }
321
+ function pushInt64BE(parts, value) {
322
+ if (!Number.isInteger(value)) {
323
+ throw new Error(`Entry signature int64 field must be an integer, got: ${value}`);
324
+ }
325
+ const buf = new Uint8Array(8);
326
+ new DataView(buf.buffer).setBigInt64(
327
+ 0,
328
+ BigInt(value),
329
+ false
330
+ /* big-endian */
331
+ );
332
+ parts.push(buf);
333
+ }
334
+ function buildEntrySigningBytes(fields, version = ENTRY_SIGNATURE_LAYOUT_VERSION) {
335
+ const parts = [];
336
+ parts.push(new Uint8Array([version & 255]));
337
+ pushString(parts, fields.entryType);
338
+ pushString(parts, fields.id);
339
+ pushString(parts, fields.docId);
340
+ pushString(parts, fields.decryptionKeyId);
341
+ pushInt64BE(parts, fields.createdAt);
342
+ pushUint32BE(parts, fields.dependencyIds.length);
343
+ for (const dep of fields.dependencyIds) {
344
+ pushString(parts, dep);
345
+ }
346
+ pushString(parts, fields.contentHash);
347
+ pushString(parts, fields.createdByPublicKey);
348
+ const attachmentRefs = fields.attachmentRefs;
349
+ if (attachmentRefs && attachmentRefs.length > 0) {
350
+ pushUint32BE(parts, attachmentRefs.length);
351
+ for (const ref of attachmentRefs) {
352
+ pushString(parts, ref.attachmentId);
353
+ pushString(parts, ref.lastChunkId);
354
+ pushInt64BE(parts, ref.size);
355
+ }
356
+ }
357
+ const provenance = fields.provenance;
358
+ if (provenance) {
359
+ parts.push(new Uint8Array([ENTRY_PROVENANCE_BLOCK_TAG]));
360
+ pushString(parts, provenance.sourceTenantId);
361
+ pushString(parts, provenance.sourceDbId);
362
+ pushLengthPrefixed(parts, buildEntrySigningBytes(provenance.source, version));
363
+ pushLengthPrefixed(
364
+ parts,
365
+ provenance.sourceMetadataSignature ? base64ToBytes(provenance.sourceMetadataSignature) : new Uint8Array(0)
366
+ );
367
+ }
368
+ const recipients = fields.recipients;
369
+ if (recipients && (recipients.wraps.length > 0 || (recipients.partial ?? []).some((tier) => tier.wraps.length > 0))) {
370
+ parts.push(new Uint8Array([ENTRY_RECIPIENTS_BLOCK_TAG]));
371
+ pushString(parts, JSON.stringify(recipients));
372
+ }
373
+ const total = parts.reduce((sum, p) => sum + p.length, 0);
374
+ const out = new Uint8Array(total);
375
+ let offset = 0;
376
+ for (const p of parts) {
377
+ out.set(p, offset);
378
+ offset += p.length;
379
+ }
380
+ return out;
381
+ }
382
+ function entrySignatureFieldsFromEntry(entry) {
383
+ return {
384
+ entryType: entry.entryType,
385
+ id: entry.id,
386
+ docId: entry.docId,
387
+ decryptionKeyId: entry.decryptionKeyId,
388
+ createdAt: entry.createdAt,
389
+ dependencyIds: entry.dependencyIds,
390
+ contentHash: entry.contentHash,
391
+ createdByPublicKey: entry.createdByPublicKey,
392
+ attachmentRefs: entry.attachmentRefs && entry.attachmentRefs.length > 0 ? entry.attachmentRefs : void 0,
393
+ provenance: entry.provenance,
394
+ recipients: entry.recipients
395
+ };
396
+ }
397
+ async function verifyEntrySignatureWithImportedKey(entry, encryptedData, cryptoKey, subtle, opts) {
398
+ if (entry.metadataSignature) {
399
+ const bytes = buildEntrySigningBytes(entrySignatureFieldsFromEntry(entry));
400
+ return subtle.verify(
401
+ { name: "Ed25519" },
402
+ cryptoKey,
403
+ entry.metadataSignature.buffer,
404
+ bytes.buffer
405
+ );
406
+ }
407
+ if (opts?.requireMetadataSignature) {
408
+ return false;
409
+ }
410
+ return subtle.verify(
411
+ { name: "Ed25519" },
412
+ cryptoKey,
413
+ entry.signature.buffer,
414
+ encryptedData.buffer
415
+ );
416
+ }
417
+
418
+ // src/core/utils/idGeneration.ts
419
+ async function computeContentHash(data, subtle) {
420
+ const buffer = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
421
+ const hashBuffer = await subtle.digest("SHA-256", buffer);
422
+ return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
423
+ }
424
+
425
+ // src/core/accesscontrol/materializationGuard.ts
426
+ function snapshotHeadsMatch(decodedHeads, declaredHeads) {
427
+ const declared = declaredHeads ?? [];
428
+ if (decodedHeads.length !== declared.length) return false;
429
+ const declaredSet = new Set(declared);
430
+ if (declaredSet.size !== declared.length) {
431
+ return false;
432
+ }
433
+ for (const head of decodedHeads) {
434
+ if (!declaredSet.has(head)) return false;
435
+ }
436
+ return true;
437
+ }
438
+
439
+ // src/core/userkeys/sealedTypes.ts
440
+ var ENCRYPT_FOR_FIELD = "_encryptFor";
441
+
442
+ // src/core/indexing/summary/extractSummaryFields.ts
443
+ function resolveFieldPath(data, path) {
444
+ if (!path.includes(".")) {
445
+ return data[path];
446
+ }
447
+ let current = data;
448
+ for (const segment of path.split(".")) {
449
+ if (current === null || typeof current !== "object" || Array.isArray(current)) {
450
+ return void 0;
451
+ }
452
+ current = current[segment];
453
+ }
454
+ return current;
455
+ }
456
+ function isScalar(value) {
457
+ return value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
458
+ }
459
+ function toSummaryValue(value) {
460
+ if (value instanceof Date) {
461
+ return Number.isNaN(value.getTime()) ? null : value.toISOString();
462
+ }
463
+ if (Array.isArray(value)) {
464
+ return value.some((item) => item instanceof Date || item !== null && typeof item === "object") ? value.map((item) => toSummaryValue(item)) : value;
465
+ }
466
+ if (value !== null && typeof value === "object" && !(value instanceof Uint8Array)) {
467
+ return Object.fromEntries(
468
+ Object.entries(value).map(([key, entry]) => [
469
+ key,
470
+ toSummaryValue(entry)
471
+ ])
472
+ );
473
+ }
474
+ return value;
475
+ }
476
+ function isAutoIncludableValue(value) {
477
+ if (isScalar(value) || value instanceof Date) {
478
+ return true;
479
+ }
480
+ if (Array.isArray(value)) {
481
+ return value.every((item) => isScalar(item) || item instanceof Date);
482
+ }
483
+ return false;
484
+ }
485
+ function estimateValueSize(value) {
486
+ if (value === void 0) {
487
+ return 0;
488
+ }
489
+ if (typeof value === "string") {
490
+ return value.length + 2;
491
+ }
492
+ try {
493
+ const json = JSON.stringify(value);
494
+ return json === void 0 ? 0 : json.length;
495
+ } catch {
496
+ return Number.POSITIVE_INFINITY;
497
+ }
498
+ }
499
+ function isExcluded(path, exclude) {
500
+ for (const excluded of exclude) {
501
+ if (path === excluded || path.startsWith(excluded + ".")) {
502
+ return true;
503
+ }
504
+ }
505
+ return false;
506
+ }
507
+ function isEncryptedConventionField(key) {
508
+ return key.endsWith("_encrypted") || key.endsWith("_encrypted_key");
509
+ }
510
+ var ATTACHMENTS_FIELD = "_attachments";
511
+ function projectAttachments(value) {
512
+ if (!Array.isArray(value) || value.length === 0) {
513
+ return void 0;
514
+ }
515
+ const projected = [];
516
+ for (const item of value) {
517
+ if (item === null || typeof item !== "object") {
518
+ continue;
519
+ }
520
+ const raw = item;
521
+ const info = {};
522
+ if (typeof raw.attachmentId === "string") info.attachmentId = raw.attachmentId;
523
+ if (typeof raw.fileName === "string") info.fileName = raw.fileName;
524
+ if (typeof raw.size === "number" && Number.isFinite(raw.size)) info.size = raw.size;
525
+ if (typeof raw.mimeType === "string") info.mimeType = raw.mimeType;
526
+ if (typeof raw.createdAt === "number" && Number.isFinite(raw.createdAt)) {
527
+ info.createdAt = raw.createdAt;
528
+ }
529
+ if (typeof raw.extractedText === "string" && raw.extractedText.length > 0) {
530
+ info.hasExtractedText = true;
531
+ }
532
+ projected.push(info);
533
+ }
534
+ return projected.length > 0 ? projected : void 0;
535
+ }
536
+ function projectRecipients(value) {
537
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
538
+ return void 0;
539
+ }
540
+ const projected = {};
541
+ let count = 0;
542
+ for (const [stableId, item] of Object.entries(value)) {
543
+ if (item === null || typeof item !== "object" || Array.isArray(item)) {
544
+ continue;
545
+ }
546
+ const raw = item;
547
+ const info = {
548
+ kind: raw.kind === "device" ? "device" : "user"
549
+ };
550
+ if (typeof raw.label === "string") info.label = raw.label;
551
+ if (typeof raw.addedAt === "number" && Number.isFinite(raw.addedAt)) {
552
+ info.addedAt = raw.addedAt;
553
+ }
554
+ if (typeof raw.removedAt === "number" && Number.isFinite(raw.removedAt)) {
555
+ info.removedAt = raw.removedAt;
556
+ }
557
+ projected[stableId] = info;
558
+ count += 1;
559
+ }
560
+ return count > 0 ? projected : void 0;
561
+ }
562
+ function extractSummaryFields(data, config) {
563
+ const fields = {};
564
+ if (config.autoInclude) {
565
+ for (const [key, value] of Object.entries(data)) {
566
+ if (key.startsWith("_")) {
567
+ continue;
568
+ }
569
+ if (isEncryptedConventionField(key)) {
570
+ continue;
571
+ }
572
+ if (isExcluded(key, config.exclude)) {
573
+ continue;
574
+ }
575
+ if (!isAutoIncludableValue(value)) {
576
+ continue;
577
+ }
578
+ const summaryValue = toSummaryValue(value);
579
+ if (estimateValueSize(summaryValue) > config.maxValueBytes) {
580
+ continue;
581
+ }
582
+ fields[key] = summaryValue;
583
+ }
584
+ }
585
+ for (const path of config.include) {
586
+ if (isExcluded(path, config.exclude)) {
587
+ continue;
588
+ }
589
+ const value = resolveFieldPath(data, path);
590
+ if (value !== void 0) {
591
+ fields[path] = toSummaryValue(value);
592
+ }
593
+ }
594
+ if (config.includeAttachments && !isExcluded(ATTACHMENTS_FIELD, config.exclude)) {
595
+ const attachments = projectAttachments(data[ATTACHMENTS_FIELD]);
596
+ if (attachments !== void 0) {
597
+ fields[ATTACHMENTS_FIELD] = attachments;
598
+ }
599
+ }
600
+ if (config.includeRecipients && !isExcluded(ENCRYPT_FOR_FIELD, config.exclude)) {
601
+ const recipients = projectRecipients(data[ENCRYPT_FOR_FIELD]);
602
+ if (recipients !== void 0) {
603
+ fields[ENCRYPT_FOR_FIELD] = recipients;
604
+ }
605
+ }
606
+ return fields;
607
+ }
608
+
609
+ // src/core/indexing/fulltext/extractFulltextText.ts
610
+ var BLOCK_MARKER_RE = /[\u{FFFC}\u{0000}-\u{0008}\u{000B}\u{000C}\u{000E}-\u{001F}]/gu;
611
+ function normalizeText(text) {
612
+ return text.replace(BLOCK_MARKER_RE, " ");
613
+ }
614
+ var SPAN_METADATA_KEYS = /* @__PURE__ */ new Set(["type", "marks", "parents", "attr", "attrs"]);
615
+ function collectPlainText(value, depth = 0) {
616
+ if (typeof value === "string") {
617
+ return normalizeText(value);
618
+ }
619
+ if (value === null || typeof value !== "object" || depth > 16) {
620
+ return "";
621
+ }
622
+ if (Array.isArray(value)) {
623
+ const parts2 = [];
624
+ for (const item of value) {
625
+ const text = collectPlainText(item, depth + 1);
626
+ if (text.length > 0) {
627
+ parts2.push(text);
628
+ }
629
+ }
630
+ return parts2.join(" ");
631
+ }
632
+ const raw = value;
633
+ if (typeof raw.type === "string") {
634
+ if ((raw.type === "text" || raw.type === "immutableString") && typeof raw.value === "string") {
635
+ return normalizeText(raw.value);
636
+ }
637
+ if (raw.type === "block") {
638
+ return "";
639
+ }
640
+ }
641
+ const parts = [];
642
+ for (const [key, item] of Object.entries(raw)) {
643
+ if (SPAN_METADATA_KEYS.has(key)) {
644
+ continue;
645
+ }
646
+ const text = collectPlainText(item, depth + 1);
647
+ if (text.length > 0) {
648
+ parts.push(text);
649
+ }
650
+ }
651
+ return parts.join(" ");
652
+ }
653
+ function truncateText(text, maxBytes) {
654
+ if (maxBytes <= 0 || text.length <= maxBytes) {
655
+ return text;
656
+ }
657
+ let end = maxBytes;
658
+ const last = text.charCodeAt(end - 1);
659
+ if (last >= 55296 && last <= 56319) {
660
+ end--;
661
+ }
662
+ return text.slice(0, end);
663
+ }
664
+ function isEncryptedConventionField2(key) {
665
+ return key.endsWith("_encrypted") || key.endsWith("_encrypted_key");
666
+ }
667
+ function extractFulltextFields(data, config) {
668
+ const fields = {};
669
+ if (config.include.length > 0) {
670
+ for (const path of config.include) {
671
+ const text = collectPlainText(resolveFieldPath(data, path));
672
+ if (text.trim().length > 0) {
673
+ fields[path] = truncateText(text, config.maxFieldBytes);
674
+ }
675
+ }
676
+ return fields;
677
+ }
678
+ for (const [key, value] of Object.entries(data)) {
679
+ if (key.startsWith("_") || isEncryptedConventionField2(key)) {
680
+ continue;
681
+ }
682
+ const text = collectPlainText(value);
683
+ if (text.trim().length > 0) {
684
+ fields[key] = truncateText(text, config.maxFieldBytes);
685
+ }
686
+ }
687
+ return fields;
688
+ }
689
+
690
+ // src/core/materialize/automergeToJs.ts
691
+ var automerge = Automerge;
692
+ function isCounter(value) {
693
+ if (value === null || typeof value !== "object") return false;
694
+ if (typeof automerge.isCounter === "function") return automerge.isCounter(value);
695
+ return typeof automerge.Counter === "function" && value instanceof automerge.Counter;
696
+ }
697
+ function isImmutableString(value) {
698
+ if (value === null || typeof value !== "object") return false;
699
+ return typeof automerge.isImmutableString === "function" && automerge.isImmutableString(value);
700
+ }
701
+ function readScalar(value) {
702
+ if (isCounter(value)) return value.value;
703
+ if (isImmutableString(value)) return String(value);
704
+ return value;
705
+ }
706
+ function normalizeScalars(value, depth = 0) {
707
+ if (value === null || typeof value !== "object") return value;
708
+ if (isCounter(value) || isImmutableString(value)) return readScalar(value);
709
+ if (value instanceof Uint8Array || value instanceof Date || depth > 100) return value;
710
+ if (Array.isArray(value)) {
711
+ for (let index = 0; index < value.length; index += 1) {
712
+ value[index] = normalizeScalars(value[index], depth + 1);
713
+ }
714
+ return value;
715
+ }
716
+ const record = value;
717
+ for (const key of Object.keys(record)) {
718
+ record[key] = normalizeScalars(record[key], depth + 1);
719
+ }
720
+ return record;
721
+ }
722
+ function walk(value, depth) {
723
+ if (value === null || value === void 0) return value;
724
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") return value;
725
+ if (value instanceof Uint8Array) return value;
726
+ if (value instanceof Date) return new Date(value.getTime());
727
+ if (isCounter(value) || isImmutableString(value)) return readScalar(value);
728
+ if (depth > 40) return null;
729
+ if (automerge.isText?.(value) || automerge.isRawString?.(value)) return String(value);
730
+ if (Array.isArray(value)) return value.map((item) => walk(item, depth + 1));
731
+ if (typeof value !== "object") return value;
732
+ const record = value;
733
+ if (typeof record.length === "number" && typeof value.concat === "function" && record.kind === void 0 && typeof value.toString === "function") {
734
+ const asString = String(value);
735
+ if (asString && asString !== "[object Object]") return asString;
736
+ }
737
+ const result = {};
738
+ for (const key of Object.keys(record)) {
739
+ if (key.startsWith("_")) continue;
740
+ result[key] = walk(record[key], depth + 1);
741
+ }
742
+ return result;
743
+ }
744
+ function automergeDocToJs(doc) {
745
+ const meta = doc[/* @__PURE__ */ Symbol.for("_am_meta")];
746
+ if (meta?.handle && typeof meta.handle.materialize === "function") {
747
+ try {
748
+ return normalizeScalars(meta.handle.materialize("/"));
749
+ } catch {
750
+ }
751
+ }
752
+ return walk(doc, 0);
753
+ }
754
+
755
+ // src/core/materialize/materializeCore.ts
756
+ function pemToBytes(pem) {
757
+ const base64 = pem.replace(/-----[^-]+-----/g, "").replace(/\s+/g, "");
758
+ const binary = atob(base64);
759
+ const bytes = new Uint8Array(binary.length);
760
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
761
+ return bytes.buffer;
762
+ }
763
+ function bytesKey(bytes) {
764
+ let out = "";
765
+ for (let i = 0; i < bytes.length; i++) out += bytes[i].toString(16).padStart(2, "0");
766
+ return out;
767
+ }
768
+ function verifyKey(deps, pem) {
769
+ const cache = deps.verifyKeys;
770
+ let key = cache?.get(pem);
771
+ if (!key) {
772
+ key = deps.subtle.importKey("spki", pemToBytes(pem), { name: "Ed25519" }, false, ["verify"]);
773
+ cache?.set(pem, key);
774
+ }
775
+ return key;
776
+ }
777
+ function aesKey(deps, raw) {
778
+ const cache = deps.aesKeys;
779
+ const id = cache ? bytesKey(raw) : "";
780
+ let key = cache?.get(id);
781
+ if (!key) {
782
+ key = deps.subtle.importKey("raw", raw.slice(), { name: "AES-GCM" }, false, ["decrypt"]);
783
+ cache?.set(id, key);
784
+ }
785
+ return key;
786
+ }
787
+ async function verifyEntry(deps, entry) {
788
+ if (await computeContentHash(entry.data, deps.subtle) !== entry.meta.contentHash) return false;
789
+ const key = await verifyKey(deps, entry.meta.createdByPublicKey);
790
+ return verifyEntrySignatureWithImportedKey(entry.meta, entry.data, key, deps.subtle, {
791
+ requireMetadataSignature: entry.requireMetadataSignature
792
+ });
793
+ }
794
+ async function decryptEntry(deps, entry, keys) {
795
+ const payload = entry.data;
796
+ if (payload.length < 12) return null;
797
+ const iv = payload.slice(0, 12);
798
+ const encrypted = payload.slice(12);
799
+ for (const raw of keys[entry.meta.decryptionKeyId] ?? []) {
800
+ try {
801
+ const key = await aesKey(deps, raw);
802
+ const plain = await deps.subtle.decrypt({ name: "AES-GCM", iv, tagLength: 128 }, key, encrypted);
803
+ return new Uint8Array(plain);
804
+ } catch {
805
+ }
806
+ }
807
+ return null;
808
+ }
809
+ var MAX_ATTACHMENT_EXTRACT_BYTES = 16 * 1024 * 1024;
810
+ function fulltextOf(doc, data, options) {
811
+ const fulltextFields = extractFulltextFields(data, options.config);
812
+ const attachments = doc._attachments ?? [];
813
+ const parts = [];
814
+ let budget = options.config.maxFieldBytes;
815
+ for (const attachment of attachments) {
816
+ if (budget <= 0) break;
817
+ if (typeof attachment.extractedText === "string") {
818
+ const persisted = attachment.extractedText;
819
+ if (persisted.trim().length > 0) {
820
+ const clipped = persisted.length > budget ? persisted.slice(0, budget) : persisted;
821
+ parts.push(clipped);
822
+ budget -= clipped.length;
823
+ }
824
+ continue;
825
+ }
826
+ if (attachment.extractionStatus !== void 0) continue;
827
+ if (options.extractors && (attachment.size ?? 0) <= MAX_ATTACHMENT_EXTRACT_BYTES) {
828
+ return { fulltextFields, attachmentText: null, fulltextNeedsDocument: true };
829
+ }
830
+ }
831
+ return { fulltextFields, attachmentText: parts.length > 0 ? parts.join(" ") : null };
832
+ }
833
+ async function materializeDocument(task, deps) {
834
+ const { docId } = task;
835
+ const fail = (reason) => ({ docId, ok: false, reason });
836
+ const previousBudget = getDocumentLoadBudget();
837
+ if (task.loadBudget !== void 0) setDocumentLoadBudget(task.loadBudget);
838
+ try {
839
+ const appliedEntryIds = [];
840
+ let doc;
841
+ let snapshotBytes = null;
842
+ if (task.snapshot) {
843
+ if (!await verifyEntry(deps, task.snapshot)) return fail("snapshot-signature");
844
+ const plain = await decryptEntry(deps, task.snapshot, task.keys);
845
+ if (!plain) return fail("key");
846
+ assertDocumentLoadWithinBudget(docId, plain, []);
847
+ doc = Automerge.load(plain);
848
+ if (!snapshotHeadsMatch(Automerge.getHeads(doc), task.snapshot.meta.snapshotHeadHashes)) {
849
+ return fail("snapshot-heads");
850
+ }
851
+ snapshotBytes = plain;
852
+ appliedEntryIds.push(task.snapshot.meta.id);
853
+ } else {
854
+ doc = Automerge.init();
855
+ }
856
+ const verified = await Promise.all(task.entries.map((entry) => verifyEntry(deps, entry)));
857
+ const invalidEntryIds = task.entries.filter((_, i) => !verified[i]).map((entry) => entry.meta.id);
858
+ const toApply = task.entries.filter((_, i) => verified[i]);
859
+ const decrypted = await Promise.all(toApply.map((entry) => decryptEntry(deps, entry, task.keys)));
860
+ if (decrypted.some((plain) => !plain)) return fail("key");
861
+ const changes = decrypted;
862
+ appliedEntryIds.push(...toApply.map((entry) => entry.meta.id));
863
+ if (changes.length > 0) {
864
+ assertDocumentLoadWithinBudget(docId, snapshotBytes, changes);
865
+ doc = applyChangesInSlices(doc, changes);
866
+ }
867
+ const lastModified = doc._lastModified;
868
+ const data = task.summary || task.fulltext ? automergeDocToJs(doc) : {};
869
+ const fulltext = task.fulltext ? fulltextOf(doc, data, task.fulltext) : null;
870
+ return {
871
+ docId,
872
+ ok: true,
873
+ appliedEntryIds,
874
+ invalidEntryIds,
875
+ ...typeof lastModified === "number" ? { payloadLastModified: lastModified } : {},
876
+ ...task.summary ? { summaryFields: extractSummaryFields(data, task.summary) } : {},
877
+ ...fulltext ?? {}
878
+ };
879
+ } catch (error) {
880
+ return fail(error instanceof Error ? `${error.name}: ${error.message}` : String(error));
881
+ } finally {
882
+ if (task.loadBudget !== void 0) setDocumentLoadBudget(previousBudget);
883
+ }
884
+ }
885
+ function materializeDocuments(tasks, deps) {
886
+ return Promise.all(tasks.map((task) => materializeDocument(task, deps)));
887
+ }
888
+
889
+ // src/core/materialize/workerPool.ts
890
+ function installMaterializeWorker(scope) {
891
+ const deps = { subtle: globalThis.crypto.subtle, verifyKeys: /* @__PURE__ */ new Map(), aesKeys: /* @__PURE__ */ new Map() };
892
+ scope.addEventListener("message", (event) => {
893
+ const request = event.data;
894
+ void materializeDocuments(request.tasks, deps).then(
895
+ (results) => scope.postMessage({ id: request.id, results })
896
+ );
897
+ });
898
+ scope.postMessage({ ready: true });
899
+ }
900
+
901
+ // src/browser/materializeWorker.ts
902
+ installMaterializeWorker(self);