@vltpkg/graph 1.0.0-rc.23 → 1.0.0-rc.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/dist/actual/load.d.ts +107 -0
  2. package/dist/actual/load.js +336 -0
  3. package/dist/browser.d.ts +14 -0
  4. package/dist/browser.js +16 -0
  5. package/dist/build.d.ts +28 -0
  6. package/dist/build.js +78 -0
  7. package/dist/dependencies.d.ts +65 -0
  8. package/dist/dependencies.js +111 -0
  9. package/dist/diff.d.ts +119 -0
  10. package/dist/diff.js +151 -0
  11. package/dist/edge.d.ts +46 -0
  12. package/dist/edge.js +77 -0
  13. package/dist/fixup-added-names.d.ts +18 -0
  14. package/dist/fixup-added-names.js +46 -0
  15. package/dist/graph.d.ts +153 -0
  16. package/dist/graph.js +444 -0
  17. package/dist/ideal/append-nodes.d.ts +31 -0
  18. package/dist/ideal/append-nodes.js +560 -0
  19. package/dist/ideal/build-ideal-from-starting-graph.d.ts +14 -0
  20. package/dist/ideal/build-ideal-from-starting-graph.js +69 -0
  21. package/dist/ideal/build.d.ts +40 -0
  22. package/dist/ideal/build.js +84 -0
  23. package/dist/ideal/get-importer-specs.d.ts +20 -0
  24. package/dist/ideal/get-importer-specs.js +180 -0
  25. package/dist/ideal/peers.d.ts +160 -0
  26. package/dist/ideal/peers.js +696 -0
  27. package/dist/ideal/refresh-ideal-graph.d.ts +43 -0
  28. package/dist/ideal/refresh-ideal-graph.js +62 -0
  29. package/dist/ideal/remove-satisfied-specs.d.ts +7 -0
  30. package/dist/ideal/remove-satisfied-specs.js +34 -0
  31. package/dist/ideal/sorting.d.ts +45 -0
  32. package/dist/ideal/sorting.js +70 -0
  33. package/dist/ideal/types.d.ts +107 -0
  34. package/dist/ideal/types.js +1 -0
  35. package/dist/index.d.ts +38 -0
  36. package/dist/index.js +32 -0
  37. package/dist/install.d.ts +19 -0
  38. package/dist/install.js +208 -0
  39. package/dist/lockfile/load-edges.d.ts +11 -0
  40. package/dist/lockfile/load-edges.js +105 -0
  41. package/dist/lockfile/load-nodes.d.ts +4 -0
  42. package/dist/lockfile/load-nodes.js +101 -0
  43. package/dist/lockfile/load.d.ts +45 -0
  44. package/dist/lockfile/load.js +84 -0
  45. package/dist/lockfile/save.d.ts +30 -0
  46. package/dist/lockfile/save.js +174 -0
  47. package/dist/lockfile/types.d.ts +95 -0
  48. package/dist/lockfile/types.js +49 -0
  49. package/dist/modifiers.d.ts +188 -0
  50. package/dist/modifiers.js +329 -0
  51. package/dist/node.d.ts +234 -0
  52. package/dist/node.js +388 -0
  53. package/dist/non-empty-list.d.ts +2 -0
  54. package/dist/non-empty-list.js +2 -0
  55. package/dist/reify/add-edge.d.ts +9 -0
  56. package/dist/reify/add-edge.js +71 -0
  57. package/dist/reify/add-edges.d.ts +4 -0
  58. package/dist/reify/add-edges.js +12 -0
  59. package/dist/reify/add-nodes.d.ts +6 -0
  60. package/dist/reify/add-nodes.js +16 -0
  61. package/dist/reify/bin-chmod.d.ts +10 -0
  62. package/dist/reify/bin-chmod.js +38 -0
  63. package/dist/reify/build.d.ts +13 -0
  64. package/dist/reify/build.js +111 -0
  65. package/dist/reify/calculate-save-value.d.ts +2 -0
  66. package/dist/reify/calculate-save-value.js +50 -0
  67. package/dist/reify/check-needed-build.d.ts +34 -0
  68. package/dist/reify/check-needed-build.js +71 -0
  69. package/dist/reify/delete-edge.d.ts +4 -0
  70. package/dist/reify/delete-edge.js +27 -0
  71. package/dist/reify/delete-edges.d.ts +4 -0
  72. package/dist/reify/delete-edges.js +13 -0
  73. package/dist/reify/delete-nodes.d.ts +4 -0
  74. package/dist/reify/delete-nodes.js +15 -0
  75. package/dist/reify/extract-node.d.ts +23 -0
  76. package/dist/reify/extract-node.js +83 -0
  77. package/dist/reify/index.d.ts +34 -0
  78. package/dist/reify/index.js +161 -0
  79. package/dist/reify/internal-hoist.d.ts +8 -0
  80. package/dist/reify/internal-hoist.js +133 -0
  81. package/dist/reify/optional-fail.d.ts +15 -0
  82. package/dist/reify/optional-fail.js +15 -0
  83. package/dist/reify/rollback.d.ts +4 -0
  84. package/dist/reify/rollback.js +23 -0
  85. package/dist/reify/update-importers-package-json.d.ts +35 -0
  86. package/dist/reify/update-importers-package-json.js +122 -0
  87. package/dist/remove-optional-subgraph.d.ts +33 -0
  88. package/dist/remove-optional-subgraph.js +47 -0
  89. package/dist/resolve-save-type.d.ts +5 -0
  90. package/dist/resolve-save-type.js +4 -0
  91. package/dist/stringify-node.d.ts +2 -0
  92. package/dist/stringify-node.js +32 -0
  93. package/dist/transfer-data/load.d.ts +43 -0
  94. package/dist/transfer-data/load.js +175 -0
  95. package/dist/uninstall.d.ts +14 -0
  96. package/dist/uninstall.js +75 -0
  97. package/dist/update.d.ts +12 -0
  98. package/dist/update.js +73 -0
  99. package/dist/virtual-root.d.ts +15 -0
  100. package/dist/virtual-root.js +78 -0
  101. package/dist/visualization/human-readable-output.d.ts +26 -0
  102. package/dist/visualization/human-readable-output.js +163 -0
  103. package/dist/visualization/json-output.d.ts +41 -0
  104. package/dist/visualization/json-output.js +50 -0
  105. package/dist/visualization/mermaid-output.d.ts +17 -0
  106. package/dist/visualization/mermaid-output.js +170 -0
  107. package/dist/visualization/object-like-output.d.ts +2 -0
  108. package/dist/visualization/object-like-output.js +47 -0
  109. package/package.json +22 -22
