@elaraai/e3 1.0.108 → 1.0.110

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/dist/src/environment-capture.d.ts +27 -57
  2. package/dist/src/environment-capture.d.ts.map +1 -1
  3. package/dist/src/environment-capture.js +86 -455
  4. package/dist/src/environment-capture.js.map +1 -1
  5. package/dist/src/environment-capture.spec.js +215 -5
  6. package/dist/src/environment-capture.spec.js.map +1 -1
  7. package/dist/src/environment-npm-lock.d.ts +77 -0
  8. package/dist/src/environment-npm-lock.d.ts.map +1 -0
  9. package/dist/src/environment-npm-lock.js +209 -0
  10. package/dist/src/environment-npm-lock.js.map +1 -0
  11. package/dist/src/environment-uv-lock.d.ts +312 -0
  12. package/dist/src/environment-uv-lock.d.ts.map +1 -0
  13. package/dist/src/environment-uv-lock.js +494 -0
  14. package/dist/src/environment-uv-lock.js.map +1 -0
  15. package/dist/src/export.d.ts.map +1 -1
  16. package/dist/src/export.js +25 -9
  17. package/dist/src/export.js.map +1 -1
  18. package/dist/src/export.spec.js +25 -3
  19. package/dist/src/export.spec.js.map +1 -1
  20. package/dist/src/function.d.ts +136 -57
  21. package/dist/src/function.d.ts.map +1 -1
  22. package/dist/src/function.js +47 -12
  23. package/dist/src/function.js.map +1 -1
  24. package/dist/src/function.spec.d.ts +3 -1
  25. package/dist/src/function.spec.d.ts.map +1 -1
  26. package/dist/src/function.spec.js +246 -3
  27. package/dist/src/function.spec.js.map +1 -1
  28. package/dist/src/index-input.d.ts +162 -0
  29. package/dist/src/index-input.d.ts.map +1 -0
  30. package/dist/src/index-input.js +216 -0
  31. package/dist/src/index-input.js.map +1 -0
  32. package/dist/src/index-input.spec.d.ts +6 -0
  33. package/dist/src/index-input.spec.d.ts.map +1 -0
  34. package/dist/src/index-input.spec.js +269 -0
  35. package/dist/src/index-input.spec.js.map +1 -0
  36. package/dist/src/index-read.d.ts +428 -0
  37. package/dist/src/index-read.d.ts.map +1 -0
  38. package/dist/src/index-read.js +747 -0
  39. package/dist/src/index-read.js.map +1 -0
  40. package/dist/src/index-read.spec.d.ts +6 -0
  41. package/dist/src/index-read.spec.d.ts.map +1 -0
  42. package/dist/src/index-read.spec.js +1447 -0
  43. package/dist/src/index-read.spec.js.map +1 -0
  44. package/dist/src/index.d.ts +12 -5
  45. package/dist/src/index.d.ts.map +1 -1
  46. package/dist/src/index.js +6 -3
  47. package/dist/src/index.js.map +1 -1
  48. package/dist/src/package.d.ts.map +1 -1
  49. package/dist/src/package.js +3 -4
  50. package/dist/src/package.js.map +1 -1
  51. package/dist/src/record-area.d.ts +12 -0
  52. package/dist/src/record-area.d.ts.map +1 -1
  53. package/dist/src/record-area.js +26 -0
  54. package/dist/src/record-area.js.map +1 -1
  55. package/dist/src/record-area.spec.js +4 -14
  56. package/dist/src/record-area.spec.js.map +1 -1
  57. package/dist/src/record-builders.d.ts +39 -14
  58. package/dist/src/record-builders.d.ts.map +1 -1
  59. package/dist/src/record-builders.js.map +1 -1
  60. package/dist/src/record-entries.spec.js +2 -15
  61. package/dist/src/record-entries.spec.js.map +1 -1
  62. package/dist/src/record-index.d.ts +11 -5
  63. package/dist/src/record-index.d.ts.map +1 -1
  64. package/dist/src/record-index.js.map +1 -1
  65. package/dist/src/record-interval.d.ts +7 -0
  66. package/dist/src/record-interval.d.ts.map +1 -1
  67. package/dist/src/record-interval.js +7 -0
  68. package/dist/src/record-interval.js.map +1 -1
  69. package/dist/src/record-nested-programs.d.ts +63 -511
  70. package/dist/src/record-nested-programs.d.ts.map +1 -1
  71. package/dist/src/record-nested-programs.js +403 -222
  72. package/dist/src/record-nested-programs.js.map +1 -1
  73. package/dist/src/record-nested.d.ts +60 -10
  74. package/dist/src/record-nested.d.ts.map +1 -1
  75. package/dist/src/record-nested.js +65 -23
  76. package/dist/src/record-nested.js.map +1 -1
  77. package/dist/src/record-nested.spec.js +113 -34
  78. package/dist/src/record-nested.spec.js.map +1 -1
  79. package/dist/src/record-series.spec.js +6 -31
  80. package/dist/src/record-series.spec.js.map +1 -1
  81. package/dist/src/record.d.ts +9 -0
  82. package/dist/src/record.d.ts.map +1 -1
  83. package/dist/src/record.js +14 -0
  84. package/dist/src/record.js.map +1 -1
  85. package/dist/src/runner.d.ts +14 -2
  86. package/dist/src/runner.d.ts.map +1 -1
  87. package/dist/src/runner.js +16 -4
  88. package/dist/src/runner.js.map +1 -1
  89. package/dist/src/stock-platforms.spec.js +7 -1
  90. package/dist/src/stock-platforms.spec.js.map +1 -1
  91. package/dist/src/task.d.ts +28 -16
  92. package/dist/src/task.d.ts.map +1 -1
  93. package/dist/src/task.js +33 -5
  94. package/dist/src/task.js.map +1 -1
  95. package/dist/src/test-helpers.d.ts +35 -0
  96. package/dist/src/test-helpers.d.ts.map +1 -0
  97. package/dist/src/test-helpers.js +56 -0
  98. package/dist/src/test-helpers.js.map +1 -0
  99. package/dist/src/types.d.ts +86 -13
  100. package/dist/src/types.d.ts.map +1 -1
  101. package/package.json +3 -3
