@modernrelay/orbit-core 0.17.0 → 0.18.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/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { DIAGNOSTIC_SAMPLE_CAP, resolveSimulation, encodeStringTable, collectTransfers, deriveClusters, resolveClusterCenters, clusterCentroids, EnvelopeSequencer, RequestLedger } from './chunk-IOC3RWQY.js';
2
- export { DEFAULT_CLUSTER_CENTER_RADIUS, DEFAULT_LAYOUT_SEED, DIAGNOSTIC_SAMPLE_CAP, SIMULATION_PRESETS, acceptColumnar, clusterCentroids, collectTransfers, decodeStringTable, deriveClusters, encodeStringTable, generateClusterCenters, judgeEpoch, resolveClusterCenters, resolveSimulation } from './chunk-IOC3RWQY.js';
1
+ import { DIAGNOSTIC_SAMPLE_CAP, resolveSimulation, encodeStringTable, collectTransfers, deriveClusters, resolveClusterCenters, clusterCentroids, EnvelopeSequencer, RequestLedger } from './chunk-A3J27JF2.js';
2
+ export { DEFAULT_CLUSTER_CENTER_RADIUS, DEFAULT_LAYOUT_SEED, DIAGNOSTIC_SAMPLE_CAP, SIMULATION_PRESETS, acceptColumnar, clusterCentroids, collectTransfers, decodeStringTable, deriveClusters, encodeStringTable, generateClusterCenters, judgeEpoch, resolveClusterCenters, resolveSimulation } from './chunk-A3J27JF2.js';
3
3
  import { createStore } from 'zustand/vanilla';
4
4
 
5
5
  // src/errors.ts
@@ -2657,6 +2657,114 @@ function resolveScope(accepted, spec, adjacency) {
2657
2657
  return { nodeIds, nodes, edges };
2658
2658
  }
2659
2659
 
2660
+ // src/exploration.ts
2661
+ function invalidQuery(detail) {
2662
+ throw new OrbitOperationError({ code: "invalid-operation", detail }, detail);
2663
+ }
2664
+ function boundedInteger(value, fallback, min, max, name) {
2665
+ const result = value ?? fallback;
2666
+ if (!Number.isInteger(result) || result < min || result > max) {
2667
+ invalidQuery(`${name} must be an integer from ${min} to ${max}`);
2668
+ }
2669
+ return result;
2670
+ }
2671
+ function validateRelationships(options) {
2672
+ if (options.direction !== void 0 && !["outgoing", "incoming", "either"].includes(options.direction)) {
2673
+ invalidQuery("direction must be outgoing, incoming, or either");
2674
+ }
2675
+ if (options.relationshipTypeField !== void 0 && (typeof options.relationshipTypeField !== "string" || options.relationshipTypeField.length === 0)) {
2676
+ invalidQuery("relationshipTypeField must be a non-empty string");
2677
+ }
2678
+ if (options.relationshipTypes !== void 0 && (!Array.isArray(options.relationshipTypes) || options.relationshipTypes.some((v) => typeof v !== "string"))) {
2679
+ invalidQuery("relationshipTypes must be an array of strings");
2680
+ }
2681
+ return {
2682
+ ...options,
2683
+ ...options.relationshipTypes === void 0 ? {} : { relationshipTypes: [...new Set(options.relationshipTypes)].sort() }
2684
+ };
2685
+ }
2686
+ function validateCursor(cursor) {
2687
+ if (cursor !== void 0 && (typeof cursor !== "string" || cursor.length === 0 || cursor.length > 1e5)) {
2688
+ invalidQuery("cursor must be a non-empty continuation token");
2689
+ }
2690
+ }
2691
+ function validateExpansion(options) {
2692
+ const result = validateRelationships(options);
2693
+ boundedInteger(options.hops, 1, 1, 1e3, "hops");
2694
+ boundedInteger(options.limit, 50, 1, 1e3, "limit");
2695
+ boundedInteger(options.edgeLimit, 1e4, 1, 1e4, "edgeLimit");
2696
+ validateCursor(options.cursor);
2697
+ if (options.preserveLayout !== void 0 && typeof options.preserveLayout !== "boolean") invalidQuery("preserveLayout must be boolean");
2698
+ if (options.onProgress !== void 0 && typeof options.onProgress !== "function") invalidQuery("onProgress must be a function");
2699
+ return result;
2700
+ }
2701
+ function validatePath(options) {
2702
+ const result = validateRelationships(options);
2703
+ if (options.universe !== void 0 && options.universe !== "visible" && options.universe !== "loaded") invalidQuery("universe must be visible or loaded");
2704
+ if (options.maxHops !== void 0) boundedInteger(options.maxHops, 0, 0, 1e3, "maxHops");
2705
+ return result;
2706
+ }
2707
+ function relationshipType(edge, field2 = "type") {
2708
+ const attrs = edge.attrs;
2709
+ const value = attrs?.[field2];
2710
+ return typeof value === "string" ? value : "";
2711
+ }
2712
+ function matchesRelationship(edge, options) {
2713
+ return options.relationshipTypes === void 0 || options.relationshipTypes.includes(relationshipType(edge, options.relationshipTypeField));
2714
+ }
2715
+ function pageOffset(cursor, key) {
2716
+ if (cursor === void 0) return 0;
2717
+ try {
2718
+ const parsed = JSON.parse(cursor);
2719
+ if (Array.isArray(parsed) && parsed.length === 2 && parsed[0] === key && Number.isSafeInteger(parsed[1]) && parsed[1] >= 0) return parsed[1];
2720
+ } catch {
2721
+ }
2722
+ return invalidQuery("cursor is stale or belongs to a different query");
2723
+ }
2724
+ function neighborhoodOf(accepted, seedId, rawOptions, revisionKey, visibilityOf, edgeVisible) {
2725
+ const options = validateRelationships(rawOptions);
2726
+ const limit = boundedInteger(options.limit, 50, 1, 1e3, "limit");
2727
+ const edgeLimit = boundedInteger(options.edgeLimit, 200, 1, 1e4, "edgeLimit");
2728
+ validateCursor(options.cursor);
2729
+ if (options.visibility !== void 0 && options.visibility !== "loaded" && options.visibility !== "visible") invalidQuery("visibility must be loaded or visible");
2730
+ const key = JSON.stringify([revisionKey, seedId, options.direction ?? "either", options.relationshipTypes ?? null, options.relationshipTypeField ?? "type", options.visibility ?? "loaded", limit, edgeLimit]);
2731
+ const offset = pageOffset(options.cursor, key);
2732
+ const empty = { seedId, status: "not-loaded", nodes: [], edges: [], visibility: /* @__PURE__ */ new Map(), relationshipTypes: [], totalNeighbors: 0, totalEdges: 0, edgesTruncated: false };
2733
+ if (accepted === null || !accepted.nodeIndex.has(seedId)) return empty;
2734
+ const neighbors = /* @__PURE__ */ new Set();
2735
+ const matched = [];
2736
+ const counts = /* @__PURE__ */ new Map();
2737
+ const direction = options.direction ?? "either";
2738
+ for (const edge of accepted.edges) {
2739
+ let neighbor;
2740
+ if (edge.source === seedId && direction !== "incoming") neighbor = edge.target;
2741
+ else if (edge.target === seedId && direction !== "outgoing") neighbor = edge.source;
2742
+ if (neighbor === void 0 || !accepted.nodeIndex.has(neighbor)) continue;
2743
+ if (options.visibility === "visible" && (!edgeVisible(edge.id) || visibilityOf(neighbor) !== "visible" || visibilityOf(seedId) !== "visible")) continue;
2744
+ const type = relationshipType(edge, options.relationshipTypeField);
2745
+ counts.set(type, (counts.get(type) ?? 0) + 1);
2746
+ if (!matchesRelationship(edge, options)) continue;
2747
+ if (neighbor !== seedId) neighbors.add(neighbor);
2748
+ matched.push(edge);
2749
+ }
2750
+ const ids = [...neighbors].slice(offset, offset + limit);
2751
+ const pageIds = /* @__PURE__ */ new Set([seedId, ...ids]);
2752
+ const pageEdges = matched.filter((e) => pageIds.has(e.source) && pageIds.has(e.target));
2753
+ const result = {
2754
+ seedId,
2755
+ status: "loaded",
2756
+ nodes: ids.map((id) => accepted.nodes[accepted.nodeIndex.get(id)]),
2757
+ edges: pageEdges.slice(0, edgeLimit),
2758
+ visibility: new Map(ids.map((id) => [id, visibilityOf(id)])),
2759
+ relationshipTypes: [...counts].map(([type, count]) => ({ type, count })),
2760
+ totalNeighbors: neighbors.size,
2761
+ totalEdges: matched.length,
2762
+ edgesTruncated: pageEdges.length > edgeLimit
2763
+ };
2764
+ if (offset + limit < neighbors.size) result.nextCursor = JSON.stringify([key, offset + limit]);
2765
+ return result;
2766
+ }
2767
+
2660
2768
  // src/services.ts
2661
2769
  var DIMENSION_ORDER = ["source", "model", "scope"];
2662
2770
  var requestSeq = 0;
@@ -2741,8 +2849,94 @@ function throwAborted(signal) {
2741
2849
  );
2742
2850
  }
