wiki-graph-sdk 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/dist/archives.cjs +316 -142
  2. package/dist/archives.cjs.map +1 -1
  3. package/dist/archives.js +326 -148
  4. package/dist/archives.js.map +1 -1
  5. package/dist/conversions.cjs +268 -99
  6. package/dist/conversions.cjs.map +1 -1
  7. package/dist/conversions.js +274 -103
  8. package/dist/conversions.js.map +1 -1
  9. package/dist/default-worker.cjs +258 -101
  10. package/dist/default-worker.cjs.map +1 -1
  11. package/dist/default-worker.js +264 -105
  12. package/dist/default-worker.js.map +1 -1
  13. package/dist/embedding.cjs +214 -54
  14. package/dist/embedding.cjs.map +1 -1
  15. package/dist/embedding.js +214 -54
  16. package/dist/embedding.js.map +1 -1
  17. package/dist/gc.cjs +214 -54
  18. package/dist/gc.cjs.map +1 -1
  19. package/dist/gc.js +214 -54
  20. package/dist/gc.js.map +1 -1
  21. package/dist/index.cjs +354 -174
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.js +369 -184
  25. package/dist/index.js.map +1 -1
  26. package/dist/local-config.cjs +214 -54
  27. package/dist/local-config.cjs.map +1 -1
  28. package/dist/local-config.js +214 -54
  29. package/dist/local-config.js.map +1 -1
  30. package/dist/maintenance.cjs +264 -97
  31. package/dist/maintenance.cjs.map +1 -1
  32. package/dist/maintenance.js +270 -101
  33. package/dist/maintenance.js.map +1 -1
  34. package/dist/node-platform.cjs +214 -54
  35. package/dist/node-platform.cjs.map +1 -1
  36. package/dist/node-platform.d.ts +2 -0
  37. package/dist/node-platform.js +214 -54
  38. package/dist/node-platform.js.map +1 -1
  39. package/dist/runtime-config.cjs +214 -54
  40. package/dist/runtime-config.cjs.map +1 -1
  41. package/dist/runtime-config.js +214 -54
  42. package/dist/runtime-config.js.map +1 -1
  43. package/dist/stage.cjs +214 -54
  44. package/dist/stage.cjs.map +1 -1
  45. package/dist/stage.js +214 -54
  46. package/dist/stage.js.map +1 -1
  47. package/dist/worker.cjs +257 -96
  48. package/dist/worker.cjs.map +1 -1
  49. package/dist/worker.js +263 -100
  50. package/dist/worker.js.map +1 -1
  51. package/package.json +2 -2
package/dist/worker.js CHANGED
@@ -45,6 +45,15 @@ var NodeFile = class {
45
45
  this.name = name;
46
46
  }
47
47
  path;
48
+ async getPhysicalIdentity() {
49
+ const value = await fsPromises.stat(this.path).catch((error) => {
50
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT")
51
+ return void 0;
52
+ throw error;
53
+ });
54
+ if (value === void 0) return void 0;
55
+ return `${value.dev}:${value.ino}`;
56
+ }
48
57
  kind = "file";
49
58
  [NODE_RESOURCE_KIND] = "file";
50
59
  identity;
@@ -169,6 +178,15 @@ var NodeDirectory = class _NodeDirectory {
169
178
  this.name = pathModule.basename(path);
170
179
  }
171
180
  path;
181
+ async getPhysicalIdentity() {
182
+ const value = await fsPromises.stat(this.path).catch((error) => {
183
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT")
184
+ return void 0;
185
+ throw error;
186
+ });
187
+ if (value === void 0) return void 0;
188
+ return `${value.dev}:${value.ino}`;
189
+ }
172
190
  kind = "directory";
173
191
  [NODE_RESOURCE_KIND] = "directory";
174
192
  identity;
@@ -178,8 +196,10 @@ var NodeDirectory = class _NodeDirectory {
178
196
  const file = new NodeFile(pathModule.join(this.path, name));
179
197
  try {
180
198
  return (await fsPromises.stat(file.path)).isFile() ? file : void 0;
181
- } catch {
182
- return void 0;
199
+ } catch (error) {
200
+ if (typeof error === "object" && error !== null && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
201
+ return void 0;
202
+ throw error;
183
203
  }
184
204
  }
185
205
  async getLastModified() {
@@ -197,8 +217,10 @@ var NodeDirectory = class _NodeDirectory {
197
217
  const directory = new _NodeDirectory(pathModule.join(this.path, name));
198
218
  try {
199
219
  return (await fsPromises.stat(directory.path)).isDirectory() ? directory : void 0;
200
- } catch {
201
- return void 0;
220
+ } catch (error) {
221
+ if (typeof error === "object" && error !== null && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
222
+ return void 0;
223
+ throw error;
202
224
  }
203
225
  }
204
226
  async list() {
@@ -322,14 +344,23 @@ async function openNativeNodeDatabase(file, flags) {
322
344
  });
323
345
  });
324
346
  }
