packstruct 0.9.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/lint.mjs CHANGED
@@ -9,61 +9,206 @@
9
9
  // (crashtest `fc93ca6` src/packs/loader.js:389-391) at author time.
10
10
  // PROBE ONLY: host module-shape norms stay host-owned (SPEC section 3) -
11
11
  // deep censes ids, it does not police the host's contract shapes.
12
- import { readFileSync, existsSync, readdirSync } from 'node:fs'
13
- import { join, resolve } from 'node:path'
12
+ import { readFileSync, existsSync, readdirSync, statSync, realpathSync } from 'node:fs'
13
+ import { join, resolve, relative, isAbsolute, dirname, basename, sep } from 'node:path'
14
14
  import { pathToFileURL } from 'node:url'
15
+ import { runCapped } from './run-capped.mjs'
15
16
 
16
- export function lintPacks(dir) {
17
+ const LANES = ['public', 'local']
18
+
19
+ // The wrong-argument lane (packstruct#13, #17): the packs ROOT is the
20
+ // argument, but the natural first-time gestures - the `public/` dir itself
21
+ // (that is exactly what the tree shows), one pack dir, the repo root - all
22
+ // produced the same doubled-segment `directory-contract` nonsense that
23
+ // blames the hypothetical packs under the arg instead of naming the fix.
24
+ // Those shapes answer with a `usage` hint naming the probable intent; a
25
+ // genuinely empty root still refuses `directory-contract` (the refusal
26
+ // matrix's missing-public-dir row depends on it).
27
+ function wrongArgHint(dir) {
28
+ const abs = resolve(dir)
29
+ if (existsSync(join(abs, 'pack.json'))) {
30
+ const parent = dirname(dir)
31
+ const root = /(^|[\\/])(public|local)$/.test(parent) ? dirname(parent) : parent
32
+ return `'${dir}' looks like a single pack (pack.json found inside) - pass the packs ROOT (the parent of public/), for example: packstruct lint ${root}`
33
+ }
34
+ let isFile = false
35
+ try { isFile = statSync(abs).isFile() } catch { /* missing path: the caller's existence check owns it */ }
36
+ if (isFile) {
37
+ return `'${dir}' is a file - pass the packs ROOT (the directory whose public/ holds the packs), for example: packstruct lint ${dirname(dir)}`
38
+ }
39
+ if (/(^|[\\/])(public|local)[\\/]?$/.test(String(dir))) {
40
+ const lane = basename(abs)
41
+ return `'${dir}' looks like a ${lane}/ directory itself - pass the packs ROOT (the parent of ${lane}/), for example: packstruct lint ${dirname(dir)}`
42
+ }
43
+ if (existsSync(join(abs, 'packs'))) {
44
+ return `'${dir}' looks like a repo root - the packs live in packs/, try: packstruct lint ${join(dir, 'packs')}`
45
+ }
46
+ return null
47
+ }
48
+
49
+ // Is `entry` a relative path that STAYS INSIDE `packDir` (SPEC section 2)?
50
+ // The old check was a `..` substring proxy: it false-refused a legitimate
51
+ // filename like `a..b.js`, yet PASSED an absolute path (`/index.js`), which
52
+ // node's `join` silently re-roots inside the pack (so shallow said clean)
53
+ // while `resolve` (the deep probe) treated as `/index.js` and refused - the
54
+ // two passes disagreed on the same manifest. Containment is a real test:
55
+ // reject non-strings, NUL, and absolute paths (POSIX or Windows-drive), then
56
+ // resolve against the pack dir and require the result to stay under it.
57
+ function entryEscape(packDir, entry) {
58
+ if (typeof entry !== 'string' || !entry.trim()) return true
59
+ if (entry.includes('\0')) return true
60
+ if (entry.startsWith('/') || entry.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(entry)) return true
61
+ const abs = resolve(packDir, entry)
62
+ const rel = relative(packDir, abs)
63
+ return rel === '' || rel === '..' || rel.startsWith('..' + sep) || isAbsolute(rel)
64
+ }
65
+
66
+ // Lexical containment is not enough: a SYMLINK whose target lives outside
67
+ // the pack passes the string test yet loads code from elsewhere (a silent
68
+ // success, worse than a shallow/deep split). Compare the PHYSICAL paths -
69
+ // both sides realpath'd, so a symlinked ancestor of packDir itself (macOS
70
+ // /tmp -> /private/tmp, a vendored packs/ link) does not false-refuse. Only
71
+ // called once the entry exists as a file, so realpathSync has a target;
72
+ // an unresolvable path here is the existence check's business, not ours.
73
+ function entryEscapesViaLink(packDir, entry) {
74
+ let realPack, realEntry
75
+ try {
76
+ realPack = realpathSync(packDir)
77
+ realEntry = realpathSync(join(packDir, entry))
78
+ } catch { return false }
79
+ const rel = relative(realPack, realEntry)
80
+ return rel === '..' || rel.startsWith('..' + sep) || isAbsolute(rel)
81
+ }
82
+
83
+ // Manifest validation for ONE pack dir (SPEC v1 section 2). Returns the
84
+ // violations plus whether the pack counted as checked (a pack.json exists).
85
+ // The caller tags lane and tallies; the checks never learn which lane they
86
+ // run in - public and local packs obey the same frozen manifest contract.
87
+ //
88
+ // `warnings` (SPEC v1.1 section 2) are advisory rows: they never redden a
89
+ // run, never change the exit code, and are reported separately from
90
+ // violations. The first warning shape is `implements` format.
91
+ function manifestViolations(packDir, name) {
92
+ const violations = []
93
+ const warnings = []
94
+ const manifestPath = join(packDir, 'pack.json')
95
+ if (!existsSync(manifestPath)) {
96
+ return { checked: false, violations: [{ pack: name, norm: 'manifest-missing', message: 'pack.json missing' }], warnings }
97
+ }
98
+ let m
99
+ try { m = JSON.parse(readFileSync(manifestPath, 'utf8')) } catch (e) {
100
+ return { checked: true, violations: [{ pack: name, norm: 'manifest-invalid', message: `pack.json is not valid JSON: ${e.message}` }], warnings }
101
+ }
102
+ if (m.schemaVersion !== 1) violations.push({ pack: name, norm: 'schemaVersion', message: `schemaVersion must be 1 (got ${JSON.stringify(m.schemaVersion)})` })
103
+ if (typeof m.name !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(m.name)) violations.push({ pack: name, norm: 'name-kebab-case', message: `name must be kebab-case (got ${JSON.stringify(m.name)})` })
104
+ if (m.name !== name) violations.push({ pack: name, norm: 'name-dir-match', message: `name "${m.name}" does not match its directory "${name}"` })
105
+ if (typeof m.version !== 'string' || !/^\d+\.\d+(\.\d+)?$/.test(m.version)) violations.push({ pack: name, norm: 'version', message: `version must be dotted MAJOR.MINOR[.PATCH] (got ${JSON.stringify(m.version)})` })
106
+ if (typeof m.description !== 'string' || !m.description.trim()) violations.push({ pack: name, norm: 'description', message: 'description missing or empty' })
107
+ if (entryEscape(packDir, m.entry)) {
108
+ violations.push({ pack: name, norm: 'entry', message: `entry must be a relative path inside the pack (got ${JSON.stringify(m.entry)})` })
109
+ } else {
110
+ // MUST exist AND be a file: SPEC §3 says an entry is an ES module, so a
111
+ // path that is a directory is not one. Checking existence alone let a
112
+ // directory entry pass shallow while the deep probe's import refused it -
113
+ // the same shallow/deep disagreement the containment fix closed.
114
+ let entryStat = null
115
+ try { entryStat = statSync(join(packDir, m.entry)) } catch { /* absent */ }
116
+ if (!entryStat) {
117
+ violations.push({ pack: name, norm: 'entry', message: `entry file "${m.entry}" does not exist - instant refusal at load time (the crashtest#16 class)` })
118
+ } else if (!entryStat.isFile()) {
119
+ violations.push({ pack: name, norm: 'entry', message: `entry "${m.entry}" is not a file - an entry is an ES module (SPEC section 3)` })
120
+ } else if (entryEscapesViaLink(packDir, m.entry)) {
121
+ violations.push({ pack: name, norm: 'entry', message: `entry "${m.entry}" is a symlink resolving OUTSIDE the pack - the manifest path is contained, but the physical target is not (SPEC section 2)` })
122
+ }
123
+ }
124
+ // armedByKey: OPTIONAL string. Type-checked only - an EMPTY value is
125
+ // "present, not yet armed" and the host owns presence semantics
126
+ // (folded from crashtest#25: our non-empty refusal was a check the
127
+ // SPEC didn't promise; the engine treats empty as valid).
128
+ if (m.armedByKey !== undefined && typeof m.armedByKey !== 'string') {
129
+ violations.push({ pack: name, norm: 'armedByKey', message: `armedByKey, when present, must be a string (got ${typeof m.armedByKey})` })
130
+ }
131
+ // implements (SPEC v1.1 section 2): OPTIONAL host-owned acknowledgement of
132
+ // the spec the pack builds against, formatted `packstruct@<MAJOR>` or an
133
+ // exact `packstruct@1.0.0`. FORMAT ONLY, and format drift is a WARNING,
134
+ // never a refusal - absence is the quiet default and never colors a
135
+ // verdict (the row's own cost-to-host: none).
136
+ if (m.implements !== undefined && (typeof m.implements !== 'string' || !/^packstruct@\d+(\.\d+){0,2}$/.test(m.implements))) {
137
+ warnings.push({ pack: name, norm: 'implements', message: `implements, when present, should be "packstruct@<major>" or an exact pin like "packstruct@1.0.0" (got ${JSON.stringify(m.implements)}) - advisory only, never a refusal` })
138
+ }
139
+ // armedCoverage (packstruct#27, optional assist): a declared claim that
140
+ // this pack lane has an armed end-to-end row (a test file that simulates
141
+ // its target with the vocabulary armed). The lint CONFIRMS the declared
142
+ // file exists - it never runs the row (runs are the host's business).
143
+ // A declared claim that names a file that isn't there is the vacuous-green
144
+ // class this key exists to make loud; an absent key is the quiet default.
145
+ if (m.armedCoverage !== undefined) {
146
+ if (entryEscape(packDir, m.armedCoverage)) {
147
+ violations.push({ pack: name, norm: 'armed-coverage', message: `armedCoverage, when present, must be a relative path inside the pack (got ${JSON.stringify(m.armedCoverage)})` })
148
+ } else if (!existsSync(join(packDir, m.armedCoverage))) {
149
+ violations.push({ pack: name, norm: 'armed-coverage', message: `armedCoverage declares "${m.armedCoverage}" but that file does not ship - the declared armed row is vacuous (packstruct#27)` })
150
+ } else if (entryEscapesViaLink(packDir, m.armedCoverage)) {
151
+ violations.push({ pack: name, norm: 'armed-coverage', message: `armedCoverage "${m.armedCoverage}" is a symlink resolving OUTSIDE the pack - the declared row is not the pack's own (SPEC section 2)` })
152
+ }
153
+ }
154
+ return { checked: true, violations, warnings }
155
+ }
156
+
157
+ // List the pack directories of one lane (<root>/<lane>/<name>/). Anything
158
+ // that is not a directory is skipped, as the public lane always has been.
159
+ function lanePackDirs(dir, lane) {
160
+ const laneDir = join(dir, lane)
161
+ if (!existsSync(laneDir)) return []
162
+ const out = []
163
+ for (const name of readdirSync(laneDir).sort()) {
164
+ try { readdirSync(join(laneDir, name)) } catch { continue }
165
+ out.push({ name, packDir: join(laneDir, name) })
166
+ }
167
+ return out
168
+ }
169
+
170
+ // opts.local (packstruct#16): opt-in, contract-preserving. The v1 default
171
+ // stays public-only; `--local` also lints the gitignored WIP lane every
172
+ // consumer repo keeps. Local violations carry `lane: 'local'` so a CI
173
+ // consumer can tell the lanes apart; public rows stay byte-identical.
174
+ export function lintPacks(dir, opts = {}) {
17
175
  const violations = []
176
+ const warnings = []
18
177
  let packsChecked = 0
178
+ let localChecked = 0
19
179
  if (!existsSync(dir)) {
20
- return { packsChecked, violations: [{ pack: dir, norm: 'usage', message: `no such directory: ${dir}` }] }
180
+ return { packsChecked, localChecked, violations: [{ pack: dir, norm: 'usage', message: `no such directory: ${dir}` }], warnings }
21
181
  }
22
182
  // Section 1 contract: packs live at <packs-root>/public/<name>/
23
183
  const publicDir = join(dir, 'public')
24
184
  if (!existsSync(publicDir)) {
25
- return { packsChecked, violations: [{ pack: dir, norm: 'directory-contract', message: `missing ${dir}/public/ - packs live at <packs-root>/public/<name>/` }] }
26
- }
27
- for (const name of readdirSync(publicDir).sort()) {
28
- const packDir = join(publicDir, name)
29
- let isDir = true
30
- try { readdirSync(packDir) } catch { isDir = false }
31
- if (!isDir) continue
32
- const manifestPath = join(packDir, 'pack.json')
33
- if (!existsSync(manifestPath)) {
34
- violations.push({ pack: name, norm: 'manifest-missing', message: 'pack.json missing' })
35
- continue
36
- }
37
- packsChecked++
38
- let m
39
- try { m = JSON.parse(readFileSync(manifestPath, 'utf8')) } catch (e) {
40
- violations.push({ pack: name, norm: 'manifest-invalid', message: `pack.json is not valid JSON: ${e.message}` })
41
- continue
42
- }
43
- if (m.schemaVersion !== 1) violations.push({ pack: name, norm: 'schemaVersion', message: `schemaVersion must be 1 (got ${JSON.stringify(m.schemaVersion)})` })
44
- if (typeof m.name !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(m.name)) violations.push({ pack: name, norm: 'name-kebab-case', message: `name must be kebab-case (got ${JSON.stringify(m.name)})` })
45
- if (m.name !== name) violations.push({ pack: name, norm: 'name-dir-match', message: `name "${m.name}" does not match its directory "${name}"` })
46
- if (typeof m.version !== 'string' || !/^\d+\.\d+(\.\d+)?$/.test(m.version)) violations.push({ pack: name, norm: 'version', message: `version must be dotted MAJOR.MINOR[.PATCH] (got ${JSON.stringify(m.version)})` })
47
- if (typeof m.description !== 'string' || !m.description.trim()) violations.push({ pack: name, norm: 'description', message: 'description missing or empty' })
48
- if (typeof m.entry !== 'string' || !m.entry.trim() || m.entry.includes('..')) {
49
- violations.push({ pack: name, norm: 'entry', message: `entry must be a relative path inside the pack (got ${JSON.stringify(m.entry)})` })
50
- } else if (!existsSync(join(packDir, m.entry))) {
51
- violations.push({ pack: name, norm: 'entry', message: `entry file "${m.entry}" does not exist - instant refusal at load time (the crashtest#16 class)` })
52
- }
53
- // armedByKey: OPTIONAL string. Type-checked only - an EMPTY value is
54
- // "present, not yet armed" and the host owns presence semantics
55
- // (folded from crashtest#25: our non-empty refusal was a check the
56
- // SPEC didn't promise; the engine treats empty as valid).
57
- if (m.armedByKey !== undefined && typeof m.armedByKey !== 'string') {
58
- violations.push({ pack: name, norm: 'armedByKey', message: `armedByKey, when present, must be a string (got ${typeof m.armedByKey})` })
185
+ const hint = wrongArgHint(dir)
186
+ if (hint) return { packsChecked, localChecked, violations: [{ pack: dir, norm: 'usage', message: hint }], warnings }
187
+ return { packsChecked, localChecked, violations: [{ pack: dir, norm: 'directory-contract', message: `missing ${dir}/public/ - packs live at <packs-root>/public/<name>/` }], warnings }
188
+ }
189
+ for (const { name, packDir } of lanePackDirs(dir, 'public')) {
190
+ const r = manifestViolations(packDir, name)
191
+ if (r.checked) packsChecked++
192
+ violations.push(...r.violations)
193
+ warnings.push(...r.warnings)
194
+ }
195
+ if (opts.local) {
196
+ for (const { name, packDir } of lanePackDirs(dir, 'local')) {
197
+ const r = manifestViolations(packDir, name)
198
+ if (r.checked) localChecked++
199
+ for (const v of r.violations) violations.push({ ...v, lane: 'local' })
200
+ for (const w of r.warnings) warnings.push({ ...w, lane: 'local' })
59
201
  }
60
202
  }
61
- return { packsChecked, violations }
203
+ return { packsChecked, localChecked, violations, warnings }
62
204
  }
63
205
 
64
- // Ids a deep probe extracts from ONE default export (generic over the two
65
- // house profiles: scenario `attacks[]/steps[]`, check `checks[]` - host
66
- // shapes stay host-owned, this never assigns shared meaning to them).
206
+ // Ids ONE default export carries (generic over the two house profiles:
207
+ // scenario `attacks[]/steps[]`, check `checks[]` - host shapes stay
208
+ // host-owned, this never assigns shared meaning to them). Runs in-process
209
+ // ONLY on inert data (JSON libraries); code modules are probed in a child
210
+ // process via childProbe below - their top-level code must never run inside
211
+ // the linter (it could exit() the CLI or spin it forever).
67
212
  function probeIds(def, pack) {
68
213
  const out = []
69
214
  const push = (id, at) => { if (typeof id === 'string' && id) out.push({ id, pack, at }) }
@@ -89,47 +234,128 @@ function probeIds(def, pack) {
89
234
 
90
235
  const DEEP_LIB_TAG = '(host-library)'
91
236
 
92
- // Load the host-library census reference (--against, packstruct#2 ask: the
93
- // id-vs-host-library census). Accepts a file or a directory: .json parses
94
- // directly, code modules import in-process and default-export ids in one of
95
- // the house profile shapes (generically probed - the library's internal
96
- // shapes stay the host's business).
97
- async function loadLibraryAgainst(ref) {
98
- if (ref.endsWith('.json')) return JSON.parse(readFileSync(ref, 'utf8'))
99
- if (existsSync(ref) && (await import('node:fs')).statSync(ref).isDirectory()) {
100
- const entries = readdirSync(ref).filter(f => f.endsWith('.js') || f.endsWith('.mjs')).sort()
101
- let merged = null
102
- for (const f of entries) {
103
- const mod = (await import(pathToFileURL(resolve(ref, f)).href)).default
104
- merged = { parts: (merged?.parts ?? []).concat([{ file: f, mod }]) }
237
+ // QC finding (crash class, fixed): deep used to import entries in-process,
238
+ // so an entry and its own top-level code could drive the probe's process -
239
+ // process.exit(7) made the CLI wire-exit 7 with no output, and an infinite
240
+ // top-level loop hung it forever. Probes now run in a disposable child
241
+ // (no shared module cache/no shared process). Kill on the timeout: a
242
+ // refusal is instant, and a pack that stalls the exit-code contract is an
243
+ // entry-import violation, not a hint.
244
+ export const PROBE_TIMEOUT_MS = 5000
245
+ const PROBE_MARKER = 'PROBE::'
246
+
247
+ function childProbeScript(fileUrl) {
248
+ return `
249
+ try {
250
+ const m = await import(${JSON.stringify(fileUrl)});
251
+ const d = m && m.default;
252
+ const out = { defaultExport: d !== undefined && d !== null, ids: [] };
253
+ const push = (id, at) => { if (typeof id === 'string' && id) out.ids.push({ id, at }) };
254
+ if (d && typeof d === 'object') {
255
+ push(d.name, 'module name');
256
+ for (const key of ['attacks', 'checks', 'scenarios']) {
257
+ const arr = d[key];
258
+ if (!Array.isArray(arr)) continue;
259
+ for (const item of arr) {
260
+ if (!item || typeof item !== 'object') continue;
261
+ push(item.id ?? item.name, key + '[]');
262
+ for (const sub of ['steps', 'phases']) {
263
+ if (!Array.isArray(item[sub])) continue;
264
+ for (const s of item[sub]) {
265
+ if (!s || typeof s !== 'object') continue;
266
+ push(s.id ?? s.name, key + '[].' + sub + '[]');
267
+ }
268
+ }
269
+ }
105
270
  }
106
- return merged
107
271
  }
108
- return (await import(pathToFileURL(resolve(ref)).href)).default
272
+ process.stdout.write(${JSON.stringify(PROBE_MARKER)} + JSON.stringify(out));
273
+ } catch (e) {
274
+ process.stdout.write(${JSON.stringify(PROBE_MARKER)} + JSON.stringify({ importError: String((e && e.message) || e) }));
275
+ }
276
+ `
277
+ }
278
+
279
+ // Probe one code module in the child. Returns the probe report or throws a
280
+ // plain Error carrying the reason the probe could not report.
281
+ //
282
+ // Stdio through runCapped (async): a killed probe must never wait on
283
+ // pipe-EOF that an orphaned grandchild spawned by the entry can hold
284
+ // forever, and an output-flooding entry hits the 1MB cap (an honest
285
+ // entry-import refusal), not a scratch-file flood that fills the disk.
286
+ async function childProbe(absPath, timeoutMs = PROBE_TIMEOUT_MS) {
287
+ const fileUrl = pathToFileURL(absPath).href
288
+ const r = await runCapped({
289
+ cmd: process.execPath,
290
+ args: ['--input-type=module', '--no-warnings', '-e', childProbeScript(fileUrl)],
291
+ timeoutMs,
292
+ maxBuffer: 1024 * 1024,
293
+ killSignal: 'SIGKILL',
294
+ })
295
+ if (r.spawnError && r.spawnError.code === 'ENOENT') throw new Error(`no node runtime to probe with`)
296
+ const out = r.stdout
297
+ const idx = out.lastIndexOf(PROBE_MARKER)
298
+ if (idx === -1) {
299
+ if (r.capped) throw new Error(`probe output hit the ${1 << 20}B cap before the probe reported (an entry flooding its own stdout) - a pack that floods the probe is refusing the exit-code contract, and a refusal is instant`)
300
+ if (r.timedOut) throw new Error(`probe killed after the ${timeoutMs}ms timeout (signal ${r.signal ?? 'SIGKILL'}) - a pack stalling the probe is refusing the exit-code contract, and a refusal is instant`)
301
+ throw new Error(`entry terminated the probe process (exit ${r.status ?? 'null'}) before the probe could report`)
302
+ }
303
+ let report
304
+ try {
305
+ report = JSON.parse(out.slice(idx + PROBE_MARKER.length).trim())
306
+ } catch {
307
+ throw new Error('probe output was not parseable as a probe report')
308
+ }
309
+ return report
109
310
  }
110
311
 
111
- // Merge a dir-shaped library into one probeUnits list: [{id, at, from}].
112
- function libraryProbeUnits(lib, ref) {
113
- if (lib?.parts) {
114
- const out = []
115
- for (const { file, mod } of lib.parts) {
116
- for (const u of probeIds(mod, DEEP_LIB_TAG)) out.push({ ...u, at: `${file}: ${u.at}` })
312
+ // Load the host-library census reference (--against, packstruct#2 ask: the
313
+ // id-vs-host-library census). Accepts a file or a directory: .json parses
314
+ // in-process (inert data - no code execution needed); code modules are
315
+ // child-probed one by one, same as pack entries. The library's internal
316
+ // shapes stay the host's business.
317
+ async function collectLibraryUnits(ref, timeoutMs) {
318
+ const units = []
319
+ if (ref.endsWith('.json')) {
320
+ const obj = JSON.parse(readFileSync(ref, 'utf8'))
321
+ for (const u of probeIds(obj, DEEP_LIB_TAG)) units.push({ id: u.id, at: `json ref: ${u.at}` })
322
+ return units
323
+ }
324
+ let files
325
+ if (existsSync(ref) && statSync(ref).isDirectory()) {
326
+ files = readdirSync(ref).filter(f => f.endsWith('.js') || f.endsWith('.mjs')).sort().map(f => join(ref, f))
327
+ } else {
328
+ files = [resolve(ref)]
329
+ }
330
+ for (const file of files) {
331
+ let report
332
+ try {
333
+ report = await childProbe(file, timeoutMs)
334
+ } catch (err) {
335
+ throw new Error(`${file}: ${err.message}`)
117
336
  }
118
- return out
337
+ if (report.importError !== undefined) throw new Error(`${file}: failed to import: ${report.importError}`)
338
+ for (const { id, at } of report.ids) units.push({ id, at: `${file}: ${at}` })
119
339
  }
120
- return probeIds(lib, DEEP_LIB_TAG).map(u => ({ ...u, at: `ref: ${u.at}` }))
340
+ return units
121
341
  }
122
342
 
123
343
  export async function deepLintPacks(dir, opts = {}) {
124
- const shallow = lintPacks(dir)
344
+ const timeoutMs = Number.isFinite(opts.probeTimeoutMs) ? opts.probeTimeoutMs : PROBE_TIMEOUT_MS
345
+ // Lanes to walk: public always, local only when asked (packstruct#16).
346
+ const lanes = opts.local ? LANES : ['public']
347
+ const tagLane = (v, lane) => (lane === 'local' ? { ...v, lane: 'local' } : v)
348
+ const shallow = lintPacks(dir, { local: opts.local })
125
349
  const violations = [...shallow.violations]
350
+ const warnings = [...(shallow.warnings ?? [])]
351
+ const localChecked = shallow.localChecked ?? 0
126
352
  const publicDir = join(dir, 'public')
127
353
  let libraryIds = 0
128
354
  if (!existsSync(publicDir)) {
129
- return { packsChecked: shallow.packsChecked, violations, modulesProbed: 0, idsCensused: 0, libraryIds }
355
+ return { packsChecked: shallow.packsChecked, localChecked, violations, warnings, modulesProbed: 0, idsCensused: 0, libraryIds }
130
356
  }
131
357
  const shallowFlagged = new Map()
132
- for (const v of shallow.violations) shallowFlagged.set(v.pack, v.norm)
358
+ for (const v of shallow.violations) shallowFlagged.set(`${v.lane ?? 'public'}/${v.pack}`, v.norm)
133
359
  const idSeen = new Map() // raw id -> first origin {pack, at}
134
360
  const nameSeen = new Map() // manifest pack name -> dir
135
361
  const MAX_IDS = 100000 // census floor: refuse pathological corpora loudly
@@ -140,74 +366,82 @@ export async function deepLintPacks(dir, opts = {}) {
140
366
  // namespaced-ids norm, engine side: the #19 44-vs-49 zero-collision claim).
141
367
  if (opts.against !== undefined) {
142
368
  try {
143
- const lib = await loadLibraryAgainst(opts.against)
144
- for (const { id, at } of libraryProbeUnits(lib, opts.against)) {
369
+ const lib = await collectLibraryUnits(opts.against, timeoutMs)
370
+ for (const { id, at } of lib) {
145
371
  if (idSeen.has(id)) continue // the library's own internals: not ours to judge
146
372
  idSeen.set(id, { pack: DEEP_LIB_TAG, at: `--against (${at})` })
147
373
  libraryIds++
148
374
  }
149
375
  } catch (err) {
150
- violations.push({ pack: DEEP_LIB_TAG, norm: 'library-ref', message: `--against "${opts.against}": failed to load the host library: ${err.message}` })
376
+ violations.push({ pack: DEEP_LIB_TAG, norm: 'library-ref', message: `--against "${opts.against}": ${err.message}` })
151
377
  }
152
378
  }
153
- for (const name of readdirSync(publicDir).sort()) {
154
- const packDir = join(publicDir, name)
155
- let isDir = true
156
- try { readdirSync(packDir) } catch { isDir = false }
157
- if (!isDir) continue
158
- // Manifest-level parity with the engine's seen map (loader.js:389-391):
159
- // two packs claiming the same pack name = one loud error at author time.
160
- const flagged = shallowFlagged.get(name)
161
- if (flagged === 'manifest-missing' || flagged === 'manifest-invalid') continue
162
- let m = null
163
- try { m = JSON.parse(readFileSync(join(packDir, 'pack.json'), 'utf8')) } catch { continue }
164
- if (typeof m.name === 'string') {
165
- const before = nameSeen.get(m.name)
166
- if (before !== undefined && before !== name) {
167
- violations.push({ pack: name, norm: 'name-collision', message: `pack name "${m.name}" claimed by both ${before}/ and ${name}/ - one loud error (the engine's seen map at author time)` })
379
+ for (const lane of lanes) {
380
+ const laneDir = join(dir, lane)
381
+ if (!existsSync(laneDir)) continue
382
+ for (const name of readdirSync(laneDir).sort()) {
383
+ const packDir = join(laneDir, name)
384
+ let isDir = true
385
+ try { readdirSync(packDir) } catch { isDir = false }
386
+ if (!isDir) continue
387
+ // Manifest-level parity with the engine's seen map (loader.js:389-391):
388
+ // two packs claiming the same pack name = one loud error at author time.
389
+ const flagged = shallowFlagged.get(`${lane}/${name}`)
390
+ if (flagged === 'manifest-missing' || flagged === 'manifest-invalid') continue
391
+ let m = null
392
+ try { m = JSON.parse(readFileSync(join(packDir, 'pack.json'), 'utf8')) } catch { continue }
393
+ if (typeof m.name === 'string') {
394
+ const before = nameSeen.get(m.name)
395
+ if (before !== undefined && before !== name) {
396
+ violations.push(tagLane({ pack: name, norm: 'name-collision', message: `pack name "${m.name}" claimed by both ${before}/ and ${name}/ - one loud error (the engine's seen map at author time)` }, lane))
397
+ }
398
+ nameSeen.set(m.name, name)
168
399
  }
169
- nameSeen.set(m.name, name)
170
- }
171
- // Entry probe (packstruct#2 ask 1): import once, in-process.
172
- if (flagged === 'entry') continue // missing/invalid entry: shallow already refused
173
- if (typeof m.entry !== 'string' || !existsSync(join(packDir, m.entry))) continue
174
- let mod = null
175
- try {
176
- mod = await import(pathToFileURL(resolve(packDir, m.entry)).href)
177
- } catch (err) {
178
- violations.push({ pack: name, norm: 'entry-import', message: `entry "${m.entry}" failed to import: ${err.message}` })
179
- continue
180
- }
181
- if (mod === null || typeof mod !== 'object' || mod.default === undefined) {
182
- violations.push({ pack: name, norm: 'entry-default-export', message: `entry "${m.entry}" has no default export - the loader would report it as an entry failure (SPEC section 3)` })
183
- continue
184
- }
185
- modulesProbed++
186
- // Census (packstruct#2 ask 2): raw ids across the pack corpus, plus
187
- // within-pack duplicates - engine parity before the host ever loads.
188
- for (const { id, at } of probeIds(mod.default, name)) {
189
- idsCensused++
190
- if (idsCensused > MAX_IDS) {
191
- violations.push({ pack: name, norm: 'deep-floor', message: `census floor exceeded (>${MAX_IDS} ids) - refusing to walk further rather than pretending` })
192
- return { packsChecked: shallow.packsChecked, violations, modulesProbed, idsCensused, libraryIds }
400
+ // Entry probe (packstruct#2 ask 1): import once, in-process.
401
+ if (flagged === 'entry') continue // missing/invalid entry: shallow already refused
402
+ if (typeof m.entry !== 'string' || !existsSync(join(packDir, m.entry))) continue
403
+ let report
404
+ try {
405
+ report = await childProbe(resolve(packDir, m.entry), timeoutMs)
406
+ } catch (err) {
407
+ violations.push(tagLane({ pack: name, norm: 'entry-import', message: `entry "${m.entry}": ${err.message}` }, lane))
408
+ continue
409
+ }
410
+ if (report.importError !== undefined) {
411
+ violations.push(tagLane({ pack: name, norm: 'entry-import', message: `entry "${m.entry}" failed to import: ${report.importError}` }, lane))
412
+ continue
413
+ }
414
+ if (!report.defaultExport) {
415
+ violations.push(tagLane({ pack: name, norm: 'entry-default-export', message: `entry "${m.entry}" has no default export - the loader would report it as an entry failure (SPEC section 3)` }, lane))
416
+ continue
193
417
  }
194
- const first = idSeen.get(id)
195
- if (first === undefined) { idSeen.set(id, { pack: name, at }); continue }
196
- if (first.pack === name) {
197
- if (!violations.some(v => v.norm === 'id-duplicate' && v.message.includes(`"${id}"`))) {
198
- violations.push({ pack: name, norm: 'id-duplicate', message: `id "${id}" appears twice within the pack (first: ${first.at})` })
418
+ modulesProbed++
419
+ // Census (packstruct#2 ask 2): raw ids across the pack corpus, plus
420
+ // within-pack duplicates - engine parity before the host ever loads.
421
+ for (const { id, at } of report.ids) {
422
+ idsCensused++
423
+ if (idsCensused > MAX_IDS) {
424
+ violations.push(tagLane({ pack: name, norm: 'deep-floor', message: `census floor exceeded (>${MAX_IDS} ids) - refusing to walk further rather than pretending` }, lane))
425
+ return { packsChecked: shallow.packsChecked, localChecked, violations, warnings, modulesProbed, idsCensused, libraryIds }
199
426
  }
200
- } else {
201
- const vsLibrary = first.pack === DEEP_LIB_TAG
202
- const norm = vsLibrary ? 'id-library-collision' : 'id-collision'
203
- if (!violations.some(v => v.norm === norm && v.message.includes(`"${id}"`))) {
204
- const who = vsLibrary
205
- ? `the host library (${first.at})` : `${first.pack}/ (${first.at})`
206
- violations.push({ pack: name, norm, message: `id "${id}" claimed by both ${who} and ${name}/ (${at}) - the host id space cannot carry both` })
427
+ const first = idSeen.get(id)
428
+ if (first === undefined) { idSeen.set(id, { pack: name, at }); continue }
429
+ if (first.pack === name) {
430
+ if (!violations.some(v => v.norm === 'id-duplicate' && v.message.includes(`"${id}"`))) {
431
+ violations.push(tagLane({ pack: name, norm: 'id-duplicate', message: `id "${id}" appears twice within the pack (first: ${first.at})` }, lane))
432
+ }
433
+ } else {
434
+ const vsLibrary = first.pack === DEEP_LIB_TAG
435
+ const norm = vsLibrary ? 'id-library-collision' : 'id-collision'
436
+ if (!violations.some(v => v.norm === norm && v.message.includes(`"${id}"`))) {
437
+ const who = vsLibrary
438
+ ? `the host library (${first.at})` : `${first.pack}/ (${first.at})`
439
+ violations.push(tagLane({ pack: name, norm, message: `id "${id}" claimed by both ${who} and ${name}/ (${at}) - the host id space cannot carry both` }, lane))
440
+ }
207
441
  }
208
442
  }
209
443
  }
210
444
  }
211
- return { packsChecked: shallow.packsChecked, violations, modulesProbed, idsCensused, libraryIds }
445
+ return { packsChecked: shallow.packsChecked, localChecked, violations, warnings, modulesProbed, idsCensused, libraryIds }
212
446
  }
213
447
 
package/src/new.mjs ADDED
@@ -0,0 +1,79 @@
1
+ // src/new.mjs - packstruct new: generate a conforming pack skeleton at
2
+ // author time (packstruct#24). Zero dependencies; no network.
3
+ //
4
+ // The charter is to kill broken pack manifests at author time. The cheapest
5
+ // break class - a new author guessing the field list from a friend's
6
+ // manifest, forgetting version's dotted form, getting name/dir parity wrong -
7
+ // dies even earlier if the starting point is GENERATED correct instead of
8
+ // post-hoc refused. Refusals are the net; a conforming skeleton is the
9
+ // trampoline. `new` is pure convenience: its output is just another manifest
10
+ // the lint grades, so the lint stays the one truth enforcer.
11
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
12
+ import { join, resolve, dirname } from 'node:path'
13
+
14
+ const KEBAB = /^[a-z0-9][a-z0-9-]*$/
15
+
16
+ // The default version: a fresh pack is pre-1.0 by convention (the shipped
17
+ // packstruct-lint-shapes pack and the deep fixtures all start at 0.1.0).
18
+ const DEFAULT_VERSION = '0.1.0'
19
+
20
+ // The packs ROOT for a run. --dir wins; else walk up from cwd looking for
21
+ // an existing `packs/` (the git-style discovery every host repo satisfies);
22
+ // else fall back to ./packs so the output is always a lint-clean tree
23
+ // (<root>/public/<name>/), never a bare pack dir the lint would refuse.
24
+ export function resolvePacksRoot(cwd, dir) {
25
+ if (dir) return resolve(cwd, dir)
26
+ let cur = resolve(cwd)
27
+ for (;;) {
28
+ const candidate = join(cur, 'packs')
29
+ if (existsSync(join(candidate, 'public'))) return candidate
30
+ const parent = dirname(cur)
31
+ if (parent === cur) break
32
+ cur = parent
33
+ }
34
+ return join(resolve(cwd), 'packs')
35
+ }
36
+
37
+ function entryStub(name) {
38
+ // ESM default export (the #19 section 3 clarifier: the default export is
39
+ // the loaded thing). Neutral shape - name + description only, no ids - so
40
+ // it deep-lints clean with nothing to collide against.
41
+ return `// ${name} - packstruct@1 pack entry.
42
+ // The default export is the loaded thing (ESM is the house default).
43
+ export default {
44
+ name: '${name}',
45
+ description: 'TODO: one-line description of ${name}.',
46
+ }
47
+ `
48
+ }
49
+
50
+ function manifestJson(name) {
51
+ return JSON.stringify({
52
+ schemaVersion: 1,
53
+ name,
54
+ description: `TODO: one-line description of ${name}.`,
55
+ version: DEFAULT_VERSION,
56
+ entry: 'index.js',
57
+ }, null, 2) + '\n'
58
+ }
59
+
60
+ // newPack(name, { dir, cwd }). Returns { dir, packDir, files, violations }.
61
+ // Refusals are nameable and non-destructive: a bad name or an occupied
62
+ // target refuses without writing (never clobber).
63
+ export function newPack(name, opts = {}) {
64
+ const cwd = opts.cwd ?? process.cwd()
65
+ if (typeof name !== 'string' || !KEBAB.test(name)) {
66
+ return { dir: null, packDir: null, files: [], violations: [{ norm: 'name-kebab-case', message: `pack name must be kebab-case (got ${JSON.stringify(name)}) - for example: packstruct new my-shapes` }] }
67
+ }
68
+ const dir = resolvePacksRoot(cwd, opts.dir)
69
+ const packDir = join(dir, 'public', name)
70
+ if (existsSync(packDir)) {
71
+ return { dir, packDir, files: [], violations: [{ norm: 'pack-exists', message: `${packDir} already exists - refusing to clobber it (pick another name or remove the directory)` }] }
72
+ }
73
+ mkdirSync(packDir, { recursive: true })
74
+ const manifestPath = join(packDir, 'pack.json')
75
+ const entryPath = join(packDir, 'index.js')
76
+ writeFileSync(manifestPath, manifestJson(name))
77
+ writeFileSync(entryPath, entryStub(name))
78
+ return { dir, packDir, files: [manifestPath, entryPath], violations: [] }
79
+ }