@exodus/stasis-core 1.0.0-beta.15 → 1.0.0-beta.17

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/src/prune.js CHANGED
@@ -4,30 +4,12 @@ import { basename, dirname, join, posix, relative, resolve, sep } from 'node:pat
4
4
 
5
5
  import { Lockfile } from './lockfile.js'
6
6
  import { sha512integrity } from './state-util.js' // also runs the posix-sep assertion
7
- import { hasNodeModulesSegment, isPathWithin, isPlainObject, moduleFileKey, posixPathEscapes, splitNodeModulesPath } from './util.js'
7
+ import { hasNodeModulesSegment, isPathWithin, isPlainObject, LOCK_FILE, moduleFileKey, posixPathEscapes, splitNodeModulesPath } from './util.js'
8
8
 
9
- const LOCKFILE = 'stasis.lock.json'
10
-
11
- // Fields copied (sanitised) from a dep's on-disk package.json; everything else is dropped as
12
- // attack surface (scripts especially).
9
+ // Fields copied (sanitised) from a dep's on-disk package.json; everything else is dropped as attack surface.
13
10
  const ROOT_FIELD_ORDER = ['license', 'type', 'main', 'module', 'jsnext:main', 'jsnext', 'source', 'browser', 'react-native', 'bin', 'sideEffects', 'exports', 'imports']
14
11
 