@@ -0,0 +1,11 @@
1
+ import { Spec } from '@vltpkg/spec/browser';
2
+ import type { SpecOptions } from '@vltpkg/spec/browser';
3
+ import type { DependencyTypeShort, GraphLike, NodeLike } from '@vltpkg/types';
4
+ import type { LockfileData } from './types.ts';
5
+ export type ProcessingEdge = {
6
+ fromNode: NodeLike;
7
+ toNode: NodeLike | undefined;
8
+ depType: DependencyTypeShort;
9
+ spec: Spec;
10
+ };
11
+ export declare const loadEdges: (graph: GraphLike, edges: LockfileData["edges"], options: SpecOptions) => void;
@@ -0,0 +1,105 @@
1
+ import { asDepID } from '@vltpkg/dep-id/browser';
2
+ import { error } from '@vltpkg/error-cause';
3
+ import { fastSplit } from '@vltpkg/fast-split';
4
+ import { Spec } from '@vltpkg/spec/browser';
5
+ import { longDependencyTypes } from '@vltpkg/types';
6
+ import { isDependencyTypeShort } from "../dependencies.js";
7
+ const retrieveNodeFromGraph = (key, value, graph, fromId, seenNodes) => {
8
+ const foundNode = graph.nodes.get(asDepID(fromId));
9
+ if (!foundNode) {
10
+ throw error('Edge info missing its `from` node', {
11
+ found: {
12
+ nodes: [...graph.nodes].map(([id]) => id),
13
+ from: foundNode,
14
+ fromId,
15
+ edge: { [key]: value },
16
+ },
17
+ });
18
+ }
19
+ if (seenNodes) {
20
+ seenNodes.set(fromId, foundNode);
21
+ }
22
+ return foundNode;
23
+ };
24
+ export const loadEdges = (graph, edges, options) => {
25
+ const entries = Object.entries(edges);
26
+ const edgeCount = entries.length;
27
+ // Only use optimizations for non-trivial graphs
28
+ const useOptimizations = edgeCount > 50;
29
+ const edgeProcessingQueue = [];
30
+ // Cache for frequently accessed nodes to avoid repeated Map lookups
31
+ const seenNodes = useOptimizations ? new Map() : undefined;
32
+ for (const [key, value] of entries) {
33
+ const [fromId, specName] = fastSplit(key, ' ', 2);
34
+ const [depType, valRest] = fastSplit(value, ' ', 2);
35
+ const vrSplit = valRest?.lastIndexOf(' ') ?? -1;
36
+ // not a valid edge record
37
+ /* c8 ignore start */
38
+ if (!valRest || !depType || !fromId || !specName || vrSplit < 1) {
39
+ continue;
40
+ }
41
+ /* c8 ignore stop */
42
+ // Validate dependency type early
43
+ if (!isDependencyTypeShort(depType)) {
44
+ throw error('Found unsupported dependency type in lockfile', {
45
+ validOptions: [...longDependencyTypes],
46
+ });
47
+ }
48
+ // Use cached node lookup for large graphs, direct lookup for small ones
49
+ let fromNode;
50
+ if (seenNodes) {
51
+ const seen = seenNodes.get(fromId);
52
+ if (seen) {
53
+ fromNode = seen;
54
+ }
55
+ else {
56
+ fromNode = retrieveNodeFromGraph(key, value, graph, fromId, seenNodes);
57
+ }
58
+ }
59
+ else {
60
+ fromNode = retrieveNodeFromGraph(key, value, graph, fromId);
61
+ }
62
+ const toId = valRest.substring(vrSplit + 1);
63
+ let toNode = undefined;
64
+ if (toId !== 'MISSING') {
65
+ if (seenNodes) {
66
+ const seen = seenNodes.get(toId);
67
+ if (seen) {
68
+ toNode = seen;
69
+ }
70
+ else {
71
+ toNode = graph.nodes.get(asDepID(toId));
72
+ if (toNode) {
73
+ seenNodes.set(toId, toNode);
74
+ }
75
+ }
76
+ }
77
+ else {
78
+ toNode = graph.nodes.get(asDepID(toId));
79
+ }
80
+ }
81
+ // Parse spec once we know the nodes are valid
82
+ const spec = Spec.parse(specName, valRest.substring(0, vrSplit), {
83
+ ...options,
84
+ registry: fromNode.registry,
85
+ });
86
+ if (useOptimizations) {
87
+ edgeProcessingQueue.push({
88
+ fromNode,
89
+ toNode,
90
+ depType,
91
+ spec,
92
+ });
93
+ }
94
+ else {
95
+ // Process immediately for small graphs
96
+ graph.addEdge(depType, spec, fromNode, toNode);
97
+ }
98
+ }
99
+ // Batch process all edges (only for non-trivial graphs)
100
+ if (useOptimizations) {
101
+ for (const { fromNode, toNode, depType, spec, } of edgeProcessingQueue) {
102
+ graph.addEdge(depType, spec, fromNode, toNode);
103
+ }
104
+ }
105
+ };
@@ -0,0 +1,4 @@
1
+ import type { LockfileData } from './types.ts';
2
+ import type { GraphLike } from '@vltpkg/types';
3
+ import type { SpecOptions } from '@vltpkg/spec/browser';
4
+ export declare const loadNodes: (graph: GraphLike, nodes: LockfileData["nodes"], options: SpecOptions, actual?: GraphLike, throwOnMissingManifest?: boolean) => void;
@@ -0,0 +1,101 @@
1
+ import { error } from '@vltpkg/error-cause';
2
+ import { splitDepID, splitExtra } from '@vltpkg/dep-id/browser';
3
+ import { getBooleanFlagsFromNum, getBuildStateFromNum, } from "./types.js";
4
+ export const loadNodes = (graph, nodes, options, actual, throwOnMissingManifest) => {
5
+ const entries = Object.entries(nodes);
6
+ const nodeCount = entries.length;
7
+ // Batch process registry spec parsing (only for large graphs)
8
+ // Only used for non-trivial graphs
9
+ const registryVersionCache = nodeCount > 50 ? new Map() : null;
10
+ for (const [id, lockfileNode] of entries) {
11
+ const [flags, name, integrity, resolved, location, manifest, rawManifest, platform, bins, buildState,] = lockfileNode;
12
+ // workspace nodes and the project root node are already part of the
13
+ // graph and it should not create new nodes if an existing one is there
14
+ if (graph.nodes.has(id))
15
+ continue;
16
+ const [type, filepath, maybeExtra, lastExtra] = splitDepID(id);
17
+ const extra = type === 'registry' || type === 'git' ? lastExtra : maybeExtra;
18
+ const registrySpec = maybeExtra;
19
+ // The reference node is a node that matches the same id from the
20
+ // current iterating node in the provided `actual` graph, this allows
21
+ // for hydrating missing manifest, integrity, and resolved values
22
+ // that may be missing from the lockfile
23
+ const referenceNode = actual?.nodes.get(id);
24
+ const mani = manifest ?? referenceNode?.manifest;
25
+ // Throw if manifest is missing and the option is enabled
26
+ if (!mani && throwOnMissingManifest) {
27
+ throw error(`Missing manifest for node ${id} and no reference node found.`);
28
+ }
29
+ // Optimize registry version extraction with caching for large graphs
30
+ let version;
31
+ if (type === 'registry' &&
32
+ registrySpec &&
33
+ registrySpec.indexOf('@') > 0) {
34
+ if (registryVersionCache) {
35
+ const seenVersion = registryVersionCache.get(registrySpec);
36
+ /* c8 ignore start */
37
+ if (seenVersion) {
38
+ version = seenVersion;
39
+ }
40
+ else {
41
+ version = registrySpec.split('@').slice(-1)[0] || undefined;
42
+ /* c8 ignore stop */
43
+ if (version) {
44
+ registryVersionCache.set(registrySpec, version);
45
+ }
46
+ }
47
+ }
48
+ else {
49
+ version = registrySpec.split('@').slice(-1)[0] || undefined;
50
+ }
51
+ }
52
+ // if the lockfile has manifest data then it should just use that
53
+ // otherwise tries to infer name / version value from the lockfile node
54
+ const node = mani ?
55
+ graph.addNode(id, mani)
56
+ : graph.addNode(id, undefined, undefined, name ?? undefined, version);
57
+ if (extra) {
58
+ const { modifier, peerSetHash } = splitExtra(extra);
59
+ if (modifier) {
60
+ node.modifier = modifier;
61
+ }
62
+ if (peerSetHash) {
63
+ node.peerSetHash = peerSetHash;
64
+ }
65
+ }
66
+ const { dev, optional } = getBooleanFlagsFromNum(flags);
67
+ node.options = options;
68
+ node.dev = dev;
69
+ node.optional = optional;
70
+ node.integrity = integrity ?? referenceNode?.integrity;
71
+ node.resolved =
72
+ type === 'remote' ? filepath : ((resolved ?? referenceNode?.resolved));
73
+ node.projectRoot = graph.projectRoot;
74
+ if (!node.resolved)
75
+ node.setResolved();
76
+ if (location) {
77
+ node.location = location;
78
+ }
79
+ else {
80
+ // set the location to file dependencies based on the id value
81
+ if (type === 'file') {
82
+ node.location = filepath;
83
+ }
84
+ }
85
+ if (mani && rawManifest) {
86
+ node.setConfusedManifest(mani, rawManifest);
87
+ }
88
+ // Set platform data if provided
89
+ if (platform) {
90
+ node.platform = platform;
91
+ }
92
+ // optionally set bin data if provided
93
+ if (bins) {
94
+ node.bins = bins;
95
+ }
96
+ // Set build state if provided
97
+ if (buildState !== undefined && buildState !== null) {
98
+ node.buildState = getBuildStateFromNum(buildState);
99
+ }
100
+ }
101
+ };
@@ -0,0 +1,45 @@
1
+ import { PackageJson } from '@vltpkg/package-json';
2
+ import { Monorepo } from '@vltpkg/workspaces';
3
+ import { Graph } from '../graph.ts';
4
+ import type { PathScurry } from 'path-scurry';
5
+ import type { NormalizedManifest } from '@vltpkg/types';
6
+ import type { SpecOptions } from '@vltpkg/spec';
7
+ import type { LockfileData } from './types.ts';
8
+ import type { GraphModifier } from '../modifiers.ts';
9
+ export type LoadOptions = SpecOptions & {
10
+ /**
11
+ * An optional {@link Graph} object to hydrate extra data from.
12
+ */
13
+ actual?: Graph;
14
+ /**
15
+ * The project root dirname.
16
+ */
17
+ projectRoot: string;
18
+ /**
19
+ * The project root manifest.
20
+ */
21
+ mainManifest: NormalizedManifest;
22
+ /**
23
+ * The graph modifiers helper object.
24
+ */
25
+ modifiers?: GraphModifier;
26
+ /**
27
+ * A {@link Monorepo} object, for managing workspaces
28
+ */
29
+ monorepo?: Monorepo;
30
+ /**
31
+ * A {@link PackageJson} object, for sharing manifest caches
32
+ */
33
+ packageJson?: PackageJson;
34
+ /**
35
+ * A {@link PathScurry} object, for use in globs
36
+ */
37
+ scurry?: PathScurry;
38
+ /**
39
+ * Whether to throw an error if a manifest is missing when loading nodes.
40
+ */
41
+ throwOnMissingManifest?: boolean;
42
+ };
43
+ export declare const load: (options: LoadOptions) => Graph;
44
+ export declare const loadHidden: (options: LoadOptions) => Graph;
45
+ export declare const loadObject: (options: LoadOptions, lockfileData: Omit<LockfileData, "options" | "lockfileVersion"> & Partial<Pick<LockfileData, "options" | "lockfileVersion">>) => Graph;
@@ -0,0 +1,84 @@
1
+ import { error } from '@vltpkg/error-cause';
2
+ import { PackageJson } from '@vltpkg/package-json';
3
+ import { Monorepo } from '@vltpkg/workspaces';
4
+ import { readFileSync } from 'node:fs';
5
+ import { resolve } from 'node:path';
6
+ import { loadEdges } from "./load-edges.js";
7
+ import { loadNodes } from "./load-nodes.js";
8
+ import { Graph } from "../graph.js";
9
+ import { LOCKFILE_VERSION } from "./types.js";
10
+ const loadLockfile = (projectRoot, lockfilePath) => JSON.parse(readFileSync(resolve(projectRoot, lockfilePath), {
11
+ encoding: 'utf8',
12
+ }));
13
+ export const load = (options) => {
14
+ const { projectRoot } = options;
15
+ return loadObject(options, loadLockfile(projectRoot, 'vlt-lock.json'));
16
+ };
17
+ export const loadHidden = (options) => {
18
+ const { projectRoot } = options;
19
+ // Ensure that missing manifests throw an error when loading hidden lockfiles
20
+ options.throwOnMissingManifest = true;
21
+ return loadObject(options, loadLockfile(projectRoot, 'node_modules/.vlt-lock.json'));
22
+ };
23
+ export const loadObject = (options, lockfileData) => {
24
+ const version = lockfileData.lockfileVersion;
25
+ // Lockfile version is required, likely a corrupted lockfile if missing
26
+ if (version == null) {
27
+ throw error('Missing lockfile version', {
28
+ code: 'ELOCKFILEVERSION',
29
+ found: version,
30
+ wanted: LOCKFILE_VERSION,
31
+ });
32
+ }
33
+ // Lockfile version must match current version
34
+ if (version !== LOCKFILE_VERSION) {
35
+ throw error(`Unsupported lockfile version.
36
+
37
+ Run: \`vlt update\` to start a new, supported lockfile.`, {
38
+ code: 'ELOCKFILEVERSION',
39
+ found: version,
40
+ wanted: LOCKFILE_VERSION,
41
+ });
42
+ }
43
+ const { mainManifest, scurry } = options;
44
+ const packageJson = options.packageJson ?? new PackageJson();
45
+ const monorepo = options.monorepo ??
46
+ Monorepo.maybeLoad(options.projectRoot, { packageJson, scurry });
47
+ const { catalog = {}, catalogs = {}, 'scope-registries': scopeRegistries, registry, registries, 'git-hosts': gitHosts, 'git-host-archives': gitHostArchives,
48
+ /* c8 ignore next */
49
+ } = lockfileData.options ?? {};
50
+ // Optimize options merging - only create new objects when needed
51
+ const mergedOptions = {
52
+ ...options,
53
+ catalog,
54
+ catalogs,
55
+ 'scope-registries': scopeRegistries ?
56
+ { ...options['scope-registries'], ...scopeRegistries }
57
+ : options['scope-registries'],
58
+ registry: registry ?? options.registry,
59
+ registries: registries ?
60
+ { ...options.registries, ...registries }
61
+ : options.registries,
62
+ 'git-hosts': gitHosts ?
63
+ { ...options['git-hosts'], ...gitHosts }
64
+ : options['git-hosts'],
65
+ 'git-host-archives': gitHostArchives ?
66
+ { ...options['git-host-archives'], ...gitHostArchives }
67
+ : options['git-host-archives'],
68
+ };
69
+ const graph = new Graph({
70
+ ...mergedOptions,
71
+ mainManifest,
72
+ monorepo,
73
+ });
74
+ loadNodes(graph, lockfileData.nodes, mergedOptions, options.actual, options.throwOnMissingManifest);
75
+ loadEdges(graph, lockfileData.edges, mergedOptions);
76
+ // hydrate missing node-level registry data
77
+ for (const node of graph.nodes.values()) {
78
+ const [firstEdge] = node.edgesIn;
79
+ if (firstEdge?.spec.registry) {
80
+ node.registry = firstEdge.spec.registry;
81
+ }
82
+ }
83
+ return graph;
84
+ };
@@ -0,0 +1,30 @@
1
+ import type { SpecOptions } from '@vltpkg/spec';
2
+ import type { Graph } from '../graph.ts';
3
+ import type { LockfileData } from './types.ts';
4
+ import type { GraphModifier } from '../modifiers.ts';
5
+ export type SaveOptions = SpecOptions & {
6
+ /**
7
+ * The graph to be stored in the lockfile.
8
+ */
9
+ graph: Graph;
10
+ /**
11
+ * The graph modifiers helper object.
12
+ */
13
+ modifiers?: GraphModifier;
14
+ /**
15
+ * Should it save manifest data in the lockfile?
16
+ */
17
+ saveManifests?: boolean;
18
+ /**
19
+ * Should it save build state data in the lockfile?
20
+ */
21
+ saveBuildData?: boolean;
22
+ /**
23
+ * Should it throw an error if a manifest is missing?
24
+ */
25
+ throwOnMissingManifest?: boolean;
26
+ };
27
+ export declare const lockfileData: ({ graph, catalog, catalogs, "git-hosts": gitHosts, "git-host-archives": gitHostArchives, modifiers, registry, registries, saveManifests, saveBuildData, "scope-registries": scopeRegistries, "jsr-registries": jsrRegistries, throwOnMissingManifest, }: SaveOptions) => LockfileData;
28
+ export declare const saveData: (data: LockfileData, fileName: string, saveManifests?: boolean) => void;
29
+ export declare const save: (options: Omit<SaveOptions, "saveManifests">) => void;
30
+ export declare const saveHidden: (options: Omit<SaveOptions, "saveManifests" | "saveBuildData">) => void;
@@ -0,0 +1,174 @@
1
+ import { expandNormalizedManifestSymbols, isRecordStringString, } from '@vltpkg/types';
2
+ import { defaultGitHostArchives, defaultGitHosts, defaultJsrRegistries, defaultRegistries, defaultRegistry, defaultScopeRegistries, } from '@vltpkg/spec';
3
+ import { mkdirSync, writeFileSync } from 'node:fs';
4
+ import { dirname, resolve } from 'node:path';
5
+ import { getFlagNumFromNode, getBuildStateFromNode, LOCKFILE_VERSION, } from "./types.js";
6
+ import { error } from '@vltpkg/error-cause';
7
+ const formatNodes = (nodes, saveManifests, saveBuildData, registry, throwOnMissingManifest) => {
8
+ // we do not store importers in the lockfile, though we do store
9
+ // their edges. when we load, we always read workspaces/main fresh.
10
+ const arr = [...nodes].filter(node => !node.importer);
11
+ // nodes are sorted in order to have a deterministic result
12
+ const orderedNodes = arr.sort((a, b) => a.id.localeCompare(b.id, 'en'));
13
+ const res = {};
14
+ for (const node of orderedNodes) {
15
+ const customRegistry = node.resolved && registry && !node.resolved.startsWith(registry);
16
+ const resolved = customRegistry ? node.resolved : undefined;
17
+ // if it's in a location other than the default, stash that
18
+ const location = node.id.startsWith('file') || node.inVltStore() ?
19
+ undefined
20
+ : node.location;
21
+ const flags = getFlagNumFromNode(node);
22
+ const lockfileNode = [flags, node.name];
23
+ if (node.integrity) {
24
+ lockfileNode[2] = node.integrity;
25
+ }
26
+ // skip resolved for remote nodes since
27
+ // these are already part of the dep id
28
+ if (resolved && !node.id.startsWith('remote')) {
29
+ lockfileNode[3] = resolved;
30
+ }
31
+ if (location) {
32
+ lockfileNode[4] = location;
33
+ }
34
+ if (saveManifests && node.manifest) {
35
+ lockfileNode[5] = expandNormalizedManifestSymbols(node.manifest);
36
+ if (node.confused && node.rawManifest) {
37
+ lockfileNode[6] = expandNormalizedManifestSymbols(node.rawManifest);
38
+ }
39
+ }
40
+ // Throw an error if a manifest is missing and the option is enabled
41
+ if (throwOnMissingManifest && !node.manifest) {
42
+ throw error(`Missing manifest for node ${node.id}.`);
43
+ }
44
+ // Always save platform data for optional dependencies if available
45
+ if (node.optional && node.platform) {
46
+ lockfileNode[7] = node.platform;
47
+ }
48
+ // Save bin data if available
49
+ if (node.bins && Object.keys(node.bins).length) {
50
+ lockfileNode[8] = node.bins;
51
+ }
52
+ // Save build state data if requested
53
+ if (saveBuildData) {
54
+ const buildState = getBuildStateFromNode(node);
55
+ if (buildState !== undefined) {
56
+ lockfileNode[9] = buildState;
57
+ }
58
+ }
59
+ res[node.id] = lockfileNode;
60
+ }
61
+ return res;
62
+ };
63
+ const formatEdges = (edges) => Object.fromEntries([...edges]
64
+ .sort((a, b) =>
65
+ /* c8 ignore start - nondeterminstic and annoying to test */
66
+ // sort importers to the top, then alphabetically by
67
+ // id, type, target
68
+ Number(b.from.importer) - Number(a.from.importer) ||
69
+ a.from.id.localeCompare(b.from.id, 'en') ||
70
+ a.type.localeCompare(b.type, 'en') ||
71
+ (a.to?.id ?? '').localeCompare(b.to?.id ?? ''))
72
+ .map((edge) => [
73
+ `${edge.from.id} ${edge.spec.name}`,
74
+ `${edge.type} ${edge.spec.bareSpec || '*'} ${edge.to?.id ?? 'MISSING'}`,
75
+ ]));
76
+ const removeDefaultItems = (defaultItems, items) => {
77
+ const res = {};
78
+ for (const [key, value] of Object.entries(items)) {
79
+ if (!defaultItems[key] || defaultItems[key] !== value) {
80
+ res[key] = value;
81
+ }
82
+ }
83
+ return res;
84
+ };
85
+ export const lockfileData = ({ graph, catalog, catalogs, 'git-hosts': gitHosts, 'git-host-archives': gitHostArchives, modifiers, registry, registries, saveManifests, saveBuildData, 'scope-registries': scopeRegistries, 'jsr-registries': jsrRegistries, throwOnMissingManifest, }) => {
86
+ const cleanGitHosts = isRecordStringString(gitHosts) ?
87
+ removeDefaultItems(defaultGitHosts, gitHosts)
88
+ : undefined;
89
+ const cleanGitHostArchives = isRecordStringString(gitHostArchives) ?
90
+ removeDefaultItems(defaultGitHostArchives, gitHostArchives)
91
+ : undefined;
92
+ const cleanModifiers = modifiers && isRecordStringString(modifiers.config) ?
93
+ modifiers.config
94
+ : undefined;
95
+ const cleanRegistries = isRecordStringString(registries) ?
96
+ removeDefaultItems(defaultRegistries, registries)
97
+ : undefined;
98
+ const cleanScopeRegistries = isRecordStringString(scopeRegistries) ?
99
+ removeDefaultItems(defaultScopeRegistries, scopeRegistries)
100
+ : undefined;
101
+ const cleanJsrRegistries = isRecordStringString(jsrRegistries) ?
102
+ removeDefaultItems(defaultJsrRegistries, jsrRegistries)
103
+ : undefined;
104
+ const hasItems = (clean) => clean && Object.keys(clean).length;
105
+ return {
106
+ lockfileVersion: LOCKFILE_VERSION,
107
+ options: {
108
+ ...(hasItems(cleanModifiers) ?
109
+ { modifiers: cleanModifiers }
110
+ : {}),
111
+ ...(hasItems(catalog) ? { catalog } : {}),
112
+ ...(hasItems(catalogs) ? { catalogs } : {}),
113
+ ...(hasItems(cleanScopeRegistries) ?
114
+ { 'scope-registries': cleanScopeRegistries }
115
+ : undefined),
116
+ ...(hasItems(cleanJsrRegistries) ?
117
+ { 'jsr-registries': cleanJsrRegistries }
118
+ : undefined),
119
+ ...(registry !== undefined && registry !== defaultRegistry ?
120
+ { registry }
121
+ : undefined),
122
+ ...(hasItems(cleanRegistries) ?
123
+ { registries: cleanRegistries }
124
+ : undefined),
125
+ ...(hasItems(cleanGitHosts) ?
126
+ { 'git-hosts': cleanGitHosts }
127
+ : undefined),
128
+ ...(hasItems(cleanGitHostArchives) ?
129
+ { 'git-host-archives': cleanGitHostArchives }
130
+ : undefined),
131
+ },
132
+ nodes: formatNodes(graph.nodes.values(), saveManifests, saveBuildData, registry, throwOnMissingManifest),
133
+ edges: formatEdges(graph.edges),
134
+ };
135
+ };
136
+ // renders each node / edge as a single line entry
137
+ const extraFormat = (jsonString) => {
138
+ const str = `${jsonString}\n`;
139
+ const [init, ...parts] = str.split(' "nodes": {');
140
+ const res = [init];
141
+ for (const part of parts) {
142
+ res.push(part.replaceAll('\n ', '').replaceAll('\n ]', ']'));
143
+ }
144
+ return res.join(' "nodes": {');
145
+ };
146
+ export const saveData = (data, fileName, saveManifests = false) => {
147
+ const json = JSON.stringify(data, null, 2);
148
+ const content = saveManifests ? json : extraFormat(json);
149
+ writeFileSync(fileName, content);
150
+ };
151
+ export const save = (options) => {
152
+ const { graph } = options;
153
+ const data = lockfileData({ ...options, saveManifests: false });
154
+ const fileName = resolve(graph.projectRoot, 'vlt-lock.json');
155
+ saveData(data, fileName, false);
156
+ };
157
+ export const saveHidden = (options) => {
158
+ const { graph } = options;
159
+ let data;
160
+ try {
161
+ data = lockfileData({
162
+ ...options,
163
+ saveManifests: true,
164
+ saveBuildData: true,
165
+ throwOnMissingManifest: true,
166
+ });
167
+ }
168
+ catch { }
169
+ if (!data)
170
+ return;
171
+ const fileName = resolve(graph.projectRoot, 'node_modules/.vlt-lock.json');
172
+ mkdirSync(dirname(fileName), { recursive: true });
173
+ saveData(data, fileName, true);
174
+ };
@@ -0,0 +1,95 @@
1
+ import type { DepID } from '@vltpkg/dep-id';
2
+ import type { Spec, SpecOptions } from '@vltpkg/spec';
3
+ import type { Integrity, NormalizedManifest, DependencyTypeShort } from '@vltpkg/types';
4
+ /**
5
+ * Platform requirements for a lockfile node
6
+ */
7
+ export type LockfilePlatform = {
8
+ engines?: Record<string, string>;
9
+ os?: string[] | string;
10
+ cpu?: string[] | string;
11
+ libc?: string[] | string;
12
+ };
13
+ /**
14
+ * This is the main type definition for the contents of the
15
+ * `vlt-lock.json` file.
16
+ *
17
+ * The nodes and edges information from the lockfile are used to reconstruct
18
+ * a {@link Graph} representing a previous install.
19
+ */
20
+ export type LockfileData = {
21
+ lockfileVersion: number;
22
+ options: SpecOptions & {
23
+ modifiers?: Record<string, string> | undefined;
24
+ };
25
+ nodes: Record<DepID, LockfileNode>;
26
+ edges: LockfileEdges;
27
+ };
28
+ /**
29
+ * Current lockfile format version.
30
+ * Only lockfiles with matching version are considered valid.
31
+ * Bump when making breaking format changes.
32
+ */
33
+ export declare const LOCKFILE_VERSION = 1;
34
+ export declare const getFlagNumFromNode: (node: {
35
+ optional?: boolean;
36
+ dev?: boolean;
37
+ }) => 1 | 0 | 2 | 3;
38
+ export declare const getBooleanFlagsFromNum: (flags: LockfileNodeFlags) => {
39
+ dev: boolean;
40
+ optional: boolean;
41
+ };
42
+ export declare const LockfileNodeFlagNone = 0;
43
+ export declare const LockfileNodeFlagOptional = 1;
44
+ export declare const LockfileNodeFlagDev = 2;
45
+ export declare const LockfileNodeFlagDevOptional = 3;
46
+ /**
47
+ * Bit flags indicating whether a node is optional and/or dev.
48
+ */
49
+ export type LockfileNodeFlags = 0 | 1 | 2 | 3;
50
+ /**
51
+ * Build state constants for lockfile nodes
52
+ */
53
+ export declare const BuildStateNone: undefined;
54
+ export declare const BuildStateNeeded = 1;
55
+ export declare const BuildStateBuilt = 2;
56
+ export declare const BuildStateFailed = 3;
57
+ /**
58
+ * Build state for a node - tracks whether it needs building, has been built, or failed
59
+ */
60
+ export type LockfileBuildState = undefined | 1 | 2 | 3;
61
+ export declare const getBuildStateFromNode: (node: {
62
+ buildState?: "none" | "needed" | "built" | "failed";
63
+ }) => LockfileBuildState;
64
+ export declare const getBuildStateFromNum: (state: LockfileBuildState) => "none" | "needed" | "built" | "failed";
65
+ /**
66
+ * Lockfile representation of a node from the install graph.
67
+ */
68
+ export type LockfileNode = [
69
+ flags: LockfileNodeFlags,
70
+ name?: string | null,
71
+ integrity?: Integrity | null,
72
+ resolved?: string | null,
73
+ location?: string | null,
74
+ manifest?: NormalizedManifest | null,
75
+ rawManifest?: NormalizedManifest | null,
76
+ platform?: LockfilePlatform | null,
77
+ bins?: Record<string, string> | null,
78
+ buildState?: LockfileBuildState | null
79
+ ];
80
+ /**
81
+ * Lockfile edges are stored as a record object where the key
82
+ * is `${from.id} ${spec.name}` and the value is
83
+ * `${type} ${spec.bareSpec} ${to.id | 'MISSING'}`
84
+ *
85
+ * Storing them in a record like this means that we are guaranteed to
86
+ * never end up with duplicates, and a standard `JSON.stringify()`
87
+ * will nicely print them out one line per edge.
88
+ */
89
+ export type LockfileEdges = {
90
+ [key: LockfileEdgeKey]: LockfileEdgeValue;
91
+ };
92
+ /** `${from} ${dep name}` */
93
+ export type LockfileEdgeKey = `${DepID} ${string}`;
94
+ /** `${type} ${spec} ${to}` */
95
+ export type LockfileEdgeValue = `${DependencyTypeShort} ${Spec['bareSpec']} ${DepID | 'MISSING'}`;