325
- async function openNodeZip(file) {
347
+ async function openNodeZip(file, options = {}) {
326
348
  const path = getBrandedNodeResourcePath(file, "file");
327
349
  if (path === void 0) {
328
350
  throw new TypeError("The Node ZIP adapter requires a NodeFile");
329
351
  }
330
- const zipFile = await new Promise((resolve4, reject) => {
331
- yauzl.open(
332
- path,
352
+ const handle = await fsPromises.open(path, "r");
353
+ let size;
354
+ try {
355
+ size = (await handle.stat()).size;
356
+ } catch (error) {
357
+ await handle.close();
358
+ throw error;
359
+ }
360
+ const open2 = () => new Promise((resolve4, reject) => {
361
+ yauzl.fromRandomAccessReader(
362
+ new NodeZipSource(handle),
363
+ size,
333
364
  { autoClose: false, lazyEntries: true },
334
365
  (error, opened) => {
335
366
  if (error || opened === void 0)
@@ -338,63 +369,192 @@ async function openNodeZip(file) {
338
369
  }
339
370
  );
340
371
  });
341
- const entries = await new Promise(
342
- (resolve4, reject) => {
343
- const discovered = /* @__PURE__ */ new Map();
344
- const rejectAndClose = (error) => {
345
- zipFile.close();
346
- reject(
347
- error instanceof Error ? error : new Error("Cannot scan ZIP central directory")
348
- );
349
- };
350
- const resolveEntries = () => {
351
- zipFile.off("error", rejectAndClose);
352
- resolve4(discovered);
353
- };
354
- zipFile.on("entry", (entry) => {
355
- if (!entry.fileName.endsWith("/")) {
356
- discovered.set(entry.fileName, entry);
357
- }
358
- zipFile.readEntry();
359
- });
360
- zipFile.once("error", rejectAndClose);
361
- zipFile.once("end", resolveEntries);
362
- zipFile.readEntry();
363
- }
364
- );
372
+ try {
373
+ (await open2()).close();
374
+ } catch (error) {
375
+ await handle.close();
376
+ throw error;
377
+ }
365
378
  let closed = false;
379
+ let pending = Promise.resolve();
380
+ let closing;
381
+ const run = (operation) => {
382
+ if (closed)
383
+ return Promise.reject(new Error("Cannot read a closed ZIP archive"));
384
+ const result = pending.then(async () => {
385
+ const zip = await open2();
386
+ try {
387
+ return await operation(zip);
388
+ } finally {
389
+ zip.close();
390
+ }
391
+ });
392
+ pending = result.then(
393
+ () => void 0,
394
+ () => void 0
395
+ );
396
+ return result;
397
+ };
398
+ const withEntry = (name, operation) => run(async (zip) => {
399
+ let exact;
400
+ let alias;
401
+ let aliasCollision = false;
402
+ await scanNodeZip(zip, (entry) => {
403
+ if (entry.fileName === name) exact = entry;
404
+ if (normalizeNodeZipName(entry.fileName) === name) {
405
+ if (alias !== void 0 && alias.fileName !== entry.fileName)
406
+ aliasCollision = true;
407
+ alias = entry;
408
+ }
409
+ });
410
+ if ((exact === void 0 || options.entryNameMode === "normalized") && aliasCollision) {
411
+ let bestPosition = -1;
412
+ const candidates = await open2();
413
+ try {
414
+ await scanNodeZip(candidates, async (entry) => {
415
+ if (normalizeNodeZipName(entry.fileName) !== name) return;
416
+ const probe = await open2();
417
+ let position = 0;
418
+ try {
419
+ await scanNodeZip(probe, (candidate) => {
420
+ if (candidate.fileName === entry.fileName) return false;
421
+ position++;
422
+ });
423
+ } finally {
424
+ probe.close();
425
+ }
426
+ if (position >= bestPosition) {
427
+ bestPosition = position;
428
+ alias = entry;
429
+ }
430
+ });
431
+ return await operation(candidates, alias);
432
+ } finally {
433
+ candidates.close();
434
+ }
435
+ }
436
+ return await operation(
437
+ zip,
438
+ options.entryNameMode === "normalized" ? alias : exact ?? alias
439
+ );
440
+ });
366
441
  return {
367
442
  close: () => {
368
- if (!closed) zipFile.close();
369
443
  closed = true;
370
- return Promise.resolve();
444
+ closing ??= pending.then(() => handle.close());
445
+ return closing;
371
446
  },
372
- copyEntry: async (name, target) => {
373
- if (closed) throw new Error("Cannot read a closed ZIP archive");
374
- const entry = entries.get(name);
447
+ copyEntry: (name, target) => withEntry(name, async (zip, entry) => {
375
448
  if (entry === void 0) return false;
376
- await copyNodeZipEntry(zipFile, entry, target);
449
+ await copyNodeZipEntry(zip, entry, target);
377
450
  return true;
378
- },
379
- getEntrySize: (name) => {
380
- if (closed) throw new Error("Cannot read a closed ZIP archive");
381
- return Promise.resolve(entries.get(name)?.uncompressedSize);
382
- },
383
- listEntries: () => Promise.resolve([...entries.keys()]),
384
- readEntryRange: async (name, offset, length) => {
385
- if (closed) throw new Error("Cannot read a closed ZIP archive");
386
- const entry = entries.get(name);
451
+ }),
452
+ getEntrySize: (name) => withEntry(
453
+ name,
454
+ (_zip, entry) => Promise.resolve(entry?.uncompressedSize)
455
+ ),
456
+ listEntries: () => run(async (zip) => {
457
+ const names = /* @__PURE__ */ new Set();
458
+ await scanNodeZip(zip, (entry) => {
459
+ names.add(entry.fileName);
460
+ });
461
+ return [...names];
462
+ }),
463
+ readEntryRange: (name, offset, length) => withEntry(name, async (zip, entry) => {
387
464
  if (entry === void 0) return void 0;
388
- return await readNodeZipEntryRange(zipFile, entry, offset, length);
389
- },
390
- readEntry: async (name) => {
391
- if (closed) throw new Error("Cannot read a closed ZIP archive");
392
- const entry = entries.get(name);
465
+ return await readNodeZipEntryRange(zip, entry, offset, length);
466
+ }),
467
+ readEntry: (name) => withEntry(name, async (zip, entry) => {
393
468
  if (entry === void 0) return void 0;
394
- return await readNodeZipEntry(zipFile, entry);
395
- }
469
+ return await readNodeZipEntry(zip, entry);
470
+ })
396
471
  };
397
472
  }
473
+ var NodeZipSource = class extends yauzl.RandomAccessReader {
474
+ constructor(handle) {
475
+ super();
476
+ this.handle = handle;
477
+ }
478
+ handle;
479
+ read(buffer, offset, length, position, callback) {
480
+ const read2 = (written) => {
481
+ if (written === length) {
482
+ callback(null);
483
+ return;
484
+ }
485
+ fs.read(
486
+ this.handle.fd,
487
+ buffer,
488
+ offset + written,
489
+ length - written,
490
+ position + written,
491
+ (error, bytesRead) => {
492
+ if (error) callback(error);
493
+ else if (bytesRead === 0)
494
+ callback(new Error("Unexpected end of ZIP file"));
495
+ else read2(written + bytesRead);
496
+ }
497
+ );
498
+ };
499
+ read2(0);
500
+ }
501
+ _readStreamForRange(start, end) {
502
+ const handle = this.handle;
503
+ return Readable.from(
504
+ (async function* () {
505
+ for (let position = start; position < end; ) {
506
+ const buffer = Buffer.allocUnsafe(
507
+ Math.min(64 * 1024, end - position)
508
+ );
509
+ const { bytesRead } = await handle.read(
510
+ buffer,
511
+ 0,
512
+ buffer.length,
513
+ position
514
+ );
515
+ if (bytesRead === 0) return;
516
+ position += bytesRead;
517
+ yield buffer.subarray(0, bytesRead);
518
+ }
519
+ })()
520
+ );
521
+ }
522
+ };
523
+ function normalizeNodeZipName(name) {
524
+ const normalized = name.replaceAll("\\", "/").trim().split("/").filter((part) => part !== "" && part !== ".").join("/");
525
+ return normalized.split("/").includes("..") ? void 0 : normalized;
526
+ }
527
+ async function scanNodeZip(zip, visit) {
528
+ await new Promise((resolve4, reject) => {
529
+ const cleanup = () => {
530
+ zip.off("entry", onEntry);
531
+ zip.off("end", onEnd);
532
+ zip.off("error", onError);
533
+ };
534
+ const onError = (error) => {
535
+ cleanup();
536
+ reject(error);
537
+ };
538
+ const onEnd = () => {
539
+ cleanup();
540
+ resolve4();
541
+ };
542
+ const onEntry = (entry) => {
543
+ void Promise.resolve().then(() => entry.fileName.endsWith("/") ? void 0 : visit(entry)).then((keepReading) => {
544
+ if (keepReading === false) onEnd();
545
+ else zip.readEntry();
546
+ }).catch(
547
+ (error) => onError(
548
+ error instanceof Error ? error : new Error("Cannot scan ZIP", { cause: error })
549
+ )
550
+ );
551
+ };
552
+ zip.on("entry", onEntry);
553
+ zip.once("end", onEnd);
554
+ zip.once("error", onError);
555
+ zip.readEntry();
556
+ });
557
+ }
398
558
  async function copyNodeZipEntry(zipFile, entry, target) {
399
559
  const writer = await target.openWriter();
400
560
  try {
@@ -804,16 +964,18 @@ async function withWikiGraphSDKHost(options, operation) {
804
964
 
805
965
  // src/archive/target.ts
806
966
  import { realpath, stat as stat2 } from "fs/promises";
807
- import { basename as basename2, dirname as dirname2, isAbsolute as isAbsolute3, join as join2, relative, resolve as resolve3 } from "path";
967
+ import { basename as basename2, dirname as dirname2, join as join2, resolve as resolve3 } from "path";
808
968
  import {
809
969
  formatLocatedWikiGraphUri,
810
970
  formatWikiGraphLibraryUri,
811
- listWikiGraphLibraries,
812
- listWikiGraphLibraryArchives,
971
+ findWikiGraphLibraryByPhysicalIdentity,
972
+ findWikiGraphLibraryArchivePhysicalAliases,
813
973
  parseLocatedWikiGraphUri,
814
974
  parseWikiGraphLibraryUri,
815
975
  resolveWikiGraphLibrary,
816
- resolveWikiGraphLibraryArchiveFile
976
+ resolveWikiGraphLibraryArchiveFile,
977
+ isWikiGraphSchemaVersionError,
978
+ WikiGraphSchemaVersionError
817
979
  } from "wiki-graph-core";
818
980
 
819
981
  // src/runtime-path.ts
@@ -846,12 +1008,7 @@ async function assertStandaloneWikiGraphArchivePath(inputPath) {
846
1008
  const path = resolveWikiGraphRuntimePath(inputPath);
847
1009
  const candidate = await canonicalPath(path);
848
1010
  const candidateIdentity = await readFileIdentity(path);
849
- const libraries = await listWikiGraphLibraries();
850
- const matches = await findMatchingMembers(
851
- libraries,
852
- candidate,
853
- candidateIdentity
854
- );
1011
+ const matches = await findMatchingMembers(candidate, candidateIdentity);
855
1012
  if (matches.length > 0) {
856
1013
  const match = requireUnambiguousManagedMatch(path, matches);
857
1014
  throw new WikiGraphArchiveOwnershipError(
@@ -860,15 +1017,26 @@ async function assertStandaloneWikiGraphArchivePath(inputPath) {
860
1017
  )}: ${path}. Use the library UUID URI ${match.archive.uri} instead.`
861
1018
  );
862
1019
  }
863
- for (const library of libraries) {
864
- const rootPath = getNodeResourcePath(library.folder);
865
- const root = await canonicalPath(rootPath);
866
- if (!isWithin(root, candidate)) continue;
867
- throw new WikiGraphArchiveOwnershipError(
868
- `Standalone archive path belongs to registered library ${formatWikiGraphLibraryUri(
869
- library.isDefault ? void 0 : library.publicId
870
- )}: ${path}. Scan the library, then address the archive by its library UUID URI.`
1020
+ const ancestors = /* @__PURE__ */ new Set();
1021
+ for (const start of [candidate, resolve3(path)]) {
1022
+ for (let parent = dirname2(start); ; parent = dirname2(parent)) {
1023
+ ancestors.add(parent);
1024
+ if (dirname2(parent) === parent) break;
1025
+ }
1026
+ }
1027
+ for (const parent of ancestors) {
1028
+ const identity = await readFileIdentity(parent);
1029
+ const library = await findWikiGraphLibraryByPhysicalIdentity(
1030
+ identity,
1031
+ new NodeDirectory(parent).identity
871
1032
  );
1033
+ if (library !== void 0) {
1034
+ throw new WikiGraphArchiveOwnershipError(
1035
+ `Standalone archive path belongs to registered library ${formatWikiGraphLibraryUri(
1036
+ library.isDefault ? void 0 : library.publicId
1037
+ )}: ${path}. Scan the library, then address the archive by its library UUID URI.`
1038
+ );
1039
+ }
872
1040
  }
873
1041
  return path;
874
1042
  }
@@ -926,48 +1094,35 @@ async function resolveLibraryLocation(target) {
926
1094
  async function canonicalPath(path) {
927
1095
  try {
928
1096
  return await realpath(path);
929
- } catch {
1097
+ } catch (error) {
1098
+ if (!(typeof error === "object" && error !== null && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")))
1099
+ throw error;
930
1100
  const absolute = resolve3(path);
931
1101
  const parent = dirname2(absolute);
932
1102
  return parent === absolute ? absolute : join2(await canonicalPath(parent), basename2(absolute));
933
1103
  }
934
1104
  }
935
- function isWithin(root, candidate) {
936
- const child = relative(root, candidate);
937
- return child === "" || !child.startsWith("..") && !isAbsolute3(child);
938
- }
939
- async function findMatchingMembers(libraries, candidate, candidateIdentity) {
1105
+ async function findMatchingMembers(candidate, candidateIdentity) {
1106
+ if (candidateIdentity === void 0) return [];
1107
+ const archives = await findWikiGraphLibraryArchivePhysicalAliases(candidateIdentity);
940
1108
  const members = [];
941
- for (const library of libraries) {
942
- const archives = await listWikiGraphLibraryArchives({
943
- isDefault: library.isDefault,
944
- kind: "scope",
945
- ...library.isDefault ? {} : { publicId: library.publicId }
946
- });
947
- for (const archive of archives) {
948
- const physical = archive.file ?? archive.directory;
949
- if (physical === void 0) continue;
1109
+ for (const archive of archives) {
1110
+ const parsed = parseWikiGraphLibraryUri(archive.libraryUri);
1111
+ const library = await resolveWikiGraphLibrary(parsed);
1112
+ const physical = archive.file ?? archive.directory;
1113
+ if (library !== void 0 && physical !== void 0)
950
1114
  members.push({
951
1115
  archive,
952
1116
  library,
953
1117
  memberPath: getNodeResourcePath(physical)
954
1118
  });
955
- }
956
1119
  }
957
1120
  const exact = [];
958
1121
  for (const member of members) {
959
- if (await canonicalPath(member.memberPath) === candidate) {
1122
+ if (await canonicalPath(member.memberPath) === candidate)
960
1123
  exact.push(member);
961
- }
962
- }
963
- if (exact.length > 0 || candidateIdentity === void 0) return exact;
964
- const identityMatches = [];
965
- for (const member of members) {
966
- if (await readFileIdentity(member.memberPath) === candidateIdentity) {
967
- identityMatches.push(member);
968
- }
969
1124
  }
970
- return identityMatches;
1125
+ return exact.length > 0 ? exact : members;
971
1126
  }
972
1127
  function requireUnambiguousManagedMatch(path, matches) {
973
1128
  if (matches.length === 1) return matches[0];
@@ -979,8 +1134,10 @@ async function readFileIdentity(path) {
979
1134
  try {
980
1135
  const value = await stat2(path);
981
1136
  return `${value.dev}:${value.ino}`;
982
- } catch {
983
- return void 0;
1137
+ } catch (error) {
1138
+ if (typeof error === "object" && error !== null && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR"))
1139
+ return void 0;
1140
+ throw error;
984
1141
  }
985
1142
  }
986
1143
 
@@ -993,6 +1150,12 @@ import {
993
1150
  async function writeWikiGraphArchiveLocation(location, operation, options = {}) {
994
1151
  const cacheOnly = options.searchIndexWritebackPolicy === "cache";
995
1152
  const write = async (archiveFile = location.archiveFile) => {
1153
+ if (cacheOnly) {
1154
+ return await new WikiGraphArchiveFile(archiveFile).readDocument(
1155
+ operation,
1156
+ { searchIndexWritebackPolicy: "cache" }
1157
+ );
1158
+ }
996
1159
  const writeOptions = {
997
1160
  ...cacheOnly ? {} : { derivedStateKeys: [location.archiveKey, location.archivePath] },
998
1161
  ...options.invalidateContinuationCursors === void 0 ? {} : {