@@ -16,140 +16,25 @@
16
16
  * surface (#99): this module shells out and reads the filesystem, so it is
17
17
  * re-exported only from the Node-only main `@elaraai/e3` entry, alongside
18
18
  * `export.ts` / `sha256.ts`.
19
+ *
20
+ * What it reads of a project's lock is the lock modules': a uv lock's
21
+ * (`environment-uv-lock.ts`) and an npm lock's (`environment-npm-lock.ts`).
22
+ * This module builds and stores what they name.
19
23
  */
20
24
  import * as fs from 'node:fs';
21
25
  import * as os from 'node:os';
22
26
  import * as path from 'node:path';
23
27
  import { execFileSync } from 'node:child_process';
24
- import { parse as parseToml } from 'smol-toml';
25
- import { variant, none, encodeBeast2For } from '@elaraai/east';
28
+ import { StringType, compareFor, variant, none, encodeBeast2For } from '@elaraai/east';
26
29
  import { EnvironmentSpecType } from '@elaraai/e3-types';
27
30
  import { validateEnvironmentDecl } from './environment.js';
31
+ import { canonicalPath, canonicalPythonName, discoverPythonRoot, findUvLock, localSource, pythonClosure, pythonRequires, requiredStart } from './environment-uv-lock.js';
32
+ import { discoverNodeRoot, findNpmRoot, npmClosure } from './environment-npm-lock.js';
33
+ export { canonicalPythonName, pythonLeftOut, pythonLockSettings, pythonMemberSources, pythonRequires, pythonWorkspaceMember, readRequiredDistribution } from './environment-uv-lock.js';
34
+ export { nodeWorkspaceMember } from './environment-npm-lock.js';
28
35
  const encodeEnvironmentSpec = encodeBeast2For(EnvironmentSpecType);
29
- /** Canonicalize a path for identity comparison — realpath when it exists,
30
- * case-folded on win32 (uv.lock stores portable forward-slash relatives). */
31
- function canonicalPath(p) {
32
- let r = p;
33
- try {
34
- r = fs.realpathSync(p);
35
- }
36
- catch { /* may not exist yet */ }
37
- return process.platform === 'win32' ? r.toLowerCase() : r;
38
- }
39
- /** PEP 503 canonical form of a python package name: lowercase, runs of
40
- * `-`/`_`/`.` collapsed to `-`. uv.lock stores canonical names while a
41
- * `{ custom }` platform ref uses the import-style name (`platform_module`),
42
- * so both sides must canonicalize before comparison (#391 — a strict match
43
- * silently derived NO environment for any underscore-named member, leaving
44
- * its source edits out of the task hash and serving stale cached outputs). */
45
- function canonicalPythonName(name) {
46
- return name.toLowerCase().replace(/[-_.]+/g, '-');
47
- }
48
- /** The on-disk directory a lock `source` points at, with its kind — or null
49
- * for registry/git/url sources (installed by uv sync, not captured). */
50
- function localSource(root, source) {
51
- if (!source)
52
- return null;
53
- for (const kind of ['editable', 'directory', 'virtual']) {
54
- if (typeof source[kind] === 'string')
55
- return { dir: path.resolve(root, source[kind]), kind };
56
- }
57
- return null;
58
- }
59
- /**
60
- * Find the workspace/standalone root governing `project` and the lock
61
- * package (`subject`) whose local source resolves to it.
62
- *
63
- * @throws {Error} P3 (no lock in project or any ancestor), P5 (unsupported
64
- * lock version), P4 (lock does not list a package at `project`)
65
- */
66
- function discoverPythonRoot(project, owner) {
67
- let dir = project;
68
- let lockPath = null;
69
- for (;;) {
70
- const candidate = path.join(dir, 'uv.lock');
71
- if (fs.existsSync(candidate)) {
72
- lockPath = candidate;
73
- break;
74
- }
75
- const parent = path.dirname(dir);
76
- if (parent === dir)
77
- break;
78
- dir = parent;
79
- }
80
- if (!lockPath) {
81
- throw new Error(`Environment for '${owner}': no uv.lock in '${project}' or any parent — run 'uv lock' in ` +
82
- `'${project}' (standalone), or add it to [tool.uv.workspace].members of the workspace root and 'uv lock' there`);
83
- }
84
- const root = path.dirname(lockPath);
85
- const lock = parseToml(fs.readFileSync(lockPath, 'utf-8'));
86
- if (lock.version !== 1) {
87
- throw new Error(`Environment for '${owner}': unsupported uv.lock version ${lock.version} at '${root}' — update @elaraai/e3 or re-lock with a compatible uv`);
88
- }
89
- const projectCanon = canonicalPath(project);
90
- const subject = (lock.package ?? []).find((p) => {
91
- const local = localSource(root, p.source);
92
- return local !== null && canonicalPath(local.dir) === projectCanon;
93
- });
94
- if (!subject) {
95
- throw new Error(`Environment for '${owner}': uv.lock at '${root}' does not list a package at '${project}' — ` +
96
- `the lockfile is out of date or the project is not a workspace member; run 'uv lock' at '${root}'`);
97
- }
98
- return { root, lock, subject: subject.name };
99
- }
100
- /**
101
- * The transitive closure of LOCAL packages reachable from `subject` — the
102
- * set whose sdists must ride the environment.
103
- *
104
- * Walks `dependencies` plus every optional-dependency and dev-dependency
105
- * group (over-capture is sound: it only over-invalidates). Registry/git/url
106
- * targets are skipped (uv sync installs them); a `path=<archive>` source is
107
- * refused, and a virtual package contributes its deps but no sdist.
108
- *
109
- * @returns The buildable closure members, sorted by name
110
- * @throws {Error} P6 (dangling edge), P7 (subject not packaged), P8 (source
111
- * dir missing), P9 (local archive dependency)
112
- */
113
- function pythonClosure(lock, root, subject, owner) {
114
- const byName = new Map((lock.package ?? []).map((p) => [p.name, p]));
115
- const build = new Map();
116
- const seen = new Set();
117
- const queue = [subject];
118
- while (queue.length > 0) {
119
- const name = queue.shift();
120
- if (seen.has(name))
121
- continue;
122
- seen.add(name);
123
- const pkg = byName.get(name);
124
- if (!pkg) {
125
- if (name === subject)
126
- throw new Error(`Environment for '${owner}': subject '${name}' not in uv.lock`);
127
- throw new Error(`Environment for '${owner}': uv.lock is inconsistent — depends on unknown '${name}'; run 'uv lock'`);
128
- }
129
- if (typeof pkg.source?.path === 'string') {
130
- throw new Error(`Environment for '${owner}': local archive dependency '${name}' is not supported — use a directory/workspace source or a registry`);
131
- }
132
- const local = localSource(root, pkg.source);
133
- if (!local)
134
- continue; // registry/git/url — sync installs it; don't recurse
135
- if (local.kind !== 'virtual') {
136
- if (!fs.existsSync(local.dir)) {
137
- throw new Error(`Environment for '${owner}': package '${name}' resolves to '${local.dir}' which does not exist — run 'uv lock' or fix its path`);
138
- }
139
- build.set(name, local.dir);
140
- }
141
- else if (name === subject) {
142
- throw new Error(`Environment for '${owner}': '${name}' is a virtual package (no build-system) and cannot be an environment subject`);
143
- }
144
- for (const edge of [
145
- ...(pkg.dependencies ?? []),
146
- ...Object.values(pkg['optional-dependencies'] ?? {}).flat(),
147
- ...Object.values(pkg['dev-dependencies'] ?? {}).flat(),
148
- ])
149
- queue.push(edge.name);
150
- }
151
- return [...build.entries()].map(([name, dir]) => ({ name, dir })).sort((a, b) => (a.name < b.name ? -1 : 1));
152
- }
36
+ /** Orders the names and paths a spec holds through East, by code point. */
37
+ const byCodePoint = compareFor(StringType);
153
38
  function readProjectFile(project, name, owner) {
154
39
  const p = path.join(project, name);
155
40
  if (!fs.existsSync(p)) {
@@ -158,38 +43,21 @@ function readProjectFile(project, name, owner) {
158
43
  }
159
44
  return fs.readFileSync(p);
160
45
  }
161
- /**
162
- * Walk up from `start` to the nearest `uv.lock`, parse and version-check it.
163
- * Returns the governing workspace/standalone root + parsed lock, or null when
164
- * no lock exists in `start` or any ancestor (no uv workspace to derive from).
165
- *
166
- * @throws {Error} if a lock is found but its version is unsupported
167
- */
168
- function findUvLock(start, owner) {
169
- let dir = start;
170
- for (;;) {
171
- const candidate = path.join(dir, 'uv.lock');
172
- if (fs.existsSync(candidate)) {
173
- const lock = parseToml(fs.readFileSync(candidate, 'utf-8'));
174
- if (lock.version !== 1) {
175
- throw new Error(`Environment for '${owner}': unsupported uv.lock version ${lock.version} at '${dir}' — update @elaraai/e3 or re-lock with a compatible uv`);
176
- }
177
- return { root: dir, lock };
178
- }
179
- const parent = path.dirname(dir);
180
- if (parent === dir)
181
- return null;
182
- dir = parent;
183
- }
184
- }
185
46
  /**
186
47
  * Build one sdist per closure member and store it, returning the sorted
187
48
  * artifact set. Shared by the explicit `{ python }` capture and the derived
188
49
  * platform capture so both produce byte-identical specs for the same closure.
50
+ * A member the export built already ({@link BuiltSdists}) is not built again.
189
51
  */
190
- function buildMemberSdists(closure, owner, addBlob, onEvent) {
52
+ function buildMemberSdists(closure, owner, addBlob, onEvent, built) {
191
53
  const sdists = [];
192
54
  for (const member of closure) {
55
+ const kept = built?.get(member.dir);
56
+ if (kept !== undefined) {
57
+ sdists.push(...kept);
58
+ continue;
59
+ }
60
+ const mine = [];
193
61
  // Build each closure member's sdist in its own out-dir so the artifact set
194
62
  // is unambiguous. Installers derive the package name from the filename.
195
63
  const outDir = fs.mkdtempSync(path.join(os.tmpdir(), 'e3-env-sdist-'));
@@ -197,31 +65,58 @@ function buildMemberSdists(closure, owner, addBlob, onEvent) {
197
65
  let memberBytes = 0;
198
66
  for (const a of buildArtifacts('uv', ['build', '--sdist', '--out-dir', outDir], member.dir, outDir, '.tar.gz', owner)) {
199
67
  memberBytes += a.data.byteLength;
200
- sdists.push({ filename: a.filename, hash: addBlob(a.data) });
68
+ mine.push({ filename: a.filename, hash: addBlob(a.data) });
201
69
  }
202
70
  onEvent?.({ member: member.name, tool: 'uv build --sdist', bytes: memberBytes });
203
71
  }
204
72
  finally {
205
73
  fs.rmSync(outDir, { recursive: true, force: true });
206
74
  }
75
+ built?.set(member.dir, mine);
76
+ sdists.push(...mine);
207
77
  }
208
- sdists.sort((a, b) => (a.filename < b.filename ? -1 : 1));
78
+ sdists.sort((a, b) => byCodePoint(a.filename, b.filename));
209
79
  return sdists;
210
80
  }
81
+ /**
82
+ * Captures the environment of members of a uv workspace: the root's manifest
83
+ * and lock, the sdists of the members and of every local package they — or
84
+ * the distributions installed beside them — depend on, and those
85
+ * distributions.
86
+ *
87
+ * @param root - The workspace root
88
+ * @param lock - Its lock
89
+ * @param subjects - The members, by the lock's names
90
+ * @param platforms - The platform packages the task's runner names
91
+ * @param built - The sdists the export built already
92
+ * @returns The encoded `workspace_python` spec
93
+ */
94
+ function captureWorkspacePython(root, lock, subjects, platforms, owner, addBlob, onEvent, built) {
95
+ const requires = pythonRequires(root, lock, platforms, owner);
96
+ // Walked as each is installed: with its extras
97
+ const members = pythonClosure(lock, root, subjects, owner, requires.map(requiredStart));
98
+ const pyproject = addBlob(readProjectFile(root, 'pyproject.toml', owner));
99
+ const lockBlob = addBlob(readProjectFile(root, 'uv.lock', owner));
100
+ const sdists = buildMemberSdists(members, owner, addBlob, onEvent, built);
101
+ return encodeEnvironmentSpec(variant('workspace_python', {
102
+ pyproject, lock: lockBlob, subjects: [...subjects].sort(byCodePoint), sdists, requires,
103
+ }));
104
+ }
211
105
  /**
212
106
  * Derive a python environment from the platform packages a task's runner
213
107
  * references. Each `custom` name that resolves to a LOCAL workspace member
214
108
  * (a directory/workspace/editable source in the governing `uv.lock`)
215
- * contributes its transitive closure; the union rides ONE `python` spec —
216
- * shared root manifest + lock, union of member sdists (byte-identical to the
217
- * explicit capture of a project depending on all of them). Names are matched
218
- * by PEP 503 canonical form, so an import-style ref (`platform_module`)
219
- * finds its lock entry (`platform-module`). Registry / first-party names
220
- * (e.g. `east-py-std`) are skipped — `uv sync` installs them. Returns null
221
- * when `anchorDir` has no uv workspace or no referenced name is a local
222
- * member (nothing to capture beyond the ambient runtime).
109
+ * contributes its transitive closure; the union rides ONE `workspace_python`
110
+ * spec — shared root manifest + lock, the members as its subjects, the union
111
+ * of their sdists. Names are matched by PEP 503 canonical form, so an
112
+ * import-style ref (`platform_module`) finds its lock entry
113
+ * (`platform-module`). A stock platform package the runner names
114
+ * (`east-py-std`) is no member: it is installed from the registry, as the
115
+ * lock pins it ({@link pythonRequires}). Returns null when `anchorDir` has no
116
+ * uv workspace or no referenced name is a local member (nothing to capture
117
+ * beyond the ambient runtime).
223
118
  */
224
- function capturePythonPlatforms(customNames, anchorDir, owner, addBlob, onEvent) {
119
+ function capturePythonPlatforms(customNames, platforms, anchorDir, owner, addBlob, onEvent, built) {
225
120
  const found = findUvLock(anchorDir, owner);
226
121
  if (!found)
227
122
  return null;
@@ -238,146 +133,7 @@ function capturePythonPlatforms(customNames, anchorDir, owner, addBlob, onEvent)
238
133
  .filter((n) => n !== null))];
239
134
  if (subjects.length === 0)
240
135
  return null;
241
- // Union the referenced members' closures, deduped by package name.
242
- const union = new Map();
243
- for (const subject of subjects) {
244
- for (const member of pythonClosure(lock, root, subject, owner))
245
- union.set(member.name, member.dir);
246
- }
247
- const pyproject = addBlob(readProjectFile(root, 'pyproject.toml', owner));
248
- const lockBlob = addBlob(readProjectFile(root, 'uv.lock', owner));
249
- const members = [...union.entries()].map(([name, dir]) => ({ name, dir })).sort((a, b) => (a.name < b.name ? -1 : 1));
250
- const sdists = buildMemberSdists(members, owner, addBlob, onEvent);
251
- return encodeEnvironmentSpec(variant('python', { pyproject, lock: lockBlob, sdists }));
252
- }
253
- /**
254
- * The local uv-workspace member a name refers to — the package a `{ custom }`
255
- * platform or an `East.importFunction(pkg, …)` names (#652) — resolved the
256
- * way {@link captureAutoEnvironment} resolves it: the governing `uv.lock`
257
- * above `anchorDir`, matched by PEP 503 canonical name, local sources only.
258
- *
259
- * @param name - The package name as referenced (import-style or canonical)
260
- * @param anchorDir - Directory the workspace is resolved from (the export cwd)
261
- * @param owner - The referencing task/function name, for error messages
262
- * @returns The member's directory and its `pyproject.toml` version, or null
263
- * when there is no uv workspace above `anchorDir` or the name is not a
264
- * local member (a registry package, a typo)
265
- */
266
- export function pythonWorkspaceMember(name, anchorDir, owner) {
267
- const found = findUvLock(anchorDir, owner);
268
- if (!found)
269
- return null;
270
- const { root, lock } = found;
271
- const canon = canonicalPythonName(name);
272
- const pkg = (lock.package ?? []).find((p) => canonicalPythonName(p.name) === canon);
273
- const local = pkg === undefined ? null : localSource(root, pkg.source);
274
- if (local === null)
275
- return null;
276
- let version = null;
277
- try {
278
- const project = parseToml(fs.readFileSync(path.join(local.dir, 'pyproject.toml'), 'utf-8'));
279
- if (typeof project.project?.version === 'string')
280
- version = project.project.version;
281
- }
282
- catch {
283
- /* no readable pyproject: the exporter records its own default */
284
- }
285
- return { dir: local.dir, version };
286
- }
287
- /**
288
- * Where a python workspace member's code can come from (#1459): the governing
289
- * workspace's root — whose `uv.lock` and `pyproject.toml` pin everything else
290
- * — and the directories of the member and of every local package it depends
291
- * on, transitively, as {@link captureAutoEnvironment} walks them. What the
292
- * export cache keys a member's manifests on.
293
- *
294
- * Unlike the environment's walk this refuses nothing: a virtual package's
295
- * directory counts, and a registry or archive package is pinned by the lock.
296
- *
297
- * @param name - The package name as referenced (import-style or canonical)
298
- * @param anchorDir - Directory the workspace is resolved from (the export cwd)
299
- * @param owner - The referencing task/function name, for error messages
300
- * @returns The workspace root and the closure's directories, sorted, or null
301
- * when there is no uv workspace above `anchorDir` or the name is not a
302
- * local member
303
- */
304
- export function pythonMemberSources(name, anchorDir, owner) {
305
- const found = findUvLock(anchorDir, owner);
306
- if (!found)
307
- return null;
308
- const { root, lock } = found;
309
- const byName = new Map((lock.package ?? []).map((p) => [p.name, p]));
310
- const canon = canonicalPythonName(name);
311
- const subject = (lock.package ?? []).find((p) => canonicalPythonName(p.name) === canon);
312
- if (subject === undefined || localSource(root, subject.source) === null)
313
- return null;
314
- const dirs = new Set();
315
- const seen = new Set();
316
- const queue = [subject.name];
317
- while (queue.length > 0) {
318
- const pkg = byName.get(queue.shift());
319
- if (pkg === undefined || seen.has(pkg.name))
320
- continue;
321
- seen.add(pkg.name);
322
- const local = localSource(root, pkg.source);
323
- if (local === null)
324
- continue;
325
- dirs.add(local.dir);
326
- for (const edge of [
327
- ...(pkg.dependencies ?? []),
328
- ...Object.values(pkg['optional-dependencies'] ?? {}).flat(),
329
- ...Object.values(pkg['dev-dependencies'] ?? {}).flat(),
330
- ])
331
- queue.push(edge.name);
332
- }
333
- return { root, dirs: [...dirs].sort() };
334
- }
335
- /** Walk up from `start` to the nearest npm lockfile (not pnpm/yarn); null if none. */
336
- function findNpmRoot(start) {
337
- const names = ['package-lock.json', 'npm-shrinkwrap.json'];
338
- let dir = start;
339
- for (;;) {
340
- const found = names.find((f) => fs.existsSync(path.join(dir, f)));
341
- if (found)
342
- return { root: dir, lock: JSON.parse(fs.readFileSync(path.join(dir, found), 'utf-8')) };
343
- const parent = path.dirname(dir);
344
- if (parent === dir)
345
- return null;
346
- dir = parent;
347
- }
348
- }
349
- /**
350
- * The local npm-workspace member a name refers to — the package a `{ custom }`
351
- * platform or an `East.importFunction(pkg, …)` names (#652) — resolved the
352
- * way {@link captureAutoEnvironment} resolves it: the governing npm lockfile
353
- * above `anchorDir`, matched by `package.json` name, workspace members only
354
- * (never an installed dependency). The python twin is
355
- * {@link pythonWorkspaceMember}.
356
- *
357
- * @param name - The package name as referenced (`@scope/name` or bare)
358
- * @param anchorDir - Directory the workspace is resolved from (the export cwd)
359
- * @returns The member's directory and its `package.json` version, or null
360
- * when there is no npm workspace above `anchorDir` or the name is not a
361
- * local member (a registry package, a typo)
362
- */
363
- export function nodeWorkspaceMember(name, anchorDir) {
364
- const found = findNpmRoot(anchorDir);
365
- if (!found)
366
- return null;
367
- const entry = Object.entries(found.lock.packages ?? {}).find(([p, v]) => p !== '' && !p.includes('node_modules/') && v.name === name && v.link !== true);
368
- if (!entry)
369
- return null;
370
- const dir = path.join(found.root, ...entry[0].split('/'));
371
- let version = null;
372
- try {
373
- const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8'));
374
- if (typeof pkg.version === 'string')
375
- version = pkg.version;
376
- }
377
- catch {
378
- /* no readable package.json: the exporter records its own default */
379
- }
380
- return { dir, version };
136
+ return captureWorkspacePython(root, lock, subjects, platforms, owner, addBlob, onEvent, built);
381
137
  }
382
138
  /**
383
139
  * Derive a node environment from the platform packages a task's runner
@@ -425,17 +181,23 @@ function captureNodePlatforms(customNames, anchorDir, owner, addBlob, onEvent) {
425
181
  * @param anchorDir - Directory the workspace is resolved from (the export cwd)
426
182
  * @param owner - The declaring task/function name, for error messages
427
183
  * @param addBlob - Stores a blob in the bundle's object store, returning its hash
184
+ * @param onEvent - Told each member's artifact as it is built
185
+ * @param platforms - The stock platform packages the runner names beside its
186
+ * custom ones (`east-py-std`): a python workspace member's environment
187
+ * installs their distributions too
188
+ * @param built - The sdists the export built already, which it adds to: each
189
+ * local python package is built once in an export ({@link BuiltSdists})
428
190
  * @returns The beast2-encoded EnvironmentSpec, or null when nothing local is
429
191
  * referenced (no workspace, or every platform is a registry/first-party package)
430
192
  */
431
- export function captureAutoEnvironment(runtime, customNames, anchorDir, owner, addBlob, onEvent) {
193
+ export function captureAutoEnvironment(runtime, customNames, anchorDir, owner, addBlob, onEvent, platforms = [], built) {
432
194
  if (customNames.length === 0)
433
195
  return null;
434
196
  // east-py resolves against a uv workspace, east-node against an npm
435
197
  // workspace. east-c (tools) is never derived — it uses explicit
436
198
  // `environment: { tools }`. Unknown runtimes never auto-derive.
437
199
  if (runtime === 'east-py')
438
- return capturePythonPlatforms(customNames, anchorDir, owner, addBlob, onEvent);
200
+ return capturePythonPlatforms(customNames, platforms, anchorDir, owner, addBlob, onEvent, built);
439
201
  if (runtime === 'east-node')
440
202
  return captureNodePlatforms(customNames, anchorDir, owner, addBlob, onEvent);
441
203
  return null;
@@ -453,154 +215,12 @@ function buildArtifacts(command, args, project, outDir, extension, owner) {
453
215
  const stderr = err.stderr?.toString() ?? String(err);
454
216
  throw new Error(`Environment for '${owner}': '${command} ${args.join(' ')}' failed in '${project}':\n${stderr}`);
455
217
  }
456
- const files = fs.readdirSync(outDir).filter((f) => f.endsWith(extension)).sort();
218
+ const files = fs.readdirSync(outDir).filter((f) => f.endsWith(extension)).sort(byCodePoint);
457
219
  if (files.length === 0) {
458
220
  throw new Error(`Environment for '${owner}': '${command}' produced no ${extension} artifacts in '${project}'`);
459
221
  }
460
222
  return files.map((f) => ({ filename: f, data: fs.readFileSync(path.join(outDir, f)) }));
461
223
  }
462
- // ---------------------------------------------------------------------------
463
- // Node (npm workspace) dependency-closure capture (#280)
464
- //
465
- // A `{ node: { project } }` declaration is either a self-contained project
466
- // (its own lockfile — captured byte-identically to before) or an npm
467
- // workspace member. For a member we capture the ROOT package.json + lockfile
468
- // plus an `npm pack` tarball per LOCAL closure member; the materializer
469
- // (#276) reconstructs a closure-only workspace and `npm ci`s it.
470
- //
471
- // Unlike python's `uv pip check`, `npm ci` is NOT a loud oracle — it will
472
- // silently install a member's unlocked deps from the registry — so the
473
- // closure walk validates the lock at export (N4/N5) rather than relying on
474
- // a run-time gate. pnpm workspaces are refused here (N8) until #284.
475
- // ---------------------------------------------------------------------------
476
- const NODE_LOCKFILES = ['package-lock.json', 'npm-shrinkwrap.json', 'pnpm-lock.yaml'];
477
- /** Workspace-relative POSIX path from the root to a dir. */
478
- function posixRel(root, dir) {
479
- return path.relative(root, dir).split(path.sep).join('/');
480
- }
481
- /** The union of every dependency section's package names. */
482
- function allDepNames(e) {
483
- if (!e)
484
- return [];
485
- return [
486
- ...Object.keys(e.dependencies ?? {}),
487
- ...Object.keys(e.devDependencies ?? {}),
488
- ...Object.keys(e.optionalDependencies ?? {}),
489
- ...Object.keys(e.peerDependencies ?? {}),
490
- ];
491
- }
492
- /**
493
- * Detect whether `project` is a self-contained node project or an npm
494
- * workspace member, and locate the governing root.
495
- *
496
- * @throws {Error} N1 (no lockfile anywhere), N8 (pnpm workspace — unsupported
497
- * yet), N3 (project is the workspace root), N2 (not a member of the workspace)
498
- */
499
- function discoverNodeRoot(project, owner) {
500
- const ownLock = NODE_LOCKFILES.find((f) => fs.existsSync(path.join(project, f)));
501
- if (ownLock) {
502
- // A workspace ROOT also has its own lockfile — but capturing it packs the
503
- // (usually code-less) root, not a member. Reject: the environment belongs
504
- // on a member.
505
- const pkg = JSON.parse(fs.readFileSync(path.join(project, 'package.json'), 'utf-8'));
506
- if (Array.isArray(pkg.workspaces) && pkg.workspaces.length > 0) {
507
- throw new Error(`Environment for '${owner}': declare the environment on a workspace member, not the workspace root '${project}'`);
508
- }
509
- return { mode: 'single', lockName: ownLock };
510
- }
511
- let dir = path.dirname(project);
512
- for (;;) {
513
- const found = NODE_LOCKFILES.find((f) => fs.existsSync(path.join(dir, f)));
514
- if (found) {
515
- if (found === 'pnpm-lock.yaml') {
516
- throw new Error(`Environment for '${owner}': pnpm workspaces are not yet supported as environments — use npm workspaces or a single-project env`);
517
- }
518
- const root = dir;
519
- if (path.resolve(root) === path.resolve(project)) {
520
- throw new Error(`Environment for '${owner}': declare the environment on a workspace member, not the workspace root '${root}'`);
521
- }
522
- const lock = JSON.parse(fs.readFileSync(path.join(root, found), 'utf-8'));
523
- const subject = posixRel(root, project);
524
- if (!lock.packages || !(subject in lock.packages)) {
525
- throw new Error(`Environment for '${owner}': '${project}' is not a member of the workspace at '${root}' — add it to "workspaces" and refresh the lockfile, or run 'npm install' in '${project}' for a standalone env`);
526
- }
527
- return { mode: 'workspace', root, lock, subject };
528
- }
529
- const parent = path.dirname(dir);
530
- if (parent === dir)
531
- break;
532
- dir = parent;
533
- }
534
- throw new Error(`Environment for '${owner}': no lockfile in '${project}' or any parent — run 'npm install' there, or add it to a workspace and lock at the root`);
535
- }
536
- /**
537
- * The transitive closure of LOCAL workspace members reachable from `subject`,
538
- * with export-time lock validation.
539
- *
540
- * @returns Closure members (workspace-relative path + package name), sorted by path
541
- * @throws {Error} N4 (a member's on-disk manifest drifted from the lock — npm
542
- * ci would silently install unlocked deps), N5 (a dep shadows a workspace
543
- * member name from the registry), N6 (root depends on a member), N7 (a local
544
- * dep resolves outside the workspace)
545
- */
546
- function npmClosure(lock, root, subject, owner) {
547
- const pkgs = lock.packages ?? {};
548
- const memberNames = new Set(Object.entries(pkgs)
549
- .filter(([p, e]) => p !== '' && !p.includes('node_modules/') && typeof e.name === 'string')
550
- .map(([, e]) => e.name));
551
- // N6: the root manifest must not depend on a workspace member.
552
- for (const dep of allDepNames(pkgs[''])) {
553
- if (memberNames.has(dep)) {
554
- throw new Error(`Environment for '${owner}': the workspace root depends on member '${dep}' — move member deps into the members that need them`);
555
- }
556
- }
557
- const resolveDep = (fromPath, dep) => {
558
- let dir = fromPath;
559
- for (;;) {
560
- const key = `${dir ? dir + '/' : ''}node_modules/${dep}`;
561
- if (pkgs[key])
562
- return pkgs[key];
563
- if (!dir)
564
- return null;
565
- dir = dir.split('/').slice(0, -1).join('/');
566
- }
567
- };
568
- const included = new Map(); // memberPath -> name
569
- const seen = new Set();
570
- const queue = [subject];
571
- while (queue.length > 0) {
572
- const memberPath = queue.shift();
573
- if (seen.has(memberPath))
574
- continue;
575
- seen.add(memberPath);
576
- const entry = pkgs[memberPath];
577
- if (!entry)
578
- continue;
579
- included.set(memberPath, entry.name ?? path.basename(memberPath));
580
- // N4: the locked dep sections must match the on-disk manifest.
581
- const onDisk = JSON.parse(fs.readFileSync(path.join(root, ...memberPath.split('/'), 'package.json'), 'utf-8'));
582
- for (const section of ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']) {
583
- if (JSON.stringify(onDisk[section] ?? {}) !== JSON.stringify(entry[section] ?? {})) {
584
- throw new Error(`Environment for '${owner}': '${memberPath}/package.json' ${section} differ from the lockfile — run 'npm install' to refresh the lock before exporting`);
585
- }
586
- }
587
- for (const dep of allDepNames(entry)) {
588
- const resolved = resolveDep(memberPath, dep);
589
- if (resolved?.link) {
590
- const target = resolved.resolved ?? '';
591
- if (target === '' || target.startsWith('..') || path.isAbsolute(target)) {
592
- throw new Error(`Environment for '${owner}': local dependency '${dep}' of '${memberPath}' resolves outside the workspace ('${target}')`);
593
- }
594
- queue.push(target);
595
- }
596
- else if (memberNames.has(dep)) {
597
- // N5: name collides with a workspace member but came from the registry.
598
- throw new Error(`Environment for '${owner}': '${dep}' in '${memberPath}' is satisfied from the registry, not the workspace — align its version to the workspace member (or rename)`);
599
- }
600
- }
601
- }
602
- return [...included.entries()].map(([p, name]) => ({ path: p, name })).sort((a, b) => (a.path < b.path ? -1 : 1));
603
- }
604
224
  /**
605
225
  * Resolves an environment declaration to an encoded {@link EnvironmentSpec}
606
226
  * at package export time.
@@ -613,10 +233,16 @@ function npmClosure(lock, root, subject, owner) {
613
233
  * @param decl - The declaration to resolve
614
234
  * @param owner - The declaring task/function name, for error messages
615
235
  * @param addBlob - Stores a blob in the bundle's object store, returning its hash
236
+ * @param onEvent - Told each member's artifact as it is built
237
+ * @param platforms - The stock platform packages the declaring task's runner
238
+ * names (`east-py-std`): the environment of a python workspace's member
239
+ * installs their distributions too
240
+ * @param built - The sdists the export built already, which it adds to: each
241
+ * local python package is built once in an export ({@link BuiltSdists})
616
242
  * @returns The beast2-encoded EnvironmentSpec bytes
617
243
  * @throws {Error} if the project is missing its manifest/lockfile or the build fails
618
244
  */
619
- export function captureEnvironment(decl, owner, addBlob, onEvent) {
245
+ export function captureEnvironment(decl, owner, addBlob, onEvent, platforms = [], built) {
620
246
  let spec;
621
247
  if ('image' in decl) {
622
248
  validateEnvironmentDecl(decl, owner);
@@ -641,20 +267,25 @@ export function captureEnvironment(decl, owner, addBlob, onEvent) {
641
267
  }
642
268
  return { path: `bin/${path.basename(p)}`, hash: addBlob(fs.readFileSync(p)) };
643
269
  });
644
- files.sort((a, b) => (a.path < b.path ? -1 : 1));
270
+ files.sort((a, b) => byCodePoint(a.path, b.path));
645
271
  spec = variant('tools', { files });
646
272
  }
647
273
  else if ('python' in decl) {
648
274
  const project = path.resolve(decl.python.project);
649
- // Identity + closure come from the governing (root) lock; the ROOT
650
- // manifest/lockfile are captured so materialization can `uv sync
651
- // --all-packages` the whole third-party set. A member's own pyproject
652
- // rides inside its sdist. For a standalone project root === project, so
653
- // the captured spec is byte-identical to the pre-#278 single-project one.
275
+ // Identity + closure come from the governing (root) lock. A member's own
276
+ // pyproject rides inside its sdist.
654
277
  const { root, lock, subject } = discoverPythonRoot(project, owner);
278
+ // A member of a workspace names itself, so its environment installs its
279
+ // own dependencies and not its workspace's (#1654)
280
+ if (canonicalPath(root) !== canonicalPath(project)) {
281
+ return captureWorkspacePython(root, lock, [subject], platforms, owner, addBlob, onEvent, built);
282
+ }
283
+ // A project that is its own root: the ROOT manifest/lockfile are its own,
284
+ // and materialization syncs the whole of its lock. The captured spec is
285
+ // byte-identical to the pre-#278 single-project one.
655
286
  const pyproject = addBlob(readProjectFile(root, 'pyproject.toml', owner));
656
287
  const lockBlob = addBlob(readProjectFile(root, 'uv.lock', owner));
657
- const sdists = buildMemberSdists(pythonClosure(lock, root, subject, owner), owner, addBlob, onEvent);
288
+ const sdists = buildMemberSdists(pythonClosure(lock, root, [subject], owner), owner, addBlob, onEvent, built);
658
289
  spec = variant('python', { pyproject, lock: lockBlob, sdists });
659
290
  }
660
291
  else {