wiki-graph-sdk 0.7.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/worker.cjs CHANGED
@@ -34,12 +34,13 @@ __export(worker_exports, {
34
34
  applyChapterJobArtifactFile: () => import_worker2.applyChapterJobArtifactFile,
35
35
  applyWikiGraphJobArtifacts: () => applyWikiGraphJobArtifacts,
36
36
  createLocalChapterJobFileExecutor: () => import_worker2.createLocalChapterJobFileExecutor,
37
+ extractWikiGraphJobSnapshots: () => extractWikiGraphJobSnapshots,
37
38
  runBuildJobWorker: () => runBuildJobWorker,
38
39
  writeChapterJobInputFile: () => import_worker2.writeChapterJobInputFile
39
40
  });
40
41
  module.exports = __toCommonJS(worker_exports);
41
42
  var import_worker = require("wiki-graph-core/worker");
42
- var import_wiki_graph_core = require("wiki-graph-core");
43
+ var import_wiki_graph_core3 = require("wiki-graph-core");
43
44
 
44
45
  // src/node-platform.ts
45
46
  var asyncHooks = __toESM(require("async_hooks"), 1);
@@ -48,7 +49,7 @@ var fs = __toESM(require("fs"), 1);
48
49
  var fsPromises = __toESM(require("fs/promises"), 1);
49
50
  var os = __toESM(require("os"), 1);
50
51
  var pathModule = __toESM(require("path"), 1);
51
- var process = __toESM(require("process"), 1);
52
+ var process2 = __toESM(require("process"), 1);
52
53
  var import_node_stream = require("stream");
53
54
  var import_promises = require("stream/promises");
54
55
  var sqlite3 = __toESM(require("sqlite3"), 1);
@@ -56,7 +57,7 @@ var yauzl = __toESM(require("yauzl"), 1);
56
57
  var yazl = __toESM(require("yazl"), 1);
57
58
  var import_nunjucks = require("nunjucks");
58
59
  var import_platform = require("wiki-graph-core/platform");
59
- var nodeProcess = process.default ?? process;
60
+ var nodeProcess = process2.default ?? process2;
60
61
  var nodeSqlite3 = sqlite3.default ?? sqlite3;
61
62
  var NODE_RESOURCE_KIND = /* @__PURE__ */ Symbol.for("wiki-graph-sdk.node-resource.v1");
62
63
  var NodeFile = class {
@@ -268,6 +269,14 @@ function decodeNodeResourceIdentity(identity, kind) {
268
269
  return void 0;
269
270
  }
270
271
  }
