okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221merge f-split-s4b 0edf5cb9f (Harness in the app chat, Manual approvals, request slots) into f-split-inta16109803

main
7.0 KiB133 linesraw
1/**
2 * Turn a pnpm "isolated" node_modules (a virtual store in `.pnpm` full of links) into an ordinary hoisted tree of real folders.
3 *
4 * Why: the installer copies the Harness folder file by file. pnpm's layout is thousands of links (junctions on Windows); a copy
5 * that follows them duplicates every package once per dependent and one that does not breaks on the first dangling link. A hoisted
6 * tree has each package once (nested only where two versions of the same name are needed), no links, and Node resolves it
7 * exactly as it resolves any npm install.
8 *
9 * Algorithm (the one npm uses, in short): the packages the root names come first, at the top. Then, walking each placed package's
10 * own dependencies: look the name up from the package's own folder upwards; if the same instance is already visible, nothing to
11 * do; if a DIFFERENT instance of that name is visible, nest this one inside the dependent; if none is visible, hoist it to the top.
12 *
13 * @param {string} out        folder holding `node_modules`
14 * @param {{skip?: RegExp}} [options]  package names never copied (the caller removes them anyway)
15 * @returns {{packages:number, copied:number, nested:number}}
16 */
17import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync } from 'node:fs';
18import { dirname, join, relative, sep } from 'node:path';
19
20export function flattenPnpm(out, { skip = null } = {}) {
21  const nm = join(out, 'node_modules');
22  const store = join(nm, '.pnpm');
23  const flatRoot = join(out, 'node_modules.flat');
24  rmSync(flatRoot, { recursive: true, force: true });
25  mkdirSync(join(flatRoot, 'node_modules'), { recursive: true });
26
27  const manifest = dir => { try { return JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')); } catch { return null; } };
28  const nameOf = dir => manifest(dir)?.name ?? null;
29  /**
30   * What makes two instances "the same package": name and version. pnpm keeps one copy per set of peer packages (the same workspace
31   * package under many hashed folders); in one hoisted tree they are one package.
32   */
33  const identity = dir => { const m = manifest(dir); return m ? `${m.name}@${m.version}` : dir; };
34  /** The sibling links of a store instance: its dependencies, by name -> real instance folder. */
35  function storeDeps(instance, name) {
36    const container = name.startsWith('@') ? dirname(dirname(instance)) : dirname(instance);
37    const found = new Map();
38    for (const e of readdirSync(container, { withFileTypes: true })) {
39      if (e.name === '.bin') continue;
40      const entries = e.name.startsWith('@') ? readdirSync(join(container, e.name), { withFileTypes: true }).map(x => [`${e.name}/${x.name}`, join(container, e.name, x.name)]) : [[e.name, join(container, e.name)]];
41      for (const [dep, p] of entries) {
42        if (dep === name) continue;
43        try { if (lstatSync(p).isSymbolicLink() || existsSync(p)) found.set(dep, realpathSync(p)); } catch { /* a dangling link: the package was removed on purpose */ }
44      }
45    }
46    return found;
47  }
48  /** Every instance in the store by package name, for packages that arrived without a store entry (copied peers). */
49  const byName = new Map();
50  if (existsSync(store)) {
51    for (const id of readdirSync(store, { withFileTypes: true })) {
52      if (!id.isDirectory()) continue;
53      const container = join(store, id.name, 'node_modules');
54      if (!existsSync(container)) continue;
55      for (const e of readdirSync(container, { withFileTypes: true })) {
56        if (e.name === '.bin') continue;
57        const dirs = e.name.startsWith('@') ? readdirSync(join(container, e.name)).map(x => join(container, e.name, x)) : [join(container, e.name)];
58        for (const d of dirs) {
59          let real; try { real = realpathSync(d); } catch { continue; }
60          if (!real.startsWith(store)) continue;       // a link to a workspace package outside the store is handled through the instance table
61          const n = nameOf(real);
62          if (n && !byName.has(n)) byName.set(n, real);
63        }
64      }
65    }
66  }
67
68  const placed = new Map();   // folder (in the flat tree) -> real instance folder it holds
69  let copied = 0, nested = 0;
70
71  const visibleFrom = (chain, name) => {
72    for (const dir of chain) {
73      const slot = join(dir, 'node_modules', ...name.split('/'));
74      if (placed.has(slot)) return { slot, instance: placed.get(slot) };
75    }
76    return null;
77  };
78  const copyInto = (slot, instance) => {
79    mkdirSync(dirname(slot), { recursive: true });
80    cpSync(instance, slot, { recursive: true, dereference: true, filter: f => !relative(instance, f).split(sep).includes('node_modules') });
81    placed.set(slot, identity(instance));
82    copied++;
83  };
84
85  const queue = [];   // { slotDir (folder of the placed package), chain (folders searched upwards), instance, name }
86  const rootChain = [flatRoot];
87  const place = (name, instance, chain, forceHere) => {
88    if (skip?.test(name)) return;
89    const seen = visibleFrom(chain, name);
90    if (seen && seen.instance === identity(instance)) return;
91    const hoist = !seen && !forceHere;
92    const base = hoist ? flatRoot : chain[0];
93    const slot = join(base, 'node_modules', ...name.split('/'));
94    if (placed.has(slot)) return;      // another instance already sits where this one would go (it nests below, handled by the caller's chain)
95    copyInto(slot, instance);
96    if (!hoist && base !== flatRoot) nested++;
97    queue.push({ slotDir: slot, chain: [slot, ...(hoist ? rootChain : chain)], instance, name });
98  };
99
100  // 1. the packages the root names
101  const rootEntries = [];
102  for (const e of readdirSync(nm, { withFileTypes: true })) {
103    if (e.name === '.pnpm' || e.name === '.bin' || e.name.startsWith('.')) continue;
104    const entries = e.name.startsWith('@') ? readdirSync(join(nm, e.name)).map(x => [`${e.name}/${x}`, join(nm, e.name, x)]) : [[e.name, join(nm, e.name)]];
105    for (const [name, p] of entries) rootEntries.push([name, p]);
106  }
107  for (const [name, p] of rootEntries) {
108    let real; try { real = realpathSync(p); } catch { continue; }
109    place(name, real, rootChain, true);
110  }
111  // 2. their dependencies, breadth first
112  while (queue.length) {
113    const { slotDir, chain, instance, name } = queue.shift();
114    let wants;
115    if (instance.startsWith(store)) wants = storeDeps(instance, name);
116    else {
117      // a package copied in without a store entry: its declared requirements, taken from the store by name when not visible yet
118      const m = manifest(instance) ?? {};
119      wants = new Map();
120      for (const dep of [...Object.keys(m.dependencies ?? {}), ...Object.keys(m.peerDependencies ?? {}), ...Object.keys(m.optionalDependencies ?? {})]) {
121        if (visibleFrom(chain, dep)) continue;
122        const real = byName.get(dep);
123        if (real) wants.set(dep, real);
124      }
125    }
126    for (const [dep, real] of wants) place(dep, real, chain, false);
127  }
128
129  rmSync(nm, { recursive: true, force: true });
130  renameSync(join(flatRoot, 'node_modules'), nm);
131  rmSync(flatRoot, { recursive: true, force: true });
132  return { packages: placed.size, copied, nested };
133}