2743
2851
  function createLocalExpansionService(getBase) {
2852
+ const pages = /* @__PURE__ */ new Map();
2853
+ const MAX_LIVE_PLANS = 256;
2854
+ async function queryNeighbors(seedIds, rawOptions, ctx) {
2855
+ const options = validateExpansion(rawOptions);
2856
+ if (ctx.signal.aborted) throwAborted(ctx.signal);
2857
+ const { cursor: _cursor, onProgress: _progress, preserveLayout: _preserve, ...params } = options;
2858
+ const key = canonicalJson([ctx.datasetKey, ctx.sourceRevision, seedIds, { ...params, hops: options.hops ?? 1, direction: options.direction ?? "either", relationshipTypeField: options.relationshipTypeField ?? "type", limit: options.limit ?? 50, edgeLimit: options.edgeLimit ?? 1e4 }]);
2859
+ let plan;
2860
+ let token;
2861
+ let offset = 0;
2862
+ if (options.cursor !== void 0) {
2863
+ let decoded;
2864
+ try {
2865
+ decoded = JSON.parse(options.cursor);
2866
+ } catch {
2867
+ invalidQuery("invalid expansion cursor");
2868
+ }
2869
+ if (!Array.isArray(decoded) || decoded.length !== 2 || typeof decoded[0] !== "string" || !Number.isSafeInteger(decoded[1]) || decoded[1] < 0) invalidQuery("invalid expansion cursor");
2870
+ token = decoded[0];
2871
+ offset = decoded[1];
2872
+ const cached = pages.get(token);
2873
+ if (cached === void 0 || cached.key !== key) invalidQuery("expansion cursor is stale or belongs to a different query");
2874
+ plan = cached;
2875
+ pages.delete(token);
2876
+ pages.set(token, plan);
2877
+ } else {
2878
+ const { accepted } = getBase();
2879
+ const seeds = new Set(seedIds.filter((id) => accepted.nodeIndex.has(id)));
2880
+ const adjacency = /* @__PURE__ */ new Map();
2881
+ const edges2 = [];
2882
+ const direction = options.direction ?? "either";
2883
+ let scanned = 0;
2884
+ for (const edge of accepted.edges) {
2885
+ if (++scanned % 4096 === 0) {
2886
+ await new Promise((resolve) => setTimeout(resolve, 0));
2887
+ if (ctx.signal.aborted) throwAborted(ctx.signal);
2888
+ }
2889
+ if (!matchesRelationship(edge, options)) continue;
2890
+ edges2.push(edge);
2891
+ if (direction !== "incoming") {
2892
+ const list = adjacency.get(edge.source) ?? [];
2893
+ list.push(edge.target);
2894
+ adjacency.set(edge.source, list);
2895
+ }
2896
+ if (direction !== "outgoing") {
2897
+ const list = adjacency.get(edge.target) ?? [];
2898
+ list.push(edge.source);
2899
+ adjacency.set(edge.target, list);
2900
+ }
2901
+ }
2902
+ const seen = new Set(seeds);
2903
+ const queue = [...seeds];
2904
+ const depths = queue.map(() => 0);
2905
+ for (let head = 0; head < queue.length; head++) {
2906
+ if (depths[head] >= (options.hops ?? 1)) continue;
2907
+ for (const neighbor of adjacency.get(queue[head]) ?? []) {
2908
+ if (++scanned % 4096 === 0) {
2909
+ await new Promise((resolve) => setTimeout(resolve, 0));
2910
+ if (ctx.signal.aborted) throwAborted(ctx.signal);
2911
+ }
2912
+ if (seen.has(neighbor) || !accepted.nodeIndex.has(neighbor)) continue;
2913
+ seen.add(neighbor);
2914
+ queue.push(neighbor);
2915
+ depths.push(depths[head] + 1);
2916
+ }
2917
+ }
2918
+ plan = { key, seeds, nodes: queue.filter((id) => !seeds.has(id)).map((id) => accepted.nodes[accepted.nodeIndex.get(id)]), edges: edges2 };
2919
+ token = ctx.requestId;
2920
+ pages.set(token, plan);
2921
+ }
2922
+ if (ctx.signal.aborted) throwAborted(ctx.signal);
2923
+ const limit = options.limit ?? 50;
2924
+ const nodes = plan.nodes.slice(offset, offset + limit);
2925
+ const ids = /* @__PURE__ */ new Set([...plan.seeds, ...nodes.map((node) => node.id)]);
2926
+ const pageEdges = plan.edges.filter((edge) => ids.has(edge.source) && ids.has(edge.target));
2927
+ const edges = pageEdges.slice(0, options.edgeLimit ?? 1e4);
2928
+ const nextCursor = offset + limit < plan.nodes.length ? JSON.stringify([token, offset + limit]) : void 0;
2929
+ if (nextCursor === void 0) pages.delete(token);
2930
+ else while (pages.size > MAX_LIVE_PLANS) pages.delete(pages.keys().next().value);
2931
+ return {
2932
+ nodes,
2933
+ edges,
2934
+ page: { returnedNodes: nodes.length, returnedEdges: edges.length, totalNeighbors: plan.nodes.length, truncated: nextCursor !== void 0 || edges.length < pageEdges.length, ...nextCursor === void 0 ? {} : { nextCursor } }
2935
+ };
2936
+ }
2744
2937
  return {
2745
2938
  revisionDependencies: ["source"],
2939
+ queryNeighbors,
2746
2940
  async neighbors(seedIds, hops, ctx) {
2747
2941
  if (ctx.signal.aborted) throwAborted(ctx.signal);
2748
2942
  const { accepted, adjacency } = getBase();
@@ -2813,78 +3007,97 @@ function throwAborted2(signal, sourceId, targetId) {
2813
3007
  );
2814
3008
  }
2815
3009
  function createLocalPathService(getBase) {
2816
- return {
2817
- revisionDependencies: ["source", "model", "scope"],
2818
- async find(sourceId, targetId, options, ctx) {
2819
- if (ctx.signal.aborted) throwAborted2(ctx.signal, sourceId, targetId);
2820
- const direction = options.direction ?? "outgoing";
2821
- const { nodes, edges, isEdgeVisible } = getBase();
2822
- const ordinalOf = /* @__PURE__ */ new Map();
2823
- for (let i = 0; i < nodes.length; i++) {
2824
- const id = nodes[i].id;
2825
- if (!ordinalOf.has(id)) ordinalOf.set(id, i);
2826
- }
2827
- const src = ordinalOf.get(sourceId);
2828
- const dst = ordinalOf.get(targetId);
2829
- if (src === void 0 || dst === void 0) return null;
2830
- if (src === dst) return { nodeIds: [nodes[src].id], edgeIds: [] };
2831
- const adjacency = new Array(nodes.length);
2832
- const edgeIds = new Array(edges.length);
2833
- const counters = /* @__PURE__ */ new Map();
2834
- let scanned = 0;
2835
- for (let e = 0; e < edges.length; e++) {
3010
+ async function findDetailed(sourceId, targetId, rawOptions, ctx) {
3011
+ const options = validatePath(rawOptions);
3012
+ if (ctx.signal.aborted) throwAborted2(ctx.signal, sourceId, targetId);
3013
+ const direction = options.direction ?? "outgoing";
3014
+ const { nodes, edges, isEdgeVisible, isNodeVisible } = getBase();
3015
+ const ordinalOf = /* @__PURE__ */ new Map();
3016
+ for (let i = 0; i < nodes.length; i++) if (!ordinalOf.has(nodes[i].id)) ordinalOf.set(nodes[i].id, i);
3017
+ const missing = [.../* @__PURE__ */ new Set([sourceId, targetId])].filter((id) => !ordinalOf.has(id));
3018
+ if (missing.length > 0) return { status: "not-loaded", nodeIds: missing };
3019
+ const filtered = options.universe === "loaded" ? [] : [.../* @__PURE__ */ new Set([sourceId, targetId])].filter((id) => isNodeVisible !== void 0 && !isNodeVisible(id));
3020
+ if (filtered.length > 0) return { status: "filtered", nodeIds: filtered };
3021
+ const src = ordinalOf.get(sourceId);
3022
+ const dst = ordinalOf.get(targetId);
3023
+ if (src === dst) return { status: "found", path: { nodeIds: [sourceId], edgeIds: [] } };
3024
+ const adjacency = new Array(nodes.length);
3025
+ const edgeIds = new Array(edges.length);
3026
+ const counters = /* @__PURE__ */ new Map();
3027
+ let scanned = 0;
3028
+ for (let e = 0; e < edges.length; e++) {
3029
+ if (++scanned % PATH_SCAN_CHUNK === 0) {
3030
+ await new Promise((resolve) => setTimeout(resolve, 0));
3031
+ if (ctx.signal.aborted) throwAborted2(ctx.signal, sourceId, targetId);
3032
+ }
3033
+ const edge = edges[e];
3034
+ const id = edge.id ?? nextSynthesizedEdgeId(counters, edge.source, edge.target);
3035
+ edgeIds[e] = id;
3036
+ if (!matchesRelationship({ ...edge}, options)) continue;
3037
+ if (options.universe !== "loaded" && (isEdgeVisible !== void 0 && !isEdgeVisible(id) || isNodeVisible !== void 0 && (!isNodeVisible(edge.source) || !isNodeVisible(edge.target)))) continue;
3038
+ const s = ordinalOf.get(edge.source);
3039
+ const t = ordinalOf.get(edge.target);
3040
+ if (s === void 0 || t === void 0) continue;
3041
+ if (direction !== "incoming") (adjacency[s] ??= []).push(t, e);
3042
+ if (direction !== "outgoing") (adjacency[t] ??= []).push(s, e);
3043
+ }
3044
+ const prevNode = new Int32Array(nodes.length).fill(-1);
3045
+ const prevEdge = new Int32Array(nodes.length).fill(-1);
3046
+ const depth = new Int32Array(nodes.length).fill(-1);
3047
+ depth[src] = 0;
3048
+ const queue = [src];
3049
+ let found = false;
3050
+ let limited = false;
3051
+ outer: for (let head = 0; head < queue.length; head++) {
3052
+ const u = queue[head];
3053
+ const list = adjacency[u];
3054
+ if (list === void 0) continue;
3055
+ for (let j = 0; j < list.length; j += 2) {
2836
3056
  if (++scanned % PATH_SCAN_CHUNK === 0) {
2837
- await Promise.resolve();
3057
+ await new Promise((resolve) => setTimeout(resolve, 0));
2838
3058
  if (ctx.signal.aborted) throwAborted2(ctx.signal, sourceId, targetId);
2839
3059
  }
2840
- const edge = edges[e];
2841
- const id = edge.id ?? nextSynthesizedEdgeId(counters, edge.source, edge.target);
2842
- edgeIds[e] = id;
2843
- if (isEdgeVisible !== void 0 && !isEdgeVisible(id)) continue;
2844
- const s = ordinalOf.get(edge.source);
2845
- const t = ordinalOf.get(edge.target);
2846
- if (s === void 0 || t === void 0) continue;
2847
- if (direction !== "incoming") (adjacency[s] ??= []).push(t, e);
2848
- if (direction !== "outgoing") (adjacency[t] ??= []).push(s, e);
2849
- }
2850
- const prevNode = new Int32Array(nodes.length).fill(-1);
2851
- const prevEdge = new Int32Array(nodes.length).fill(-1);
2852
- const visited = new Uint8Array(nodes.length);
2853
- visited[src] = 1;
2854
- const queue = [src];
2855
- let found = false;
2856
- outer: for (let head = 0; head < queue.length; head++) {
2857
- const u = queue[head];
2858
- const list = adjacency[u];
2859
- if (list === void 0) continue;
2860
- for (let j = 0; j < list.length; j += 2) {
2861
- if (++scanned % PATH_SCAN_CHUNK === 0) {
2862
- await Promise.resolve();
2863
- if (ctx.signal.aborted) throwAborted2(ctx.signal, sourceId, targetId);
2864
- }
2865
- const v = list[j];
2866
- if (visited[v] !== 0) continue;
2867
- visited[v] = 1;
2868
- prevNode[v] = u;
2869
- prevEdge[v] = list[j + 1];
2870
- if (v === dst) {
2871
- found = true;
2872
- break outer;
2873
- }
2874
- queue.push(v);
3060
+ const v = list[j];
3061
+ if (depth[v] >= 0) continue;
3062
+ if (options.maxHops !== void 0 && depth[u] >= options.maxHops) {
3063
+ limited = true;
3064
+ continue;
3065
+ }
3066
+ depth[v] = depth[u] + 1;
3067
+ prevNode[v] = u;
3068
+ prevEdge[v] = list[j + 1];
3069
+ if (v === dst) {
3070
+ found = true;
3071
+ break outer;
2875
3072
  }
3073
+ queue.push(v);
2876
3074
  }
2877
- if (!found) return null;
2878
- const nodeIds = [];
2879
- const pathEdgeIds = [];
2880
- for (let at = dst; at !== src; at = prevNode[at]) {
2881
- nodeIds.push(nodes[at].id);
2882
- pathEdgeIds.push(edgeIds[prevEdge[at]]);
3075
+ }
3076
+ if (ctx.signal.aborted) throwAborted2(ctx.signal, sourceId, targetId);
3077
+ if (!found) {
3078
+ if (!limited && options.universe !== "loaded" && (isNodeVisible !== void 0 || isEdgeVisible !== void 0)) {
3079
+ const loaded = await findDetailed(sourceId, targetId, { ...options, universe: "loaded" }, ctx);
3080
+ if (loaded.status === "found") return { status: "filtered", nodeIds: loaded.path.nodeIds.filter((id) => isNodeVisible !== void 0 && !isNodeVisible(id)) };
2883
3081
  }
2884
- nodeIds.push(nodes[src].id);
2885
- nodeIds.reverse();
2886
- pathEdgeIds.reverse();
2887
- return { nodeIds, edgeIds: pathEdgeIds };
3082
+ return { status: limited ? "hop-limit" : "unreachable" };
3083
+ }
3084
+ const nodeIds = [];
3085
+ const pathEdgeIds = [];
3086
+ for (let at = dst; at !== src; at = prevNode[at]) {
3087
+ nodeIds.push(nodes[at].id);
3088
+ pathEdgeIds.push(edgeIds[prevEdge[at]]);
3089
+ }
3090
+ nodeIds.push(nodes[src].id);
3091
+ nodeIds.reverse();
3092
+ pathEdgeIds.reverse();
3093
+ return { status: "found", path: { nodeIds, edgeIds: pathEdgeIds } };
3094
+ }
3095
+ return {
3096
+ revisionDependencies: ["source", "model", "scope"],
3097
+ findDetailed,
3098
+ async find(sourceId, targetId, options, ctx) {
3099
+ const outcome = await findDetailed(sourceId, targetId, options, ctx);
3100
+ return outcome.status === "found" ? outcome.path : null;
2888
3101
  }
2889
3102
  };
2890
3103
  }
@@ -6498,12 +6711,20 @@ function createGraphInstance(opts) {
6498
6711
  let acceptedAdjacency = null;
6499
6712
  const expansionLedger = new PendingExpansions();
6500
6713
  const expansionPromises = /* @__PURE__ */ new Map();
6714
+ const expansionKeys = /* @__PURE__ */ new Map();
6715
+ const expansionObservers = /* @__PURE__ */ new Map();
6501
6716
  const expansionHandles = /* @__PURE__ */ new Map();
6502
6717
  const expansionRejectors = /* @__PURE__ */ new Map();
6503
6718
  const expansionOverlays = /* @__PURE__ */ new Map();
6504
6719
  let expansionRecords = [];
6505
6720
  const effectiveRemovedIds = /* @__PURE__ */ new Set();
6506
6721
  let accretionPinIds = null;
6722
+ let explorationPinIds = /* @__PURE__ */ new Set();
6723
+ let explorationPinsNeedPush = false;
6724
+ function clearExplorationPins() {
6725
+ if (explorationPinIds.size > 0) explorationPinsNeedPush = true;
6726
+ explorationPinIds = /* @__PURE__ */ new Set();
6727
+ }
6507
6728
  const expansionService = opts.services?.expansion ?? createLocalExpansionService(() => {
6508
6729
  if (accepted === null) {
6509
6730
  throw new OrbitOperationError(
@@ -6523,26 +6744,15 @@ function createGraphInstance(opts) {
6523
6744
  let pathDimEdges = null;
6524
6745
  let activePath = null;
6525
6746
  let pathSeq = 0;
6526
- const pathServiceImpl = opts.services?.path ?? createLocalPathService(() => ({
6527
- nodes: accepted === null ? [] : accepted.nodes,
6528
- edges: accepted === null ? [] : accepted.edges,
6529
- isEdgeVisible: (id) => {
6530
- if (scene === null) return true;
6531
- const k = sceneLinkIndexOf(id);
6532
- if (k === void 0) return false;
6533
- return softMask === null || softMask.isEdgeVisible(k);
6534
- }
6535
- }));
6536
- let sceneLinkIndexCache = null;
6537
- function sceneLinkIndexOf(id) {
6538
- if (scene === null) return void 0;
6539
- if (sceneLinkIndexCache === null || sceneLinkIndexCache.scene !== scene) {
6540
- const map = /* @__PURE__ */ new Map();
6541
- for (let k = 0; k < scene.edgeIdByIndex.length; k++) map.set(scene.edgeIdByIndex[k], k);
6542
- sceneLinkIndexCache = { scene, map };
6543
- }
6544
- return sceneLinkIndexCache.map.get(id);
6545
- }
6747
+ const pathServiceImpl = opts.services?.path ?? createLocalPathService(() => {
6748
+ const pin = captureExportPin("visible");
6749
+ return {
6750
+ nodes: accepted === null ? [] : accepted.nodes,
6751
+ edges: accepted === null ? [] : accepted.edges,
6752
+ isNodeVisible: (id) => nodeVisibilityOf(id) === "visible",
6753
+ isEdgeVisible: (id) => pin?.visibleEdgeIds?.has(id) ?? true
6754
+ };
6755
+ });
6546
6756
  const searchService = opts.services?.search ?? createLocalSearchService(() => ({
6547
6757
  nodes: accepted === null ? [] : accepted.nodes,
6548
6758
  searchIndex: searchIndexFields
@@ -6620,6 +6830,7 @@ function createGraphInstance(opts) {
6620
6830
  let linkColor;
6621
6831
  let linkWidth;
6622
6832
  let layout = "force";
6833
+ let pauseOnReadyAfterRestore = false;
6623
6834
  let simulation = resolveSimulation(void 0);
6624
6835
  let theme = resolveTheme(void 0);
6625
6836
  let edgeArrows = false;
@@ -8238,6 +8449,8 @@ function createGraphInstance(opts) {
8238
8449
  }
8239
8450
  }
8240
8451
  const structuralTouched = scopeTouched || effectiveTouched || foldsTouched;
8452
+ if (scopeTouched || effectiveTouched) hardScopeGen += 1;
8453
+ if (structuralTouched) visibleGen += 1;
8241
8454
  let structuralChange = false;
8242
8455
  let positionChange = false;
8243
8456
  if (structuralTouched && accepted !== null) {
@@ -8276,6 +8489,10 @@ function createGraphInstance(opts) {
8276
8489
  if (pinsNext !== null) patch.pins = pinsNext;
8277
8490
  if (pinnedNodesNext !== null) patch.pinnedNodeIds = pinnedNodesNext;
8278
8491
  if (scopeTouched) patch.scope = scopeSpec;
8492
+ if (foldsTouched) {
8493
+ const nextFoldCounts = foldCountsIfChanged(prev.folds);
8494
+ if (nextFoldCounts !== null) patch.folds = nextFoldCounts;
8495
+ }
8279
8496
  const eng = engineIfReady();
8280
8497
  let revisions = prev.revisions;
8281
8498
  let simRestarted = false;
@@ -8319,16 +8536,26 @@ function createGraphInstance(opts) {
8319
8536
  const nodesAffected = drain.nodes.length > 0 || drain.nodesAlpha.length > 0;
8320
8537
  const edgesAffected = drain.edges.length > 0 || drain.edgesAlpha.length > 0;
8321
8538
  if (nodesAffected || edgesAffected) {
8539
+ visibleGen += 1;
8322
8540
  revisions = { ...prev.revisions };
8323
8541
  revisions.scope += 1;
8324
8542
  revisions.render += 1;
8325
8543
  if (eng !== null) {
8326
8544
  nodeAlphaComposer.reset();
8327
8545
  edgeAlphaComposer.reset();
8328
- const buffers = {};
8329
- if (nodesAffected) buffers.pointColor = composeNodeAlphaBuffer(basePointColorBuffer());
8546
+ const visDirty = {
8547
+ nodeColor: scaleUsesVisibleDomain(nodeColor),
8548
+ nodeSize: scaleUsesVisibleDomain(nodeSize),
8549
+ linkColor: false,
8550
+ linkWidth: false
8551
+ };
8552
+ const buffers = visDirty.nodeColor || visDirty.nodeSize ? { ...projectChannelBuffers(visDirty) ?? {} } : {};
8553
+ if (visDirty.nodeColor || visDirty.nodeSize) filterDiagsChanged = true;
8554
+ if (nodesAffected && buffers.pointColor === void 0) {
8555
+ buffers.pointColor = composeNodeAlphaBuffer(basePointColorBuffer());
8556
+ }
8330
8557
  if (edgesAffected) buffers.linkColor = composeEdgeAlphaBuffer(baseLinkColorBuffer());
8331
- eng.commit({ revision: revisions.render, buffers });
8558
+ commitToEngine(eng, { revision: revisions.render, buffers });
8332
8559
  revisions.appliedRender = eng.appliedRevision();
8333
8560
  }
8334
8561
  }
@@ -8346,8 +8573,7 @@ function createGraphInstance(opts) {
8346
8573
  pushSelectionToEngine(eng, selForPush.nodeIds);
8347
8574
  }
8348
8575
  const pinsForPush = pinsNext ?? prev.pins;
8349
- const persistentSize = store.getState().pinnedNodeIds.size;
8350
- if (pinsNext !== null || pinnedNodesNext !== null || structuralChange && (pinsForPush.size > 0 || persistentSize > 0)) {
8576
+ if (pinsNext !== null || pinnedNodesNext !== null || explorationPinsNeedPush || structuralChange && (pinsForPush.size > 0 || store.getState().pinnedNodeIds.size > 0 || explorationPinIds.size > 0)) {
8351
8577
  pushPinsToEngine(eng, pinsForPush);
8352
8578
  }
8353
8579
  }
@@ -9147,9 +9373,10 @@ function createGraphInstance(opts) {
9147
9373
  eng.setSelectedIndices(indices.length > 0 ? indices : null);
9148
9374
  }
9149
9375
  function pushPinsToEngine(eng, pins) {
9376
+ explorationPinsNeedPush = false;
9150
9377
  if (eng.setPinnedIndices === void 0) return;
9151
9378
  const persistent = store.getState().pinnedNodeIds;
9152
- if (scene === null || pins.size === 0 && persistent.size === 0 && accretionPinIds === null) {
9379
+ if (scene === null || pins.size === 0 && persistent.size === 0 && accretionPinIds === null && explorationPinIds.size === 0) {
9153
9380
  eng.setPinnedIndices(null);
9154
9381
  return;
9155
9382
  }
@@ -9162,6 +9389,10 @@ function createGraphInstance(opts) {
9162
9389
  const idx = scene.indexById.get(id);
9163
9390
  if (idx !== void 0) indexSet.add(idx);
9164
9391
  }
9392
+ for (const id of explorationPinIds) {
9393
+ const idx = scene.indexById.get(id);
9394
+ if (idx !== void 0) indexSet.add(idx);
9395
+ }
9165
9396
  if (accretionPinIds !== null) {
9166
9397
  for (const id of accretionPinIds) {
9167
9398
  const idx = scene.indexById.get(id);
@@ -9179,7 +9410,7 @@ function createGraphInstance(opts) {
9179
9410
  if (selection.nodeIds.length > 0 || selection.groupIds.length > 0) {
9180
9411
  pushSelectionToEngine(eng, selection.nodeIds);
9181
9412
  }
9182
- if (pins.size > 0 || pinnedNodeIds.size > 0) pushPinsToEngine(eng, pins);
9413
+ if (pins.size > 0 || pinnedNodeIds.size > 0 || explorationPinIds.size > 0) pushPinsToEngine(eng, pins);
9183
9414
  if (emphasizedNodeId !== null && scene !== null && !scene.indexById.has(emphasizedNodeId)) {
9184
9415
  emphasizedNodeId = null;
9185
9416
  }
@@ -9922,6 +10153,8 @@ function createGraphInstance(opts) {
9922
10153
  expansionHandles.clear();
9923
10154
  expansionRejectors.clear();
9924
10155
  expansionPromises.clear();
10156
+ expansionKeys.clear();
10157
+ expansionObservers.clear();
9925
10158
  for (const id of expansionLedger.ids()) expansionLedger.abort(id);
9926
10159
  }
9927
10160
  function publishIngestModel(p) {
@@ -9933,9 +10166,14 @@ function createGraphInstance(opts) {
9933
10166
  scopeSpec = null;
9934
10167
  scopeExtraIds.clear();
9935
10168
  expansionOverlays.clear();
10169
+ clearExplorationPins();
9936
10170
  abortExpansionsForDatasetSwap();
9937
10171
  abortSearchFlight("dataset-changed", "search aborted: the datasetKey changed");
9938
10172
  resetMaskState();
10173
+ failPendingRestore("restore-diverged", {
10174
+ problem: "the datasetKey changed while the restore was awaiting acknowledgement",
10175
+ rollbackCursor: false
10176
+ });
9939
10177
  historyKernel.clear();
9940
10178
  stopTimelineTimer();
9941
10179
  timelinePlayingKey = null;
@@ -9956,6 +10194,9 @@ function createGraphInstance(opts) {
9956
10194
  }
9957
10195
  }
9958
10196
  accepted = p.merged;
10197
+ rejectStalePendingRestore();
10198
+ pauseOnReadyAfterRestore = false;
10199
+ pendingDeriveToken += 1;
9959
10200
  invalidateExpansionRecords();
9960
10201
  edgeIndexById = new Map(p.merged.edges.map((e, k) => [e.id, k]));
9961
10202
  adjacency = null;
@@ -10126,7 +10367,7 @@ function createGraphInstance(opts) {
10126
10367
  if (selectedNodesChanged || structuralChange && nextSelection.nodeIds.length > 0) {
10127
10368
  pushSelectionToEngine(eng, nextSelection.nodeIds);
10128
10369
  }
10129
- if (pinsChanged || pinnedChanged || structuralChange && (nextPins.size > 0 || nextPinned.size > 0)) {
10370
+ if (pinsChanged || pinnedChanged || explorationPinsNeedPush || structuralChange && (nextPins.size > 0 || nextPinned.size > 0 || explorationPinIds.size > 0)) {
10130
10371
  pushPinsToEngine(eng, nextPins);
10131
10372
  }
10132
10373
  if (structuralChange && emphasizedNodeId !== null && !ingestScene.indexById.has(emphasizedNodeId)) {
@@ -10568,7 +10809,28 @@ function createGraphInstance(opts) {
10568
10809
  `expandNode('${id}') result discarded: ${why}`
10569
10810
  );
10570
10811
  }
10571
- async function mergeExpansionSession(id, ctx, at, batches, provenance) {
10812
+ function notifyExpansion(progress) {
10813
+ for (const observer of expansionObservers.get(progress.requestId) ?? []) {
10814
+ try {
10815
+ observer(progress);
10816
+ } catch {
10817
+ }
10818
+ }
10819
+ }
10820
+ function responsePage(page, required) {
10821
+ if (page === void 0) {
10822
+ if (required) invalidQuery("queryNeighbors must return explicit page metadata");
10823
+ return;
10824
+ }
10825
+ for (const field2 of ["returnedNodes", "returnedEdges", "totalNeighbors"]) {
10826
+ const value = page[field2];
10827
+ if (value !== void 0 && (!Number.isSafeInteger(value) || value < 0)) invalidQuery(`expansion page ${field2} must be a nonnegative integer`);
10828
+ }
10829
+ if (typeof page.returnedNodes !== "number" || typeof page.returnedEdges !== "number" || typeof page.truncated !== "boolean") invalidQuery("expansion page requires counts and truncated");
10830
+ validateCursor(page.nextCursor);
10831
+ if (page.nextCursor !== void 0 && !page.truncated) invalidQuery("a continuation requires truncated:true");
10832
+ }
10833
+ async function mergeExpansionSession(id, ctx, at, batches, provenance, options, bounded, page) {
10572
10834
  const requestId = ctx.requestId;
10573
10835
  const overlayId = `expand:${id}:${requestId}`;
10574
10836
  const ingest = beginIngest({
@@ -10578,13 +10840,25 @@ function createGraphInstance(opts) {
10578
10840
  atomic: true,
10579
10841
  overlayId
10580
10842
  });
10843
+ const abortIngest = () => {
10844
+ if (ingest.state === "open") void ingest.abort(ctx.signal.reason).catch(() => {
10845
+ });
10846
+ };
10847
+ ctx.signal.addEventListener("abort", abortIngest, { once: true });
10581
10848
  const allNodes = [];
10849
+ const receivedIds = /* @__PURE__ */ new Set();
10850
+ let receivedEdges = 0;
10582
10851
  let sequence = 0;
10583
10852
  try {
10584
10853
  for await (const b of batches) {
10585
10854
  if (!ownsExpansion(id, requestId)) {
10586
10855
  throw new OrbitOperationError({ code: "aborted", cause: "collapsed" });
10587
10856
  }
10857
+ for (const node of b.nodes ?? []) if (node.id !== id) receivedIds.add(node.id);
10858
+ receivedEdges += b.edges?.length ?? 0;
10859
+ if (bounded && (receivedIds.size > (options.limit ?? 50) || receivedEdges > (options.edgeLimit ?? 1e4))) {
10860
+ invalidQuery("expansion response exceeded the requested node or edge budget");
10861
+ }
10588
10862
  const batch = { sequence, batchId: `${requestId}#${sequence}` };
10589
10863
  if (b.nodes !== void 0) {
10590
10864
  batch.nodes = b.nodes;
@@ -10593,6 +10867,7 @@ function createGraphInstance(opts) {
10593
10867
  if (b.edges !== void 0) batch.edges = b.edges;
10594
10868
  sequence++;
10595
10869
  await ingest.append(batch);
10870
+ notifyExpansion({ requestId, seedId: id, batches: sequence, receivedNodes: receivedIds.size, receivedEdges, status: "loading" });
10596
10871
  }
10597
10872
  } catch (err) {
10598
10873
  if (ingest.state === "open") await ingest.abort(err).catch(() => {
@@ -10606,6 +10881,13 @@ function createGraphInstance(opts) {
10606
10881
  `expansion stream for '${id}' failed mid-stream; all batches rolled back: ${err instanceof Error ? err.message : String(err)}`
10607
10882
  );
10608
10883
  throw err;
10884
+ } finally {
10885
+ ctx.signal.removeEventListener("abort", abortIngest);
10886
+ }
10887
+ if (page !== void 0 && (page.returnedNodes !== receivedIds.size || page.returnedEdges !== receivedEdges || page.totalNeighbors !== void 0 && page.totalNeighbors < receivedIds.size)) {
10888
+ await ingest.abort("invalid page metadata").catch(() => {
10889
+ });
10890
+ invalidQuery("expansion page counts do not match its response");
10609
10891
  }
10610
10892
  const denial = acceptanceQueue.admit(() => {
10611
10893
  if (!ownsExpansion(id, requestId)) return "collapsed";
@@ -10649,6 +10931,11 @@ function createGraphInstance(opts) {
10649
10931
  }
10650
10932
  }
10651
10933
  }
10934
+ const previousExplorationPins = explorationPinIds;
10935
+ if (options.preserveLayout === true && scene !== null) {
10936
+ cancelSettleFollow();
10937
+ explorationPinIds = /* @__PURE__ */ new Set([...explorationPinIds, ...scene.idByIndex]);
10938
+ }
10652
10939
  if (layout === "force" && scene !== null && revealed.length > 0) {
10653
10940
  accretionPinIds = new Set(scene.idByIndex);
10654
10941
  }
@@ -10658,6 +10945,7 @@ function createGraphInstance(opts) {
10658
10945
  for (const rid of addedExtras) scopeExtraIds.delete(rid);
10659
10946
  for (const rid of removedRestores) effectiveRemovedIds.add(rid);
10660
10947
  accretionPinIds = null;
10948
+ explorationPinIds = previousExplorationPins;
10661
10949
  pushServiceDiagnostic(
10662
10950
  "service-error",
10663
10951
  "error",
@@ -10681,14 +10969,20 @@ function createGraphInstance(opts) {
10681
10969
  if (view !== null) {
10682
10970
  for (const rid of revealed) if (view.nodeIndex.has(rid)) added++;
10683
10971
  }
10684
- return { added };
10972
+ notifyExpansion({ requestId, seedId: id, batches: sequence, receivedNodes: receivedIds.size, receivedEdges, status: "committed" });
10973
+ return page === void 0 ? { added } : { added, page: { ...page } };
10685
10974
  }
10686
- async function runExpansion(id, hops, handle, at) {
10975
+ async function runExpansion(id, options, bounded, handle, at) {
10687
10976
  const ctx = handle.context;
10688
10977
  const requestId = ctx.requestId;
10689
10978
  let response;
10690
10979
  try {
10691
- response = await expansionService.neighbors([id], hops, ctx);
10980
+ if (bounded) {
10981
+ const { onProgress: _progress, preserveLayout: _preserve, ...query } = options;
10982
+ void _progress;
10983
+ void _preserve;
10984
+ response = await expansionService.queryNeighbors([id], query, ctx);
10985
+ } else response = await expansionService.neighbors([id], options.hops ?? 1, ctx);
10692
10986
  } catch (err) {
10693
10987
  if (!ownsExpansion(id, requestId) || ctx.signal.aborted) {
10694
10988
  throw err;
@@ -10703,23 +10997,39 @@ function createGraphInstance(opts) {
10703
10997
  if (!ownsExpansion(id, requestId) || ctx.signal.aborted) {
10704
10998
  throw new OrbitOperationError({ code: "aborted", cause: "collapsed" });
10705
10999
  }
11000
+ responsePage(response.page, bounded);
11001
+ const page = response.page === void 0 ? void 0 : { ...response.page };
10706
11002
  if ("batches" in response) {
10707
11003
  const denial2 = acceptanceQueue.admit(() => expansionAdmissible(id, ctx, at));
10708
11004
  if (denial2 !== null) discardExpansion(id, denial2);
10709
- return mergeExpansionSession(id, ctx, at, response.batches, response.provenance);
11005
+ return mergeExpansionSession(id, ctx, at, response.batches, response.provenance, options, bounded, page);
10710
11006
  }
10711
11007
  const denial = acceptanceQueue.admit(() => expansionAdmissible(id, ctx, at));
10712
11008
  if (denial !== null) discardExpansion(id, denial);
10713
11009
  const nodes = response.nodes ?? [];
10714
11010
  const edges = response.edges ?? [];
10715
11011
  const revealed = revealedIdsOf(nodes);
10716
- if (revealed.length === 0 && !anyUnknownEdge(edges)) return { noop: true };
11012
+ const nodeCount = new Set(nodes.filter((node) => node.id !== id).map((node) => node.id)).size;
11013
+ if (bounded && (nodeCount > (options.limit ?? 50) || edges.length > (options.edgeLimit ?? 1e4))) invalidQuery("expansion response exceeded the requested node or edge budget");
11014
+ if (page !== void 0 && (page.returnedNodes !== nodeCount || page.returnedEdges !== edges.length || page.totalNeighbors !== void 0 && page.totalNeighbors < nodeCount)) invalidQuery("expansion page counts do not match its response");
11015
+ if (revealed.length === 0 && !anyUnknownEdge(edges)) {
11016
+ notifyExpansion({ requestId, seedId: id, batches: 1, receivedNodes: nodeCount, receivedEdges: edges.length, status: "committed" });
11017
+ return page === void 0 ? { noop: true } : { noop: true, page: { ...page } };
11018
+ }
10717
11019
  const rows = {};
10718
11020
  if (response.nodes !== void 0) rows.nodes = response.nodes;
10719
11021
  if (response.edges !== void 0) rows.edges = response.edges;
10720
- return mergeExpansionSession(id, ctx, at, [rows], response.provenance);
11022
+ return mergeExpansionSession(id, ctx, at, [rows], response.provenance, options, bounded, page);
10721
11023
  }
10722
11024
  function expandNode(id, expandOpts) {
11025
+ let options;
11026
+ try {
11027
+ options = validateExpansion(expandOpts ?? {});
11028
+ } catch (error) {
11029
+ return Promise.reject(error);
11030
+ }
11031
+ const bounded = options.direction !== void 0 || options.relationshipTypes !== void 0 || options.relationshipTypeField !== void 0 || options.limit !== void 0 || options.edgeLimit !== void 0 || options.cursor !== void 0;
11032
+ if (bounded && expansionService.queryNeighbors === void 0) return Promise.reject(new OrbitOperationError({ code: "unsupported-operation", detail: "the expansion service does not implement queryNeighbors" }));
10723
11033
  if (destroyed) {
10724
11034
  return Promise.reject(
10725
11035
  new OrbitOperationError(
@@ -10728,11 +11038,16 @@ function createGraphInstance(opts) {
10728
11038
  )
10729
11039
  );
10730
11040
  }
11041
+ const { onProgress, ...keyOptions } = options;
11042
+ const key = serviceCacheKey({ serviceId: "expansion", params: { ...keyOptions, hops: options.hops ?? 1, preserveLayout: options.preserveLayout ?? false, bounded, ...bounded ? { direction: options.direction ?? "either", limit: options.limit ?? 50, edgeLimit: options.edgeLimit ?? 1e4, relationshipTypeField: options.relationshipTypeField ?? "type" } : {} }, datasetKey: accepted?.datasetKey ?? "", declared: expansionService.revisionDependencies, revisions: revisionSnapshot() });
10731
11043
  const inFlight = expansionPromises.get(id);
10732
- if (inFlight !== void 0) return inFlight;
11044
+ if (inFlight !== void 0 && expansionKeys.get(id) === key) {
11045
+ const requestId2 = expansionLedger.requestIdFor(id);
11046
+ if (onProgress !== void 0) expansionObservers.get(requestId2)?.add(onProgress);
11047
+ return inFlight;
11048
+ }
10733
11049
  if (accepted === null) return Promise.resolve({ noop: true });
10734
- const rawHops = expandOpts?.hops ?? 1;
10735
- const hops = Number.isFinite(rawHops) ? Math.max(1, Math.floor(rawHops)) : 1;
11050
+ if (inFlight !== void 0) cancelExpansion(id);
10736
11051
  const at = revisionSnapshot();
10737
11052
  const handle = createRequestContext({ datasetKey: accepted.datasetKey, revisions: at });
10738
11053
  const requestId = handle.context.requestId;
@@ -10752,16 +11067,23 @@ function createGraphInstance(opts) {
10752
11067
  }
10753
11068
  });
10754
11069
  expansionPromises.set(id, promise);
11070
+ expansionKeys.set(id, key);
11071
+ expansionObservers.set(requestId, new Set(onProgress === void 0 ? [] : [onProgress]));
10755
11072
  publish({ pendingExpansions: expansionLedger.ids() });
11073
+ notifyExpansion({ requestId, seedId: id, batches: 0, receivedNodes: 0, receivedEdges: 0, status: "loading" });
10756
11074
  const finishExpansion = () => {
10757
- if (expansionPromises.get(id) === promise) expansionPromises.delete(id);
11075
+ if (expansionPromises.get(id) === promise) {
11076
+ expansionPromises.delete(id);
11077
+ expansionKeys.delete(id);
11078
+ }
11079
+ expansionObservers.delete(requestId);
10758
11080
  expansionHandles.delete(requestId);
10759
11081
  expansionRejectors.delete(requestId);
10760
11082
  if (expansionLedger.resolve(id, requestId) && !destroyed) {
10761
11083
  publish({ pendingExpansions: expansionLedger.ids() });
10762
11084
  }
10763
11085
  };
10764
- void runExpansion(id, hops, handle, at).then(
11086
+ void runExpansion(id, options, bounded, handle, at).then(
10765
11087
  (r) => {
10766
11088
  finishExpansion();
10767
11089
  if (!settled) {
@@ -10779,24 +11101,32 @@ function createGraphInstance(opts) {
10779
11101
  );
10780
11102
  return promise;
10781
11103
  }
10782
- function retractExpansion(id) {
11104
+ function cancelExpansion(id) {
10783
11105
  if (destroyed) return;
10784
11106
  const requestId = expansionLedger.abort(id);
10785
11107
  if (requestId !== null) {
10786
11108
  expansionPromises.delete(id);
11109
+ expansionKeys.delete(id);
11110
+ expansionObservers.delete(requestId);
10787
11111
  const err = new OrbitOperationError(
10788
11112
  { code: "aborted", cause: "collapsed" },
10789
- `expandNode('${id}') aborted by retractExpansion()`
11113
+ `expandNode('${id}') aborted by cancelExpansion()`
10790
11114
  );
10791
11115
  expansionHandles.get(requestId)?.abort(err);
10792
11116
  expansionRejectors.get(requestId)?.(err);
11117
+ expansionHandles.delete(requestId);
11118
+ expansionRejectors.delete(requestId);
10793
11119
  pushServiceDiagnostic(
10794
11120
  "service-aborted",
10795
11121
  "info",
10796
- `pending expansion of '${id}' aborted by retractExpansion()`
11122
+ `pending expansion of '${id}' aborted by cancelExpansion()`
10797
11123
  );
10798
11124
  publish({ pendingExpansions: expansionLedger.ids() });
10799
11125
  }
11126
+ }
11127
+ function retractExpansion(id) {
11128
+ if (destroyed) return;
11129
+ cancelExpansion(id);
10800
11130
  acceptanceQueue.admit(() => {
10801
11131
  collapseTopRecord(id);
10802
11132
  });
@@ -10950,9 +11280,7 @@ function createGraphInstance(opts) {
10950
11280
  pushSelectionToEngine(eng, sel.nodeIds);
10951
11281
  }
10952
11282
  const pins = store.getState().pins;
10953
- if (pins.size > 0 || store.getState().pinnedNodeIds.size > 0) {
10954
- pushPinsToEngine(eng, pins);
10955
- }
11283
+ pushPinsToEngine(eng, pins);
10956
11284
  }
10957
11285
  if (labelRerank.setChanged) notifyLabelSubs(candidateSubs);
10958
11286
  }
@@ -11168,6 +11496,28 @@ function createGraphInstance(opts) {
11168
11496
  function getActivePath() {
11169
11497
  return activePath;
11170
11498
  }
11499
+ async function findPathDetailed(sourceId, targetId, rawOptions = {}) {
11500
+ const options = validatePath(rawOptions);
11501
+ if (destroyed) throw new OrbitOperationError({ code: "aborted", cause: "destroyed" });
11502
+ const rich = options.universe !== void 0 || options.maxHops !== void 0 || options.relationshipTypes !== void 0 || options.relationshipTypeField !== void 0;
11503
+ if (rich && pathServiceImpl.findDetailed === void 0) throw new OrbitOperationError({ code: "unsupported-operation", detail: "the path service does not implement findDetailed" });
11504
+ if (accepted === null) return { status: "not-loaded", nodeIds: [.../* @__PURE__ */ new Set([sourceId, targetId])] };
11505
+ const at = revisionSnapshot();
11506
+ const handle = createRequestContext({ datasetKey: accepted.datasetKey, revisions: at });
11507
+ let outcome;
11508
+ if (pathServiceImpl.findDetailed !== void 0) outcome = await pathServiceImpl.findDetailed(sourceId, targetId, options, handle.context);
11509
+ else {
11510
+ const missing = [.../* @__PURE__ */ new Set([sourceId, targetId])].filter((id) => !accepted.nodeIndex.has(id));
11511
+ if (missing.length > 0) return { status: "not-loaded", nodeIds: missing };
11512
+ const filtered = [.../* @__PURE__ */ new Set([sourceId, targetId])].filter((id) => nodeVisibilityOf(id) !== "visible");
11513
+ if (filtered.length > 0) return { status: "filtered", nodeIds: filtered };
11514
+ const path = await pathServiceImpl.find(sourceId, targetId, options, handle.context);
11515
+ outcome = path === null ? { status: "unreachable" } : { status: "found", path };
11516
+ }
11517
+ const denial = acceptanceQueue.admit(() => pathAdmissible(handle.context, at));
11518
+ if (denial !== null) throw new OrbitOperationError({ code: "aborted", cause: "stale" }, `path query discarded: ${denial}`);
11519
+ return outcome;
11520
+ }
11171
11521
  async function findPath(sourceId, targetId, options) {
11172
11522
  if (destroyed) {
11173
11523
  throw new OrbitOperationError(
@@ -11175,19 +11525,11 @@ function createGraphInstance(opts) {
11175
11525
  "findPath() called on a destroyed GraphInstance"
11176
11526
  );
11177
11527
  }
11528
+ const validated = validatePath(options ?? {});
11529
+ if (pathServiceImpl.findDetailed === void 0 && (validated.universe !== void 0 || validated.maxHops !== void 0 || validated.relationshipTypes !== void 0 || validated.relationshipTypeField !== void 0)) throw new OrbitOperationError({ code: "unsupported-operation", detail: "the path service does not implement findDetailed" });
11178
11530
  const token = ++pathSeq;
11179
- if (accepted === null) return null;
11180
- const at = revisionSnapshot();
11181
- const issuedDatasetKey = accepted.datasetKey;
11182
- const handle = createRequestContext({ datasetKey: issuedDatasetKey, revisions: at });
11183
- const result = await pathServiceImpl.find(sourceId, targetId, options ?? {}, handle.context);
11184
- const denial = acceptanceQueue.admit(() => pathAdmissible(handle.context, at));
11185
- if (denial !== null) {
11186
- throw new OrbitOperationError(
11187
- { code: "aborted", cause: "stale" },
11188
- `findPath('${sourceId}' \u2192 '${targetId}') discarded: ${denial}`
11189
- );
11190
- }
11531
+ const outcome = await findPathDetailed(sourceId, targetId, validated);
11532
+ const result = outcome.status === "found" ? outcome.path : null;
11191
11533
  if (token !== pathSeq || result === null) return result;
11192
11534
  if (scene !== null) {
11193
11535
  const plan = computePathEmphasis(result, {
@@ -11213,6 +11555,23 @@ function createGraphInstance(opts) {
11213
11555
  }
11214
11556
  return result;
11215
11557
  }
11558
+ function nodeVisibilityOf(id) {
11559
+ if (scene === null) return "visible";
11560
+ const index = scene.indexById.get(id);
11561
+ if (index === void 0) return "out-of-scope";
11562
+ return softMask === null || softMask.isNodeVisible(index) ? "visible" : "filtered";
11563
+ }
11564
+ function getNeighborhood(id, options = {}) {
11565
+ const pin = options.visibility === "visible" ? captureExportPin("visible") : null;
11566
+ return neighborhoodOf(
11567
+ accepted,
11568
+ id,
11569
+ options,
11570
+ JSON.stringify([accepted?.datasetKey, store.getState().revisions.model, store.getState().revisions.scope]),
11571
+ nodeVisibilityOf,
11572
+ (edgeId) => pin?.visibleEdgeIds?.has(edgeId) ?? true
11573
+ );
11574
+ }
11216
11575
  function activateSearchResult(result) {
11217
11576
  const id = result.id;
11218
11577
  const plain = result;
@@ -11342,11 +11701,16 @@ function createGraphInstance(opts) {
11342
11701
  overlayIdsCleared = clearOverlayState();
11343
11702
  datasetKeyChanged = baseAccepted !== null && baseAccepted.datasetKey !== data.datasetKey;
11344
11703
  if (datasetKeyChanged) {
11704
+ clearExplorationPins();
11345
11705
  reconciler = new Reconciler();
11346
11706
  engineDiags = [];
11347
11707
  abortExpansionsForDatasetSwap();
11348
11708
  abortSearchFlight("dataset-changed", "search aborted: the datasetKey changed");
11349
11709
  resetMaskState();
11710
+ failPendingRestore("restore-diverged", {
11711
+ problem: "the datasetKey changed while the restore was awaiting acknowledgement",
11712
+ rollbackCursor: false
11713
+ });
11350
11714
  historyKernel.clear();
11351
11715
  stopTimelineTimer();
11352
11716
  timelinePlayingKey = null;
@@ -11363,6 +11727,8 @@ function createGraphInstance(opts) {
11363
11727
  bankReadyEnginePositions();
11364
11728
  }
11365
11729
  accepted = nextAccepted;
11730
+ rejectStalePendingRestore();
11731
+ pauseOnReadyAfterRestore = false;
11366
11732
  invalidateExpansionRecords();
11367
11733
  acceptedModelSeq += 1;
11368
11734
  baseAccepted = nextAccepted;
@@ -11692,7 +12058,10 @@ function createGraphInstance(opts) {
11692
12058
  c.linkArrows = edgeArrows;
11693
12059
  any = true;
11694
12060
  }
11695
- if (update.dataRef !== void 0) dataRef = update.dataRef;
12061
+ if (update.dataRef !== void 0) {
12062
+ dataRef = update.dataRef;
12063
+ rejectStalePendingRestore();
12064
+ }
11696
12065
  if (update.showLinks !== void 0 && update.showLinks !== showLinks) {
11697
12066
  showLinks = update.showLinks;
11698
12067
  c.renderLinks = showLinks;
@@ -11706,7 +12075,11 @@ function createGraphInstance(opts) {
11706
12075
  c.cluster = clusterConfigPayload();
11707
12076
  any = true;
11708
12077
  }
11709
- if (layoutChanged) layout = nextLayout;
12078
+ if (layoutChanged) {
12079
+ clearExplorationPins();
12080
+ layout = nextLayout;
12081
+ pauseOnReadyAfterRestore = false;
12082
+ }
11710
12083
  if (any) configPatch = c;
11711
12084
  }
11712
12085
  let labelsDirty = false;
@@ -12088,7 +12461,7 @@ function createGraphInstance(opts) {
12088
12461
  if (selectedNodesChanged || selectedGroupsChanged || structuralChange && (nextSelection.nodeIds.length > 0 || nextSelection.groupIds.length > 0)) {
12089
12462
  pushSelectionToEngine(eng, nextSelection.nodeIds);
12090
12463
  }
12091
- if (pinsChanged || pinnedChanged || structuralChange && (nextPins.size > 0 || nextPinned.size > 0)) {
12464
+ if (pinsChanged || pinnedChanged || explorationPinsNeedPush || structuralChange && (nextPins.size > 0 || nextPinned.size > 0 || explorationPinIds.size > 0)) {
12092
12465
  pushPinsToEngine(eng, nextPins);
12093
12466
  }
12094
12467
  if (structuralChange && emphasizedNodeId !== null && scene !== null && !scene.indexById.has(emphasizedNodeId)) {
@@ -12358,14 +12731,18 @@ function createGraphInstance(opts) {
12358
12731
  if (status !== "lost") return;
12359
12732
  publish({ status: "recovering" });
12360
12733
  try {
12361
- const restarted = buildAndCommitFullReplay(s, layout === "force" ? RECOVERY_RESTART_ALPHA : null) && accepted !== null && layout === "force";
12734
+ const pauseRestoredLayout = pauseOnReadyAfterRestore;
12735
+ const restartAlpha = layout === "force" && !pauseRestoredLayout ? RECOVERY_RESTART_ALPHA : null;
12736
+ const restarted = buildAndCommitFullReplay(s, restartAlpha) && accepted !== null && restartAlpha !== null;
12737
+ pauseOnReadyAfterRestore = false;
12738
+ if (pauseRestoredLayout) s.engine.pause();
12362
12739
  const { viewport } = store.getState();
12363
12740
  if (viewport !== null) s.engine.setViewport(viewport);
12364
12741
  reapplyInteractionState(s.engine);
12365
12742
  publish({
12366
12743
  status: "ready",
12367
12744
  revisions: { ...store.getState().revisions, appliedRender: s.engine.appliedRevision() },
12368
- ...restarted ? { simulationRunning: true } : {}
12745
+ ...restarted ? { simulationRunning: true } : pauseRestoredLayout ? { simulationRunning: false } : {}
12369
12746
  });
12370
12747
  } catch (err) {
12371
12748
  emitInstanceError({ code: "context-lost" }, "recovery", err);
@@ -12460,15 +12837,17 @@ function createGraphInstance(opts) {
12460
12837
  // mask — no re-arm needed on mask changes.
12461
12838
  linkVisible: (linkIndex) => maskEdgeVisibleAt(linkIndex)
12462
12839
  });
12463
- const restartAlpha = layout === "force" ? 1 : null;
12840
+ const pauseRestoredLayout = pauseOnReadyAfterRestore;
12841
+ const restartAlpha = layout === "force" && !pauseRestoredLayout ? 1 : null;
12464
12842
  const committed = buildAndCommitFullReplay(s, restartAlpha);
12843
+ pauseOnReadyAfterRestore = false;
12465
12844
  const restarted = committed && accepted !== null && restartAlpha !== null;
12466
- if (layout === "fixed") eng.pause();
12845
+ if (layout === "fixed" || pauseRestoredLayout) eng.pause();
12467
12846
  publish({
12468
12847
  status: "ready",
12469
12848
  revisions: { ...store.getState().revisions, appliedRender: eng.appliedRevision() },
12470
12849
  diagnostics: composeDiagnostics(),
12471
- ...restarted ? { simulationRunning: true } : {}
12850
+ ...restarted ? { simulationRunning: true } : pauseRestoredLayout ? { simulationRunning: false } : {}
12472
12851
  });
12473
12852
  reapplyInteractionState(eng);
12474
12853
  if (committed) maybeFitView(eng);
@@ -12572,6 +12951,10 @@ function createGraphInstance(opts) {
12572
12951
  function destroy() {
12573
12952
  if (destroyed) return;
12574
12953
  destroyed = true;
12954
+ failPendingRestore("restore-diverged", {
12955
+ problem: "the instance was destroyed while the restore was awaiting acknowledgement",
12956
+ rollbackCursor: false
12957
+ });
12575
12958
  workerLane?.terminate();
12576
12959
  workerLane = null;
12577
12960
  stopTimelineTimer();
@@ -12597,8 +12980,11 @@ function createGraphInstance(opts) {
12597
12980
  expansionHandles.clear();
12598
12981
  expansionRejectors.clear();
12599
12982
  expansionPromises.clear();
12983
+ expansionKeys.clear();
12984
+ expansionObservers.clear();
12600
12985
  }
12601
12986
  accretionPinIds = null;
12987
+ clearExplorationPins();
12602
12988
  abortSearchFlight("destroyed", "GraphInstance destroyed with a search in flight");
12603
12989
  abortAllSessions(null, "destroyed");
12604
12990
  if (session !== null) {
@@ -12776,21 +13162,42 @@ function createGraphInstance(opts) {
12776
13162
  function hasRestoreListener() {
12777
13163
  return (listeners.get("viewStateRestore")?.size ?? 0) > 0;
12778
13164
  }
12779
- function failPendingRestore(code) {
13165
+ function failPendingRestore(code, options = {}) {
12780
13166
  const pending = pendingRestore;
12781
13167
  if (pending === null) return;
12782
13168
  pendingRestore = null;
12783
13169
  clearTimeout(pending.timer);
12784
- pending.rollbackCursor?.();
13170
+ if (options.rollbackCursor !== false) pending.rollbackCursor?.();
12785
13171
  pending.resolve({
12786
13172
  status: "rejected",
12787
13173
  code,
12788
13174
  problems: [
12789
- code === "restore-timeout" ? `the host did not reflect the restore intent within ${RESTORE_ACK_TIMEOUT_MS}ms` : "the host reflected different values than the intent asked for"
13175
+ options.problem ?? (code === "restore-timeout" ? `the host did not reflect the restore intent within ${RESTORE_ACK_TIMEOUT_MS}ms` : "the host reflected different values than the intent asked for")
12790
13176
  ]
12791
13177
  });
12792
13178
  }
13179
+ function restoreSourceKey() {
13180
+ try {
13181
+ return canonicalJson2({
13182
+ datasetKey: accepted?.datasetKey ?? null,
13183
+ sourceRevision: accepted?.sourceRevision ?? null,
13184
+ ...dataRef === void 0 ? {} : { dataRef }
13185
+ }) ?? null;
13186
+ } catch {
13187
+ return null;
13188
+ }
13189
+ }
13190
+ function rejectStalePendingRestore() {
13191
+ const pending = pendingRestore;
13192
+ if (pending?.sourceKey === void 0) return false;
13193
+ if (pending.sourceKey !== null && pending.sourceKey === restoreSourceKey()) return false;
13194
+ failPendingRestore("restore-diverged", {
13195
+ problem: "the graph source changed while the restore was awaiting acknowledgement"
13196
+ });
13197
+ return true;
13198
+ }
12793
13199
  function commitPendingRestore() {
13200
+ if (rejectStalePendingRestore()) return;
12794
13201
  const pending = pendingRestore;
12795
13202
  if (pending === null) return;
12796
13203
  pendingRestore = null;
@@ -12810,6 +13217,7 @@ function createGraphInstance(opts) {
12810
13217
  pending.resolve({ status: "applied" });
12811
13218
  }
12812
13219
  function checkRestoreAcknowledgement(update) {
13220
+ if (rejectStalePendingRestore()) return;
12813
13221
  const pending = pendingRestore;
12814
13222
  if (pending === null) return;
12815
13223
  const met = (lane) => {
@@ -12976,38 +13384,44 @@ function createGraphInstance(opts) {
12976
13384
  }
12977
13385
  if (state.positions !== void 0 && scene !== null) {
12978
13386
  const eng = engineIfReady();
12979
- if (eng !== null) {
12980
- const next = new Float32Array(scene.positions);
12981
- let touched = 0;
12982
- for (const [id, x, y] of state.positions) {
12983
- const idx = scene.indexById.get(id);
12984
- if (idx === void 0) continue;
12985
- next[2 * idx] = x;
12986
- next[2 * idx + 1] = y;
12987
- touched++;
12988
- }
12989
- if (touched > 0) {
12990
- reconciler.noteEnginePositions(next);
12991
- scene = { ...scene, positions: next };
12992
- const prevState = store.getState();
12993
- const nextRevisions = {
12994
- ...prevState.revisions,
12995
- render: prevState.revisions.render + 1
12996
- };
12997
- commitToEngine(eng, {
13387
+ const next = new Float32Array(scene.positions);
13388
+ let touched = 0;
13389
+ for (const [id, x, y] of state.positions) {
13390
+ const idx = scene.indexById.get(id);
13391
+ if (idx === void 0) continue;
13392
+ next[2 * idx] = x;
13393
+ next[2 * idx + 1] = y;
13394
+ touched++;
13395
+ }
13396
+ if (touched > 0) {
13397
+ reconciler.noteEnginePositions(next);
13398
+ scene = { ...scene, positions: next };
13399
+ labelPositionCache = null;
13400
+ const prevState = store.getState();
13401
+ const nextRevisions = {
13402
+ ...prevState.revisions,
13403
+ render: prevState.revisions.render + 1
13404
+ };
13405
+ if (eng !== null) {
13406
+ const commit = {
12998
13407
  revision: nextRevisions.render,
12999
13408
  structure: {
13000
13409
  pointCount: scene.count,
13001
13410
  positions: next,
13002
13411
  links: scene.links
13003
13412
  }
13004
- });
13413
+ };
13414
+ const syncIndex = structuralPointImageIndex();
13415
+ if (syncIndex !== null) commit.resources = { pointImageIndex: syncIndex };
13416
+ commitToEngine(eng, commit);
13005
13417
  nextRevisions.appliedRender = eng.appliedRevision();
13006
13418
  eng.pause();
13007
- const patch = { revisions: nextRevisions };
13008
- if (prevState.simulationRunning) patch.simulationRunning = false;
13009
- publish(patch);
13419
+ } else {
13420
+ pauseOnReadyAfterRestore = true;
13010
13421
  }
13422
+ const patch = { revisions: nextRevisions };
13423
+ if (prevState.simulationRunning) patch.simulationRunning = false;
13424
+ publish(patch);
13011
13425
  }
13012
13426
  }
13013
13427
  if (state.camera !== null) {
@@ -13024,6 +13438,7 @@ function createGraphInstance(opts) {
13024
13438
  pendingRestore = {
13025
13439
  transactionId,
13026
13440
  source: "setViewState",
13441
+ sourceKey: restoreSourceKey(),
13027
13442
  commands,
13028
13443
  awaiting,
13029
13444
  finish: finishTail,
@@ -13221,16 +13636,40 @@ function createGraphInstance(opts) {
13221
13636
  { maxElements: limit }
13222
13637
  );
13223
13638
  }
13224
- function captureExportPin() {
13639
+ function captureExportPin(scope) {
13225
13640
  if (accepted === null) return null;
13226
13641
  let visibleIds = null;
13227
- if (scene !== null) {
13642
+ let visibleEdgeIds = null;
13643
+ if (scope === "visible" && scene !== null) {
13228
13644
  const slots = visibleSlotsOf(scene, softMask);
13229
13645
  const ids = /* @__PURE__ */ new Set();
13230
13646
  for (const i of slots) ids.add(scene.idByIndex[i]);
13231
13647
  visibleIds = ids;
13648
+ const edgeIds = /* @__PURE__ */ new Set();
13649
+ const physicalLinks = scene.groups?.physicalLinkCount ?? scene.linkCount;
13650
+ for (let k = 0; k < physicalLinks; k++) {
13651
+ if (!maskEdgeVisibleAt(k)) continue;
13652
+ const source = scene.idByIndex[scene.links[2 * k]];
13653
+ const target = scene.idByIndex[scene.links[2 * k + 1]];
13654
+ if (ids.has(source) && ids.has(target)) edgeIds.add(scene.edgeIdByIndex[k]);
13655
+ }
13656
+ if (groupRewrite !== null) {
13657
+ const model = renderModel();
13658
+ for (let j = 0; j < groupRewrite.metaEdges.length; j++) {
13659
+ if (!maskEdgeVisibleAt(physicalLinks + j)) continue;
13660
+ for (const k of groupRewrite.metaEdges[j].underlying) {
13661
+ const edge = model.edges[k];
13662
+ if (!ids.has(edge.source) || !ids.has(edge.target)) continue;
13663
+ if (activeFilterMode === "hide" && compiledEdgeSelector !== null && !compiledEdgeSelector.test(edge)) {
13664
+ continue;
13665
+ }
13666
+ edgeIds.add(edge.id);
13667
+ }
13668
+ }
13669
+ }
13670
+ visibleEdgeIds = edgeIds;
13232
13671
  }
13233
- return { accepted, scene, visibleIds };
13672
+ return { accepted, scene, visibleIds, visibleEdgeIds };
13234
13673
  }
13235
13674
  function pinnedVisibleIds(pin) {
13236
13675
  return pin.visibleIds;
@@ -13239,14 +13678,10 @@ function createGraphInstance(opts) {
13239
13678
  if (scope === "accepted") return pin.accepted.nodes.length + pin.accepted.edges.length;
13240
13679
  const visible = pinnedVisibleIds(pin);
13241
13680
  if (visible === null) return pin.accepted.nodes.length + pin.accepted.edges.length;
13242
- let count = visible.size;
13243
- for (const e of pin.accepted.edges) {
13244
- if (visible.has(e.source) && visible.has(e.target)) count++;
13245
- }
13246
- return count;
13681
+ return visible.size + pin.visibleEdgeIds.size;
13247
13682
  }
13248
13683
  async function exportData(scope = "visible", opts2) {
13249
- const pin = captureExportPin();
13684
+ const pin = captureExportPin(scope);
13250
13685
  if (pin === null) return { nodes: [], edges: [] };
13251
13686
  const rowCount = pinnedRowCount(pin, scope);
13252
13687
  const limit = opts2?.limit ?? 1e5;
@@ -13261,13 +13696,11 @@ function createGraphInstance(opts) {
13261
13696
  if (visible === null) return { nodes: pin.accepted.nodes, edges: pin.accepted.edges };
13262
13697
  return {
13263
13698
  nodes: pin.accepted.nodes.filter((n) => visible.has(n.id)),
13264
- edges: pin.accepted.edges.filter(
13265
- (e) => visible.has(e.source) && visible.has(e.target)
13266
- )
13699
+ edges: pin.accepted.edges.filter((e) => pin.visibleEdgeIds.has(e.id))
13267
13700
  };
13268
13701
  }
13269
13702
  function exportDataStream(scope = "visible") {
13270
- const pin = captureExportPin();
13703
+ const pin = captureExportPin(scope);
13271
13704
  return (async function* dataRows() {
13272
13705
  if (pin === null) return;
13273
13706
  const visible = scope === "visible" ? pinnedVisibleIds(pin) : null;
@@ -13276,7 +13709,7 @@ function createGraphInstance(opts) {
13276
13709
  yield JSON.stringify({ kind: "node", value: n }) + "\n";
13277
13710
  }
13278
13711
  for (const e of pin.accepted.edges) {
13279
- if (visible !== null && (!visible.has(e.source) || !visible.has(e.target))) continue;
13712
+ if (pin.visibleEdgeIds !== null && !pin.visibleEdgeIds.has(e.id)) continue;
13280
13713
  yield JSON.stringify({ kind: "edge", value: e }) + "\n";
13281
13714
  }
13282
13715
  })();
@@ -13529,7 +13962,11 @@ function createGraphInstance(opts) {
13529
13962
  isolateSelection,
13530
13963
  resetIsolation,
13531
13964
  expandNode,
13965
+ cancelExpansion,
13966
+ getNeighborhood,
13967
+ getSource: () => accepted === null ? null : { datasetKey: accepted.datasetKey, sourceRevision: accepted.sourceRevision },
13532
13968
  retractExpansion,
13969
+ getExpansionRecords: () => expansionRecords.map((record2) => ({ ...record2, addedNodeIds: [...record2.addedNodeIds] })),
13533
13970
  getExpansionOverlays: (id) => {
13534
13971
  const records = expansionOverlays.get(id);
13535
13972
  return records === void 0 ? EMPTY_EXPANSION_RECORDS : [...records];
@@ -13538,6 +13975,7 @@ function createGraphInstance(opts) {
13538
13975
  clearSearch,
13539
13976
  activateSearchResult,
13540
13977
  findPath,
13978
+ findPathDetailed,
13541
13979
  clearPath,
13542
13980
  getActivePath,
13543
13981
  pauseSimulation: () => {
@@ -13549,8 +13987,11 @@ function createGraphInstance(opts) {
13549
13987
  },
13550
13988
  resumeSimulation: () => {
13551
13989
  if (destroyed) return;
13990
+ clearExplorationPins();
13991
+ pauseOnReadyAfterRestore = false;
13552
13992
  const eng = engineIfReady();
13553
13993
  if (eng === null) return;
13994
+ if (explorationPinsNeedPush) pushPinsToEngine(eng, store.getState().pins);
13554
13995
  eng.start();
13555
13996
  if (!store.getState().simulationRunning) publish({ simulationRunning: true });
13556
13997
  },
@@ -13592,6 +14033,528 @@ function createGraphInstance(opts) {
13592
14033
  getAccessibility: () => accessibilityConfig
13593
14034
  };
13594
14035
  }
14036
+ var InvestigationError = class extends Error {
14037
+ constructor(code, message) {
14038
+ super(message);
14039
+ this.code = code;
14040
+ }
14041
+ code;
14042
+ name = "InvestigationError";
14043
+ };
14044
+ function invalid(message) {
14045
+ throw new InvestigationError("invalid-investigation", message);
14046
+ }
14047
+ function object(value, name) {
14048
+ if (value === null || typeof value !== "object" || Array.isArray(value)) invalid(`${name} must be an object`);
14049
+ return value;
14050
+ }
14051
+ function string(value, name, nonempty = false) {
14052
+ if (typeof value !== "string" || nonempty && value.length === 0) invalid(`${name} must be ${nonempty ? "a nonempty string" : "a string"}`);
14053
+ return value;
14054
+ }
14055
+ function jsonCopy(value) {
14056
+ const seen = /* @__PURE__ */ new Set();
14057
+ const walk = (item, depth) => {
14058
+ if (depth > 64) invalid("Investigation nesting exceeds 64 levels");
14059
+ if (item === null || typeof item === "string" || typeof item === "boolean") return;
14060
+ if (typeof item === "number" && Number.isFinite(item)) return;
14061
+ if (typeof item !== "object") invalid("Investigation values must be finite JSON data");
14062
+ if (seen.has(item)) invalid("Investigation values must not contain cycles");
14063
+ const proto = Object.getPrototypeOf(item);
14064
+ if (!Array.isArray(item) && proto !== Object.prototype && proto !== null) invalid("Investigation values must be plain JSON objects");
14065
+ seen.add(item);
14066
+ for (const key of Object.keys(item)) {
14067
+ const descriptor = Object.getOwnPropertyDescriptor(item, key);
14068
+ if (!("value" in descriptor)) invalid("Investigation values must not contain accessors");
14069
+ if (descriptor.value === void 0 && !Array.isArray(item)) continue;
14070
+ walk(descriptor.value, depth + 1);
14071
+ }
14072
+ seen.delete(item);
14073
+ };
14074
+ walk(value, 0);
14075
+ const text = JSON.stringify(value);
14076
+ if (text.length > 16 * 1024 * 1024) invalid("Investigation exceeds the 16 MiB JSON limit");
14077
+ return JSON.parse(text);
14078
+ }
14079
+ function freeze(value) {
14080
+ if (value !== null && typeof value === "object") {
14081
+ for (const child of Object.values(value)) freeze(child);
14082
+ Object.freeze(value);
14083
+ }
14084
+ return value;
14085
+ }
14086
+ function relationshipOptions(value, name, path = false) {
14087
+ const opts = object(value, name);
14088
+ const allowed = new Set(path ? ["direction", "relationshipTypes", "relationshipTypeField", "universe", "maxHops"] : ["direction", "relationshipTypes", "relationshipTypeField", "hops", "limit", "edgeLimit", "preserveLayout"]);
14089
+ for (const key of Object.keys(opts)) if (!allowed.has(key)) invalid(`${name}.${key} is not replayable`);
14090
+ if (opts.direction !== void 0 && !["incoming", "outgoing", "either"].includes(String(opts.direction))) invalid(`${name}.direction is invalid`);
14091
+ if (opts.relationshipTypeField !== void 0) string(opts.relationshipTypeField, `${name}.relationshipTypeField`, true);
14092
+ if (opts.relationshipTypes !== void 0) {
14093
+ if (!Array.isArray(opts.relationshipTypes) || !opts.relationshipTypes.every((v) => typeof v === "string")) invalid(`${name}.relationshipTypes must be strings`);
14094
+ }
14095
+ for (const [key, max] of [["hops", 1e3], ["maxHops", 1e3], ["limit", 1e3], ["edgeLimit", 1e4]]) {
14096
+ const n = opts[key];
14097
+ if (n !== void 0 && (typeof n !== "number" || !Number.isInteger(n) || n < (key === "maxHops" ? 0 : 1) || n > max)) invalid(`${name}.${key} is outside its supported bounds`);
14098
+ }
14099
+ if (opts.preserveLayout !== void 0 && typeof opts.preserveLayout !== "boolean") invalid(`${name}.preserveLayout must be boolean`);
14100
+ if (opts.universe !== void 0 && opts.universe !== "loaded" && opts.universe !== "visible") invalid(`${name}.universe is invalid`);
14101
+ return opts;
14102
+ }
14103
+ function validatePath2(value) {
14104
+ const p = object(value, "path");
14105
+ for (const key of ["id", "title", "sourceId", "targetId"]) string(p[key], `path.${key}`, key !== "title");
14106
+ relationshipOptions(p.options, "path.options", true);
14107
+ const result = object(p.path, "path.path");
14108
+ for (const key of ["nodeIds", "edgeIds"]) {
14109
+ if (!Array.isArray(result[key]) || !result[key].every((id) => typeof id === "string")) invalid(`path.path.${key} must be strings`);
14110
+ }
14111
+ const nodes = result.nodeIds;
14112
+ const edges = result.edgeIds;
14113
+ if (nodes.length === 0 || nodes[0] !== p.sourceId || nodes.at(-1) !== p.targetId || edges.length !== nodes.length - 1) invalid("Saved path endpoints and ordered steps do not agree");
14114
+ return p;
14115
+ }
14116
+ function parseInvestigation(raw) {
14117
+ let input = raw;
14118
+ if (typeof raw === "string") {
14119
+ if (raw.length > 16 * 1024 * 1024) invalid("Investigation exceeds the 16 MiB JSON limit");
14120
+ try {
14121
+ input = JSON.parse(raw);
14122
+ } catch {
14123
+ invalid("Investigation is not valid JSON");
14124
+ }
14125
+ }
14126
+ const value = object(jsonCopy(input), "investigation");
14127
+ if (value.v !== 1) invalid("Unsupported investigation version");
14128
+ for (const key of ["id", "title", "notes", "createdAt", "searchQuery"]) string(value[key], key, key === "id");
14129
+ value.tableQuery = value.tableQuery === void 0 ? "" : string(value.tableQuery, "tableQuery");
14130
+ if (!Number.isFinite(Date.parse(value.createdAt))) invalid("createdAt must be an ISO date");
14131
+ const source = object(value.source, "source");
14132
+ string(source.datasetKey, "source.datasetKey", true);
14133
+ const revision = source.sourceRevision;
14134
+ if (revision !== null && typeof revision !== "string" && !(typeof revision === "number" && Number.isFinite(revision))) invalid("source.sourceRevision must be a string, finite number, or null");
14135
+ const view = validateViewState(value.view);
14136
+ if (!view.ok) invalid(view.problems.join("; "));
14137
+ if (canonicalJson2(source.dataRef) !== canonicalJson2(view.state.dataRef)) invalid("Source reference and view reference must agree");
14138
+ if (!Array.isArray(value.expansions) || value.expansions.length > 1e4) invalid("expansions must contain at most 10000 requests");
14139
+ const priorQueries = /* @__PURE__ */ new Set();
14140
+ for (const entry of value.expansions) {
14141
+ const action = object(entry, "expansion");
14142
+ string(action.seedId, "expansion.seedId", true);
14143
+ relationshipOptions(action.options, "expansion.options");
14144
+ if (typeof action.continuation !== "boolean") invalid("expansion.continuation must be boolean");
14145
+ const key = queryKey(action.seedId, action.options);
14146
+ if (action.continuation && !priorQueries.has(key)) invalid("An expansion continuation needs a preceding page");
14147
+ priorQueries.add(key);
14148
+ }
14149
+ if (!Array.isArray(value.paths) || value.paths.length > 1e4) invalid("paths must contain at most 10000 results");
14150
+ const ids = /* @__PURE__ */ new Set();
14151
+ for (const path of value.paths) {
14152
+ const parsed = validatePath2(path);
14153
+ if (ids.has(parsed.id)) invalid("Saved path IDs must be unique");
14154
+ ids.add(parsed.id);
14155
+ }
14156
+ return freeze(value);
14157
+ }
14158
+ function serializeInvestigation(value) {
14159
+ return JSON.stringify(parseInvestigation(value), null, 2);
14160
+ }
14161
+ function queryKey(seedId, options) {
14162
+ return canonicalJson2([seedId, options]);
14163
+ }
14164
+ function replayOptions(options) {
14165
+ const { cursor: _cursor, onProgress: _onProgress, ...serializable } = options;
14166
+ relationshipOptions(serializable, "expansion.options");
14167
+ return jsonCopy(serializable);
14168
+ }
14169
+ function createInvestigationSession(target, options = {}) {
14170
+ const store = createStore(() => ({
14171
+ title: "Untitled investigation",
14172
+ notes: "",
14173
+ searchQuery: "",
14174
+ tableQuery: "",
14175
+ paths: [],
14176
+ expansions: [],
14177
+ checkpoints: [],
14178
+ activeCheckpointId: null,
14179
+ status: "idle",
14180
+ error: null
14181
+ }));
14182
+ const get = typeof target === "function" ? target : () => target;
14183
+ let disposed = false;
14184
+ let sequence = 0;
14185
+ let restoreFlight = null;
14186
+ let trackedSource = null;
14187
+ let bound = null;
14188
+ let unsubscribe = null;
14189
+ const cursors = /* @__PURE__ */ new Map();
14190
+ const ownedActions = /* @__PURE__ */ new WeakSet();
14191
+ const recordIds = /* @__PURE__ */ new WeakMap();
14192
+ const actionPredecessors = /* @__PURE__ */ new WeakMap();
14193
+ let actionCatalog = [];
14194
+ const pendingSeeds = /* @__PURE__ */ new Set();
14195
+ const now = options.now ?? (() => /* @__PURE__ */ new Date());
14196
+ const nextId = (kind) => `${kind}-${now().getTime()}-${++sequence}`;
14197
+ const graph = () => {
14198
+ const instance = get();
14199
+ if (disposed || instance === null || instance.store.getState().status === "destroyed") throw new InvestigationError("graph-unavailable", "The investigation graph is unavailable");
14200
+ return instance;
14201
+ };
14202
+ const sourceOf = (instance) => {
14203
+ const source = instance.getSource();
14204
+ if (source === null) throw new InvestigationError("graph-unavailable", "Load a graph before saving or restoring an investigation");
14205
+ const dataRef = instance.getViewState().dataRef;
14206
+ return { ...source, ...dataRef === void 0 ? {} : { dataRef } };
14207
+ };
14208
+ const sourceKey = (source) => canonicalJson2(source);
14209
+ const syncSource = (instance) => {
14210
+ const key = sourceKey(sourceOf(instance));
14211
+ if (trackedSource !== null && trackedSource !== key) {
14212
+ cursors.clear();
14213
+ actionCatalog = [];
14214
+ store.setState({ expansions: [], paths: [], activeCheckpointId: null });
14215
+ }
14216
+ trackedSource = key;
14217
+ return key;
14218
+ };
14219
+ const reconcileHistory = (instance) => {
14220
+ const live = new Set(instance.getExpansionRecords().map((record2) => record2.overlayId));
14221
+ const activeActions = /* @__PURE__ */ new Set();
14222
+ const active = actionCatalog.filter((action) => {
14223
+ const id = recordIds.get(action);
14224
+ const predecessor = actionPredecessors.get(action);
14225
+ if (id !== void 0 && !live.has(id) || predecessor !== void 0 && !activeActions.has(predecessor)) return false;
14226
+ activeActions.add(action);
14227
+ return true;
14228
+ });
14229
+ const previous = store.getState().expansions;
14230
+ if (active.length !== previous.length || active.some((action, index) => action !== previous[index])) {
14231
+ if (previous.some((action) => !active.includes(action))) cursors.clear();
14232
+ store.setState({ expansions: freeze(active), activeCheckpointId: null });
14233
+ }
14234
+ };
14235
+ let issueCounter = 0;
14236
+ const issuedAt = /* @__PURE__ */ new WeakMap();
14237
+ const issueOf = (action) => issuedAt.get(action) ?? Number.MAX_SAFE_INTEGER;
14238
+ const insertByIssue = (list, action) => {
14239
+ const seq = issueOf(action);
14240
+ let index = list.length;
14241
+ while (index > 0 && issueOf(list[index - 1]) > seq) index--;
14242
+ return [...list.slice(0, index), action, ...list.slice(index)];
14243
+ };
14244
+ const precedingQueryAction = (actions, key) => {
14245
+ for (let index = actions.length - 1; index >= 0; index--) {
14246
+ const action = actions[index];
14247
+ if (queryKey(action.seedId, action.options) === key) return action;
14248
+ }
14249
+ return null;
14250
+ };
14251
+ const trackAction = (instance, action, result, predecessor = precedingQueryAction(actionCatalog, queryKey(action.seedId, action.options))) => {
14252
+ ownedActions.delete(action);
14253
+ recordIds.delete(action);
14254
+ actionPredecessors.delete(action);
14255
+ if (predecessor !== null && (action.continuation || "noop" in result)) actionPredecessors.set(action, predecessor);
14256
+ if ("added" in result) {
14257
+ ownedActions.add(action);
14258
+ const record2 = instance.getExpansionRecords().filter((item) => item.expandedId === action.seedId).at(-1);
14259
+ if (record2?.overlayId != null) recordIds.set(action, record2.overlayId);
14260
+ }
14261
+ if (!issuedAt.has(action)) issuedAt.set(action, ++issueCounter);
14262
+ actionCatalog = insertByIssue(actionCatalog, action);
14263
+ };
14264
+ const assertRetractable = (instance, actions) => {
14265
+ const records = [...instance.getExpansionRecords()];
14266
+ for (const action of actions) {
14267
+ if (!ownedActions.has(action)) continue;
14268
+ let index = records.length - 1;
14269
+ while (index >= 0 && records[index].expandedId !== action.seedId) index--;
14270
+ if (index < 0 || records[index].overlayId !== recordIds.get(action)) {
14271
+ throw new InvestigationError("untracked-expansion", `An expansion of '${action.seedId}' changed outside this investigation; reconcile it before retracting or restoring`);
14272
+ }
14273
+ records.splice(index, 1);
14274
+ }
14275
+ };
14276
+ const refreshSource = () => {
14277
+ if (disposed) return;
14278
+ const instance = get();
14279
+ if (instance !== bound) {
14280
+ unsubscribe?.();
14281
+ bound = instance;
14282
+ unsubscribe = instance?.store.subscribe((next, previous) => {
14283
+ if (!disposed && instance.getSource() !== null && (next.revisions.model !== previous.revisions.model || next.revisions.scope !== previous.revisions.scope || next.history !== previous.history)) {
14284
+ syncSource(instance);
14285
+ if (restoreFlight === null) reconcileHistory(instance);
14286
+ }
14287
+ }) ?? null;
14288
+ }
14289
+ if (instance !== null && instance.getSource() !== null) {
14290
+ syncSource(instance);
14291
+ reconcileHistory(instance);
14292
+ }
14293
+ };
14294
+ const editable = () => {
14295
+ if (disposed) throw new InvestigationError("graph-unavailable", "The investigation session was destroyed");
14296
+ if (restoreFlight !== null) throw new InvestigationError("restore-pending", "Wait for the investigation restore to finish");
14297
+ };
14298
+ const checkAbort = (signal) => {
14299
+ if (disposed || signal.aborted) throw new InvestigationError("aborted", "Investigation restore was cancelled");
14300
+ };
14301
+ const resolveCheckpoint = (value) => {
14302
+ if (typeof value !== "string") return parseInvestigation(value);
14303
+ const result = store.getState().checkpoints.find((item) => item.id === value);
14304
+ if (result === void 0) invalid(`Unknown checkpoint: ${value}`);
14305
+ return result;
14306
+ };
14307
+ const remember = (checkpoint) => {
14308
+ const prior = store.getState().checkpoints;
14309
+ store.setState({ checkpoints: freeze([...prior.filter((v) => v.id !== checkpoint.id), checkpoint]) });
14310
+ };
14311
+ const recordPage = (seedId, opts, result) => {
14312
+ const key = queryKey(seedId, opts);
14313
+ const cursor = result.page?.nextCursor;
14314
+ if (cursor === void 0) cursors.delete(key);
14315
+ else cursors.set(key, cursor);
14316
+ };
14317
+ const api = {
14318
+ store,
14319
+ refreshSource,
14320
+ setTitle(title) {
14321
+ editable();
14322
+ store.setState({ title: string(title, "title") });
14323
+ },
14324
+ setNotes(notes) {
14325
+ editable();
14326
+ store.setState({ notes: string(notes, "notes") });
14327
+ },
14328
+ setSearchQuery(searchQuery) {
14329
+ editable();
14330
+ store.setState({ searchQuery: string(searchQuery, "searchQuery") });
14331
+ },
14332
+ setTableQuery(tableQuery) {
14333
+ editable();
14334
+ store.setState({ tableQuery: string(tableQuery, "tableQuery") });
14335
+ },
14336
+ async expandNode(id, expandOptions = {}) {
14337
+ editable();
14338
+ const instance = graph();
14339
+ const source = syncSource(instance);
14340
+ const serializable = replayOptions(expandOptions);
14341
+ const key = queryKey(id, serializable);
14342
+ const predecessor = precedingQueryAction(store.getState().expansions, key);
14343
+ if (expandOptions.cursor !== void 0 && cursors.get(key) !== expandOptions.cursor) throw new InvestigationError("untracked-cursor", "Load the preceding page through this investigation before continuing");
14344
+ if (pendingSeeds.has(id)) throw new InvestigationError("restore-pending", "This entity already has an expansion in progress");
14345
+ pendingSeeds.add(id);
14346
+ const issue = ++issueCounter;
14347
+ try {
14348
+ const result = await instance.expandNode(id, expandOptions);
14349
+ if (disposed || get() !== instance || sourceKey(sourceOf(instance)) !== source) throw new InvestigationError("source-mismatch", "The graph source changed during expansion");
14350
+ recordPage(id, serializable, result);
14351
+ const action = freeze({ seedId: id, options: serializable, continuation: expandOptions.cursor !== void 0 });
14352
+ issuedAt.set(action, issue);
14353
+ trackAction(instance, action, result, predecessor);
14354
+ store.setState({ expansions: freeze(insertByIssue(store.getState().expansions, action)), activeCheckpointId: null, error: null });
14355
+ return result;
14356
+ } finally {
14357
+ pendingSeeds.delete(id);
14358
+ }
14359
+ },
14360
+ retractExpansion(id) {
14361
+ editable();
14362
+ if (pendingSeeds.has(id)) {
14363
+ graph().cancelExpansion(id);
14364
+ return;
14365
+ }
14366
+ const instance = graph();
14367
+ syncSource(instance);
14368
+ const actions = [...store.getState().expansions];
14369
+ let index = actions.length - 1;
14370
+ while (index >= 0 && actions[index].seedId !== id) index--;
14371
+ if (index < 0) return;
14372
+ const [removed] = actions.splice(index, 1);
14373
+ assertRetractable(instance, [removed]);
14374
+ if (ownedActions.has(removed)) instance.retractExpansion(id);
14375
+ else actionCatalog = actionCatalog.filter((action) => action !== removed);
14376
+ cursors.delete(queryKey(id, removed.options));
14377
+ store.setState({ expansions: freeze(actions), activeCheckpointId: null });
14378
+ },
14379
+ savePath(input) {
14380
+ editable();
14381
+ syncSource(graph());
14382
+ const path = freeze(jsonCopy(validatePath2({ ...input, id: nextId("path"), title: input.title ?? `${input.sourceId} \u2192 ${input.targetId}`, options: input.options ?? {} })));
14383
+ store.setState({ paths: freeze([...store.getState().paths, path]), activeCheckpointId: null });
14384
+ return path;
14385
+ },
14386
+ removePath(id) {
14387
+ editable();
14388
+ store.setState({ paths: store.getState().paths.filter((p) => p.id !== id), activeCheckpointId: null });
14389
+ },
14390
+ async checkpoint(title, captureOptions = {}) {
14391
+ editable();
14392
+ if (pendingSeeds.size > 0) throw new InvestigationError("restore-pending", "Wait for pending expansions before saving a checkpoint");
14393
+ const instance = graph();
14394
+ const key = syncSource(instance);
14395
+ const state = store.getState();
14396
+ const revision = instance.getRevisions();
14397
+ const source = sourceOf(instance);
14398
+ const view = captureOptions.includePositions === false ? instance.getViewState() : await instance.getViewState({ includePositions: true });
14399
+ const after = instance.getRevisions();
14400
+ if (disposed || get() !== instance || sourceKey(sourceOf(instance)) !== key || after.model !== revision.model || after.scope !== revision.scope || pendingSeeds.size > 0) throw new InvestigationError("source-mismatch", "The graph changed while saving; save a new checkpoint");
14401
+ const checkpoint = parseInvestigation({
14402
+ v: 1,
14403
+ id: nextId("checkpoint"),
14404
+ title: title ?? state.title,
14405
+ notes: state.notes,
14406
+ createdAt: now().toISOString(),
14407
+ source,
14408
+ view,
14409
+ searchQuery: state.searchQuery,
14410
+ tableQuery: state.tableQuery,
14411
+ expansions: state.expansions,
14412
+ paths: state.paths,
14413
+ ...options.captureHostState === void 0 ? {} : { hostState: options.captureHostState() }
14414
+ });
14415
+ remember(checkpoint);
14416
+ store.setState({ activeCheckpointId: checkpoint.id, title: checkpoint.title, error: null });
14417
+ return checkpoint;
14418
+ },
14419
+ async restoreCheckpoint(value, restoreOptions = {}) {
14420
+ editable();
14421
+ if (pendingSeeds.size > 0) throw new InvestigationError("restore-pending", "Cancel pending expansions before restoring");
14422
+ const checkpoint = resolveCheckpoint(value);
14423
+ if (checkpoint.hostState !== void 0 && options.restoreHostState === void 0) throw new InvestigationError("restore-failed", "This checkpoint requires a host-state restore callback");
14424
+ const current = graph();
14425
+ const currentSource = sourceOf(current);
14426
+ const expectedSource = sourceKey(checkpoint.source);
14427
+ const mismatch = sourceKey(currentSource) !== expectedSource;
14428
+ if (mismatch && options.loadSource === void 0) throw new InvestigationError("source-mismatch", "Load the checkpoint source before restoring this investigation");
14429
+ const flight = new AbortController();
14430
+ const upstream = restoreOptions.signal;
14431
+ const abort = () => flight.abort();
14432
+ if (upstream?.aborted) abort();
14433
+ else upstream?.addEventListener("abort", abort, { once: true });
14434
+ checkAbort(flight.signal);
14435
+ restoreFlight = flight;
14436
+ store.setState({ status: "restoring", error: null });
14437
+ const applied = [];
14438
+ let replayStarted = false;
14439
+ let instance = current;
14440
+ const checkSource = () => {
14441
+ if (get() !== instance || sourceKey(sourceOf(instance)) !== expectedSource) {
14442
+ throw new InvestigationError("source-mismatch", "The source changed during investigation restore");
14443
+ }
14444
+ };
14445
+ try {
14446
+ if (mismatch) {
14447
+ await options.loadSource(checkpoint.source, { signal: flight.signal });
14448
+ checkAbort(flight.signal);
14449
+ instance = graph();
14450
+ }
14451
+ checkSource();
14452
+ if (bound !== instance) refreshSource();
14453
+ if (!mismatch && trackedSource === sourceKey(currentSource)) {
14454
+ const retract = [...store.getState().expansions].reverse();
14455
+ assertRetractable(instance, retract);
14456
+ replayStarted = true;
14457
+ for (const action of retract) {
14458
+ if (ownedActions.has(action)) instance.retractExpansion(action.seedId);
14459
+ }
14460
+ }
14461
+ replayStarted = true;
14462
+ cursors.clear();
14463
+ trackedSource = expectedSource;
14464
+ const replayed = [];
14465
+ actionCatalog = [];
14466
+ store.setState({ expansions: [], paths: [], activeCheckpointId: null });
14467
+ for (const action of checkpoint.expansions) {
14468
+ checkAbort(flight.signal);
14469
+ checkSource();
14470
+ const cursor = action.continuation ? cursors.get(queryKey(action.seedId, action.options)) : void 0;
14471
+ if (action.continuation && cursor === void 0) throw new InvestigationError("restore-failed", "An expansion no longer has the saved continuation page");
14472
+ const cancel = () => instance.cancelExpansion(action.seedId);
14473
+ flight.signal.addEventListener("abort", cancel, { once: true });
14474
+ let result2;
14475
+ try {
14476
+ result2 = await instance.expandNode(action.seedId, { ...action.options, ...cursor === void 0 ? {} : { cursor } });
14477
+ } finally {
14478
+ flight.signal.removeEventListener("abort", cancel);
14479
+ }
14480
+ checkSource();
14481
+ if ("added" in result2) applied.push(action);
14482
+ trackAction(instance, action, result2);
14483
+ checkAbort(flight.signal);
14484
+ recordPage(action.seedId, action.options, result2);
14485
+ replayed.push(action);
14486
+ }
14487
+ if (checkpoint.hostState !== void 0) await options.restoreHostState(checkpoint.hostState, { signal: flight.signal });
14488
+ checkAbort(flight.signal);
14489
+ checkSource();
14490
+ const result = await instance.setViewState(checkpoint.view);
14491
+ checkAbort(flight.signal);
14492
+ checkSource();
14493
+ if (result.status !== "applied") throw new InvestigationError("restore-failed", result.status === "mismatch" ? "The view source reference changed" : result.problems.join("; "));
14494
+ remember(checkpoint);
14495
+ store.setState({
14496
+ title: checkpoint.title,
14497
+ notes: checkpoint.notes,
14498
+ searchQuery: checkpoint.searchQuery,
14499
+ tableQuery: checkpoint.tableQuery ?? "",
14500
+ expansions: freeze(replayed),
14501
+ paths: checkpoint.paths,
14502
+ activeCheckpointId: checkpoint.id
14503
+ });
14504
+ } catch (error) {
14505
+ if (!disposed && get() === instance && instance.getSource() !== null && instance.store.getState().status !== "destroyed" && sourceKey(sourceOf(instance)) === expectedSource) {
14506
+ for (const action of applied.reverse()) {
14507
+ try {
14508
+ assertRetractable(instance, [action]);
14509
+ } catch {
14510
+ continue;
14511
+ }
14512
+ instance.retractExpansion(action.seedId);
14513
+ }
14514
+ }
14515
+ if (replayStarted) {
14516
+ cursors.clear();
14517
+ actionCatalog = [];
14518
+ }
14519
+ if (!disposed) store.setState({ ...replayStarted ? { expansions: [] } : {}, error: error instanceof Error ? error.message : String(error) });
14520
+ throw error;
14521
+ } finally {
14522
+ upstream?.removeEventListener("abort", abort);
14523
+ restoreFlight = null;
14524
+ if (!disposed) store.setState({ status: "idle" });
14525
+ }
14526
+ },
14527
+ importCheckpoint(raw) {
14528
+ editable();
14529
+ const checkpoint = parseInvestigation(raw);
14530
+ remember(checkpoint);
14531
+ return checkpoint;
14532
+ },
14533
+ exportCheckpoint(value) {
14534
+ return serializeInvestigation(resolveCheckpoint(value));
14535
+ },
14536
+ removeCheckpoint(id) {
14537
+ editable();
14538
+ store.setState({
14539
+ checkpoints: store.getState().checkpoints.filter((c) => c.id !== id),
14540
+ ...store.getState().activeCheckpointId === id ? { activeCheckpointId: null } : {}
14541
+ });
14542
+ },
14543
+ destroy() {
14544
+ if (disposed) return;
14545
+ disposed = true;
14546
+ unsubscribe?.();
14547
+ unsubscribe = null;
14548
+ restoreFlight?.abort();
14549
+ const instance = get();
14550
+ for (const seed of pendingSeeds) instance?.cancelExpansion(seed);
14551
+ pendingSeeds.clear();
14552
+ cursors.clear();
14553
+ }
14554
+ };
14555
+ refreshSource();
14556
+ return api;
14557
+ }
13595
14558
 
13596
14559
  // src/overview.ts
13597
14560
  var OVERVIEW_SIZE_DEFAULT = 256;
@@ -13781,6 +14744,6 @@ function evaluateFieldAccessor(accessor, id, attrs) {
13781
14744
  }
13782
14745
  }
13783
14746
 
13784
- export { ATLAS_MAX_CONCURRENT_DEFAULT, ATLAS_MAX_ENTRIES_DEFAULT, ATLAS_MAX_RETRIES_DEFAULT, AcceptanceQueue, BASE_PENDING_KEY, BRUSH_HISTORY_COALESCE_MS, CATEGORICAL_PALETTE, DEFAULT_BIN_COUNT, DIM_ALPHA_DEFAULT, DIVERGING_RANGE_DEFAULT, DomainStore, EDGE_PICK_TOLERANCE_PX, EdgePickingFacade, GRAPH_THEME_DARK, GRAPH_THEME_LIGHT, HISTORY_LIMIT_DEFAULT, HistoryKernel, INGEST_MAX_FLUSH_LATENCY_MS_DEFAULT, INGEST_MAX_PENDING_BYTES_DEFAULT, INGEST_OVERFLOW_FACTOR, ImageAtlasPipeline, LABEL_MAX_VISIBLE_CAP, LABEL_MAX_VISIBLE_DEFAULT, LinkPickIndex, META_EDGE_MAX_WIDTH, MetricStore, OVERVIEW_HOT_INTERVAL_MS, OVERVIEW_IDLE_INTERVAL_MS, OVERVIEW_SIZE_DEFAULT, OrbitOperationError, OverviewController, PHYSICAL_DEFAULT_LINK_WIDTH, PHYSICAL_DEFAULT_POINT_SIZE, PendingExpansions, Reconciler, SEARCH_CACHE_LIMIT, SEARCH_LIMIT_DEFAULT, SEARCH_SCAN_CHUNK, SEARCH_SCORE_EXACT_ID, SEARCH_SCORE_ID_PREFIX, SEARCH_SCORE_SUBSTRING, SEARCH_SCORE_TOKEN_START_BONUS, SEQUENTIAL_RANGE_DEFAULT, SUPER_NODE_MAX_SIZE, SVG_MAX_ELEMENTS_DEFAULT, SoftMask, SvgBudgetError, TIMELINE_STEP_DEFAULT, TIMELINE_TICK_MS_DEFAULT, TypedColumnCrossfilter, VIEW_STATE_VERSION, admitServiceResult, assertCapabilityMethodParity, baseFromAccepted, baseFromContribution, buildAcceptedAdjacency, buildAcceptedFromColumnar, buildAdjacency, canonicalFilterKey, canonicalJson2 as canonicalJson, canonicalScaleKey, cascadeEdges, categoricalIndex, categoricalRows, coerceNumeric, coerceNumericInto, collapseParallelEdges, columnarArrayBuffers, compileEdgeFilter, compileNodeFilter, computeNumericDomain, createGraphInstance, createLocalExpansionService, createLocalSearchService, createRequestContext, deriveGroupsByKey, descriptorKey, detachColumnarBuffers, divergingColor, escapeXml, estimateBatchBytes, evaluateFieldAccessor, evaluateFilterExpr, field, graphErrorToError, groupByDerivedId, groupSceneKey, interpolateColor, isColumnarSnapshot, isFatalGraphError, isFieldAccessor, materializeColumnarSnapshot, medianLinkWidthPx, mergeDiagnostics, mergeModel, metaEdgePublicId, metaEdgeSceneKey, metaEdgeWidthFor, neighborsOf, newContribution, newStagingTallies, nextRequestId, normalizeCommitForCapabilities, parseColor, pointSegmentDistanceSquared, projectColors, projectSizes, renderSvg, resolveEnginePolicy, resolveFilterField, resolveManualGroups, resolveScope, resolveTheme, resourceLimitFatal, rewriteGroups, sameDataRef, sameGroupBySpec, sameGroupSpecArrays, sceneGroupsOf, sceneLinkRefAt, scenePointRefAt, selectLabelCandidates, sequentialColor, sequentialSize, serviceCacheKey, sessionCommitDiagnostics, stageBatch, superNodeSizeFor, validateColumnarStructure, validateFieldAccessor, validateFilterExpr, validateGroupBySpec, validateGroupSpecs, validateSnapshot, validateViewState };
14747
+ export { ATLAS_MAX_CONCURRENT_DEFAULT, ATLAS_MAX_ENTRIES_DEFAULT, ATLAS_MAX_RETRIES_DEFAULT, AcceptanceQueue, BASE_PENDING_KEY, BRUSH_HISTORY_COALESCE_MS, CATEGORICAL_PALETTE, DEFAULT_BIN_COUNT, DIM_ALPHA_DEFAULT, DIVERGING_RANGE_DEFAULT, DomainStore, EDGE_PICK_TOLERANCE_PX, EdgePickingFacade, GRAPH_THEME_DARK, GRAPH_THEME_LIGHT, HISTORY_LIMIT_DEFAULT, HistoryKernel, INGEST_MAX_FLUSH_LATENCY_MS_DEFAULT, INGEST_MAX_PENDING_BYTES_DEFAULT, INGEST_OVERFLOW_FACTOR, ImageAtlasPipeline, InvestigationError, LABEL_MAX_VISIBLE_CAP, LABEL_MAX_VISIBLE_DEFAULT, LinkPickIndex, META_EDGE_MAX_WIDTH, MetricStore, OVERVIEW_HOT_INTERVAL_MS, OVERVIEW_IDLE_INTERVAL_MS, OVERVIEW_SIZE_DEFAULT, OrbitOperationError, OverviewController, PHYSICAL_DEFAULT_LINK_WIDTH, PHYSICAL_DEFAULT_POINT_SIZE, PendingExpansions, Reconciler, SEARCH_CACHE_LIMIT, SEARCH_LIMIT_DEFAULT, SEARCH_SCAN_CHUNK, SEARCH_SCORE_EXACT_ID, SEARCH_SCORE_ID_PREFIX, SEARCH_SCORE_SUBSTRING, SEARCH_SCORE_TOKEN_START_BONUS, SEQUENTIAL_RANGE_DEFAULT, SUPER_NODE_MAX_SIZE, SVG_MAX_ELEMENTS_DEFAULT, SoftMask, SvgBudgetError, TIMELINE_STEP_DEFAULT, TIMELINE_TICK_MS_DEFAULT, TypedColumnCrossfilter, VIEW_STATE_VERSION, admitServiceResult, assertCapabilityMethodParity, baseFromAccepted, baseFromContribution, buildAcceptedAdjacency, buildAcceptedFromColumnar, buildAdjacency, canonicalFilterKey, canonicalJson2 as canonicalJson, canonicalScaleKey, cascadeEdges, categoricalIndex, categoricalRows, coerceNumeric, coerceNumericInto, collapseParallelEdges, columnarArrayBuffers, compileEdgeFilter, compileNodeFilter, computeNumericDomain, createGraphInstance, createInvestigationSession, createLocalExpansionService, createLocalSearchService, createRequestContext, deriveGroupsByKey, descriptorKey, detachColumnarBuffers, divergingColor, escapeXml, estimateBatchBytes, evaluateFieldAccessor, evaluateFilterExpr, field, graphErrorToError, groupByDerivedId, groupSceneKey, interpolateColor, isColumnarSnapshot, isFatalGraphError, isFieldAccessor, materializeColumnarSnapshot, medianLinkWidthPx, mergeDiagnostics, mergeModel, metaEdgePublicId, metaEdgeSceneKey, metaEdgeWidthFor, neighborsOf, newContribution, newStagingTallies, nextRequestId, normalizeCommitForCapabilities, parseColor, parseInvestigation, pointSegmentDistanceSquared, projectColors, projectSizes, renderSvg, resolveEnginePolicy, resolveFilterField, resolveManualGroups, resolveScope, resolveTheme, resourceLimitFatal, rewriteGroups, sameDataRef, sameGroupBySpec, sameGroupSpecArrays, sceneGroupsOf, sceneLinkRefAt, scenePointRefAt, selectLabelCandidates, sequentialColor, sequentialSize, serializeInvestigation, serviceCacheKey, sessionCommitDiagnostics, stageBatch, superNodeSizeFor, validateColumnarStructure, validateFieldAccessor, validateFilterExpr, validateGroupBySpec, validateGroupSpecs, validateSnapshot, validateViewState };
13785
14748
  //# sourceMappingURL=index.js.map
13786
14749
  //# sourceMappingURL=index.js.map