@exodus/stasis-core 1.0.0-beta.3 → 1.0.0-beta.5
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/bin/stasis-core.js +17 -3
- package/package.json +7 -4
- package/src/add.js +35 -46
- package/src/artifact-util.js +487 -0
- package/src/bundle-util.js +220 -33
- package/src/bundle.js +176 -111
- package/src/config.js +163 -223
- package/src/extract.js +7 -15
- package/src/fs.js +180 -296
- package/src/hooks.js +228 -108
- package/src/host.js +45 -0
- package/src/lockfile.js +22 -75
- package/src/prune.js +63 -130
- package/src/shard.js +13 -5
- package/src/state-util.js +10 -6
- package/src/state.js +438 -477
- package/src/util.js +37 -348
package/src/state.js
CHANGED
|
@@ -3,51 +3,64 @@ import { isUtf8 } from 'node:buffer'
|
|
|
3
3
|
import * as fs from 'node:fs'
|
|
4
4
|
import { join, resolve, relative, basename, dirname, extname, isAbsolute } from 'node:path'
|
|
5
5
|
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
6
|
-
import { findPackageJSON } from 'node:module'
|
|
7
6
|
import { brotliCompressSync, brotliDecompressSync } from 'node:zlib'
|
|
8
7
|
|
|
9
8
|
import { Config } from './config.js'
|
|
10
|
-
import { Bundle } from './bundle.js'
|
|
9
|
+
import { Bundle, mergeRepo } from './bundle.js'
|
|
11
10
|
import { Lockfile } from './lockfile.js'
|
|
12
11
|
import { parseShard, serializeShard } from './shard.js'
|
|
13
12
|
import { canonicalizePath, sha512integrity, readFileSyncMaybe, noupsert } from './state-util.js'
|
|
14
13
|
import { brotliOptions } from './brotli.js'
|
|
15
|
-
import { CODE_EXTENSIONS, canObserveExecuteBits, classifyFormat, fileMapToObject, hasNodeModulesSegment, isBinaryPlist, isStatFormat, moduleFileKey, narrowExecutable, objectToMaps, observeExecutable, pathExt, reconcileFormat, sortPaths, splitNodeModulesPath } from './util.js'
|
|
16
|
-
import { readModuleManifest } from './bundle-util.js'
|
|
14
|
+
import { CODE_EXTENSIONS, canObserveExecuteBits, classifyFormat, erasedTypeScriptFormat, fileMapToObject, hasNodeModulesSegment, isBinaryPlist, isNativeArtifact, isPathWithin, isStatFormat, moduleFileKey, moduleInfo, narrowExecutable, nestedMap, objectToMaps, observeExecutable, pathExt, reconcileFormat, relativeEscapes, sortPaths, splitNodeModulesPath } from './util.js'
|
|
15
|
+
import { detectRepo, packageJSONStat, packageJSONText, readModuleManifest } from './bundle-util.js'
|
|
16
|
+
import { diskHost } from './host.js'
|
|
17
17
|
import corePackage from './package.cjs'
|
|
18
18
|
|
|
19
19
|
// Destructure off the namespace: captures the real fns at eval time, so writes survive --mock's
|
|
20
20
|
// syncBuiltinESMExports() remock of node:fs.
|
|
21
|
-
const { existsSync, mkdirSync, readdirSync,
|
|
21
|
+
const { existsSync, mkdirSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } = fs
|
|
22
22
|
|
|
23
23
|
const FILE_CONFIG = 'stasis.config.json'
|
|
24
24
|
const FILE_LOCK = 'stasis.lock.json'
|
|
25
25
|
const FILE_CODE = 'stasis.code.br'
|
|
26
26
|
|
|
27
|
-
function readPackageJSON(pkgAbsolute) {
|
|
28
|
-
const buf = readFileSync(pkgAbsolute)
|
|
29
|
-
assert.ok(isUtf8(buf))
|
|
30
|
-
return JSON.parse(buf.toString())
|
|
31
|
-
}
|
|
32
|
-
|
|
33
27
|
// Via src/package.cjs: a bundler-safe re-export of package.json.
|
|
34
28
|
const VERSION = corePackage.version
|
|
35
29
|
|
|
36
30
|
const CAN_OBSERVE_EXECUTE_BITS = canObserveExecuteBits()
|
|
37
31
|
|
|
32
|
+
const invalidPackageConfig = (pkgAbsolute, cause) => Object.assign(
|
|
33
|
+
cause === undefined ? new Error(`Invalid package config ${pkgAbsolute}.`) : new Error(`Invalid package config ${pkgAbsolute}.`, { cause }),
|
|
34
|
+
{ code: 'ERR_INVALID_PACKAGE_CONFIG' })
|
|
35
|
+
|
|
36
|
+
// A package.json's fields; one that is no JSON object is refused as Node refuses it.
|
|
37
|
+
function readPackageJSON(host, pkgAbsolute) {
|
|
38
|
+
const buf = host.readFile(pkgAbsolute)
|
|
39
|
+
assert.ok(isUtf8(buf))
|
|
40
|
+
let json
|
|
41
|
+
try {
|
|
42
|
+
json = JSON.parse(packageJSONText(buf))
|
|
43
|
+
} catch (cause) {
|
|
44
|
+
throw invalidPackageConfig(pkgAbsolute, cause)
|
|
45
|
+
}
|
|
46
|
+
if (json === null || typeof json !== 'object' || Array.isArray(json)) throw invalidPackageConfig(pkgAbsolute)
|
|
47
|
+
return json
|
|
48
|
+
}
|
|
49
|
+
|
|
38
50
|
// A weak 'stat:*' yields to a real format; two real formats or a stat kind flip are fatal.
|
|
39
51
|
function upsertFormat(map, file, format) {
|
|
40
52
|
const currentFormat = map.get(file)
|
|
41
53
|
map.set(file, currentFormat === undefined ? format : reconcileFormat(format, currentFormat, file))
|
|
42
54
|
}
|
|
43
55
|
|
|
44
|
-
//
|
|
56
|
+
// Loader formats the extension alone decides; `.js`/`.ts` follow the nearest package `type`.
|
|
57
|
+
const EXT_FORMATS = { __proto__: null, '.json': 'json', '.mjs': 'module', '.cjs': 'commonjs', '.mts': 'module-typescript', '.cts': 'commonjs-typescript' }
|
|
58
|
+
// With no `type`, Node decides .js/.ts by syntax detection: either variant is possible, the first is the default.
|
|
59
|
+
const UNTYPED_VARIANTS = { __proto__: null, '.js': ['commonjs', 'module'], '.ts': ['commonjs-typescript', 'module-typescript'] }
|
|
45
60
|
|
|
46
61
|
// On globalThis via `Symbol.for` so the registry is shared across duplicate stasis-core copies.
|
|
47
62
|
const STATES_KEY = Symbol.for('@exodus/stasis-core/states')
|
|
48
|
-
|
|
49
|
-
return (globalThis[STATES_KEY] ??= new Set())
|
|
50
|
-
}
|
|
63
|
+
const liveStates = () => (globalThis[STATES_KEY] ??= new Set())
|
|
51
64
|
|
|
52
65
|
export class State {
|
|
53
66
|
hashes = new Map()
|
|
@@ -63,25 +76,23 @@ export class State {
|
|
|
63
76
|
config
|
|
64
77
|
root
|
|
65
78
|
#parent
|
|
66
|
-
|
|
67
79
|
#isPreload = false
|
|
80
|
+
#host
|
|
68
81
|
|
|
69
|
-
// Claimed write-target paths (canonicalized -> label), for cross-State collision detection
|
|
82
|
+
// Claimed write-target paths (canonicalized -> label), for cross-State collision detection; a
|
|
83
|
+
// State built with `claim: false`, which never writes (a static build), claims none.
|
|
84
|
+
#claim
|
|
70
85
|
#claims = new Map()
|
|
71
86
|
|
|
72
87
|
// WRITE-mode sidecars: lockfile CONTRIBUTORS (#mergedImports/#mergedFormats union theirs in).
|
|
73
88
|
#sidecars = new Set()
|
|
74
|
-
|
|
75
89
|
// LOAD-mode sidecars: read-only, NOT lockfile contributors (getFs*Family serves bytes from them).
|
|
76
90
|
#readSidecars = new Set()
|
|
77
91
|
|
|
78
|
-
// Lockfile-attested resolutions (conditions -> parent -> specifier -> file)
|
|
79
|
-
//
|
|
92
|
+
// Lockfile-attested resolutions (conditions -> parent -> specifier -> file) and loader formats
|
|
93
|
+
// (file -> format), or null; may be supersets of what a run observes, so kept apart from the live maps.
|
|
80
94
|
#lockImports = null
|
|
81
|
-
|
|
82
|
-
// Lockfile-attested loader formats (file -> format), or null; kept apart from this.formats.
|
|
83
95
|
#lockFormats = null
|
|
84
|
-
|
|
85
96
|
// Loaded a lockfile at construction: #mergeBundleMetadata cross-checks bundle metadata against
|
|
86
97
|
// it instead of absorbing it as source of truth.
|
|
87
98
|
#lockfileLoaded = false
|
|
@@ -108,6 +119,17 @@ export class State {
|
|
|
108
119
|
// shim: require.resolve()/CJS require()s bypassing the resolve hook.
|
|
109
120
|
#observedResolutions = new Map()
|
|
110
121
|
|
|
122
|
+
// Files a require() actually EXECUTED (from the Module._load shim) -- unlike a resolve-only
|
|
123
|
+
// edge, an executed file with no captured bytes is a hole in the attestation, so write()
|
|
124
|
+
// backfills it from disk (a transplanted require.extensions handler, e.g. a transforming
|
|
125
|
+
// preload's CJS TypeScript pipeline, loads files without ever hitting the load hook).
|
|
126
|
+
#executedFiles = new Set()
|
|
127
|
+
|
|
128
|
+
// Files whose BYTES this run captured via addFile. Distinct from this.hashes, which also
|
|
129
|
+
// absorbs lockfile-seeded entries: #backfillExecutedFiles must key on "observed this run", or
|
|
130
|
+
// a frozen/add run would skip verifying an executed file merely because a hash is on record.
|
|
131
|
+
#filesCapturedThisRun = new Set()
|
|
132
|
+
|
|
111
133
|
// Node's require-condition set, from the first require()-context addImport;
|
|
112
134
|
// #backfillObservedResolutions keys native edges under it so the lockfile is Node-version-stable.
|
|
113
135
|
#requireConditions = null
|
|
@@ -121,14 +143,25 @@ export class State {
|
|
|
121
143
|
#lastUnifiedBundle = null
|
|
122
144
|
#lastCodeBundle = null
|
|
123
145
|
#lastResourcesBundle = null
|
|
146
|
+
// Lazy `{ value: detectRepo(this.root, this.#host) }`.
|
|
147
|
+
#detectedRepoCache
|
|
148
|
+
// Half ('code' | 'resources') -> `repo` of the bundle absorbed there for adding to.
|
|
149
|
+
#absorbedRepos = new Map()
|
|
124
150
|
|
|
125
|
-
//
|
|
126
|
-
//
|
|
127
|
-
//
|
|
151
|
+
// Memoized #canonicalUncached (per URL, State-lifetime): a realpathSync per node_modules URL, and
|
|
152
|
+
// hot callers repeat relentlessly. Sound only because the tree holds still mid-run; the cached
|
|
153
|
+
// result is shared -- never mutate it.
|
|
154
|
+
#canonicalCache = new Map()
|
|
155
|
+
|
|
156
|
+
// Options: `preload` (the unique preload State), `parent` (run as a sidecar sharing the parent's
|
|
157
|
+
// hashes/entries/modules, with its own sources/formats/imports/resources and bundle) and
|
|
158
|
+
// `skipDiscovery` (a caller-populated in-memory State, NO filesystem discovery; read-only modes
|
|
159
|
+
// only). All other keys forward to Config.
|
|
128
160
|
constructor(root, options = {}) {
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
this
|
|
161
|
+
const { preload: isPreload = false, parent: parentState, preloadRoot, skipDiscovery = false, host = diskHost, env = process.env, claim = true, ...configOptions } = options
|
|
162
|
+
this.config = new Config({ ...configOptions, env, host })
|
|
163
|
+
this.#host = host
|
|
164
|
+
this.#claim = claim
|
|
132
165
|
if (isPreload) assert.ok(!State.preload, 'Only one preload Stasis instance is supported')
|
|
133
166
|
assert.ok(!(isPreload && parentState), 'preload and parent are mutually exclusive')
|
|
134
167
|
this.#isPreload = isPreload
|
|
@@ -153,16 +186,13 @@ export class State {
|
|
|
153
186
|
assert.ok(this.config.bundleFile, 'sidecar State requires bundleFile')
|
|
154
187
|
// Only writing States claim, so two write-intent States can't silently target the same file.
|
|
155
188
|
if (this.config.writeBundle) {
|
|
156
|
-
this.#claimWritePath(
|
|
157
|
-
|
|
158
|
-
this.#claimWritePath(`sidecar resourcesBundleFile '${this.config.resourcesBundleFile}'`,
|
|
159
|
-
this.config.resourcesBundleFile)
|
|
160
|
-
}
|
|
189
|
+
this.#claimWritePath('bundleFile', 'sidecar ')
|
|
190
|
+
this.#claimWritePath('resourcesBundleFile', 'sidecar ')
|
|
161
191
|
}
|
|
162
192
|
// frozenBundle MUST go through this branch too -- it has its own attestation snapshot to build.
|
|
163
|
-
if (this.config.
|
|
193
|
+
if (this.config.bundle) {
|
|
164
194
|
const sourcesPath = this.config.bundleFile
|
|
165
|
-
const sources =
|
|
195
|
+
const sources = this.#readMaybe(sourcesPath)
|
|
166
196
|
if (sources && !this.config.replaceBundle) {
|
|
167
197
|
const bundle = Bundle.parse(brotliDecompressSync(sources).toString('utf-8'))
|
|
168
198
|
// v0 bundle has no per-file formats or import map -- serving one via a sidecar widens trust.
|
|
@@ -170,32 +200,11 @@ export class State {
|
|
|
170
200
|
`stasis sidecar requires a v1 bundle; ${sourcesPath} is v${bundle.version}. ` +
|
|
171
201
|
`Re-bundle with the current stasis or \`bundle=replace\` against a v0-free starting point.`)
|
|
172
202
|
assert.equal(bundle.config.scope, this.config.scope)
|
|
173
|
-
// Cross-
|
|
203
|
+
// Cross-checked against the parent's lockfile, or absorbed if none (shared hashes/entries/
|
|
174
204
|
// modules mean those writes propagate to the parent).
|
|
175
|
-
this.#
|
|
176
|
-
for (const [file, content] of bundle.sources) {
|
|
177
|
-
if (Bundle.isResourceFormat(bundle.formats.get(file))) this.resources.set(file, content)
|
|
178
|
-
else this.sources.set(file, content)
|
|
179
|
-
}
|
|
180
|
-
this.formats = bundle.formats
|
|
181
|
-
this.imports = bundle.imports
|
|
182
|
-
this.#absorbExecutable(bundle)
|
|
183
|
-
this.#seedReasonFromBundle(bundle)
|
|
184
|
-
if (this.config.frozenBundle) {
|
|
185
|
-
this.#bundleSources = new Set(this.sources.keys())
|
|
186
|
-
this.#bundleResources = new Set(this.resources.keys())
|
|
187
|
-
this.#bundleImports = objectToMaps(fileMapToObject(bundle.imports))
|
|
188
|
-
this.#bundleFormats = new Map(bundle.formats)
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
if (this.config.resourcesBundleFile) {
|
|
193
|
-
const resourcesPath = this.config.resourcesBundleFile
|
|
194
|
-
const resourcesData = readFileSyncMaybe(dirname(resourcesPath), basename(resourcesPath))
|
|
195
|
-
if (resourcesData && !this.config.replaceBundle) {
|
|
196
|
-
this.#absorbResourcesBundle(resourcesData, { lockfileLoaded: this.#lockfileLoaded, resourcesPath })
|
|
197
|
-
}
|
|
205
|
+
this.#absorbCodeBundle(bundle, this.#lockfileLoaded)
|
|
198
206
|
}
|
|
207
|
+
this.#absorbResourcesBundleFile(this.#lockfileLoaded)
|
|
199
208
|
}
|
|
200
209
|
if (this.config.frozenBundle) {
|
|
201
210
|
assert.ok(this.#bundleSources !== null, 'No bundle, but attempting to run in frozen bundle mode')
|
|
@@ -204,7 +213,7 @@ export class State {
|
|
|
204
213
|
// join neither registry (--fs neither captures nor serves in frozen-bundle mode).
|
|
205
214
|
if (this.config.writeBundle) parentState.registerSidecar(this)
|
|
206
215
|
else if (this.config.loadBundle) parentState.registerReadSidecar(this)
|
|
207
|
-
liveStates().add(this)
|
|
216
|
+
if (this.#claims.size > 0) liveStates().add(this)
|
|
208
217
|
return
|
|
209
218
|
}
|
|
210
219
|
|
|
@@ -212,32 +221,24 @@ export class State {
|
|
|
212
221
|
assert.ok(!this.config.frozen && !this.config.frozenBundle && !this.config.writeBundle && !this.config.writeLockfile,
|
|
213
222
|
'skipDiscovery is read-only: incompatible with frozen and write (add/replace) lock/bundle modes')
|
|
214
223
|
this.root = resolve(root)
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
this.#preloadRoot = preloadRoot
|
|
218
|
-
}
|
|
219
|
-
liveStates().add(this)
|
|
224
|
+
this.#setPreloadRoot(preloadRoot)
|
|
225
|
+
if (isPreload) liveStates().add(this)
|
|
220
226
|
return
|
|
221
227
|
}
|
|
222
228
|
|
|
229
|
+
// Capture and load MUST agree on where the upward walk stops (PROJECT_CWD/.git/
|
|
230
|
+
// pnpm-workspace.yaml), else they commit different roots and fail "outside the project root".
|
|
223
231
|
const potentialRoots = []
|
|
224
|
-
let cursor = root
|
|
225
|
-
|
|
226
|
-
if (
|
|
232
|
+
for (let cursor = root; cursor; cursor = dirname(cursor)) {
|
|
233
|
+
// One there that can't be read is refused, not walked past to a root above (packageJSONStat).
|
|
234
|
+
if (packageJSONStat(this.#host, join(cursor, 'package.json')) !== null) {
|
|
227
235
|
potentialRoots.push(cursor)
|
|
228
|
-
} else if (
|
|
229
|
-
existsSync(join(cursor, FILE_CONFIG)) ||
|
|
230
|
-
existsSync(join(cursor, FILE_LOCK)) ||
|
|
231
|
-
existsSync(join(cursor, FILE_CODE))) {
|
|
236
|
+
} else if ([FILE_CONFIG, FILE_LOCK, FILE_CODE].some((file) => this.#exists(join(cursor, file)))) {
|
|
232
237
|
throw new Error('Unexpected stasis config without package.json')
|
|
233
238
|
}
|
|
234
|
-
|
|
235
|
-
if (cursor
|
|
236
|
-
if (
|
|
237
|
-
if (existsSync(join(cursor, 'pnpm-workspace.yaml'))) break
|
|
238
|
-
const parent = dirname(cursor)
|
|
239
|
-
if (!parent || parent === cursor) break
|
|
240
|
-
cursor = parent
|
|
239
|
+
if (cursor === env.PROJECT_CWD) break // e.g. yarn sets this
|
|
240
|
+
if (this.#exists(join(cursor, '.git')) || this.#exists(join(cursor, 'pnpm-workspace.yaml'))) break
|
|
241
|
+
if (dirname(cursor) === cursor) break
|
|
241
242
|
}
|
|
242
243
|
|
|
243
244
|
// default root is top-level package.json, to opt-in to per-dir create stasis.config.json
|
|
@@ -254,57 +255,45 @@ export class State {
|
|
|
254
255
|
// root. A config-only bundleFile is NOT suppressed (its dir already carries the config signal).
|
|
255
256
|
const explicitBundlePath = this.config.bundleFile
|
|
256
257
|
for (const rootDir of potentialRoots) {
|
|
257
|
-
const config = readFileSyncMaybe(rootDir, FILE_CONFIG, 'utf-8')
|
|
258
|
-
const lockProbe = explicitLockPath ? null : readFileSyncMaybe(rootDir, FILE_LOCK, 'utf-8')
|
|
259
|
-
let sourcesPath =
|
|
260
|
-
let sources =
|
|
261
|
-
// Root-SELECTION
|
|
262
|
-
// explicitBundlePath
|
|
263
|
-
|
|
264
|
-
if (
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
sources = readFileSyncMaybe(dirname(sourcesPath), basename(sourcesPath))
|
|
276
|
-
}
|
|
258
|
+
const config = readFileSyncMaybe(rootDir, FILE_CONFIG, 'utf-8', this.#host)
|
|
259
|
+
const lockProbe = explicitLockPath ? null : readFileSyncMaybe(rootDir, FILE_LOCK, 'utf-8', this.#host)
|
|
260
|
+
let sourcesPath = explicitBundlePath || join(rootDir, FILE_CODE)
|
|
261
|
+
let sources = this.#readMaybe(sourcesPath)
|
|
262
|
+
// Root-SELECTION signals: a config, a lockfile, or only the DEFAULT <rootDir>/stasis.code.br
|
|
263
|
+
// (see explicitBundlePath; an explicit bundleFile is still loaded via `sources`).
|
|
264
|
+
if (config === null && lockProbe === null && (explicitBundlePath || sources === null)) continue
|
|
265
|
+
if (loaded) throw new Error('Stasis config already loaded')
|
|
266
|
+
loaded = true
|
|
267
|
+
this.root = rootDir
|
|
268
|
+
|
|
269
|
+
if (config) {
|
|
270
|
+
this.config.loadConfig(config)
|
|
271
|
+
// stasis.config.json may set a `bundleFile` the probe couldn't see -- re-resolve and re-read.
|
|
272
|
+
const configuredPath = this.config.bundleFile || join(rootDir, FILE_CODE)
|
|
273
|
+
if (configuredPath !== sourcesPath) {
|
|
274
|
+
sourcesPath = configuredPath
|
|
275
|
+
sources = this.#readMaybe(sourcesPath)
|
|
277
276
|
}
|
|
277
|
+
}
|
|
278
278
|
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
const lockPath = explicitLockPath || join(rootDir, FILE_LOCK)
|
|
283
|
-
|
|
284
|
-
lockfileLoaded = this.#absorbLockfile(lock, lockPath)
|
|
285
|
-
this.#loadBundleArtifacts(sources, sourcesPath, lockfileLoaded)
|
|
279
|
+
const lock = explicitLockPath ? this.#readMaybe(explicitLockPath, 'utf-8') : lockProbe
|
|
280
|
+
lockfileLoaded = this.#absorbLockfile(lock, explicitLockPath || join(rootDir, FILE_LOCK))
|
|
281
|
+
this.#loadBundleArtifacts(sources, sourcesPath, lockfileLoaded)
|
|
286
282
|
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
}
|
|
283
|
+
// Innermost matching rootDir wins (per-dir opt-in); without this break an outer root
|
|
284
|
+
// re-detects a rootDir-independent bundleFile and trips `loaded`.
|
|
285
|
+
break
|
|
291
286
|
}
|
|
292
287
|
|
|
293
288
|
// Explicit lockfile but no discovery indicator: the loop never ran, so absorb here against
|
|
294
289
|
// `this.root` (outermost) so the run still has attestation.
|
|
295
290
|
if (!loaded && explicitLockPath) {
|
|
296
|
-
|
|
297
|
-
lockfileLoaded = this.#absorbLockfile(lock, explicitLockPath)
|
|
291
|
+
lockfileLoaded = this.#absorbLockfile(this.#readMaybe(explicitLockPath, 'utf-8'), explicitLockPath)
|
|
298
292
|
}
|
|
299
293
|
|
|
300
294
|
// Explicit bundleFile suppressed as a root signal above: load against `this.root` (outermost).
|
|
301
|
-
// Capture and load MUST agree on where the upward walk stops (PROJECT_CWD/.git/
|
|
302
|
-
// pnpm-workspace.yaml), else they commit different roots and fail "outside the project root".
|
|
303
295
|
if (!loaded && (explicitBundlePath || this.config.resourcesBundleFile)) {
|
|
304
|
-
|
|
305
|
-
? readFileSyncMaybe(dirname(explicitBundlePath), basename(explicitBundlePath))
|
|
306
|
-
: null
|
|
307
|
-
this.#loadBundleArtifacts(sources, explicitBundlePath, lockfileLoaded)
|
|
296
|
+
this.#loadBundleArtifacts(explicitBundlePath ? this.#readMaybe(explicitBundlePath) : null, explicitBundlePath, lockfileLoaded)
|
|
308
297
|
}
|
|
309
298
|
|
|
310
299
|
// Post-loop: with no stasis files the loop never runs, and a frozen run must fail closed.
|
|
@@ -312,22 +301,31 @@ export class State {
|
|
|
312
301
|
if (this.config.frozenBundle) assert.ok(this.#bundleSources !== null, 'No bundle, but attempting to run in frozen bundle mode')
|
|
313
302
|
|
|
314
303
|
// Claim write targets so no other live State (any copy) silently targets the same file.
|
|
315
|
-
if (this.config.writeBundle
|
|
316
|
-
this.#claimWritePath(
|
|
317
|
-
|
|
318
|
-
if (this.config.writeBundle && this.config.resourcesBundleFile) {
|
|
319
|
-
this.#claimWritePath(`resourcesBundleFile '${this.config.resourcesBundleFile}'`, this.config.resourcesBundleFile)
|
|
320
|
-
}
|
|
321
|
-
if (this.config.writeLockfile && this.config.lockFile) {
|
|
322
|
-
this.#claimWritePath(`lockFile '${this.config.lockFile}'`, this.config.lockFile)
|
|
304
|
+
if (this.config.writeBundle) {
|
|
305
|
+
this.#claimWritePath('bundleFile')
|
|
306
|
+
this.#claimWritePath('resourcesBundleFile')
|
|
323
307
|
}
|
|
308
|
+
if (this.config.writeLockfile) this.#claimWritePath('lockFile')
|
|
324
309
|
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
310
|
+
this.#setPreloadRoot(preloadRoot)
|
|
311
|
+
|
|
312
|
+
// The registry answers for the preload and for write claims; any other State stays out of it.
|
|
313
|
+
if (isPreload || this.#claims.size > 0) liveStates().add(this)
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
#exists(p) {
|
|
317
|
+
return this.#host.stat(p) !== null
|
|
318
|
+
}
|
|
329
319
|
|
|
330
|
-
|
|
320
|
+
// The file at `path` through the host, or null when there is none.
|
|
321
|
+
#readMaybe(path, encoding) {
|
|
322
|
+
return readFileSyncMaybe(dirname(path), basename(path), encoding, this.#host)
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
#setPreloadRoot(preloadRoot) {
|
|
326
|
+
if (preloadRoot === undefined) return
|
|
327
|
+
assert.equal(typeof preloadRoot, 'string', 'preloadRoot must be a string')
|
|
328
|
+
this.#preloadRoot = preloadRoot
|
|
331
329
|
}
|
|
332
330
|
|
|
333
331
|
// Absorb a lockfile's attestation; returns whether it was actually absorbed. Lockfile.parse
|
|
@@ -348,9 +346,7 @@ export class State {
|
|
|
348
346
|
if (includeSources) this.entries = lockfile.entries
|
|
349
347
|
|
|
350
348
|
for (const [dir, { files }] of this.modules) {
|
|
351
|
-
for (const [name, hash] of Object.entries(files))
|
|
352
|
-
noupsert(this.hashes, join(dir, name), hash)
|
|
353
|
-
}
|
|
349
|
+
for (const [name, hash] of Object.entries(files)) noupsert(this.hashes, join(dir, name), hash)
|
|
354
350
|
}
|
|
355
351
|
this.#lockImports = lockfile.imports
|
|
356
352
|
this.#lockFormats = lockfile.formats
|
|
@@ -361,29 +357,33 @@ export class State {
|
|
|
361
357
|
return true
|
|
362
358
|
}
|
|
363
359
|
|
|
360
|
+
// An on-disk bundle is read in under add/load/frozen; replace starts over.
|
|
361
|
+
get #absorbsBundles() {
|
|
362
|
+
return this.config.bundle && !this.config.replaceBundle
|
|
363
|
+
}
|
|
364
|
+
|
|
364
365
|
// Gate and load the bundle artifacts for a committed root; `sources` may be null (no bundle, or
|
|
365
366
|
// resources-only).
|
|
366
367
|
#loadBundleArtifacts(sources, sourcesPath, lockfileLoaded) {
|
|
367
|
-
if (sources &&
|
|
368
|
+
if (sources && this.config.bundleMode === 'none') {
|
|
368
369
|
throw new Error(`Unexpected ${sourcesPath} with config.bundle = 'none'`)
|
|
369
370
|
}
|
|
370
371
|
// A frozen bundle is self-attesting, so it needs no sibling lockfile and is exempt here.
|
|
371
372
|
if (sources && !lockfileLoaded && this.config.useLockfile && !this.config.replaceLockfile && !this.config.frozenBundle) {
|
|
372
373
|
throw new Error('stasis.lock.json missing, can not use sources')
|
|
373
374
|
}
|
|
374
|
-
if (sources &&
|
|
375
|
-
|
|
376
|
-
}
|
|
377
|
-
if (this.config.resourcesBundleFile) {
|
|
378
|
-
const resourcesPath = this.config.resourcesBundleFile
|
|
379
|
-
const resourcesData = readFileSyncMaybe(dirname(resourcesPath), basename(resourcesPath))
|
|
380
|
-
if (resourcesData && (this.config.writeBundle || this.config.loadBundle || this.config.frozenBundle) && !this.config.replaceBundle) {
|
|
381
|
-
this.#absorbResourcesBundle(resourcesData, { lockfileLoaded, resourcesPath })
|
|
382
|
-
}
|
|
383
|
-
}
|
|
375
|
+
if (sources && this.#absorbsBundles) this.#loadCodeBundle(sources, sourcesPath, lockfileLoaded)
|
|
376
|
+
this.#absorbResourcesBundleFile(lockfileLoaded)
|
|
384
377
|
}
|
|
385
378
|
|
|
386
|
-
|
|
379
|
+
// The resources half of a split layout, when configured and present on disk.
|
|
380
|
+
#absorbResourcesBundleFile(lockfileLoaded) {
|
|
381
|
+
const resourcesPath = this.config.resourcesBundleFile
|
|
382
|
+
const resourcesData = resourcesPath ? this.#readMaybe(resourcesPath) : null
|
|
383
|
+
if (resourcesData && this.#absorbsBundles) this.#absorbResourcesBundle(resourcesData, { lockfileLoaded, resourcesPath })
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
#loadCodeBundle(sources, sourcesPath, lockfileLoaded) {
|
|
387
387
|
const bundle = Bundle.parse(brotliDecompressSync(sources).toString('utf-8'))
|
|
388
388
|
// Bundle.parse accepts v0 for offline tooling; the runtime refuses it -- v0 has no per-file
|
|
389
389
|
// formats or import map, so serving one widens the trust boundary.
|
|
@@ -397,6 +397,12 @@ export class State {
|
|
|
397
397
|
assert.ok(!this.config.full || bundle.entries.size > 0 || !bundle.hasCode,
|
|
398
398
|
`${sourcesPath}: a full-scope bundle carrying code must declare an entry to run ` +
|
|
399
399
|
`(an add-only attestation has none; run a bundle built by \`stasis bundle\`/\`stasis run\`)`)
|
|
400
|
+
this.#absorbCodeBundle(bundle, lockfileLoaded)
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// Take a parsed code bundle (unified, or the code half) as the live maps, cross-checked against
|
|
404
|
+
// the loaded lockfile, and snapshot it when it is the frozen attestation.
|
|
405
|
+
#absorbCodeBundle(bundle, lockfileLoaded) {
|
|
400
406
|
this.#mergeBundleMetadata(bundle, { lockfileLoaded })
|
|
401
407
|
for (const [file, content] of bundle.sources) {
|
|
402
408
|
if (Bundle.isResourceFormat(bundle.formats.get(file))) this.resources.set(file, content)
|
|
@@ -406,6 +412,7 @@ export class State {
|
|
|
406
412
|
this.imports = bundle.imports
|
|
407
413
|
this.#absorbExecutable(bundle)
|
|
408
414
|
this.#seedReasonFromBundle(bundle)
|
|
415
|
+
this.#absorbRepo('code', bundle)
|
|
409
416
|
if (this.config.frozenBundle) {
|
|
410
417
|
// Snapshot before addFile/addImport mutate the live maps; imports is deep-cloned because
|
|
411
418
|
// this.imports shares bundle.imports's nested Maps.
|
|
@@ -421,18 +428,17 @@ export class State {
|
|
|
421
428
|
#mergeBundleMetadata(bundle, { lockfileLoaded }) {
|
|
422
429
|
if (lockfileLoaded) {
|
|
423
430
|
if (bundle.entries.size > 0) {
|
|
424
|
-
assert.deepStrictEqual(
|
|
425
|
-
[...bundle.entries].toSorted(),
|
|
426
|
-
[...this.entries].toSorted(),
|
|
427
|
-
'bundle/lockfile entries mismatch'
|
|
428
|
-
)
|
|
431
|
+
assert.deepStrictEqual([...bundle.entries].toSorted(), [...this.entries].toSorted(), 'bundle/lockfile entries mismatch')
|
|
429
432
|
}
|
|
430
433
|
for (const [dir, info] of bundle.modules) {
|
|
431
434
|
if (!info.name) continue // workspace bucket or fallback: no inferable name
|
|
432
435
|
assert.ok(this.modules.has(dir), `bundle module ${dir} missing in lockfile`)
|
|
433
436
|
const lockModule = this.modules.get(dir)
|
|
434
437
|
assert.equal(info.name, lockModule.name)
|
|
435
|
-
|
|
438
|
+
// Strict, absent included: every absorb site requires a v1 bundle, so a missing version is
|
|
439
|
+
// a real workspace identity (or a stripped field), never v0 partial metadata -- a
|
|
440
|
+
// version-less bundle bucket must not dodge the lockfile consistency check.
|
|
441
|
+
assert.equal(info.version, lockModule.version, `bundle module ${dir} version mismatch with lockfile`)
|
|
436
442
|
for (const rel of Object.keys(info.files)) {
|
|
437
443
|
assert.ok(Object.hasOwn(lockModule.files, rel), `bundle file ${dir}/${rel} missing in lockfile`)
|
|
438
444
|
}
|
|
@@ -470,16 +476,16 @@ export class State {
|
|
|
470
476
|
// Mutate in place: this.entries may be shared by reference with a sidecar's parent.
|
|
471
477
|
for (const e of bundle.entries) this.entries.add(e)
|
|
472
478
|
for (const [dir, info] of bundle.modules) {
|
|
473
|
-
|
|
474
|
-
|
|
479
|
+
// Skip v0 partial metadata (nameless workspace buckets, version-less node_modules
|
|
480
|
+
// buckets); a v1 workspace bucket may omit version, so its identity is absorbed anyway.
|
|
481
|
+
if (!info.name || (!info.version && hasNodeModulesSegment(dir))) continue
|
|
482
|
+
const existing = this.modules.get(dir)
|
|
483
|
+
if (existing === undefined) {
|
|
484
|
+
this.modules.set(dir, moduleInfo({ ...info, files: Object.create(null) }))
|
|
485
|
+
} else {
|
|
475
486
|
// A dir may be added twice (code + resource entries), and both must agree.
|
|
476
|
-
const existing = this.modules.get(dir)
|
|
477
487
|
assert.equal(info.name, existing.name, `bundle ${dir} name mismatch`)
|
|
478
488
|
assert.equal(info.version, existing.version, `bundle ${dir} version mismatch`)
|
|
479
|
-
} else {
|
|
480
|
-
this.modules.set(dir, info.ecosystem === undefined
|
|
481
|
-
? { name: info.name, version: info.version, files: Object.create(null) }
|
|
482
|
-
: { name: info.name, version: info.version, ecosystem: info.ecosystem, files: Object.create(null) })
|
|
483
489
|
}
|
|
484
490
|
}
|
|
485
491
|
}
|
|
@@ -501,9 +507,7 @@ export class State {
|
|
|
501
507
|
`resources bundle ${resourcesPath} declares non-resource format='${format}' for ${file}`)
|
|
502
508
|
}
|
|
503
509
|
this.#mergeBundleMetadata(bundle, { lockfileLoaded })
|
|
504
|
-
for (const [file, content] of bundle.sources)
|
|
505
|
-
this.resources.set(file, content)
|
|
506
|
-
}
|
|
510
|
+
for (const [file, content] of bundle.sources) this.resources.set(file, content)
|
|
507
511
|
// Union formats: the two halves' file sets must be disjoint.
|
|
508
512
|
for (const [file, format] of bundle.formats) {
|
|
509
513
|
const existing = this.formats.get(file)
|
|
@@ -513,13 +517,14 @@ export class State {
|
|
|
513
517
|
}
|
|
514
518
|
this.#absorbExecutable(bundle)
|
|
515
519
|
this.#seedReasonFromBundle(bundle)
|
|
520
|
+
this.#absorbRepo('resources', bundle)
|
|
516
521
|
if (this.config.frozenBundle) {
|
|
517
522
|
// Extend the frozen snapshot, init lazily: resources-only deployments are legal, so
|
|
518
523
|
// bundleFile may not have populated these.
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
524
|
+
this.#bundleResources ??= new Set()
|
|
525
|
+
this.#bundleFormats ??= new Map()
|
|
526
|
+
this.#bundleImports ??= objectToMaps(fileMapToObject(this.imports))
|
|
527
|
+
this.#bundleSources ??= new Set(this.sources.keys())
|
|
523
528
|
for (const f of bundle.sources.keys()) this.#bundleResources.add(f)
|
|
524
529
|
for (const [f, fmt] of bundle.formats) this.#bundleFormats.set(f, fmt)
|
|
525
530
|
}
|
|
@@ -564,7 +569,7 @@ export class State {
|
|
|
564
569
|
}
|
|
565
570
|
|
|
566
571
|
assertEntry(url) {
|
|
567
|
-
// No entry attestation to check against (lock=none/ignore, fresh build) -- #
|
|
572
|
+
// No entry attestation to check against (lock=none/ignore, fresh build) -- #loadCodeBundle
|
|
568
573
|
// already refuses a runnable code bundle that declares none.
|
|
569
574
|
if (this.entries.size === 0) return
|
|
570
575
|
const file = this.#canonicalFile(url)
|
|
@@ -587,13 +592,15 @@ export class State {
|
|
|
587
592
|
}
|
|
588
593
|
|
|
589
594
|
// Refuse a path another live State (ANY copy) already claims; canonicalized so `./x`/`x`/symlinks
|
|
590
|
-
// compare equal.
|
|
591
|
-
#claimWritePath(
|
|
592
|
-
|
|
593
|
-
|
|
595
|
+
// compare equal. `key` names the config option; nothing is claimed when it is unset.
|
|
596
|
+
#claimWritePath(key, prefix = '') {
|
|
597
|
+
const value = this.config[key]
|
|
598
|
+
if (!value || !this.#claim) return
|
|
599
|
+
const label = `${prefix}${key} '${value}'`
|
|
600
|
+
const canonical = canonicalizePath(value, this.#host)
|
|
594
601
|
for (const other of liveStates()) {
|
|
595
602
|
const owner = other.claimedWritePathLabel(canonical)
|
|
596
|
-
assert.ok(owner === undefined, `${label}
|
|
603
|
+
assert.ok(owner === undefined, `${label} is already claimed by ${owner} of another live State`)
|
|
597
604
|
}
|
|
598
605
|
this.#claims.set(canonical, label)
|
|
599
606
|
}
|
|
@@ -634,16 +641,11 @@ export class State {
|
|
|
634
641
|
relative(absolute) {
|
|
635
642
|
assert.ok(absolute)
|
|
636
643
|
const file = relative(this.root, absolute)
|
|
637
|
-
assert.ok(!file
|
|
644
|
+
assert.ok(!relativeEscapes(file))
|
|
638
645
|
// The project root is keyed '.', never '' -- mixing the two desyncs write from read.
|
|
639
646
|
return file === '' ? '.' : file
|
|
640
647
|
}
|
|
641
648
|
|
|
642
|
-
// Memoized #canonicalUncached (per URL, State-lifetime): a realpathSync per node_modules URL, and
|
|
643
|
-
// hot callers repeat relentlessly. Sound only because the tree holds still mid-run; the cached
|
|
644
|
-
// result is shared -- never mutate it.
|
|
645
|
-
#canonicalCache = new Map()
|
|
646
|
-
|
|
647
649
|
#canonical(url) {
|
|
648
650
|
let result = this.#canonicalCache.get(url)
|
|
649
651
|
if (result === undefined) {
|
|
@@ -658,16 +660,16 @@ export class State {
|
|
|
658
660
|
#canonicalUncached(url) {
|
|
659
661
|
const absolute = this.absolute(url)
|
|
660
662
|
const file = relative(this.root, absolute)
|
|
661
|
-
if (file
|
|
663
|
+
if (relativeEscapes(file) || !splitNodeModulesPath(file)) return { url, absolute }
|
|
662
664
|
let real
|
|
663
665
|
try {
|
|
664
|
-
real =
|
|
666
|
+
real = this.#host.realpath(absolute)
|
|
665
667
|
} catch {
|
|
666
668
|
return { url, absolute }
|
|
667
669
|
}
|
|
668
670
|
if (real === absolute) return { url, absolute }
|
|
669
671
|
const realFile = relative(this.root, real)
|
|
670
|
-
if (realFile
|
|
672
|
+
if (relativeEscapes(realFile) || splitNodeModulesPath(realFile)) return { url, absolute }
|
|
671
673
|
return { url: pathToFileURL(real).toString(), absolute: real }
|
|
672
674
|
}
|
|
673
675
|
|
|
@@ -675,29 +677,31 @@ export class State {
|
|
|
675
677
|
return this.relative(this.#canonical(url).absolute)
|
|
676
678
|
}
|
|
677
679
|
|
|
678
|
-
//
|
|
679
|
-
|
|
680
|
-
inNodeModules(url) {
|
|
681
|
-
let file
|
|
680
|
+
// #canonicalFile, or undefined for a URL outside the project root (the shims then pass through).
|
|
681
|
+
#canonicalFileMaybe(url) {
|
|
682
682
|
try {
|
|
683
|
-
|
|
683
|
+
return this.#canonicalFile(url)
|
|
684
684
|
} catch {
|
|
685
|
-
return
|
|
685
|
+
return undefined
|
|
686
686
|
}
|
|
687
|
-
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
// True when `url` resolves (through any workspace symlink) into node_modules -- not a raw
|
|
690
|
+
// `/node_modules/` substring test, so a symlinked workspace source is read from disk.
|
|
691
|
+
inNodeModules(url) {
|
|
692
|
+
const file = this.#canonicalFileMaybe(url)
|
|
693
|
+
return file !== undefined && splitNodeModulesPath(file) !== null
|
|
688
694
|
}
|
|
689
695
|
|
|
690
696
|
// Nearest package.json at or above a directory (findPackageJSON is unreliable for a directory
|
|
691
|
-
// URL, see #locateModule)
|
|
697
|
+
// URL, see #locateModule), refusing one there that can't be read as findPackageJSON does
|
|
698
|
+
// (packageJSONStat). Bounded by the project root.
|
|
692
699
|
#nearestPackageJsonFor(dirAbsolute) {
|
|
693
|
-
let dir = dirAbsolute
|
|
694
|
-
while (true) {
|
|
700
|
+
for (let dir = dirAbsolute; ; dir = dirname(dir)) {
|
|
695
701
|
const candidate = join(dir, 'package.json')
|
|
696
|
-
if (
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
if (parent === dir) break
|
|
700
|
-
dir = parent
|
|
702
|
+
if (packageJSONStat(this.#host, candidate)?.isFile()) return candidate
|
|
703
|
+
// The root's package.json was just checked; never escape root.
|
|
704
|
+
if (dir === this.root || dirname(dir) === dir) break
|
|
701
705
|
}
|
|
702
706
|
// Unreachable: state.root is resolved to a dir that has package.json.
|
|
703
707
|
assert.fail(`no package.json at or above directory ${this.relative(dirAbsolute)}`)
|
|
@@ -707,14 +711,12 @@ export class State {
|
|
|
707
711
|
// ourselves -- Node's findPackageJSON is unreliable for a directory URL (EISDIR, or the parent's).
|
|
708
712
|
#locateModule(url, { directory = false } = {}) {
|
|
709
713
|
// Canonicalize first: a linked-in workspace source is recorded under its real path (a source).
|
|
710
|
-
const
|
|
711
|
-
|
|
712
|
-
const absolute = canonical.absolute
|
|
713
|
-
assert.ok(existsSync(absolute))
|
|
714
|
+
const { absolute } = this.#canonical(url)
|
|
715
|
+
assert.ok(this.#host.stat(absolute) !== null)
|
|
714
716
|
const file = this.relative(absolute)
|
|
715
717
|
|
|
716
|
-
const closestPkgAbsolute = directory ? this.#nearestPackageJsonFor(absolute) : findPackageJSON(
|
|
717
|
-
const closestPkg = readPackageJSON(closestPkgAbsolute)
|
|
718
|
+
const closestPkgAbsolute = directory ? this.#nearestPackageJsonFor(absolute) : this.#host.findPackageJSON(absolute)
|
|
719
|
+
const closestPkg = readPackageJSON(this.#host, closestPkgAbsolute)
|
|
718
720
|
|
|
719
721
|
const closestType = closestPkg.type
|
|
720
722
|
assert.ok(closestType === undefined || closestType === 'module' || closestType === 'commonjs')
|
|
@@ -724,36 +726,32 @@ export class State {
|
|
|
724
726
|
let pkgAbsolute, name, version
|
|
725
727
|
if (nmRoot) {
|
|
726
728
|
pkgAbsolute = resolve(this.root, nmRoot, 'package.json')
|
|
727
|
-
const rootPkg = pkgAbsolute === closestPkgAbsolute ? closestPkg : readPackageJSON(pkgAbsolute)
|
|
729
|
+
const rootPkg = pkgAbsolute === closestPkgAbsolute ? closestPkg : readPackageJSON(this.#host, pkgAbsolute)
|
|
728
730
|
;({ name, version } = rootPkg)
|
|
729
731
|
assert.ok(name, `Missing name in ${this.relative(pkgAbsolute)}`)
|
|
730
732
|
assert.ok(version, `Missing version in ${this.relative(pkgAbsolute)}`)
|
|
731
733
|
if (closestPkgAbsolute !== pkgAbsolute) {
|
|
732
734
|
const message = `Inconsistent data between ${this.relative(closestPkgAbsolute)} and ${this.relative(pkgAbsolute)}`
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
assert.ok(closestPkg.name.startsWith(`${name}/`), message)
|
|
736
|
-
}
|
|
737
|
-
|
|
735
|
+
// Allow fake module-name subpaths: the real module owns the prefix (npm wouldn't publish this).
|
|
736
|
+
if (closestPkg.name !== undefined && closestPkg.name !== name) assert.ok(closestPkg.name.startsWith(`${name}/`), message)
|
|
738
737
|
if (closestPkg.version !== undefined) assert.equal(closestPkg.version, version, message)
|
|
739
738
|
}
|
|
740
739
|
} else {
|
|
741
740
|
pkgAbsolute = closestPkgAbsolute
|
|
742
741
|
let json = closestPkg
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
break
|
|
747
|
-
}
|
|
742
|
+
// A workspace package outside node_modules may omit version (private/unpublished): the
|
|
743
|
+
// name alone claims the bucket. node_modules buckets (above) still require both.
|
|
744
|
+
while (json.name === undefined) {
|
|
748
745
|
assert.ok(Object.keys(json).every((k) => k === 'type'))
|
|
749
|
-
const
|
|
750
|
-
assert.ok(
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
)
|
|
754
|
-
pkgAbsolute = next
|
|
755
|
-
json = readPackageJSON(pkgAbsolute)
|
|
746
|
+
const dir = dirname(pkgAbsolute)
|
|
747
|
+
assert.ok(dir !== this.root && isPathWithin(this.root, dir), `No package.json with a name found for ${file}`)
|
|
748
|
+
pkgAbsolute = this.#nearestPackageJsonFor(dirname(dir))
|
|
749
|
+
json = readPackageJSON(this.#host, pkgAbsolute)
|
|
756
750
|
}
|
|
751
|
+
name = json.name
|
|
752
|
+
// A literal `"version": null` folds to undefined here too: the parsers normalize the same
|
|
753
|
+
// way, and recording null verbatim would split identity on the next run's re-read.
|
|
754
|
+
version = json.version ?? undefined
|
|
757
755
|
}
|
|
758
756
|
const pkg = this.relative(pkgAbsolute)
|
|
759
757
|
assert.ok(pkg === 'package.json' || pkg.endsWith('/package.json'))
|
|
@@ -762,13 +760,17 @@ export class State {
|
|
|
762
760
|
if (nmRoot) assert.equal(dir, nmRoot)
|
|
763
761
|
if (!this.modules.has(dir)) {
|
|
764
762
|
// Tag node_modules buckets `npm`; workspace/top-level buckets carry no ecosystem.
|
|
765
|
-
this.modules.set(dir, nmRoot
|
|
766
|
-
? { name, version, ecosystem: 'npm', files: Object.create(null) }
|
|
767
|
-
: { name, version, files: Object.create(null) })
|
|
763
|
+
this.modules.set(dir, moduleInfo({ name, version, ecosystem: nmRoot ? 'npm' : undefined, files: Object.create(null) }))
|
|
768
764
|
}
|
|
769
765
|
const module = this.modules.get(dir)
|
|
770
|
-
|
|
771
|
-
|
|
766
|
+
if (module.name !== name || module.version !== version) {
|
|
767
|
+
// Message built only on failure: addFile is hot, and the mismatch is a migration/drift event.
|
|
768
|
+
const hint = (module.version == null) === (version == null) ? '' :
|
|
769
|
+
' -- an artifact from an older stasis may record a placeholder version for a workspace ' +
|
|
770
|
+
'package without one; regenerate it (lock=replace / bundle=replace)'
|
|
771
|
+
assert.fail(`module identity mismatch for '${dir}': artifact records ` +
|
|
772
|
+
`'${module.name}@${module.version ?? '(none)'}', package.json has '${name}@${version ?? '(none)'}'${hint}`)
|
|
773
|
+
}
|
|
772
774
|
|
|
773
775
|
return { absolute, file, dir, module, closestType }
|
|
774
776
|
}
|
|
@@ -792,38 +794,33 @@ export class State {
|
|
|
792
794
|
// actual format instead of conflicting with 'stat:*'.
|
|
793
795
|
if (isStatFormat(this.formats.get(file))) this.formats.delete(file)
|
|
794
796
|
|
|
795
|
-
|
|
797
|
+
const ext = extname(file)
|
|
798
|
+
if (asResource && CODE_EXTENSIONS.has(ext.slice(1).toLowerCase())) {
|
|
796
799
|
throw new Error(`addFile: a code file can't be recorded as a resource: ${file}`)
|
|
797
800
|
}
|
|
798
801
|
|
|
799
802
|
if (!asResource && inferFormat) {
|
|
800
|
-
const
|
|
801
|
-
|
|
802
|
-
'.json': 'json',
|
|
803
|
-
'.mjs': 'module',
|
|
804
|
-
'.cjs': 'commonjs',
|
|
805
|
-
'.mts': 'module-typescript',
|
|
806
|
-
'.cts': 'commonjs-typescript',
|
|
807
|
-
}
|
|
808
|
-
if (closestType !== undefined) {
|
|
809
|
-
extToFormat['.js'] = closestType
|
|
810
|
-
extToFormat['.ts'] = `${closestType}-typescript`
|
|
811
|
-
}
|
|
812
|
-
const inferredFormat = extToFormat[extname(file)]
|
|
803
|
+
const inferredFormat = EXT_FORMATS[ext] ??
|
|
804
|
+
(closestType === undefined ? undefined : ext === '.js' ? closestType : ext === '.ts' ? `${closestType}-typescript` : undefined)
|
|
813
805
|
if (inferredFormat !== undefined) {
|
|
806
|
+
// A transforming preload (`stasis run --import tsx`) loads a TypeScript file as its
|
|
807
|
+
// post-erasure family ('module-typescript' arrives as 'module'): attest the on-disk
|
|
808
|
+
// format, not the transformer's runtime view. Anything else must still match exactly.
|
|
809
|
+
if (format != null && format === erasedTypeScriptFormat(inferredFormat)) format = inferredFormat
|
|
814
810
|
if (format != null) assert.equal(format, inferredFormat)
|
|
815
811
|
else format = inferredFormat
|
|
816
812
|
} else if (format == null) {
|
|
817
|
-
// No `type`:
|
|
818
|
-
//
|
|
819
|
-
|
|
820
|
-
const variants = {
|
|
821
|
-
__proto__: null,
|
|
822
|
-
'.js': ['commonjs', 'module'],
|
|
823
|
-
'.ts': ['commonjs-typescript', 'module-typescript'],
|
|
824
|
-
}[extname(file)]
|
|
813
|
+
// No `type`: reuse an extension-appropriate format already recorded this session (the
|
|
814
|
+
// loader's call, or the parent's for a sidecar) rather than re-defaulting to commonjs and mis-attesting.
|
|
815
|
+
const variants = UNTYPED_VARIANTS[ext]
|
|
825
816
|
const known = this.formats.get(file) ?? this.#parent?.formats.get(file)
|
|
826
817
|
format = variants?.includes(known) ? known : variants?.[0]
|
|
818
|
+
} else if (ext === '.ts' && (format === 'commonjs' || format === 'module')) {
|
|
819
|
+
// No `type`, but a transforming preload reported this .ts as its post-erasure family:
|
|
820
|
+
// attest the on-disk '-typescript' variant, keeping same-stack replays self-consistent.
|
|
821
|
+
// Stacks can still honestly disagree about a no-`type` .ts (tsx defaults to commonjs,
|
|
822
|
+
// Node syntax-detects) -- that rightly surfaces as a format flip, not silently here.
|
|
823
|
+
format = `${format}-typescript`
|
|
827
824
|
}
|
|
828
825
|
}
|
|
829
826
|
|
|
@@ -831,14 +828,17 @@ export class State {
|
|
|
831
828
|
if (typeof source === 'string') {
|
|
832
829
|
assert.ok(source.isWellFormed())
|
|
833
830
|
} else {
|
|
834
|
-
if (source
|
|
831
|
+
if (source == null) {
|
|
832
|
+
source = this.#host.readFile(absolute)
|
|
833
|
+
sourceFromDisk = true
|
|
834
|
+
}
|
|
835
835
|
assert.ok(Buffer.isBuffer(source))
|
|
836
836
|
if (!asResource) assert.ok(isUtf8(source), `File is not UTF-8: ${file}`)
|
|
837
837
|
}
|
|
838
838
|
|
|
839
839
|
const buf = typeof source === 'string' ? Buffer.from(source) : source
|
|
840
840
|
// Verify a CALLER-PROVIDED source against disk; tautological when we read it ourselves.
|
|
841
|
-
if (!sourceFromDisk) assert.deepStrictEqual(
|
|
841
|
+
if (!sourceFromDisk) assert.deepStrictEqual(this.#host.readFile(absolute), buf)
|
|
842
842
|
|
|
843
843
|
if (asResource) {
|
|
844
844
|
const derived = isUtf8(buf) ? 'resource' : 'resource:base64'
|
|
@@ -849,9 +849,11 @@ export class State {
|
|
|
849
849
|
if (isEntry) this.entries.add(file)
|
|
850
850
|
const integrity = sha512integrity(source)
|
|
851
851
|
noupsert(this.hashes, file, integrity)
|
|
852
|
+
this.#filesCapturedThisRun.add(file)
|
|
852
853
|
if (this.config.childProcess) this.#observed.add(file) // only a child's shardSnapshot reads it; skip when the channel is off
|
|
854
|
+
// Provenance for the bundle's `reason` field (null = the caller attributes it, see includePackageJson).
|
|
853
855
|
if (this.config.bundle && reason !== null) {
|
|
854
|
-
this.#recordReason(reason, file)
|
|
856
|
+
this.#recordReason(reason, file)
|
|
855
857
|
// Track HOW 'run' saw this file so #bundleReason can drop files run merely fs-READ post-plugin.
|
|
856
858
|
if (reason === 'run') {
|
|
857
859
|
if (!fsRead) this.#runImported.add(file)
|
|
@@ -859,7 +861,7 @@ export class State {
|
|
|
859
861
|
}
|
|
860
862
|
}
|
|
861
863
|
const rel = relative(dir, file)
|
|
862
|
-
assert.ok(!rel
|
|
864
|
+
assert.ok(!relativeEscapes(rel))
|
|
863
865
|
|
|
864
866
|
const inAttestedZone = hasNodeModulesSegment(dir) || this.config.full
|
|
865
867
|
if (this.config.frozen && inAttestedZone) {
|
|
@@ -895,12 +897,8 @@ export class State {
|
|
|
895
897
|
assert.equal(module.files[rel], integrity)
|
|
896
898
|
|
|
897
899
|
if (this.config.bundle) {
|
|
898
|
-
if (asResource)
|
|
899
|
-
|
|
900
|
-
noupsert(this.resources, file, content)
|
|
901
|
-
} else {
|
|
902
|
-
noupsert(this.sources, file, typeof source === 'string' ? source : source.toString())
|
|
903
|
-
}
|
|
900
|
+
if (asResource) noupsert(this.resources, file, buf.toString(format === 'resource:base64' ? 'base64' : 'utf8'))
|
|
901
|
+
else noupsert(this.sources, file, typeof source === 'string' ? source : source.toString())
|
|
904
902
|
}
|
|
905
903
|
|
|
906
904
|
if (format) noupsert(this.formats, file, format)
|
|
@@ -913,18 +911,14 @@ export class State {
|
|
|
913
911
|
// A record touches only this State; a REFUTATION must reach the whole family, else
|
|
914
912
|
// #mergedExecutable's union resurrects the bit from a sibling's seeded entry.
|
|
915
913
|
#recordExecutable(file, absolute) {
|
|
916
|
-
const executable = observeExecutable(absolute)
|
|
914
|
+
const executable = observeExecutable(absolute, this.#host)
|
|
917
915
|
if (executable === true) {
|
|
918
916
|
this.executable.add(file)
|
|
919
917
|
return
|
|
920
918
|
}
|
|
921
919
|
if (executable !== false || !CAN_OBSERVE_EXECUTE_BITS) return
|
|
922
|
-
const root = this.#parent ?? this
|
|
923
|
-
if (root.executable.size === 0 && root.sidecars().size === 0) {
|
|
924
|
-
this.executable.delete(file)
|
|
925
|
-
return
|
|
926
|
-
}
|
|
927
920
|
this.executable.delete(file)
|
|
921
|
+
const root = this.#parent ?? this
|
|
928
922
|
root.executable.delete(file)
|
|
929
923
|
for (const sidecar of root.sidecars()) sidecar.executable.delete(file)
|
|
930
924
|
}
|
|
@@ -942,17 +936,13 @@ export class State {
|
|
|
942
936
|
assert.ok(Buffer.isBuffer(source), 'addFsFile requires a Buffer source')
|
|
943
937
|
const path = fileURLToPath(url)
|
|
944
938
|
const format = classifyFormat(path, { content: source })
|
|
945
|
-
if (format
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
throw new Error(
|
|
951
|
-
`addFsFile: ${path} is neither code nor a declared resource; ` +
|
|
952
|
-
`add its extension or filename to the resources allowlist or stop reading it`
|
|
953
|
-
)
|
|
939
|
+
if (format !== undefined && !isBinaryPlist(path, source)) {
|
|
940
|
+
this.addFile(url, { source, format: format ?? undefined, inferFormat: false, fsRead: true })
|
|
941
|
+
} else if (this.config.resources.has(pathExt(path) || basename(path).toLowerCase())) {
|
|
942
|
+
this.addFile(url, { source, resource: true, fsRead: true })
|
|
943
|
+
} else {
|
|
944
|
+
throw new Error(`addFsFile: ${path} is neither code nor a declared resource; add its extension or filename to the resources allowlist or stop reading it`)
|
|
954
945
|
}
|
|
955
|
-
this.addFile(url, { source, format: format ?? undefined, inferFormat: false, fsRead: true })
|
|
956
946
|
}
|
|
957
947
|
|
|
958
948
|
// Record an `fs.readdirSync` capture: the listing is SORTED for reproducibility and stored as a
|
|
@@ -970,7 +960,7 @@ export class State {
|
|
|
970
960
|
if (this.config.childProcess) this.#observed.add(file) // only a child's shardSnapshot reads it; skip when the channel is off
|
|
971
961
|
if (this.config.bundle) this.#recordReason('run', file)
|
|
972
962
|
const rel = relative(dir, file)
|
|
973
|
-
assert.ok(!rel
|
|
963
|
+
assert.ok(!relativeEscapes(rel))
|
|
974
964
|
|
|
975
965
|
const inAttestedZone = hasNodeModulesSegment(dir) || this.config.full
|
|
976
966
|
if (this.config.frozen && inAttestedZone) {
|
|
@@ -1011,20 +1001,15 @@ export class State {
|
|
|
1011
1001
|
// Serve an `fs.readFileSync` from the bundle: raw bytes, or undefined when uncaptured (the hook
|
|
1012
1002
|
// falls back to disk) or a captured directory. Served by presence, not format.
|
|
1013
1003
|
getFsFile(url) {
|
|
1014
|
-
|
|
1015
|
-
try { file = this.#canonicalFile(url) } catch { return undefined }
|
|
1016
|
-
if (this.formats.get(file) === 'directory') return undefined
|
|
1017
|
-
if (!this.sources.has(file) && !this.resources.has(file)) return undefined
|
|
1004
|
+
if (!this.hasFsFileContent(url)) return undefined
|
|
1018
1005
|
const { source } = this.getFile(url)
|
|
1019
1006
|
return Buffer.isBuffer(source) ? source : Buffer.from(source, 'utf8')
|
|
1020
1007
|
}
|
|
1021
1008
|
|
|
1022
1009
|
getFsDir(url) {
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
const { source } = this.getFile(url)
|
|
1027
|
-
const names = JSON.parse(source)
|
|
1010
|
+
const file = this.#canonicalFileMaybe(url)
|
|
1011
|
+
if (file === undefined || this.formats.get(file) !== 'directory') return undefined
|
|
1012
|
+
const names = JSON.parse(this.getFile(url).source)
|
|
1028
1013
|
assert.ok(Array.isArray(names), `corrupt directory listing for ${file}`)
|
|
1029
1014
|
return names
|
|
1030
1015
|
}
|
|
@@ -1034,12 +1019,8 @@ export class State {
|
|
|
1034
1019
|
if (this.#impliedDirIndex) return this.#impliedDirIndex
|
|
1035
1020
|
const dirs = new Set(['.'])
|
|
1036
1021
|
const add = (key) => {
|
|
1037
|
-
let prefix = ''
|
|
1038
1022
|
const parts = key.split('/')
|
|
1039
|
-
for (let i =
|
|
1040
|
-
prefix = prefix === '' ? parts[i] : `${prefix}/${parts[i]}`
|
|
1041
|
-
dirs.add(prefix)
|
|
1042
|
-
}
|
|
1023
|
+
for (let i = 1; i < parts.length; i++) dirs.add(parts.slice(0, i).join('/'))
|
|
1043
1024
|
}
|
|
1044
1025
|
for (const key of this.sources.keys()) add(key)
|
|
1045
1026
|
for (const key of this.resources.keys()) add(key)
|
|
@@ -1053,23 +1034,19 @@ export class State {
|
|
|
1053
1034
|
// shim falls back to disk). Order matters: 'directory' first, content before stat records, implied
|
|
1054
1035
|
// dirs last. NB: 'file' means "recorded", NOT "bytes serveable" (use hasFsFileContent).
|
|
1055
1036
|
getFsStat(url) {
|
|
1056
|
-
|
|
1057
|
-
|
|
1037
|
+
const file = this.#canonicalFileMaybe(url)
|
|
1038
|
+
if (file === undefined) return undefined
|
|
1058
1039
|
const format = this.formats.get(file)
|
|
1059
1040
|
if (format === 'directory') return 'directory'
|
|
1060
|
-
if (this.sources.has(file) || this.resources.has(file)) return 'file'
|
|
1061
|
-
if (format === 'stat:
|
|
1062
|
-
if (format === 'stat:directory') return 'directory'
|
|
1063
|
-
if (this.#impliedDirs().has(file)) return 'directory'
|
|
1041
|
+
if (this.sources.has(file) || this.resources.has(file) || format === 'stat:file') return 'file'
|
|
1042
|
+
if (format === 'stat:directory' || this.#impliedDirs().has(file)) return 'directory'
|
|
1064
1043
|
return undefined
|
|
1065
1044
|
}
|
|
1066
1045
|
|
|
1067
1046
|
// True when the bundle carries actual BYTE content for `url` (not a directory/stat-only record).
|
|
1068
1047
|
hasFsFileContent(url) {
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
if (this.formats.get(file) === 'directory') return false
|
|
1072
|
-
return this.sources.has(file) || this.resources.has(file)
|
|
1048
|
+
const file = this.#canonicalFileMaybe(url)
|
|
1049
|
+
return file !== undefined && this.formats.get(file) !== 'directory' && (this.sources.has(file) || this.resources.has(file))
|
|
1073
1050
|
}
|
|
1074
1051
|
|
|
1075
1052
|
// --fs <-> bundler-plugin coordination: CAPTURE skips a read a write-mode sidecar already attests,
|
|
@@ -1081,27 +1058,28 @@ export class State {
|
|
|
1081
1058
|
return false
|
|
1082
1059
|
}
|
|
1083
1060
|
|
|
1084
|
-
// getFs*
|
|
1085
|
-
//
|
|
1086
|
-
|
|
1087
|
-
const own = this
|
|
1061
|
+
// getFs* over this State first, then its load-mode sidecars. Only #readSidecars -- write-mode
|
|
1062
|
+
// sidecars only capture.
|
|
1063
|
+
#fromFamily(method, url) {
|
|
1064
|
+
const own = this[method](url)
|
|
1088
1065
|
if (own !== undefined) return own
|
|
1089
|
-
for (const s of this.#readSidecars) {
|
|
1066
|
+
for (const s of this.#readSidecars) {
|
|
1067
|
+
const v = s[method](url)
|
|
1068
|
+
if (v !== undefined) return v
|
|
1069
|
+
}
|
|
1090
1070
|
return undefined
|
|
1091
1071
|
}
|
|
1092
1072
|
|
|
1073
|
+
getFsFileFamily(url) {
|
|
1074
|
+
return this.#fromFamily('getFsFile', url)
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1093
1077
|
getFsStatFamily(url) {
|
|
1094
|
-
|
|
1095
|
-
if (own !== undefined) return own
|
|
1096
|
-
for (const s of this.#readSidecars) { const v = s.getFsStat(url); if (v !== undefined) return v }
|
|
1097
|
-
return undefined
|
|
1078
|
+
return this.#fromFamily('getFsStat', url)
|
|
1098
1079
|
}
|
|
1099
1080
|
|
|
1100
1081
|
getFsDirFamily(url) {
|
|
1101
|
-
|
|
1102
|
-
if (own !== undefined) return own
|
|
1103
|
-
for (const s of this.#readSidecars) { const v = s.getFsDir(url); if (v !== undefined) return v }
|
|
1104
|
-
return undefined
|
|
1082
|
+
return this.#fromFamily('getFsDir', url)
|
|
1105
1083
|
}
|
|
1106
1084
|
|
|
1107
1085
|
getFile(url) {
|
|
@@ -1163,7 +1141,7 @@ export class State {
|
|
|
1163
1141
|
const path = specifier.startsWith('file:') ? fileURLToPath(specifier) : specifier
|
|
1164
1142
|
if (!isAbsolute(path)) return specifier
|
|
1165
1143
|
const fromRoot = relative(this.root, path)
|
|
1166
|
-
if (fromRoot === '' || fromRoot
|
|
1144
|
+
if (fromRoot === '' || relativeEscapes(fromRoot)) return specifier // outside the project root
|
|
1167
1145
|
const rel = relative(dirname(fileURLToPath(parentURL)), path)
|
|
1168
1146
|
return rel.startsWith('.') ? rel : `./${rel}`
|
|
1169
1147
|
}
|
|
@@ -1191,11 +1169,7 @@ export class State {
|
|
|
1191
1169
|
this.#assertAttestedResolution(this.#bundleImports, key, parent, specifier, file, { what: 'observed', source: 'frozen bundle', tolerateUnknown })
|
|
1192
1170
|
}
|
|
1193
1171
|
|
|
1194
|
-
|
|
1195
|
-
const imports = this.imports.get(key)
|
|
1196
|
-
if (!imports.has(parent)) imports.set(parent, new Map())
|
|
1197
|
-
const specifiers = imports.get(parent)
|
|
1198
|
-
noupsert(specifiers, specifier, file)
|
|
1172
|
+
noupsert(nestedMap(nestedMap(this.imports, key), parent), specifier, file)
|
|
1199
1173
|
// upsertFormat, not noupsert: a real format must replace a weak 'stat:*' record from an --fs stat.
|
|
1200
1174
|
if (format) upsertFormat(this.formats, file, format)
|
|
1201
1175
|
}
|
|
@@ -1209,42 +1183,33 @@ export class State {
|
|
|
1209
1183
|
// Static bundles store edges under '*' (Node's condition set is unpredictable); the runtime
|
|
1210
1184
|
// loader records precise conditions, so the specific lookup wins.
|
|
1211
1185
|
let file = this.imports.get(key)?.get(parent)?.get(specifier)
|
|
1212
|
-
if (file === undefined && key !== '*')
|
|
1213
|
-
file = this.imports.get('*')?.get(parent)?.get(specifier)
|
|
1214
|
-
}
|
|
1186
|
+
if (file === undefined && key !== '*') file = this.imports.get('*')?.get(parent)?.get(specifier)
|
|
1215
1187
|
if (file === undefined) {
|
|
1216
1188
|
// The edge may be recorded under a DIFFERENT conditions bucket -- resolveBundled scans every bucket.
|
|
1217
1189
|
if (this.config.loadBundle) {
|
|
1218
1190
|
const abs = this.resolveBundled(parentURL, specifier)
|
|
1219
|
-
if (abs !== undefined) {
|
|
1220
|
-
const f = relative(this.root, abs)
|
|
1221
|
-
return { url: pathToFileURL(abs).toString(), format: this.#loaderFormat(f) }
|
|
1222
|
-
}
|
|
1191
|
+
if (abs !== undefined) return { url: pathToFileURL(abs).toString(), format: this.#loaderFormat(relative(this.root, abs)) }
|
|
1223
1192
|
}
|
|
1224
1193
|
// Node's ERR_MODULE_NOT_FOUND shape, not a bare assert: dynamic-import callers guard on that
|
|
1225
1194
|
// code, which ERR_ASSERTION escapes.
|
|
1226
|
-
|
|
1227
|
-
err.code = 'ERR_MODULE_NOT_FOUND'
|
|
1228
|
-
throw err
|
|
1195
|
+
throw Object.assign(new Error(`Cannot find module '${specifier}' imported from ${parent}`), { code: 'ERR_MODULE_NOT_FOUND' })
|
|
1229
1196
|
}
|
|
1230
1197
|
// A --metro per-platform edge is a { platform: file } Map; plain bundle=load has no platform
|
|
1231
1198
|
// context to pick one, so fail closed rather than feed a Map where a path is expected.
|
|
1232
1199
|
if (typeof file !== 'string') {
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1200
|
+
throw Object.assign(
|
|
1201
|
+
new Error(`Resolution of '${specifier}' from ${parent} is platform-specific (a --metro multi-platform bundle); it can't be loaded by plain node, build a single-platform bundle to load`),
|
|
1202
|
+
{ code: 'ERR_STASIS_PLATFORM_SPECIFIC' })
|
|
1236
1203
|
}
|
|
1237
|
-
|
|
1238
|
-
const format = this.#loaderFormat(file)
|
|
1239
|
-
return { url, format }
|
|
1204
|
+
return { url: pathToFileURL(resolve(this.root, file)).toString(), format: this.#loaderFormat(file) }
|
|
1240
1205
|
}
|
|
1241
1206
|
|
|
1242
1207
|
// Resolve a CJS require() target to a bundled absolute path, or undefined to defer to Node (the
|
|
1243
1208
|
// hooks.js CJS shim needs this: registerHooks can't intercept Module._resolveFilename). Matches
|
|
1244
1209
|
// under ANY conditions bucket, since native require gives none; divergent buckets -> defer.
|
|
1245
1210
|
resolveBundled(parentURL, specifier) {
|
|
1246
|
-
|
|
1247
|
-
|
|
1211
|
+
const parent = this.#canonicalFileMaybe(parentURL)
|
|
1212
|
+
if (parent === undefined) return undefined
|
|
1248
1213
|
const spec = this.#canonicalSpecifier(parentURL, specifier)
|
|
1249
1214
|
const matches = new Set()
|
|
1250
1215
|
for (const [, byParent] of this.imports) {
|
|
@@ -1254,8 +1219,7 @@ export class State {
|
|
|
1254
1219
|
if (matches.size !== 1) return undefined
|
|
1255
1220
|
const [only] = matches
|
|
1256
1221
|
// Per-platform { platform: file } Map (--metro) has no single path: defer to native, not resolve()'s TypeError.
|
|
1257
|
-
|
|
1258
|
-
return resolve(this.root, only)
|
|
1222
|
+
return typeof only === 'string' ? resolve(this.root, only) : undefined
|
|
1259
1223
|
}
|
|
1260
1224
|
|
|
1261
1225
|
// Union of lockfile-attested and live resolutions, so a partial lock=add run extends without
|
|
@@ -1264,14 +1228,10 @@ export class State {
|
|
|
1264
1228
|
const merged = new Map()
|
|
1265
1229
|
const mergeIn = (imports) => {
|
|
1266
1230
|
for (const [conditions, byParent] of imports) {
|
|
1267
|
-
|
|
1268
|
-
const mergedParents = merged.get(conditions)
|
|
1231
|
+
const mergedParents = nestedMap(merged, conditions)
|
|
1269
1232
|
for (const [parent, specifiers] of byParent) {
|
|
1270
|
-
|
|
1271
|
-
const mergedSpecifiers
|
|
1272
|
-
for (const [specifier, file] of specifiers) {
|
|
1273
|
-
noupsert(mergedSpecifiers, specifier, file)
|
|
1274
|
-
}
|
|
1233
|
+
const mergedSpecifiers = nestedMap(mergedParents, parent)
|
|
1234
|
+
for (const [specifier, file] of specifiers) noupsert(mergedSpecifiers, specifier, file)
|
|
1275
1235
|
}
|
|
1276
1236
|
}
|
|
1277
1237
|
}
|
|
@@ -1285,8 +1245,7 @@ export class State {
|
|
|
1285
1245
|
// Union of lockfile-attested and observed formats (+ sidecars'), append-only like #mergedImports,
|
|
1286
1246
|
// except that a weak 'stat:*' is UPGRADED by real content; two real formats stay fatal.
|
|
1287
1247
|
#mergedFormats() {
|
|
1288
|
-
const merged = new Map()
|
|
1289
|
-
if (this.#lockFormats) for (const [file, format] of this.#lockFormats) merged.set(file, format)
|
|
1248
|
+
const merged = new Map(this.#lockFormats ?? [])
|
|
1290
1249
|
for (const [file, format] of this.formats) upsertFormat(merged, file, format)
|
|
1291
1250
|
for (const sidecar of this.#sidecars) {
|
|
1292
1251
|
for (const [file, format] of sidecar.formats) upsertFormat(merged, file, format)
|
|
@@ -1314,7 +1273,7 @@ export class State {
|
|
|
1314
1273
|
return narrowExecutable(this.executable, { modules, formats, scope: this.config.scope })
|
|
1315
1274
|
}
|
|
1316
1275
|
|
|
1317
|
-
get
|
|
1276
|
+
get lockfile() {
|
|
1318
1277
|
const formats = this.#mergedFormats()
|
|
1319
1278
|
return new Lockfile({
|
|
1320
1279
|
config: this.config.values,
|
|
@@ -1323,7 +1282,11 @@ export class State {
|
|
|
1323
1282
|
imports: this.#mergedImports(),
|
|
1324
1283
|
formats,
|
|
1325
1284
|
executable: this.#mergedExecutable(formats),
|
|
1326
|
-
})
|
|
1285
|
+
})
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
get lockData() {
|
|
1289
|
+
return this.lockfile.serialize()
|
|
1327
1290
|
}
|
|
1328
1291
|
|
|
1329
1292
|
// Pair each module's recorded file list with content from perFile, dropping modules with none.
|
|
@@ -1332,15 +1295,10 @@ export class State {
|
|
|
1332
1295
|
for (const [dir, info] of this.modules) {
|
|
1333
1296
|
const files = {}
|
|
1334
1297
|
for (const rel of Object.keys(info.files)) {
|
|
1335
|
-
const
|
|
1336
|
-
const content = perFile.get(file)
|
|
1298
|
+
const content = perFile.get(moduleFileKey(dir, rel))
|
|
1337
1299
|
if (content !== undefined) files[rel] = content
|
|
1338
1300
|
}
|
|
1339
|
-
if (Object.keys(files).length > 0) {
|
|
1340
|
-
modules.set(dir, info.ecosystem === undefined
|
|
1341
|
-
? { name: info.name, version: info.version, files }
|
|
1342
|
-
: { name: info.name, version: info.version, ecosystem: info.ecosystem, files })
|
|
1343
|
-
}
|
|
1301
|
+
if (Object.keys(files).length > 0) modules.set(dir, moduleInfo({ ...info, files }))
|
|
1344
1302
|
}
|
|
1345
1303
|
return modules
|
|
1346
1304
|
}
|
|
@@ -1358,7 +1316,7 @@ export class State {
|
|
|
1358
1316
|
}
|
|
1359
1317
|
|
|
1360
1318
|
// Seed `reason` from an absorbed on-disk bundle so a bundle=add re-run preserves other consumers'
|
|
1361
|
-
// attribution. Called from every absorb site, including the sidecar's
|
|
1319
|
+
// attribution. Called from every absorb site, including the sidecar's.
|
|
1362
1320
|
#seedReasonFromBundle(bundle) {
|
|
1363
1321
|
if (!this.config.writeBundle || bundle.reason === undefined) return
|
|
1364
1322
|
for (const [consumer, files] of Object.entries(bundle.reason)) {
|
|
@@ -1373,8 +1331,7 @@ export class State {
|
|
|
1373
1331
|
// A file run merely fs-READ post-plugin that a plugin also bundles is the plugin's, not run's.
|
|
1374
1332
|
const pluginFiles = new Set()
|
|
1375
1333
|
for (const [who, recorded] of this.#reasonFiles) {
|
|
1376
|
-
if (who
|
|
1377
|
-
for (const file of recorded) pluginFiles.add(file)
|
|
1334
|
+
if (who !== 'run') for (const file of recorded) pluginFiles.add(file)
|
|
1378
1335
|
}
|
|
1379
1336
|
const runOverclaims = (file) =>
|
|
1380
1337
|
this.#fsReadPostPlugin.has(file) && !this.#runImported.has(file) && pluginFiles.has(file)
|
|
@@ -1384,13 +1341,11 @@ export class State {
|
|
|
1384
1341
|
// Sort keys and file lists: the JSON must be byte-reproducible regardless of record order, else
|
|
1385
1342
|
// #emitBundle's compare-and-skip sees spurious diffs.
|
|
1386
1343
|
for (const who of [...this.#reasonFiles.keys()].toSorted()) {
|
|
1387
|
-
const files = []
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
files.push(file)
|
|
1344
|
+
const files = [...this.#reasonFiles.get(who)].filter((file) => inBundle.has(file) && !(who === 'run' && runOverclaims(file)))
|
|
1345
|
+
if (files.length > 0) {
|
|
1346
|
+
reason[who] = files.toSorted(sortPaths)
|
|
1347
|
+
consumers += 1
|
|
1392
1348
|
}
|
|
1393
|
-
if (files.length > 0) { reason[who] = files.toSorted(sortPaths); consumers += 1 }
|
|
1394
1349
|
}
|
|
1395
1350
|
return consumers > 1 ? reason : undefined
|
|
1396
1351
|
}
|
|
@@ -1403,104 +1358,126 @@ export class State {
|
|
|
1403
1358
|
let out = null // copy-on-write: clone only when an entry must be dropped
|
|
1404
1359
|
for (const [file, format] of this.formats) {
|
|
1405
1360
|
if (isStatFormat(format) && merged.get(file) !== format) {
|
|
1406
|
-
|
|
1361
|
+
out ??= new Map(this.formats)
|
|
1407
1362
|
out.delete(file)
|
|
1408
1363
|
}
|
|
1409
1364
|
}
|
|
1410
1365
|
return out ?? this.formats
|
|
1411
1366
|
}
|
|
1412
1367
|
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1368
|
+
#absorbRepo(half, bundle) {
|
|
1369
|
+
this.#absorbedRepos.set(half, this.#absorbedRepos.has(half) ? mergeRepo(this.#absorbedRepos.get(half), bundle.repo) : bundle.repo)
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
get #detectedRepo() {
|
|
1373
|
+
return (this.#detectedRepoCache ??= { value: detectRepo(this.root, this.#host) }).value
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
// `repo` to write for a half: detected, merged with that half's absorbed one when adding to it.
|
|
1377
|
+
#repoFor(half) {
|
|
1378
|
+
if (!this.#absorbedRepos.has(half)) return this.#detectedRepo
|
|
1379
|
+
const absorbed = this.#absorbedRepos.get(half)
|
|
1380
|
+
return absorbed && mergeRepo(absorbed, this.#detectedRepo)
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
// One bundle artifact over `contents` (file -> stored content) with the `formats` it declares;
|
|
1384
|
+
// the code side carries entries/imports, the resources half none.
|
|
1385
|
+
#bundle(half, contents, formats, { entries = this.entries, imports = this.imports } = {}) {
|
|
1421
1386
|
const modules = this.#bundleModules(contents)
|
|
1422
|
-
const formats = this.#formatsForBundle()
|
|
1423
1387
|
return new Bundle({
|
|
1424
1388
|
config: this.config.values,
|
|
1425
|
-
entries
|
|
1389
|
+
entries,
|
|
1426
1390
|
modules,
|
|
1427
1391
|
formats,
|
|
1428
|
-
imports
|
|
1392
|
+
imports,
|
|
1429
1393
|
executable: this.#bundleExecutable(modules, formats),
|
|
1430
1394
|
reason: this.#bundleReason(contents.keys()),
|
|
1395
|
+
repo: this.#repoFor(half),
|
|
1431
1396
|
})
|
|
1432
1397
|
}
|
|
1433
1398
|
|
|
1399
|
+
get sourceBundle() {
|
|
1400
|
+
// One bundle holds code + resources, with `formats` tagging which; the key sets must be
|
|
1401
|
+
// disjoint, asserted so an overlap fails locally rather than silently.
|
|
1402
|
+
const contents = new Map(this.sources)
|
|
1403
|
+
for (const [file, content] of this.resources) {
|
|
1404
|
+
assert.ok(!contents.has(file), `state invariant: file ${file} in both sources and resources`)
|
|
1405
|
+
contents.set(file, content)
|
|
1406
|
+
}
|
|
1407
|
+
return this.#bundle('code', contents, this.#formatsForBundle())
|
|
1408
|
+
}
|
|
1409
|
+
|
|
1434
1410
|
get sourceData() {
|
|
1435
1411
|
return this.sourceBundle.serialize()
|
|
1436
1412
|
}
|
|
1437
1413
|
|
|
1438
1414
|
// Split-bundle counterparts to sourceBundle/sourceData: the code half owns entries/imports + code
|
|
1439
|
-
// formats
|
|
1440
|
-
//
|
|
1415
|
+
// formats (stat records too: they aren't resource formats, so the resources half's shape check
|
|
1416
|
+
// would reject them), the resources half owns resource formats + bytes. Both declare per-dir
|
|
1417
|
+
// module identity so each file verifies alone.
|
|
1441
1418
|
get codeBundle() {
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
const codeFormats = new Map()
|
|
1445
|
-
for (const [file, format] of this.#formatsForBundle()) {
|
|
1446
|
-
if (!Bundle.isResourceFormat(format)) codeFormats.set(file, format)
|
|
1447
|
-
}
|
|
1448
|
-
const modules = this.#bundleModules(this.sources)
|
|
1449
|
-
return new Bundle({
|
|
1450
|
-
config: this.config.values,
|
|
1451
|
-
entries: this.entries,
|
|
1452
|
-
modules,
|
|
1453
|
-
formats: codeFormats,
|
|
1454
|
-
imports: this.imports,
|
|
1455
|
-
executable: this.#bundleExecutable(modules, codeFormats),
|
|
1456
|
-
reason: this.#bundleReason(this.sources.keys()),
|
|
1457
|
-
})
|
|
1419
|
+
const codeFormats = new Map([...this.#formatsForBundle()].filter(([, format]) => !Bundle.isResourceFormat(format)))
|
|
1420
|
+
return this.#bundle('code', this.sources, codeFormats)
|
|
1458
1421
|
}
|
|
1459
1422
|
|
|
1460
1423
|
get resourcesBundle() {
|
|
1461
|
-
const resourceFormats = new Map()
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
}
|
|
1465
|
-
const modules = this.#bundleModules(this.resources)
|
|
1466
|
-
return new Bundle({
|
|
1467
|
-
config: this.config.values,
|
|
1468
|
-
// Resources bundle carries no entries/imports (Bundle.parse waives the entries requirement when no code).
|
|
1469
|
-
entries: new Set(),
|
|
1470
|
-
modules,
|
|
1471
|
-
formats: resourceFormats,
|
|
1472
|
-
imports: new Map(),
|
|
1473
|
-
executable: this.#bundleExecutable(modules, resourceFormats),
|
|
1474
|
-
reason: this.#bundleReason(this.resources.keys()),
|
|
1475
|
-
})
|
|
1424
|
+
const resourceFormats = new Map([...this.formats].filter(([, format]) => Bundle.isResourceFormat(format)))
|
|
1425
|
+
// No entries/imports (Bundle.parse waives the entries requirement when no code).
|
|
1426
|
+
return this.#bundle('resources', this.resources, resourceFormats, { entries: new Set(), imports: new Map() })
|
|
1476
1427
|
}
|
|
1477
1428
|
|
|
1478
1429
|
// Record a native resolution verbatim (last-write-wins per parent+specifier);
|
|
1479
1430
|
// #backfillObservedResolutions decides at write() which to add.
|
|
1480
1431
|
observeResolution(parentURL, specifier, resolvedURL) {
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1432
|
+
nestedMap(this.#observedResolutions, parentURL).set(specifier, resolvedURL)
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
// Record that a require() executed `url` (from the Module._load shim). Out-of-root targets are
|
|
1436
|
+
// skipped like #backfillObservedResolutions' -- the live hooks correctly ignore them too.
|
|
1437
|
+
observeExecution(url) {
|
|
1438
|
+
const file = this.#canonicalFileMaybe(url)
|
|
1439
|
+
if (file !== undefined) this.#executedFiles.add(file)
|
|
1440
|
+
}
|
|
1441
|
+
|
|
1442
|
+
// Whether the bundle carries source bytes for `url` (the hooks' bundle-bypass reconciliation).
|
|
1443
|
+
isBundledSource(url) {
|
|
1444
|
+
const file = this.#canonicalFileMaybe(url)
|
|
1445
|
+
return file !== undefined && this.sources.has(file)
|
|
1446
|
+
}
|
|
1447
|
+
|
|
1448
|
+
// Attest every executed-but-never-captured file from disk. A resolve-only edge stays byte-less
|
|
1449
|
+
// by design (see #backfillBeforeWrite), but an EXECUTED file the load hook never saw is a hole:
|
|
1450
|
+
// leaving it silent would ship an artifact that misses code the run provably evaluated, and a
|
|
1451
|
+
// frozen replay would never verify it. addFile re-checks bytes against the lockfile/bundle in
|
|
1452
|
+
// frozen modes, so tampering still fails the run -- at write time, but loudly.
|
|
1453
|
+
#backfillExecutedFiles() {
|
|
1454
|
+
for (const file of this.#executedFiles) {
|
|
1455
|
+
// "Captured this run", NOT this.hashes: a lockfile-seeded hash must still be VERIFIED
|
|
1456
|
+
// against disk here when the run executed the file without the load hook observing it.
|
|
1457
|
+
if (this.#filesCapturedThisRun.has(file)) continue
|
|
1458
|
+
// A require()d native addon never passes the load hook and is deliberately not captured
|
|
1459
|
+
// (non-deterministic across installs, like the rest of NATIVE_ARTIFACT_EXTS).
|
|
1460
|
+
if (isNativeArtifact(file)) continue
|
|
1461
|
+
const url = pathToFileURL(resolve(this.root, file)).toString()
|
|
1462
|
+
if (!this.config.full && !this.inNodeModules(url)) continue
|
|
1463
|
+
this.addFile(url, { reason: 'run' })
|
|
1464
|
+
}
|
|
1484
1465
|
}
|
|
1485
1466
|
|
|
1486
1467
|
// Backfill edges the live resolve hook never observed (require.resolve()/native CJS require()).
|
|
1487
1468
|
// The resolution is attested but its bytes are NOT seeded -- that would widen trust to everything
|
|
1488
1469
|
// that merely resolves. Skips out-of-scope targets and dedups across all condition buckets.
|
|
1489
1470
|
#backfillObservedResolutions() {
|
|
1490
|
-
if (this.#observedResolutions.size === 0) return
|
|
1491
1471
|
for (const [parentURL, specs] of this.#observedResolutions) {
|
|
1492
|
-
|
|
1493
|
-
|
|
1472
|
+
const parent = this.#canonicalFileMaybe(parentURL)
|
|
1473
|
+
if (parent === undefined) continue
|
|
1494
1474
|
for (const [specifier, resolvedURL] of specs) {
|
|
1495
|
-
|
|
1496
|
-
|
|
1475
|
+
const file = this.#canonicalFileMaybe(resolvedURL)
|
|
1476
|
+
if (file === undefined) continue
|
|
1497
1477
|
const bundled = this.sources.has(file) || this.resources.has(file)
|
|
1498
1478
|
if (!bundled && !this.config.full && !this.inNodeModules(resolvedURL)) continue
|
|
1499
1479
|
const spec = this.#canonicalSpecifier(parentURL, specifier)
|
|
1500
|
-
|
|
1501
|
-
for (const [, byParent] of this.imports) {
|
|
1502
|
-
if (byParent.get(parent)?.get(spec) !== undefined) { recorded = true; break }
|
|
1503
|
-
}
|
|
1480
|
+
const recorded = this.imports.values().some((byParent) => byParent.get(parent)?.get(spec) !== undefined)
|
|
1504
1481
|
if (!recorded) this.addImport(parentURL, specifier, resolvedURL, { conditions: this.#requireConditions ?? '*' })
|
|
1505
1482
|
}
|
|
1506
1483
|
}
|
|
@@ -1512,22 +1489,29 @@ export class State {
|
|
|
1512
1489
|
// reference across sidecars).
|
|
1513
1490
|
includePackageJson() {
|
|
1514
1491
|
// Gather first: addFile mutates this.modules, so don't addFile while iterating it.
|
|
1515
|
-
const realRoot =
|
|
1492
|
+
const realRoot = this.#host.realpath(this.root)
|
|
1516
1493
|
const toAdd = []
|
|
1517
1494
|
for (const [dir, module] of this.modules) {
|
|
1518
1495
|
const rel = moduleFileKey(dir, 'package.json')
|
|
1519
1496
|
if (this.sources.has(rel) || this.resources.has(rel)) continue // already in this bundle
|
|
1520
|
-
const buf = readModuleManifest({ baseDir: this.root, realBase: realRoot, rel })
|
|
1497
|
+
const buf = readModuleManifest({ baseDir: this.root, realBase: realRoot, rel, host: this.#host })
|
|
1521
1498
|
if (!buf) continue
|
|
1522
1499
|
// Only carry a manifest whose on-disk identity still matches the bundled bucket: under
|
|
1523
1500
|
// bundle=add a dep may have drifted, and addFile -> #locateModule would crash on it.
|
|
1524
1501
|
let pkg
|
|
1525
1502
|
try { pkg = JSON.parse(buf.toString()) } catch { continue } // malformed manifest for an untouched bucket: skip
|
|
1526
1503
|
if (pkg?.name !== module.name || pkg?.version !== module.version) continue
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1504
|
+
// The manifest rides along BECAUSE some consumer bundled the bucket, so it inherits every
|
|
1505
|
+
// consumer that recorded a file of the bucket -- nothing observed the manifest itself, but an
|
|
1506
|
+
// unattributed file can't be sorted by provenance downstream. Derived BEFORE the adds below,
|
|
1507
|
+
// so one fold's manifest can't count as another bucket's consumer evidence.
|
|
1508
|
+
const files = Object.keys(module.files)
|
|
1509
|
+
const consumers = [...this.#reasonFiles].filter(([, recorded]) => files.some((f) => recorded.has(moduleFileKey(dir, f)))).map(([who]) => who)
|
|
1510
|
+
toAdd.push({ rel, buf, consumers })
|
|
1511
|
+
}
|
|
1512
|
+
for (const { rel, buf, consumers } of toAdd) {
|
|
1530
1513
|
this.addFile(pathToFileURL(resolve(this.root, rel)).toString(), { source: buf, reason: null })
|
|
1514
|
+
for (const who of consumers) this.#recordReason(who, rel)
|
|
1531
1515
|
}
|
|
1532
1516
|
}
|
|
1533
1517
|
|
|
@@ -1535,11 +1519,12 @@ export class State {
|
|
|
1535
1519
|
// BEFORE the stasis-core BFS: a resolve-only edge to a stasis-core submodule is added only here,
|
|
1536
1520
|
// and the BFS must see it to seed the file's bytes, else the bundle ships a dangling edge.
|
|
1537
1521
|
this.#backfillObservedResolutions()
|
|
1522
|
+
this.#backfillExecutedFiles()
|
|
1538
1523
|
this.#backfillBeforeWrite()
|
|
1539
1524
|
// AFTER the backfills, so buckets they create are covered too.
|
|
1540
1525
|
if (this.config.writeBundle && this.config.packageJSON) this.includePackageJson()
|
|
1541
|
-
// Sidecars never write the lockfile (parent owns it); they only emit their bundle.
|
|
1542
1526
|
|
|
1527
|
+
// Sidecars never write the lockfile (parent owns it); they only emit their bundle.
|
|
1543
1528
|
if (this.config.writeLockfile && !this.#parent) {
|
|
1544
1529
|
const lockText = this.lockData
|
|
1545
1530
|
if (lockText !== this.#lastLockData) {
|
|
@@ -1553,15 +1538,10 @@ export class State {
|
|
|
1553
1538
|
const sourcesPath = this.config.bundleFile || join(this.root, FILE_CODE)
|
|
1554
1539
|
if (this.config.resourcesBundleFile) {
|
|
1555
1540
|
// hasContent gates each half so an empty one is dropped under bundle=replace.
|
|
1556
|
-
this.#lastCodeBundle = this.#emitBundle(
|
|
1557
|
-
|
|
1558
|
-
this.#lastResourcesBundle = this.#emitBundle(
|
|
1559
|
-
this.config.resourcesBundleFile, this.resources.size > 0, this.#lastResourcesBundle,
|
|
1560
|
-
() => this.resourcesBundle.serialize())
|
|
1541
|
+
this.#lastCodeBundle = this.#emitBundle(sourcesPath, this.sources.size > 0, this.#lastCodeBundle, () => this.codeBundle.serialize())
|
|
1542
|
+
this.#lastResourcesBundle = this.#emitBundle(this.config.resourcesBundleFile, this.resources.size > 0, this.#lastResourcesBundle, () => this.resourcesBundle.serialize())
|
|
1561
1543
|
} else {
|
|
1562
|
-
this.#lastUnifiedBundle = this.#emitBundle(
|
|
1563
|
-
sourcesPath, this.sources.size > 0 || this.resources.size > 0, this.#lastUnifiedBundle,
|
|
1564
|
-
() => this.sourceData)
|
|
1544
|
+
this.#lastUnifiedBundle = this.#emitBundle(sourcesPath, this.sources.size > 0 || this.resources.size > 0, this.#lastUnifiedBundle, () => this.sourceData)
|
|
1565
1545
|
}
|
|
1566
1546
|
}
|
|
1567
1547
|
}
|
|
@@ -1570,6 +1550,7 @@ export class State {
|
|
|
1570
1550
|
// omitted -- the root re-reads bytes from disk.
|
|
1571
1551
|
shardSnapshot() {
|
|
1572
1552
|
this.#backfillObservedResolutions()
|
|
1553
|
+
this.#backfillExecutedFiles()
|
|
1573
1554
|
this.#backfillBeforeWrite()
|
|
1574
1555
|
// Only what THIS process observed, never the seeded baseline (shard-size bloat). Entries are
|
|
1575
1556
|
// dropped: a child's "entry" is its fork target, not a root's.
|
|
@@ -1583,12 +1564,9 @@ export class State {
|
|
|
1583
1564
|
// Only edges whose PARENT was observed, dropping the bundle-seeded ones the root already attests.
|
|
1584
1565
|
const imports = new Map()
|
|
1585
1566
|
for (const [conditions, byParent] of this.imports) {
|
|
1586
|
-
let kept
|
|
1587
1567
|
for (const parent of this.#observed) {
|
|
1588
1568
|
const specs = byParent.get(parent)
|
|
1589
|
-
if (specs
|
|
1590
|
-
if (kept === undefined) imports.set(conditions, (kept = new Map()))
|
|
1591
|
-
kept.set(parent, specs)
|
|
1569
|
+
if (specs !== undefined) nestedMap(imports, conditions).set(parent, specs)
|
|
1592
1570
|
}
|
|
1593
1571
|
}
|
|
1594
1572
|
return serializeShard({ scope: this.config.scope, files, formats, imports })
|
|
@@ -1611,8 +1589,7 @@ export class State {
|
|
|
1611
1589
|
}
|
|
1612
1590
|
let real
|
|
1613
1591
|
try { real = realpathSync(absolute) } catch { return false }
|
|
1614
|
-
|
|
1615
|
-
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
|
|
1592
|
+
return isPathWithin(realRoot, real)
|
|
1616
1593
|
}
|
|
1617
1594
|
// Files first, then edges. Merged files are NEVER marked entries -- a child's "entry" is its
|
|
1618
1595
|
// fork-target main, not a root entry.
|
|
@@ -1626,17 +1603,13 @@ export class State {
|
|
|
1626
1603
|
this.#recordExecutable(file, absolute)
|
|
1627
1604
|
// Skip a file the root already attests (the byte re-read dominates merge cost), EXCEPT to
|
|
1628
1605
|
// carry a concrete format the root LACKS, else a later frozen run rejects the unattested format.
|
|
1629
|
-
if (this.hashes.has(file)) {
|
|
1630
|
-
const shardFormat = shard.formats.get(file)
|
|
1631
|
-
if (shardFormat === undefined || (this.formats.get(file) ?? this.#lockFormats?.get(file)) !== undefined) continue
|
|
1632
|
-
}
|
|
1633
|
-
const url = pathToFileURL(absolute).toString()
|
|
1634
1606
|
const format = shard.formats.get(file)
|
|
1607
|
+
if (this.hashes.has(file) && (format === undefined || (this.formats.get(file) ?? this.#lockFormats?.get(file)) !== undefined)) continue
|
|
1608
|
+
const url = pathToFileURL(absolute).toString()
|
|
1635
1609
|
try {
|
|
1636
1610
|
if (format === 'directory') {
|
|
1637
1611
|
// Range-check FIRST so a child-forged `..` key can't make us list it.
|
|
1638
|
-
|
|
1639
|
-
if (relFromRoot.startsWith('..') || isAbsolute(relFromRoot)) continue
|
|
1612
|
+
if (!isPathWithin(this.root, absolute)) continue
|
|
1640
1613
|
this.addFsDir(url, readdirSync(absolute))
|
|
1641
1614
|
} else if (format === 'resource' || format === 'resource:base64') {
|
|
1642
1615
|
// Let addFile re-derive the exact resource tag from the re-read bytes rather than trusting
|
|
@@ -1660,17 +1633,15 @@ export class State {
|
|
|
1660
1633
|
for (const [file, format] of shard.formats) {
|
|
1661
1634
|
if (!isStatFormat(format)) continue
|
|
1662
1635
|
const absolute = resolve(this.root, file)
|
|
1663
|
-
|
|
1664
|
-
if (relFromRoot.startsWith('..') || isAbsolute(relFromRoot)) continue
|
|
1636
|
+
if (!isPathWithin(this.root, absolute)) continue
|
|
1665
1637
|
try {
|
|
1666
1638
|
// statSync, NOT lstatSync: the child's capture followed symlinks, so this reproduces the kind
|
|
1667
1639
|
// a legitimate shard carries where lstatSync would report the link and drop it.
|
|
1668
1640
|
const stats = statSync(absolute)
|
|
1669
1641
|
const kind = stats.isDirectory() ? 'directory' : stats.isFile() ? 'file' : null
|
|
1670
|
-
if (kind === null) continue
|
|
1671
1642
|
// statSync follows links: a symlink pointing OUT must not attest an external kind under an
|
|
1672
1643
|
// in-root key.
|
|
1673
|
-
if (!realContained(absolute)) continue
|
|
1644
|
+
if (kind === null || !realContained(absolute)) continue
|
|
1674
1645
|
this.addFsStat(pathToFileURL(absolute).toString(), kind)
|
|
1675
1646
|
} catch {
|
|
1676
1647
|
// Gone/dangling, or a kind conflict with the root's capture: skip.
|
|
@@ -1687,15 +1658,12 @@ export class State {
|
|
|
1687
1658
|
try { importAttributes = JSON.parse(conditions.slice(withAt + ' (with: '.length, -1)) } catch { /* leave undefined */ }
|
|
1688
1659
|
}
|
|
1689
1660
|
const cond = condStr === '*' ? '*' : condStr.split(', ')
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1661
|
+
for (const [parent, specs] of byParent) {
|
|
1662
|
+
const parentURL = pathToFileURL(resolve(this.root, parent)).toString()
|
|
1663
|
+
for (const [specifier, file] of specs) {
|
|
1693
1664
|
const url = pathToFileURL(resolve(this.root, file)).toString()
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
} catch {
|
|
1697
|
-
// Same best-effort stance as addFile above.
|
|
1698
|
-
}
|
|
1665
|
+
// Same best-effort stance as addFile above.
|
|
1666
|
+
try { this.addImport(parentURL, specifier, url, { conditions: cond, importAttributes }) } catch { /* skipped */ }
|
|
1699
1667
|
}
|
|
1700
1668
|
}
|
|
1701
1669
|
}
|
|
@@ -1712,9 +1680,8 @@ export class State {
|
|
|
1712
1680
|
if (text !== lastText) {
|
|
1713
1681
|
mkdirSync(dirname(path), { recursive: true })
|
|
1714
1682
|
writeFileSync(path, brotliCompressSync(text, brotliOptions(this.config.brotliQuality)))
|
|
1715
|
-
return text
|
|
1716
1683
|
}
|
|
1717
|
-
return
|
|
1684
|
+
return text
|
|
1718
1685
|
}
|
|
1719
1686
|
|
|
1720
1687
|
get parent() {
|
|
@@ -1736,9 +1703,7 @@ export class State {
|
|
|
1736
1703
|
if (stasisCoreMissing.length === 0) return
|
|
1737
1704
|
|
|
1738
1705
|
const preloadRel = this.#preloadRoot ? relative(this.root, this.#preloadRoot) : null
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
assert.ok(canBackfill,
|
|
1706
|
+
assert.ok(preloadRel !== null && !relativeEscapes(preloadRel),
|
|
1742
1707
|
`state.write() has imports referencing un-captured stasis-core files but no usable preloadRoot ` +
|
|
1743
1708
|
`(preloadRoot=${this.#preloadRoot ?? 'unset'}). The live load hook missed an in-scope target -- ` +
|
|
1744
1709
|
`investigate rather than silently patch: ${stasisCoreMissing.slice(0, 3).join(', ')}`)
|
|
@@ -1748,16 +1713,15 @@ export class State {
|
|
|
1748
1713
|
assert.ok(isStasisCoreFile(file),
|
|
1749
1714
|
`state.write() backfill refused: '${file}' is not a stasis-core source file ` +
|
|
1750
1715
|
`(expected '.../@exodus/stasis-core/src/<name>.js')`)
|
|
1751
|
-
|
|
1716
|
+
// reason 'run': Node evaluated these before registerHooks could observe it (that blindness is
|
|
1717
|
+
// why this backfill exists), so they're run-loaded modules like any other. A consumer-less
|
|
1718
|
+
// record can't be sorted by provenance downstream (app code vs toolchain).
|
|
1719
|
+
this.addFile(pathToFileURL(resolve(this.root, file)).toString(), { reason: 'run' })
|
|
1752
1720
|
}
|
|
1753
1721
|
|
|
1754
1722
|
// Seeded from the missing files + every stasis-core file already in sources, to walk their
|
|
1755
1723
|
// transitive imports too.
|
|
1756
|
-
const queue = [...stasisCoreMissing]
|
|
1757
|
-
for (const file of this.sources.keys()) {
|
|
1758
|
-
if (isStasisCoreFile(file)) queue.push(file)
|
|
1759
|
-
}
|
|
1760
|
-
|
|
1724
|
+
const queue = [...stasisCoreMissing, ...[...this.sources.keys()].filter(isStasisCoreFile)]
|
|
1761
1725
|
const processed = new Set()
|
|
1762
1726
|
while (queue.length > 0) {
|
|
1763
1727
|
const file = queue.shift()
|
|
@@ -1772,8 +1736,7 @@ export class State {
|
|
|
1772
1736
|
const targetAbsolute = fileURLToPath(targetURL)
|
|
1773
1737
|
let targetFile
|
|
1774
1738
|
try { targetFile = this.relative(targetAbsolute) } catch { return }
|
|
1775
|
-
if (!isStasisCoreFile(targetFile)) return
|
|
1776
|
-
if (!existsSync(targetAbsolute)) return
|
|
1739
|
+
if (!isStasisCoreFile(targetFile) || !existsSync(targetAbsolute)) return
|
|
1777
1740
|
queue.push(targetFile)
|
|
1778
1741
|
this.addImport(baseURL, specifier, targetURL, { conditions: PRELOAD_CONDITIONS })
|
|
1779
1742
|
}
|
|
@@ -1791,8 +1754,7 @@ export class State {
|
|
|
1791
1754
|
for (const [, byParent] of this.imports) {
|
|
1792
1755
|
for (const [, specifiers] of byParent) {
|
|
1793
1756
|
for (const [, file] of specifiers) {
|
|
1794
|
-
if (typeof file !== 'string') continue
|
|
1795
|
-
if (missing.has(file)) continue
|
|
1757
|
+
if (typeof file !== 'string' || missing.has(file)) continue
|
|
1796
1758
|
if (this.hashes.has(file) || this.sources.has(file) || this.resources.has(file)) continue
|
|
1797
1759
|
const url = pathToFileURL(resolve(this.root, file)).toString()
|
|
1798
1760
|
if (!this.config.full && !this.inNodeModules(url)) continue
|
|
@@ -1807,4 +1769,3 @@ export class State {
|
|
|
1807
1769
|
// Backfillable stasis-core paths. Anchored against `/${file}` so a project-root file merely ending
|
|
1808
1770
|
// in `@exodus/stasis-core/...` isn't matched.
|
|
1809
1771
|
const STASIS_CORE_FILE_RE = /\/@exodus\/stasis-core\/(?:src\/[a-zA-Z-]+\.c?js|package\.json)$/
|
|
1810
|
-
|