15
- function assertGlobalVirtualStoreDisabled() {
16
- // Global virtual store fills node_modules with symlinks, which prune skips -- lockfile-vs-disk goes blind.
17
- const env = process.env.npm_config_enable_global_virtual_store
18
- if (env !== undefined && env !== 'false' && env !== '') {
19
- throw new Error(`stasis prune: enableGlobalVirtualStore must be false, got ${JSON.stringify(env)}`)
20
- }
21
- }
22
-
23
- function loadLockfile(root) {
24
- const path = join(root, LOCKFILE)
25
- assert.ok(existsSync(path), `stasis prune: ${LOCKFILE} not found at ${path}`)
26
- return Lockfile.parse(readFileSync(path, 'utf8'))
27
- }
28
-
29
- // The file -> hash the lockfile expects under node_modules (workspace sources aren't pnpm-managed),
30
- // and the bucket dirs it knows.
12
+ // Under node_modules alone: workspace sources aren't pnpm-managed.
31
13
  function buildExpected(lockfile) {
32
14
  const expected = new Map()
33
15
  const knownDirs = new Set()
@@ -35,9 +17,9 @@ function buildExpected(lockfile) {
35
17
  if (!hasNodeModulesSegment(dir)) continue
36
18
  knownDirs.add(dir)
37
19
  for (const [rel, hash] of Object.entries(files)) {
38
- // moduleFileKey, not `${dir}/${rel}`: a root capture's rel === '' would demand a file at `<pkg>/`.
20
+ // A root capture's rel === '' would demand a file at `<pkg>/`.
39
21
  const file = moduleFileKey(dir, rel)
40
- // A `directory` entry is an attested listing, not a file on disk; demanding one would fail "missing on disk".
22
+ // An attested listing, not a file on disk.
41
23
  if (lockfile.formats?.get(file) === 'directory') continue
42
24
  expected.set(file, hash)
43
25
  }
@@ -48,69 +30,58 @@ function buildExpected(lockfile) {
48
30
  // A rewritten manifest must never point resolution at a path prune is about to delete.
49
31
  const EXTENSIONS = ['.js', '.cjs', '.mjs', '.json', '.node']
50
32
 
51
- function normalizeRef(ref) {
52
- if (typeof ref !== 'string' || ref === '' || posixPathEscapes(ref)) return null
53
- return posix.normalize(ref).replace(/^\.\//u, '')
54
- }
55
-
56
33
  function referencesPresentFile(ref, present, { exact = false } = {}) {
57
- const base = normalizeRef(ref)
58
- if (base === null) return false
34
+ if (typeof ref !== 'string' || ref === '' || posixPathEscapes(ref)) return false
35
+ const base = posix.normalize(ref).replace(/^\.\//u, '')
59
36
  if (base.includes('*')) return true // subpath pattern: unverifiable, kept
60
37
  if (present.has(base)) return true
61
38
  if (exact) return false // exports/imports targets resolve verbatim -- no extension/index fallback
62
39
  return EXTENSIONS.some((ext) => present.has(base + ext) || present.has(`${base}/index${ext}`))
63
40
  }
64
41
 
65
- // Cap the recursion; real exports/imports trees nest a few deep and a deep one must not overflow.
42
+ function filterEntries(obj, map) {
43
+ const out = {}
44
+ let any = false
45
+ for (const [key, value] of Object.entries(obj)) {
46
+ const kept = map(value)
47
+ if (kept !== undefined) {
48
+ out[key] = kept
49
+ any = true
50
+ }
51
+ }
52
+ return any ? out : undefined
53
+ }
54
+
55
+ // Real exports/imports trees nest a few deep, and a deep one must not overflow.
66
56
  const MAX_TARGET_DEPTH = 64
67
57
 
68
- // Filter a target tree to attested files. An object/array filtering to empty is dropped:
69
- // `exports: {}` would block every subpath instead of `main`.
58
+ // An object/array filtering to empty is dropped: `exports: {}` would block every subpath instead of `main`.
70
59
  function filterTargets(value, present, opts, depth = 0) {
71
- if (depth > MAX_TARGET_DEPTH) return { keep: false }
60
+ if (depth > MAX_TARGET_DEPTH) return undefined
72
61
  const { allowBare, allowFalse, exact } = opts
73
- if (value === null) return { keep: true, value: null }
74
- if (value === false) return allowFalse ? { keep: true, value: false } : { keep: false }
62
+ if (value === null) return null
63
+ if (value === false) return allowFalse ? false : undefined
75
64
  if (typeof value === 'string') {
76
65
  const keep = value.startsWith('.') ? referencesPresentFile(value, present, { exact }) : allowBare
77
- return keep ? { keep: true, value } : { keep: false }
66
+ return keep ? value : undefined
78
67
  }
79
68
  if (Array.isArray(value)) {
80
- const out = []
81
- for (const item of value) {
82
- const r = filterTargets(item, present, opts, depth + 1)
83
- if (r.keep) out.push(r.value)
84
- }
85
- return out.length > 0 ? { keep: true, value: out } : { keep: false }
69
+ const out = value.map((item) => filterTargets(item, present, opts, depth + 1)).filter((item) => item !== undefined)
70
+ return out.length > 0 ? out : undefined
86
71
  }
87
- if (isPlainObject(value)) {
88
- const out = {}
89
- let any = false
90
- for (const [k, v] of Object.entries(value)) {
91
- const r = filterTargets(v, present, opts, depth + 1)
92
- if (r.keep) {
93
- out[k] = r.value
94
- any = true
95
- }
96
- }
97
- return any ? { keep: true, value: out } : { keep: false }
98
- }
99
- return { keep: false }
72
+ if (isPlainObject(value)) return filterEntries(value, (target) => filterTargets(target, present, opts, depth + 1))
73
+ return undefined
100
74
  }
101
75
 
102
76
  // Printable ASCII only, so a copied `license` can't smuggle control or escape characters.
103
77
  const isAscii = (s) => /^[\x20-\x7e]*$/u.test(s)
104
78
 
105
- // `browser`/`react-native`: a string, or a map to replacements/`false`. undefined means drop the field.
106
79
  function browserField(value, present) {
107
80
  if (typeof value === 'string') return referencesPresentFile(value, present) ? value : undefined
108
81
  if (!isPlainObject(value)) return undefined
109
- const r = filterTargets(value, present, { allowBare: true, allowFalse: true, exact: false })
110
- return r.keep ? r.value : undefined
82
+ return filterTargets(value, present, { allowBare: true, allowFalse: true, exact: false })
111
83
  }
112
84
 
113
- // Resolution fields (`type`, entry points, exports/imports), every file reference filtered to an attested file.
114
85
  function resolutionFields(pkg, present) {
115
86
  const out = { __proto__: null }
116
87
  // Only the values Node honours; a garbage `type` is dropped rather than recategorising the package's .js files.
@@ -124,32 +95,22 @@ function resolutionFields(pkg, present) {
124
95
  if (v !== undefined) out[field] = v
125
96
  }
126
97
  const exp = filterTargets(pkg.exports, present, { allowBare: false, allowFalse: false, exact: true })
127
- if (exp.keep) out.exports = exp.value
98
+ if (exp !== undefined) out.exports = exp
128
99
  const imp = filterTargets(pkg.imports, present, { allowBare: true, allowFalse: false, exact: true })
129
- if (imp.keep) out.imports = imp.value
100
+ if (imp !== undefined) out.imports = imp
130
101
  return out
131
102
  }
132
103
 
133
104
  // On-disk `pkg` is untrusted: every copied field needs its own guard. name/version come from the lockfile.
134
105
  function minimalRootFields(pkg, { name, version, present }) {
135
106
  const fields = resolutionFields(pkg, present)
136
-
137
- if (typeof pkg.license === 'string' && isAscii(pkg.license) && Buffer.byteLength(pkg.license) < 64) {
138
- fields.license = pkg.license
139
- }
107
+ if (typeof pkg.license === 'string' && isAscii(pkg.license) && Buffer.byteLength(pkg.license) < 64) fields.license = pkg.license
140
108
 
141
109
  if (typeof pkg.bin === 'string') {
142
110
  if (referencesPresentFile(pkg.bin, present)) fields.bin = pkg.bin
143
111
  } else if (isPlainObject(pkg.bin)) {
144
- const bin = {}
145
- let any = false
146
- for (const [cmd, target] of Object.entries(pkg.bin)) {
147
- if (typeof target === 'string' && referencesPresentFile(target, present)) {
148
- bin[cmd] = target
149
- any = true
150
- }
151
- }
152
- if (any) fields.bin = bin
112
+ const bin = filterEntries(pkg.bin, (target) => (referencesPresentFile(target, present) ? target : undefined))
113
+ if (bin !== undefined) fields.bin = bin
153
114
  }
154
115
 
155
116
  // A sideEffects list filtering to empty is dropped: `[]` would assert "no side effects" and over-tree-shake.
@@ -165,9 +126,8 @@ function minimalRootFields(pkg, { name, version, present }) {
165
126
  return out
166
127
  }
167
128
 
168
- // The minimal manifest for a known module's package.json at `rel`, root or nested: a nested one's refs
169
- // are relative to its own dir, so the recorded files are re-based first, and it survives because it
170
- // flips its subtree's module system (dropping it would revert those .js files to the root's).
129
+ // A nested one's refs are relative to its own dir, so the recorded files are re-based first; it survives because
130
+ // it flips its subtree's module system (dropping it would revert those .js files to the root's).
171
131
  function minimalManifest(lockfile, owner, rel, raw) {
172
132
  let parsed
173
133
  try { parsed = JSON.parse(raw) } catch { parsed = null }
@@ -184,10 +144,6 @@ function minimalManifest(lockfile, owner, rel, raw) {
184
144
  return resolutionFields(pkg, present)
185
145
  }
186
146
 
187
- // In a workspace the symlink-containment boundary widens from node_modules to the whole workspace,
188
- // since a dep legitimately links to a sibling package's source dir.
189
- const isPnpmWorkspaceRoot = (root) => existsSync(join(root, 'pnpm-workspace.yaml'))
190
-
191
147
  function discoverNodeModulesDirs(root) {
192
148
  const found = []
193
149
  const stack = [root]
@@ -200,14 +156,11 @@ function discoverNodeModulesDirs(root) {
200
156
  continue
201
157
  }
202
158
  for (const entry of entries) {
203
- if (entry.name.startsWith('.')) continue
159
+ if (entry.name.startsWith('.') || !entry.isDirectory()) continue
204
160
  const full = join(dir, entry.name)
205
- if (entry.name === 'node_modules') {
206
- // A symlinked node_modules is skipped; if the lockfile records files under it, prune fails closed.
207
- if (entry.isDirectory()) found.push(full)
208
- continue // don't descend; prune walks node_modules internals itself
209
- }
210
- if (entry.isDirectory()) stack.push(full)
161
+ // A symlinked node_modules is skipped (prune fails closed on files the lockfile records there); none is descended.
162
+ if (entry.name === 'node_modules') found.push(full)
163
+ else stack.push(full)
211
164
  }
212
165
  }
213
166
  return found
@@ -223,13 +176,10 @@ function assertSymlinkInternal({ root, realBoundary, label }, linkPath) {
223
176
  if (err.code === 'ENOENT') return
224
177
  throw err
225
178
  }
226
- if (!isPathWithin(realBoundary, real)) {
227
- throw new Error(`stasis prune: symlink escapes ${label}: ${relative(root, linkPath)} -> ${real}`)
228
- }
179
+ if (!isPathWithin(realBoundary, real)) throw new Error(`stasis prune: symlink escapes ${label}: ${relative(root, linkPath)} -> ${real}`)
229
180
  }
230
181
 
231
- // Every regular file under the node_modules roots, tagged with its root so deletion and empty-dir
232
- // pruning stay scoped to it. Symlinks are checked, never followed.
182
+ // Tagged with its root so deletion and empty-dir pruning stay scoped to it. Symlinks are checked, never followed.
233
183
  function* walkFiles(nmRoots, ctx) {
234
184
  for (const nmRoot of nmRoots) {
235
185
  if (!existsSync(nmRoot)) continue
@@ -247,15 +197,9 @@ function* walkFiles(nmRoots, ctx) {
247
197
  }
248
198
 
249
199
  function pruneEmptyDirs(dir, stopAt) {
250
- while (dir.startsWith(stopAt) && dir !== stopAt && existsSync(dir)) {
251
- let entries
252
- try {
253
- entries = readdirSync(dir)
254
- } catch {
255
- return
256
- }
257
- if (entries.length > 0) return
200
+ while (dir.startsWith(stopAt) && dir !== stopAt) {
258
201
  try {
202
+ if (readdirSync(dir).length > 0) return
259
203
  rmdirSync(dir)
260
204
  } catch {
261
205
  return
@@ -265,9 +209,14 @@ function pruneEmptyDirs(dir, stopAt) {
265
209
  }
266
210
 
267
211
  export function prune({ root = process.cwd() } = {}) {
268
- assertGlobalVirtualStoreDisabled()
212
+ // Global virtual store fills node_modules with symlinks, which prune skips -- lockfile-vs-disk goes blind.
213
+ const store = process.env.npm_config_enable_global_virtual_store
214
+ if (store !== undefined && store !== 'false' && store !== '') {
215
+ throw new Error(`stasis prune: enableGlobalVirtualStore must be false, got ${JSON.stringify(store)}`)
216
+ }
269
217
  root = resolve(root)
270
- const workspace = isPnpmWorkspaceRoot(root)
218
+ // In a workspace a dep legitimately links to a sibling package's source dir, so the boundary widens to it.
219
+ const workspace = existsSync(join(root, 'pnpm-workspace.yaml'))
271
220
  const nmRoots = workspace ? discoverNodeModulesDirs(root) : [join(root, 'node_modules')]
272
221
  const boundary = workspace ? root : join(root, 'node_modules')
273
222
  const ctx = {
@@ -275,7 +224,9 @@ export function prune({ root = process.cwd() } = {}) {
275
224
  realBoundary: existsSync(boundary) ? realpathSync(boundary) : boundary,
276
225
  label: workspace ? 'the workspace' : 'node_modules',
277
226
  }
278
- const lockfile = loadLockfile(root)
227
+ const lockPath = join(root, LOCK_FILE)
228
+ assert.ok(existsSync(lockPath), `stasis prune: ${LOCK_FILE} not found at ${lockPath}`)
229
+ const lockfile = Lockfile.parse(readFileSync(lockPath, 'utf8'))
279
230
  const { expected, knownDirs } = buildExpected(lockfile)
280
231
 
281
232
  // Plan first, mutate later: any failure throws before anything on disk is touched.
@@ -318,8 +269,7 @@ export function prune({ root = process.cwd() } = {}) {
318
269
 
319
270
  const missing = [...expected.keys()].filter((rel) => !seen.has(rel))
320
271
  if (mismatches.length > 0) {
321
- const lines = mismatches.map(({ rel, expected: exp, actual }) =>
322
- ` ${rel}: expected ${exp}, got ${actual}`).join('\n')
272
+ const lines = mismatches.map(({ rel, expected: exp, actual }) => ` ${rel}: expected ${exp}, got ${actual}`).join('\n')
323
273
  throw new Error(`stasis prune: hash mismatch for ${mismatches.length} file(s):\n${lines}`)
324
274
  }
325
275
  if (missing.length > 0) {
@@ -328,23 +278,19 @@ export function prune({ root = process.cwd() } = {}) {
328
278
  throw new Error(`stasis prune: files listed in lockfile are missing on disk: ${sample}${suffix}`)
329
279
  }
330
280
 
331
- const minimized = []
332
- for (const [i, { full, rel, text }] of toMinimize.entries()) {
281
+ for (const [i, { full, text }] of toMinimize.entries()) {
333
282
  // Write+rename, never in place: a dep's package.json is often a hardlink into pnpm's store (shared inode).
334
283
  const tmp = `${full}.stasis-${process.pid}-${i}.tmp`
335
284
  writeFileSync(tmp, text)
336
285
  renameSync(tmp, full)
337
- minimized.push(rel)
338
286
  }
339
287
 
340
- const removed = []
341
288
  const touchedDirs = new Map() // dir -> the node_modules root under it (prune stops there)
342
289
  for (const { full, nmRoot } of toRemove) {
343
290
  unlinkSync(full)
344
- removed.push(relative(root, full))
345
291
  touchedDirs.set(dirname(full), nmRoot)
346
292
  }
347
- for (const d of [...touchedDirs.keys()].toSorted((a, b) => b.length - a.length)) pruneEmptyDirs(d, touchedDirs.get(d))
293
+ for (const [dir, nmRoot] of [...touchedDirs].toSorted(([a], [b]) => b.length - a.length)) pruneEmptyDirs(dir, nmRoot)
348
294
 
349
- return { removed, validated, kept, minimized }
295
+ return { removed: toRemove.map(({ full }) => relative(root, full)), validated, kept, minimized: toMinimize.map(({ rel }) => rel) }
350
296
  }
package/src/shard.js CHANGED
@@ -1,15 +1,11 @@
1
- // Wire format for child->root capture forwarding (--child-process). A shard carries only keys, formats and
2
- // resolution edges; content, listings, stat kinds and exec bits are re-derived from the root's OWN disk, so
3
- // a shard cannot inject content or a forged bit. `files` and `formats` are independent -- don't collapse them.
1
+ // Child->root capture forwarding (--child-process). Content, listings, stat kinds and exec bits are re-derived from
2
+ // the root's OWN disk, so a shard can't inject content or a forged bit; `files` and `formats` are independent.
4
3
 
5
- import { KNOWN_FORMATS, assert, fileMapToObject, isPlainObject, isRefusedPath, objectToMaps } from './artifact-util.js'
4
+ import { assertScope, isArtifactKey, KNOWN_FORMATS, assert, fileMapToObject, isPlainObject, objectToMaps } from './artifact-util.js'
6
5
 
7
6
  export const SHARD_VERSION = 1
8
7
 
9
- // `imports` nests (conditions -> parent -> specifier -> file, or -> platform -> file under --metro),
10
- // so the conversion recurses rather than flattening one level.
11
8
  export function serializeShard({ scope, files, formats, imports }) {
12
- // Never send a shard the root's parseShard would reject.
13
9
  assertShard(files, formats, imports)
14
10
  return JSON.stringify({
15
11
  version: SHARD_VERSION,
@@ -20,13 +16,12 @@ export function serializeShard({ scope, files, formats, imports }) {
20
16
  })
21
17
  }
22
18
 
23
- // The upstream signature is what makes a shard trustworthy; this only guards a malformed message,
24
- // applying the same schema rules Lockfile.parse will. Maps keep lookups off Object.prototype.
19
+ // The upstream signature is what makes a shard trustworthy; this only guards a malformed message.
25
20
  export function parseShard(text) {
26
21
  const json = JSON.parse(text)
27
22
  assert(isPlainObject(json), 'shard must be an object')
28
23
  assert(json.version === SHARD_VERSION, `shard version ${json.version} != ${SHARD_VERSION}`)
29
- assert(['node_modules', 'full'].includes(json.scope), `shard scope: ${json.scope}`)
24
+ assertScope(json.scope, 'shard')
30
25
  assert(Array.isArray(json.files), 'shard files must be an array')
31
26
  assert(isPlainObject(json.formats) && isPlainObject(json.imports), 'shard formats/imports must be objects')
32
27
 
@@ -36,8 +31,6 @@ export function parseShard(text) {
36
31
  return { scope: json.scope, files: json.files, formats, imports }
37
32
  }
38
33
 
39
- // THE rules a shard's keys, formats and import edges satisfy, on write (serializeShard) and on read
40
- // (parseShard).
41
34
  function assertShard(files, formats, imports) {
42
35
  for (const file of files) assertKey(file, 'shard file')
43
36
  for (const [file, format] of formats) {
@@ -49,20 +42,12 @@ function assertShard(files, formats, imports) {
49
42
  for (const [parent, specs] of byParent) {
50
43
  assertKey(parent, 'shard import parent')
51
44
  assert(specs instanceof Map, `shard imports for ${parent}: expected a specifier map`)
52
- for (const [, target] of specs) assertTarget(target, parent)
45
+ // A file, or (--metro) a platform -> file map; nothing deeper.
46
+ for (const [, target] of specs) {
47
+ for (const file of target instanceof Map ? target.values() : [target]) assertKey(file, `shard import target from ${parent}`)
48
+ }
53
49
  }
54
50
  }
55
51
  }
56
52
 
57
- function assertKey(key, what) {
58
- assert(typeof key === 'string' && key !== '' && !isRefusedPath(key), `${what}: ${key}`)
59
- }
60
-
61
- // A target is a file, or (--metro) a platform -> file map; nothing deeper.
62
- function assertTarget(target, parent) {
63
- if (target instanceof Map) {
64
- for (const [, file] of target) assertKey(file, `shard import target from ${parent}`)
65
- return
66
- }
67
- assertKey(target, `shard import target from ${parent}`)
68
- }
53
+ const assertKey = (key, what) => assert(isArtifactKey(key), `${what}: ${key}`)
package/src/state-util.js CHANGED
@@ -5,52 +5,29 @@ import { join, resolve, sep } from 'node:path'
5
5
  import { pathToFileURL } from 'node:url'
6
6
 
7
7
  import { diskHost } from './host.js'
8
- import { Lockfile } from './lockfile.js'
9
8
  import { isPathWithin } from './util.js'
10
9
 
11
10
  // Genuine fs readers snapshotted off the namespace before any --fs patch. A plain `import { readFileSync }`
12
- // won't do: --fs monkey-patches fs then syncBuiltinESMExports() rebinds named imports, so snapshotting dodges that.
11
+ // won't do: --fs patches fs, then syncBuiltinESMExports() rebinds named imports to the patched fns.
13
12
  export const realReadFileSync = fs.readFileSync
14
13
  export const realReadFile = fs.promises.readFile
15
- export const realReaddirSync = fs.readdirSync
16
- export const realExistsSync = fs.existsSync
17
14
  const realRealpathSync = fs.realpathSync
15
+ const realpathOr = (path, fallback) => { try { return realRealpathSync(path) } catch { return fallback } }
18
16
 
19
17
  let realRootCache
20
- // Capture-side containment: the REAL location of `abs` must stay inside `root`'s real path (`root`
21
- // itself where that has none), else an in-tree symlink pointing OUT would pull external content in.
18
+ // Capture-side containment: an in-tree symlink pointing OUT of `root`'s real path would pull external content in.
22
19
  export function realContained(root, abs) {
23
- if (realRootCache?.root !== root) {
24
- let real
25
- try { real = realRealpathSync(root) } catch { real = root }
26
- realRootCache = { root, real }
27
- }
28
- let real
29
- try { real = realRealpathSync(abs) } catch { return false }
30
- return isPathWithin(realRootCache.real, real)
20
+ if (realRootCache?.root !== root) realRootCache = { root, real: realpathOr(root, root) }
21
+ const real = realpathOr(abs, null)
22
+ return real !== null && isPathWithin(realRootCache.real, real)
31
23
  }
32
24
 
33
25
  assert.equal(sep, '/', 'Not tested on Windows')
34
26
 
35
27
  export const sha512integrity = (x) => `sha512-${hash('sha512', x, 'base64')}`
36
28
 
37
- // A bundled file's integrity from its `content` as a bundle stores it: of the bytes it stands for,
38
- // a 'resource:base64' payload's decoded ones, else its UTF-8 text's.
39
29
  export const bundledIntegrity = (content, format) => sha512integrity(format === 'resource:base64' ? Buffer.from(content, 'base64') : content)
40
30
 
41
- // The companion lockfile of `bundle` as it is now (Lockfile.fromBundle's), built on the first call,
42
- // the same one after: each file's integrity that of the bytes its content stands for
43
- // (bundledIntegrity), so a file is hashed only once the lockfile is wanted, for a bundle whose
44
- // content is the bytes read, encoded without loss. Its records are taken now: one the bundle
45
- // replaces after (a commit pinned onto a module) is not the lockfile's.
46
- // -> () => Lockfile
47
- export function deferredLockfile(bundle) {
48
- const { config, entries, imports, formats, executable } = bundle
49
- const now = { config, entries, modules: new Map(bundle.modules), imports, formats, executable }
50
- let lockfile
51
- return () => (lockfile ??= Lockfile.fromBundle(now, (file, content) => bundledIntegrity(content, formats.get(file))))
52
- }
53
-
54
31
  export function readFileSyncMaybe(dir, file, encoding, host = diskHost) {
55
32
  let buf
56
33
  try {
@@ -63,14 +40,11 @@ export function readFileSyncMaybe(dir, file, encoding, host = diskHost) {
63
40
  }
64
41
 
65
42
  export function noupsert(map, key, value) {
66
- if (map.has(key)) {
67
- assert.deepStrictEqual(map.get(key), value, `Conflict for ${JSON.stringify(key)}`)
68
- } else {
69
- map.set(key, value)
70
- }
43
+ if (!map.has(key)) map.set(key, value)
44
+ else if (!Object.is(map.get(key), value)) assert.deepStrictEqual(map.get(key), value, `Conflict for ${JSON.stringify(key)}`)
71
45
  }
72
46
 
73
- // Canonicalize for write-target collision detection: the host's realpath catches symlink aliases resolve() would miss; lexical fallback for not-yet-written targets.
47
+ // The host's realpath catches symlink aliases resolve() would miss; lexical fallback for not-yet-written targets.
74
48
  export function canonicalizePath(p, host = diskHost) {
75
49
  const abs = resolve(p)
76
50
  try {
@@ -80,11 +54,8 @@ export function canonicalizePath(p, host = diskHost) {
80
54
  }
81
55
  }
82
56
 
83
- // Whether `url` is in `state`'s scope, as it attests one: anywhere under scope=full, else in
84
- // node_modules. Over State's public members alone, so a plugin may ask it of a State another
85
- // stasis-core copy made (State.preload).
57
+ // Over State's public members alone, so a plugin may ask it of a State another stasis-core copy made (State.preload).
86
58
  export const inScope = (state, url) => state.config.full || state.inNodeModules(url)
87
59
 
88
- // Whether the file at `absolute` is one `state`'s bundle serves under load: within its root (outside
89
- // it: system files, scratch, read from disk) and in its scope. Over State's public members, as inScope.
60
+ // Outside its root (system files, scratch) a file is read from disk. Over State's public members, as inScope.
90
61
  export const servedByBundle = (state, absolute) => isPathWithin(state.root, absolute) && inScope(state, pathToFileURL(absolute).toString())