wiki-graph-sdk 0.7.0 → 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
@@ -32,12 +32,15 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
32
32
  var worker_exports = {};
33
33
  __export(worker_exports, {
34
34
  applyChapterJobArtifactFile: () => import_worker2.applyChapterJobArtifactFile,
35
+ applyWikiGraphJobArtifacts: () => applyWikiGraphJobArtifacts,
35
36
  createLocalChapterJobFileExecutor: () => import_worker2.createLocalChapterJobFileExecutor,
37
+ extractWikiGraphJobSnapshots: () => extractWikiGraphJobSnapshots,
36
38
  runBuildJobWorker: () => runBuildJobWorker,
37
39
  writeChapterJobInputFile: () => import_worker2.writeChapterJobInputFile
38
40
  });
39
41
  module.exports = __toCommonJS(worker_exports);
40
42
  var import_worker = require("wiki-graph-core/worker");
43
+ var import_wiki_graph_core3 = require("wiki-graph-core");
41
44
 
42
45
  // src/node-platform.ts
43
46
  var asyncHooks = __toESM(require("async_hooks"), 1);
@@ -46,7 +49,7 @@ var fs = __toESM(require("fs"), 1);
46
49
  var fsPromises = __toESM(require("fs/promises"), 1);
47
50
  var os = __toESM(require("os"), 1);
48
51
  var pathModule = __toESM(require("path"), 1);
49
- var process = __toESM(require("process"), 1);
52
+ var process2 = __toESM(require("process"), 1);
50
53
  var import_node_stream = require("stream");
51
54
  var import_promises = require("stream/promises");
52
55
  var sqlite3 = __toESM(require("sqlite3"), 1);
@@ -54,7 +57,7 @@ var yauzl = __toESM(require("yauzl"), 1);
54
57
  var yazl = __toESM(require("yazl"), 1);
55
58
  var import_nunjucks = require("nunjucks");
56
59
  var import_platform = require("wiki-graph-core/platform");
57
- var nodeProcess = process.default ?? process;
60
+ var nodeProcess = process2.default ?? process2;
58
61
  var nodeSqlite3 = sqlite3.default ?? sqlite3;
59
62
  var NODE_RESOURCE_KIND = /* @__PURE__ */ Symbol.for("wiki-graph-sdk.node-resource.v1");