272
+ function getNodeResourcePath(resource) {
273
+ const brandedPath = getBrandedNodeResourcePath(resource, resource.kind);
274
+ if (brandedPath !== void 0) return brandedPath;
275
+ if (typeof resource === "object" && resource !== null && "path" in resource && typeof resource.path === "string") {
276
+ return resource.path;
277
+ }
278
+ throw new TypeError("Expected a Node File or Directory resource");
279
+ }
271
280
  function assertChildName(name) {
272
281
  if (name.length === 0 || name === "." || name === ".." || pathModule.isAbsolute(name) || name.includes("/") || name.includes("\\")) {
273
282
  throw new TypeError(`Directory child must be a relative name: ${name}`);
@@ -279,42 +288,42 @@ var NodeDatabaseConnection = class {
279
288
  }
280
289
  database;
281
290
  async close() {
282
- await new Promise((resolve2, reject) => {
291
+ await new Promise((resolve4, reject) => {
283
292
  this.database.close((error) => {
284
293
  if (error) reject(error);
285
- else resolve2();
294
+ else resolve4();
286
295
  });
287
296
  });
288
297
  }
289
298
  async execute(sql) {
290
- await new Promise((resolve2, reject) => {
299
+ await new Promise((resolve4, reject) => {
291
300
  this.database.exec(sql, (error) => {
292
301
  if (error) reject(error);
293
- else resolve2();
302
+ else resolve4();
294
303
  });
295
304
  });
296
305
  }
297
306
  async queryAll(sql, params = []) {
298
- return await new Promise((resolve2, reject) => {
307
+ return await new Promise((resolve4, reject) => {
299
308
  this.database.all(sql, [...params], (error, rows) => {
300
309
  if (error) reject(error);
301
- else resolve2(rows);
310
+ else resolve4(rows);
302
311
  });
303
312
  });
304
313
  }
305
314
  async queryOne(sql, params = []) {
306
- return await new Promise((resolve2, reject) => {
315
+ return await new Promise((resolve4, reject) => {
307
316
  this.database.get(sql, [...params], (error, row) => {
308
317
  if (error) reject(error);
309
- else resolve2(row);
318
+ else resolve4(row);
310
319
  });
311
320
  });
312
321
  }
313
322
  async run(sql, params = []) {
314
- await new Promise((resolve2, reject) => {
323
+ await new Promise((resolve4, reject) => {
315
324
  this.database.run(sql, [...params], (error) => {
316
325
  if (error) reject(error);
317
- else resolve2();
326
+ else resolve4();
318
327
  });
319
328
  });
320
329
  }
@@ -328,10 +337,10 @@ async function openNativeNodeDatabase(file, flags) {
328
337
  if (path === void 0) {
329
338
  throw new TypeError("The Node database adapter requires a NodeFile");
330
339
  }
331
- return await new Promise((resolve2, reject) => {
340
+ return await new Promise((resolve4, reject) => {
332
341
  const database = new nodeSqlite3.Database(path, flags, (error) => {
333
342
  if (error) reject(error);
334
- else resolve2(database);
343
+ else resolve4(database);
335
344
  });
336
345
  });
337
346
  }
@@ -340,19 +349,19 @@ async function openNodeZip(file) {
340
349
  if (path === void 0) {
341
350
  throw new TypeError("The Node ZIP adapter requires a NodeFile");
342
351
  }
343
- const zipFile = await new Promise((resolve2, reject) => {
352
+ const zipFile = await new Promise((resolve4, reject) => {
344
353
  yauzl.open(
345
354
  path,
346
355
  { autoClose: false, lazyEntries: true },
347
356
  (error, opened) => {
348
357
  if (error || opened === void 0)
349
358
  reject(error ?? new Error("Cannot open ZIP"));
350
- else resolve2(opened);
359
+ else resolve4(opened);
351
360
  }
352
361
  );
353
362
  });
354
363
  const entries = await new Promise(
355
- (resolve2, reject) => {
364
+ (resolve4, reject) => {
356
365
  const discovered = /* @__PURE__ */ new Map();
357
366
  const rejectAndClose = (error) => {
358
367
  zipFile.close();
@@ -362,7 +371,7 @@ async function openNodeZip(file) {
362
371
  };
363
372
  const resolveEntries = () => {
364
373
  zipFile.off("error", rejectAndClose);
365
- resolve2(discovered);
374
+ resolve4(discovered);
366
375
  };
367
376
  zipFile.on("entry", (entry) => {
368
377
  if (!entry.fileName.endsWith("/")) {
@@ -472,12 +481,12 @@ async function collectDecodedNodeStreamRange(input, offset, length) {
472
481
  return Buffer.concat(chunks, collected);
473
482
  }
474
483
  async function openNodeZipEntryStream(zipFile, entry, options) {
475
- return await new Promise((resolve2, reject) => {
484
+ return await new Promise((resolve4, reject) => {
476
485
  const callback = (error, opened) => {
477
486
  if (error || opened === void 0) {
478
487
  reject(error ?? new Error(`Cannot read ZIP entry: ${entry.fileName}`));
479
488
  } else {
480
- resolve2(opened);
489
+ resolve4(opened);
481
490
  }
482
491
  };
483
492
  if (options === void 0) zipFile.openReadStream(entry, callback);
@@ -608,11 +617,11 @@ async function writeNodeStream(input, writer) {
608
617
  );
609
618
  }
610
619
  async function collectNodeStream(input) {
611
- return await new Promise((resolve2, reject) => {
620
+ return await new Promise((resolve4, reject) => {
612
621
  const chunks = [];
613
622
  input.on("data", (chunk) => chunks.push(chunk));
614
623
  input.once("error", reject);
615
- input.once("end", () => resolve2(Buffer.concat(chunks)));
624
+ input.once("end", () => resolve4(Buffer.concat(chunks)));
616
625
  });
617
626
  }
618
627
  var nodeWikiGraphPlatform = {
@@ -728,13 +737,271 @@ async function withNodeWikiGraphStorage(stateRoot, operation) {
728
737
  );
729
738
  }
730
739
 
740
+ // src/archive/target.ts
741
+ var import_promises2 = require("fs/promises");
742
+ var import_path2 = require("path");
743
+ var import_wiki_graph_core = require("wiki-graph-core");
744
+
745
+ // src/runtime-path.ts
746
+ var import_os = require("os");
747
+ var import_path = require("path");
748
+
749
+ // src/runtime-context.ts
750
+ var import_async_hooks = require("async_hooks");
751
+ var RUNTIME_CONTEXT_KEY = /* @__PURE__ */ Symbol.for("wiki-graph-sdk.runtime-context.v1");
752
+ var runtimeContext = getRuntimeContextStorage();
753
+ function getRuntimeContextStorage() {
754
+ const runtimeGlobal = globalThis;
755
+ const existing = runtimeGlobal[RUNTIME_CONTEXT_KEY];
756
+ if (existing !== void 0) {
757
+ return existing;
758
+ }
759
+ const storage = new import_async_hooks.AsyncLocalStorage();
760
+ Object.defineProperty(runtimeGlobal, RUNTIME_CONTEXT_KEY, {
761
+ configurable: false,
762
+ enumerable: false,
763
+ value: storage,
764
+ writable: false
765
+ });
766
+ return storage;
767
+ }
768
+ function getWikiGraphSDKRuntimeContext() {
769
+ return runtimeContext.getStore() ?? {
770
+ cwd: process.cwd(),
771
+ env: process.env,
772
+ envPolicy: "production"
773
+ };
774
+ }
775
+
776
+ // src/runtime-path.ts
777
+ function resolveWikiGraphRuntimePath(path) {
778
+ const context = getWikiGraphSDKRuntimeContext();
779
+ const environmentHome = context.env.HOME?.trim();
780
+ const home = environmentHome === void 0 || environmentHome === "" ? (0, import_os.homedir)() : environmentHome;
781
+ if (path === "~") return home;
782
+ if (path.startsWith("~/")) return (0, import_path.resolve)(home, path.slice(2));
783
+ return (0, import_path.isAbsolute)(path) ? path : (0, import_path.resolve)(context.cwd, path);
784
+ }
785
+
786
+ // src/archive/target.ts
787
+ var WikiGraphArchiveOwnershipError = class extends Error {
788
+ code = "WIKI_GRAPH_ARCHIVE_OWNERSHIP_MISMATCH";
789
+ constructor(message) {
790
+ super(message);
791
+ this.name = "WikiGraphArchiveOwnershipError";
792
+ }
793
+ };
794
+ async function resolveWikiGraphArchiveLocation(target) {
795
+ if (target.kind === "standalone") {
796
+ return await resolveStandaloneLocation(target);
797
+ }
798
+ return await resolveLibraryLocation(target);
799
+ }
800
+ async function assertStandaloneWikiGraphArchivePath(inputPath) {
801
+ const path = resolveWikiGraphRuntimePath(inputPath);
802
+ const candidate = await canonicalPath(path);
803
+ const candidateIdentity = await readFileIdentity(path);
804
+ const libraries = await (0, import_wiki_graph_core.listWikiGraphLibraries)();
805
+ const matches = await findMatchingMembers(
806
+ libraries,
807
+ candidate,
808
+ candidateIdentity
809
+ );
810
+ if (matches.length > 0) {
811
+ const match = requireUnambiguousManagedMatch(path, matches);
812
+ throw new WikiGraphArchiveOwnershipError(
813
+ `Standalone archive path belongs to registered library ${(0, import_wiki_graph_core.formatWikiGraphLibraryUri)(
814
+ match.library.isDefault ? void 0 : match.library.publicId
815
+ )}: ${path}. Use the library UUID URI ${match.archive.uri} instead.`
816
+ );
817
+ }
818
+ for (const library of libraries) {
819
+ const rootPath = getNodeResourcePath(library.folder);
820
+ const root = await canonicalPath(rootPath);
821
+ if (!isWithin(root, candidate)) continue;
822
+ throw new WikiGraphArchiveOwnershipError(
823
+ `Standalone archive path belongs to registered library ${(0, import_wiki_graph_core.formatWikiGraphLibraryUri)(
824
+ library.isDefault ? void 0 : library.publicId
825
+ )}: ${path}. Scan the library, then address the archive by its library UUID URI.`
826
+ );
827
+ }
828
+ return path;
829
+ }
830
+ async function resolveStandaloneLocation(target) {
831
+ if (target.path.startsWith("wikg://lib/")) {
832
+ throw new WikiGraphArchiveOwnershipError(
833
+ `A library archive URI cannot be used as a standalone path: ${target.path}`
834
+ );
835
+ }
836
+ const path = await assertStandaloneWikiGraphArchivePath(target.path);
837
+ const normalized = {
838
+ kind: "standalone",
839
+ path,
840
+ ...target.objectUri === void 0 ? {} : { objectUri: target.objectUri }
841
+ };
842
+ return {
843
+ archiveFile: new NodeFile(path),
844
+ archiveKey: path,
845
+ archivePath: path,
846
+ indexScope: { archiveKey: path, archivePath: path, kind: "archive-index" },
847
+ locatedUri: (0, import_wiki_graph_core.formatLocatedWikiGraphUri)(path, target.objectUri),
848
+ target: normalized
849
+ };
850
+ }
851
+ async function resolveLibraryLocation(target) {
852
+ const parsedLocated = (0, import_wiki_graph_core.parseLocatedWikiGraphUri)(target.uri);
853
+ const archiveUri = parsedLocated.archivePath ?? target.uri;
854
+ const parsed = (0, import_wiki_graph_core.parseWikiGraphLibraryUri)(archiveUri);
855
+ if (parsed?.kind !== "archive") {
856
+ throw new WikiGraphArchiveOwnershipError(
857
+ `Library archive target must be a UUID archive URI: ${target.uri}`
858
+ );
859
+ }
860
+ await (0, import_wiki_graph_core.resolveWikiGraphLibrary)(parsed);
861
+ const archiveFile = await (0, import_wiki_graph_core.resolveWikiGraphLibraryArchiveFile)(archiveUri);
862
+ const normalized = {
863
+ kind: "library",
864
+ uri: target.uri
865
+ };
866
+ return {
867
+ archiveFile,
868
+ archiveKey: archiveUri,
869
+ archivePath: archiveUri,
870
+ indexScope: {
871
+ archiveKey: archiveUri,
872
+ archivePath: archiveUri,
873
+ kind: "archive-index"
874
+ },
875
+ libraryArchiveTarget: parsed,
876
+ locatedUri: target.uri,
877
+ publicArchiveUri: archiveUri,
878
+ target: normalized
879
+ };
880
+ }
881
+ async function canonicalPath(path) {
882
+ try {
883
+ return await (0, import_promises2.realpath)(path);
884
+ } catch {
885
+ const absolute = (0, import_path2.resolve)(path);
886
+ const parent = (0, import_path2.dirname)(absolute);
887
+ return parent === absolute ? absolute : (0, import_path2.join)(await canonicalPath(parent), (0, import_path2.basename)(absolute));
888
+ }
889
+ }
890
+ function isWithin(root, candidate) {
891
+ const child = (0, import_path2.relative)(root, candidate);
892
+ return child === "" || !child.startsWith("..") && !(0, import_path2.isAbsolute)(child);
893
+ }
894
+ async function findMatchingMembers(libraries, candidate, candidateIdentity) {
895
+ const members = [];
896
+ for (const library of libraries) {
897
+ const archives = await (0, import_wiki_graph_core.listWikiGraphLibraryArchives)({
898
+ isDefault: library.isDefault,
899
+ kind: "scope",
900
+ ...library.isDefault ? {} : { publicId: library.publicId }
901
+ });
902
+ for (const archive of archives) {
903
+ if (archive.file === void 0) continue;
904
+ members.push({
905
+ archive,
906
+ library,
907
+ memberPath: getNodeResourcePath(archive.file)
908
+ });
909
+ }
910
+ }
911
+ const exact = [];
912
+ for (const member of members) {
913
+ if (await canonicalPath(member.memberPath) === candidate) {
914
+ exact.push(member);
915
+ }
916
+ }
917
+ if (exact.length > 0 || candidateIdentity === void 0) return exact;
918
+ const identityMatches = [];
919
+ for (const member of members) {
920
+ if (await readFileIdentity(member.memberPath) === candidateIdentity) {
921
+ identityMatches.push(member);
922
+ }
923
+ }
924
+ return identityMatches;
925
+ }
926
+ function requireUnambiguousManagedMatch(path, matches) {
927
+ if (matches.length === 1) return matches[0];
928
+ throw new WikiGraphArchiveOwnershipError(
929
+ `Archive file identity is ambiguous across managed archives: ${path}. Use an explicit library UUID URI (${matches.map((match) => match.archive.uri).join(", ")}).`
930
+ );
931
+ }
932
+ async function readFileIdentity(path) {
933
+ try {
934
+ const value = await (0, import_promises2.stat)(path);
935
+ return `${value.dev}:${value.ino}`;
936
+ } catch {
937
+ return void 0;
938
+ }
939
+ }
940
+
941
+ // src/archive/write.ts
942
+ var import_wiki_graph_core2 = require("wiki-graph-core");
943
+ async function writeWikiGraphArchiveLocation(location, operation, options = {}) {
944
+ const cacheOnly = options.searchIndexWritebackPolicy === "cache";
945
+ const write = async (archiveFile = location.archiveFile) => await new import_wiki_graph_core2.WikiGraphArchiveFile(archiveFile).write(operation, {
946
+ ...cacheOnly ? {} : { derivedStateKeys: [location.archiveKey, location.archivePath] },
947
+ ...options.invalidateContinuationCursors === void 0 ? {} : {
948
+ invalidateContinuationCursors: options.invalidateContinuationCursors
949
+ },
950
+ ...options.searchIndexWritebackPolicy === void 0 ? {} : { searchIndexWritebackPolicy: options.searchIndexWritebackPolicy }
951
+ });
952
+ if (location.libraryArchiveTarget === void 0 || cacheOnly || options.refreshLibraryIndex === false) {
953
+ return await write();
954
+ }
955
+ return await (0, import_wiki_graph_core2.writeWikiGraphLibraryArchive)({
956
+ additionalDerivedStateKeys: [location.archiveKey, location.archivePath],
957
+ ...options.invalidateContinuationCursors === void 0 ? {} : {
958
+ invalidateContinuationCursors: options.invalidateContinuationCursors
959
+ },
960
+ ...options.onIndexSyncError === void 0 ? {} : { onIndexSyncError: options.onIndexSyncError },
961
+ operation: async (archiveFile) => await write(archiveFile),
962
+ target: location.libraryArchiveTarget
963
+ });
964
+ }
965
+
731
966
  // src/worker.ts
732
967
  var import_worker2 = require("wiki-graph-core/worker");
968
+ async function extractWikiGraphJobSnapshots(options) {
969
+ ensureNodeWikiGraphPlatform();
970
+ return await withNodeWikiGraphStorage(
971
+ options.stateDir,
972
+ async () => await new import_wiki_graph_core3.WikiGraphArchiveFile(
973
+ new NodeFile(options.wikgPath)
974
+ ).readDocument(async (document) => {
975
+ const results = [];
976
+ for (const request of options.requests) {
977
+ options.signal?.throwIfAborted();
978
+ const chapterId = await (0, import_wiki_graph_core3.resolveChapterPathReadonly)(
979
+ document,
980
+ request.chapterPath
981
+ );
982
+ const revision = await (0, import_worker.writeChapterJobInputFile)(
983
+ document,
984
+ chapterId,
985
+ request.kind,
986
+ new NodeFile(request.outputPath),
987
+ request.options
988
+ );
989
+ const result = { ...request, chapterId, revision };
990
+ results.push(result);
991
+ await options.onSnapshot?.(result);
992
+ }
993
+ options.signal?.throwIfAborted();
994
+ return results;
995
+ })
996
+ );
997
+ }
733
998
  async function applyWikiGraphJobArtifacts(options) {
734
999
  ensureNodeWikiGraphPlatform();
735
1000
  return await withNodeWikiGraphStorage(options.stateDir, async () => {
1001
+ const location = await resolveWikiGraphArchiveLocation(options.archive);
736
1002
  let applied = 0;
737
- await new import_wiki_graph_core.WikiGraphArchiveFile(new NodeFile(options.wikgPath)).write(
1003
+ await writeWikiGraphArchiveLocation(
1004
+ location,
738
1005
  async (document) => {
739
1006
  for await (const artifact of options.artifacts) {
740
1007
  options.signal?.throwIfAborted();
@@ -750,7 +1017,8 @@ async function applyWikiGraphJobArtifacts(options) {
750
1017
  );
751
1018
  applied += 1;
752
1019
  }
753
- }
1020
+ },
1021
+ { invalidateContinuationCursors: true }
754
1022
  );
755
1023
  options.signal?.throwIfAborted();
756
1024
  return { applied };
@@ -769,6 +1037,7 @@ async function runBuildJobWorker(options) {
769
1037
  applyChapterJobArtifactFile,
770
1038
  applyWikiGraphJobArtifacts,
771
1039
  createLocalChapterJobFileExecutor,
1040
+ extractWikiGraphJobSnapshots,
772
1041
  runBuildJobWorker,
773
1042
  writeChapterJobInputFile
774
1043
  });