60
63
  var NodeFile = class {
@@ -266,6 +269,14 @@ function decodeNodeResourceIdentity(identity, kind) {
266
269
  return void 0;
267
270
  }
268
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
+ }
269
280
  function assertChildName(name) {
270
281
  if (name.length === 0 || name === "." || name === ".." || pathModule.isAbsolute(name) || name.includes("/") || name.includes("\\")) {
271
282
  throw new TypeError(`Directory child must be a relative name: ${name}`);
@@ -277,42 +288,42 @@ var NodeDatabaseConnection = class {
277
288
  }
278
289
  database;
279
290
  async close() {
280
- await new Promise((resolve2, reject) => {
291
+ await new Promise((resolve4, reject) => {
281
292
  this.database.close((error) => {
282
293
  if (error) reject(error);
283
- else resolve2();
294
+ else resolve4();
284
295
  });
285
296
  });
286
297
  }
287
298
  async execute(sql) {
288
- await new Promise((resolve2, reject) => {
299
+ await new Promise((resolve4, reject) => {
289
300
  this.database.exec(sql, (error) => {
290
301
  if (error) reject(error);
291
- else resolve2();
302
+ else resolve4();
292
303
  });
293
304
  });
294
305
  }
295
306
  async queryAll(sql, params = []) {
296
- return await new Promise((resolve2, reject) => {
307
+ return await new Promise((resolve4, reject) => {
297
308
  this.database.all(sql, [...params], (error, rows) => {
298
309
  if (error) reject(error);
299
- else resolve2(rows);
310
+ else resolve4(rows);
300
311
  });
301
312
  });
302
313
  }
303
314
  async queryOne(sql, params = []) {
304
- return await new Promise((resolve2, reject) => {
315
+ return await new Promise((resolve4, reject) => {
305
316
  this.database.get(sql, [...params], (error, row) => {
306
317
  if (error) reject(error);
307
- else resolve2(row);
318
+ else resolve4(row);
308
319
  });
309
320
  });
310
321
  }
311
322
  async run(sql, params = []) {
312
- await new Promise((resolve2, reject) => {
323
+ await new Promise((resolve4, reject) => {
313
324
  this.database.run(sql, [...params], (error) => {
314
325
  if (error) reject(error);
315
- else resolve2();
326
+ else resolve4();
316
327
  });
317
328
  });
318
329
  }
@@ -326,10 +337,10 @@ async function openNativeNodeDatabase(file, flags) {
326
337
  if (path === void 0) {
327
338
  throw new TypeError("The Node database adapter requires a NodeFile");
328
339
  }
329
- return await new Promise((resolve2, reject) => {
340
+ return await new Promise((resolve4, reject) => {
330
341
  const database = new nodeSqlite3.Database(path, flags, (error) => {
331
342
  if (error) reject(error);
332
- else resolve2(database);
343
+ else resolve4(database);
333
344
  });
334
345
  });
335
346
  }
@@ -338,19 +349,19 @@ async function openNodeZip(file) {
338
349
  if (path === void 0) {
339
350
  throw new TypeError("The Node ZIP adapter requires a NodeFile");
340
351
  }
341
- const zipFile = await new Promise((resolve2, reject) => {
352
+ const zipFile = await new Promise((resolve4, reject) => {
342
353
  yauzl.open(
343
354
  path,
344
355
  { autoClose: false, lazyEntries: true },
345
356
  (error, opened) => {
346
357
  if (error || opened === void 0)
347
358
  reject(error ?? new Error("Cannot open ZIP"));
348
- else resolve2(opened);
359
+ else resolve4(opened);
349
360
  }
350
361
  );
351
362
  });
352
363
  const entries = await new Promise(
353
- (resolve2, reject) => {
364
+ (resolve4, reject) => {
354
365
  const discovered = /* @__PURE__ */ new Map();
355
366
  const rejectAndClose = (error) => {
356
367
  zipFile.close();
@@ -360,7 +371,7 @@ async function openNodeZip(file) {
360
371
  };
361
372
  const resolveEntries = () => {
362
373
  zipFile.off("error", rejectAndClose);
363
- resolve2(discovered);
374
+ resolve4(discovered);
364
375
  };
365
376
  zipFile.on("entry", (entry) => {
366
377
  if (!entry.fileName.endsWith("/")) {
@@ -470,12 +481,12 @@ async function collectDecodedNodeStreamRange(input, offset, length) {
470
481
  return Buffer.concat(chunks, collected);
471
482
  }
472
483
  async function openNodeZipEntryStream(zipFile, entry, options) {
473
- return await new Promise((resolve2, reject) => {
484
+ return await new Promise((resolve4, reject) => {
474
485
  const callback = (error, opened) => {
475
486
  if (error || opened === void 0) {
476
487
  reject(error ?? new Error(`Cannot read ZIP entry: ${entry.fileName}`));
477
488
  } else {
478
- resolve2(opened);
489
+ resolve4(opened);
479
490
  }
480
491
  };
481
492
  if (options === void 0) zipFile.openReadStream(entry, callback);
@@ -606,11 +617,11 @@ async function writeNodeStream(input, writer) {
606
617
  );
607
618
  }
608
619
  async function collectNodeStream(input) {
609
- return await new Promise((resolve2, reject) => {
620
+ return await new Promise((resolve4, reject) => {
610
621
  const chunks = [];
611
622
  input.on("data", (chunk) => chunks.push(chunk));
612
623
  input.once("error", reject);
613
- input.once("end", () => resolve2(Buffer.concat(chunks)));
624
+ input.once("end", () => resolve4(Buffer.concat(chunks)));
614
625
  });
615
626
  }
616
627
  var nodeWikiGraphPlatform = {
@@ -711,6 +722,14 @@ function installNodeWikiGraphPlatform(stateRoot) {
711
722
  (0, import_platform.installWikiGraphPlatform)(nodeWikiGraphPlatform);
712
723
  (0, import_platform.installWikiGraphStorage)(createNodeWikiGraphStorage(stateRoot));
713
724
  }
725
+ function ensureNodeWikiGraphPlatform() {
726
+ (0, import_platform.installWikiGraphPlatform)(nodeWikiGraphPlatform);
727
+ try {
728
+ (0, import_platform.getWikiGraphStorage)();
729
+ } catch {
730
+ (0, import_platform.installWikiGraphStorage)(createNodeWikiGraphStorage());
731
+ }
732
+ }
714
733
  async function withNodeWikiGraphStorage(stateRoot, operation) {
715
734
  return await (0, import_platform.withWikiGraphStorage)(
716
735
  stateRoot === void 0 ? void 0 : createNodeWikiGraphStorage(stateRoot),
@@ -718,8 +737,293 @@ async function withNodeWikiGraphStorage(stateRoot, operation) {
718
737
  );
719
738
  }
720
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
+
721
966
  // src/worker.ts
722
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
+ }
998
+ async function applyWikiGraphJobArtifacts(options) {
999
+ ensureNodeWikiGraphPlatform();
1000
+ return await withNodeWikiGraphStorage(options.stateDir, async () => {
1001
+ const location = await resolveWikiGraphArchiveLocation(options.archive);
1002
+ let applied = 0;
1003
+ await writeWikiGraphArchiveLocation(
1004
+ location,
1005
+ async (document) => {
1006
+ for await (const artifact of options.artifacts) {
1007
+ options.signal?.throwIfAborted();
1008
+ const revision = await document.serials.getRevision(
1009
+ artifact.chapterId
1010
+ );
1011
+ await (0, import_worker.applyChapterJobArtifactFile)(
1012
+ document,
1013
+ artifact.chapterId,
1014
+ artifact.kind,
1015
+ revision,
1016
+ new NodeFile(artifact.artifactPath)
1017
+ );
1018
+ applied += 1;
1019
+ }
1020
+ },
1021
+ { invalidateContinuationCursors: true }
1022
+ );
1023
+ options.signal?.throwIfAborted();
1024
+ return { applied };
1025
+ });
1026
+ }
723
1027
  async function runBuildJobWorker(options) {
724
1028
  installNodeWikiGraphPlatform();
725
1029
  const { stateDir, ...coreOptions } = options;
@@ -731,7 +1035,9 @@ async function runBuildJobWorker(options) {
731
1035
  // Annotate the CommonJS export names for ESM import in node:
732
1036
  0 && (module.exports = {
733
1037
  applyChapterJobArtifactFile,
1038
+ applyWikiGraphJobArtifacts,
734
1039
  createLocalChapterJobFileExecutor,
1040
+ extractWikiGraphJobSnapshots,
735
1041
  runBuildJobWorker,
736
1042
  writeChapterJobInputFile
737
1043
  });