@givelotus/compiler 0.0.0-stage → 0.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.
Files changed (87) hide show
  1. package/README.md +331 -2
  2. package/artifact-v2.schema.json +58 -0
  3. package/artifact.schema.json +19 -0
  4. package/dist/ast.d.ts +292 -0
  5. package/dist/ast.js +150 -0
  6. package/dist/bindings.d.ts +6 -0
  7. package/dist/bindings.js +134 -0
  8. package/dist/call-runtime.d.ts +84 -0
  9. package/dist/call-runtime.js +249 -0
  10. package/dist/cli.d.ts +2 -0
  11. package/dist/cli.js +22 -0
  12. package/dist/compiler.d.ts +79 -0
  13. package/dist/compiler.js +125 -0
  14. package/dist/diagnostics.d.ts +163 -0
  15. package/dist/diagnostics.js +498 -0
  16. package/dist/ecash.d.ts +41 -0
  17. package/dist/ecash.js +190 -0
  18. package/dist/fees.d.ts +164 -0
  19. package/dist/fees.js +208 -0
  20. package/dist/fixture-cli.d.ts +2 -0
  21. package/dist/fixture-cli.js +41 -0
  22. package/dist/fixtures.d.ts +68 -0
  23. package/dist/fixtures.js +46 -0
  24. package/dist/forth-ir.d.ts +73 -0
  25. package/dist/forth-ir.js +147 -0
  26. package/dist/generic-cli.d.ts +2 -0
  27. package/dist/generic-cli.js +140 -0
  28. package/dist/generic.d.ts +48 -0
  29. package/dist/generic.js +2566 -0
  30. package/dist/lints.d.ts +8 -0
  31. package/dist/lints.js +204 -0
  32. package/dist/names.d.ts +1 -0
  33. package/dist/names.js +7 -0
  34. package/dist/opcodes.d.ts +154 -0
  35. package/dist/opcodes.js +162 -0
  36. package/dist/optimizer.d.ts +58 -0
  37. package/dist/optimizer.js +786 -0
  38. package/dist/package-fetch-cli.d.ts +2 -0
  39. package/dist/package-fetch-cli.js +17 -0
  40. package/dist/package-lock-cli.d.ts +2 -0
  41. package/dist/package-lock-cli.js +28 -0
  42. package/dist/package-sources.d.ts +82 -0
  43. package/dist/package-sources.js +785 -0
  44. package/dist/package-update-cli.d.ts +2 -0
  45. package/dist/package-update-cli.js +20 -0
  46. package/dist/packages.d.ts +231 -0
  47. package/dist/packages.js +1307 -0
  48. package/dist/parser.d.ts +32 -0
  49. package/dist/parser.js +575 -0
  50. package/dist/policy.d.ts +83 -0
  51. package/dist/policy.js +207 -0
  52. package/dist/runtime.d.ts +58 -0
  53. package/dist/runtime.js +126 -0
  54. package/dist/scheduler.d.ts +38 -0
  55. package/dist/scheduler.js +76 -0
  56. package/dist/semantic-ir.d.ts +76 -0
  57. package/dist/semantic-ir.js +231 -0
  58. package/dist/std.d.ts +27 -0
  59. package/dist/std.js +225 -0
  60. package/dist/target-compiler.d.ts +9 -0
  61. package/dist/target-compiler.js +139 -0
  62. package/dist/targets.d.ts +53 -0
  63. package/dist/targets.js +67 -0
  64. package/dist/toml-subset.d.ts +19 -0
  65. package/dist/toml-subset.js +81 -0
  66. package/dist/transaction-runtime.d.ts +182 -0
  67. package/dist/transaction-runtime.js +646 -0
  68. package/dist/version.d.ts +3 -0
  69. package/dist/version.js +3 -0
  70. package/dist/vm-cost.d.ts +11 -0
  71. package/dist/vm-cost.js +541 -0
  72. package/package.json +71 -4
  73. package/policy-artifact.schema.json +20 -0
  74. package/std/custody/arbiter-escrow.lotus +20 -0
  75. package/std/custody/htlc.lotus +15 -0
  76. package/std/custody/multisig-2of3.lotus +13 -0
  77. package/std/custody/single-owner-wallet.lotus +9 -0
  78. package/std/custody/vault-with-recovery.lotus +14 -0
  79. package/std/defi/amm-pool-v2.lotus +97 -0
  80. package/std/defi/indexed-limit-order.lotus +37 -0
  81. package/std/nft/nft-collection.lotus +51 -0
  82. package/std/nft/royalty-transfer-rules.lotus +38 -0
  83. package/std/nft/unique-nft.lotus +30 -0
  84. package/std/tokens/capped-supply-token.lotus +76 -0
  85. package/std/tokens/fixed-supply-token.lotus +29 -0
  86. package/std/tokens/standard-transfer-rules.lotus +15 -0
  87. package/std/tokens/voucher-mint-token.lotus +31 -0
@@ -0,0 +1,785 @@
1
+ /**
2
+ * Decentralized package sources for the Lotus compiler. A package is named by the
3
+ * path where it lives: known forges derive `https://host/owner/repo.git`, and any
4
+ * other host needs an explicit root `[sources]` locator. There is no registry.
5
+ *
6
+ * `fetchPackages` is the only networked entry. It runs git with hooks and templates
7
+ * disabled and writes `.lotus/deps` or `vendor`. `compilePackage` and lock checks
8
+ * stay offline: they read the lock, that cache and declared files, and never spawn git.
9
+ */
10
+ import { spawnSync } from 'node:child_process';
11
+ import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
12
+ import { tmpdir } from 'node:os';
13
+ import { join, sep } from 'node:path';
14
+ import { hex } from './compiler.js';
15
+ import { CompileError } from './diagnostics.js';
16
+ import { parseModuleSource } from './generic.js';
17
+ import { DEFAULT_PACKAGE_LIMITS, LOCK_FILE, MANIFEST_FILE, PackageError, parseManifest, relPath, resolveWorkspace, scanPackage } from './packages.js';
18
+ export const LOCK_SCHEMA_V2 = 'lotus/package-lock/2';
19
+ const FORGES = new Set(['github.com', 'gitlab.com', 'bitbucket.org', 'codeberg.org']);
20
+ const SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
21
+ const TAG = /^v(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})$/;
22
+ const COMMIT = /^[0-9a-f]{40}$/;
23
+ const RANGE = /^([~^])v?(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})$/;
24
+ const GIT_FLAGS = ['-c', 'core.hooksPath=', '-c', 'core.fsmonitor=', '-c', 'credential.helper=', '-c', 'safe.directory=*',
25
+ '-c', 'filter.smudge=', '-c', 'filter.clean=', '-c', 'filter.process=', '-c', 'protocol.file.allow=always'];
26
+ const posix = (...parts) => parts.filter(part => part !== '' && part !== '.').join('/');
27
+ export function isGitLocator(value) { return value.startsWith('https://') || value.startsWith('file://'); }
28
+ export function assertGitLocator(value, file) {
29
+ const hash = value.lastIndexOf('#');
30
+ const url = hash >= 0 ? value.slice(0, hash) : value;
31
+ const dir = hash >= 0 ? value.slice(hash + 1) : '';
32
+ if (!isGitLocator(url))
33
+ throw new PackageError('locator', 'git locator must be an https or file URL', file);
34
+ assertUrl(url, file);
35
+ if (dir)
36
+ relPath(dir, 'locator dir', file ?? 'lotus.toml');
37
+ return { url, dir };
38
+ }
39
+ function assertUrl(url, file) {
40
+ if (url.startsWith('-') || /\s/.test(url) || url.includes('\\') || url.includes('@'))
41
+ throw new PackageError('locator', `refusing git URL ${url}`, file);
42
+ if (url.startsWith('file://')) {
43
+ if (!url.startsWith('file:///'))
44
+ throw new PackageError('locator', 'file URL must be absolute (file:///...)', file);
45
+ return;
46
+ }
47
+ if (!/^https:\/\/[^/\s]+\/\S+$/.test(url))
48
+ throw new PackageError('locator', `git URL must be https or file: ${url}`, file);
49
+ }
50
+ /** Known-forge and explicit module paths. `/vN` (N >= 2) is only a major suffix when it is the final element. */
51
+ export function parseModulePath(module, file) {
52
+ if (/\/v[01]$/.test(module))
53
+ throw new PackageError('manifest', `module path ${module} must not use a /v0 or /v1 suffix; v0 and v1 have no major suffix`, file);
54
+ if (!module || module.length > 512 || module.includes('\\') || module.includes('@') || module.startsWith('/') || module.endsWith('/'))
55
+ throw new PackageError('manifest', `invalid module path ${module}`, file);
56
+ const parts = module.split('/');
57
+ if (parts.length < 2 || parts.some(part => !SEGMENT.test(part)))
58
+ throw new PackageError('manifest', `invalid module path ${module}`, file);
59
+ let suffixMajor;
60
+ const suffix = /^v([2-9]|[1-9][0-9]+)$/.exec(parts[parts.length - 1] ?? '');
61
+ if (suffix) {
62
+ suffixMajor = Number(suffix[1]);
63
+ parts.pop();
64
+ if (parts.length < 2)
65
+ throw new PackageError('manifest', `invalid module path ${module}`, file);
66
+ }
67
+ const host = parts[0];
68
+ if (FORGES.has(host)) {
69
+ if (parts.length < 3)
70
+ throw new PackageError('manifest', `forge module ${module} needs host/owner/repo`, file);
71
+ return { module, host, owner: parts[1], repo: parts[2], forge: true, ...(suffixMajor !== undefined ? { suffixMajor } : {}), subdir: parts.slice(3).join('/') };
72
+ }
73
+ return { module, host, forge: false, ...(suffixMajor !== undefined ? { suffixMajor } : {}), subdir: '' };
74
+ }
75
+ export function isModulePath(module) { try {
76
+ parseModulePath(module);
77
+ return true;
78
+ }
79
+ catch {
80
+ return false;
81
+ } }
82
+ /** `https://host/owner/repo.git` for a known forge. Major suffixes and subdirectories are not part of the URL. */
83
+ export function forgeGitUrl(module, file) {
84
+ const ref = parseModulePath(module, file);
85
+ if (!ref.forge || !ref.owner || !ref.repo)
86
+ throw new PackageError('locator', `${module} has no forge repository`, file);
87
+ return `https://${ref.host}/${ref.owner}/${ref.repo}.git`;
88
+ }
89
+ function semver(major, minor, patch) {
90
+ const value = { major: Number(major), minor: Number(minor), patch: Number(patch), text: '' };
91
+ value.text = `v${value.major}.${value.minor}.${value.patch}`;
92
+ return value;
93
+ }
94
+ function classifySelector(selector, ref, file) {
95
+ const tag = TAG.exec(selector);
96
+ if (tag) {
97
+ const value = semver(tag[1], tag[2], tag[3]);
98
+ assertMajor(ref, value, file);
99
+ return { kind: 'tag', semver: value };
100
+ }
101
+ if (COMMIT.test(selector))
102
+ return { kind: 'commit', commit: selector };
103
+ const range = RANGE.exec(selector);
104
+ if (range) {
105
+ const value = semver(range[2], range[3], range[4]);
106
+ assertMajor(ref, value, file);
107
+ return { kind: 'range', op: range[1], semver: value, text: selector };
108
+ }
109
+ return { kind: 'branch', name: selector };
110
+ }
111
+ function assertMajor(ref, version, file) {
112
+ if (ref.suffixMajor !== undefined) {
113
+ if (version.major !== ref.suffixMajor)
114
+ throw new PackageError('manifest', `module ${ref.module} requires v${ref.suffixMajor}.x.y, not ${version.text}`, file);
115
+ return;
116
+ }
117
+ if (version.major >= 2)
118
+ throw new PackageError('manifest', `${version.text} must use module path ${ref.module}/v${version.major}`, file);
119
+ }
120
+ export function classifyRequirement(target, file) {
121
+ const at = target.lastIndexOf('@');
122
+ if (at <= 0 || at !== target.indexOf('@'))
123
+ throw new PackageError('manifest', `dependency ${JSON.stringify(target)} must be name@version or module@selector`, file);
124
+ const left = target.slice(0, at);
125
+ const right = target.slice(at + 1);
126
+ if (!right || right.includes(' ') || right.includes('..'))
127
+ throw new PackageError('manifest', `invalid selector in ${JSON.stringify(target)}`, file);
128
+ if (!left.includes('/')) {
129
+ if (!/^[a-z_][a-z0-9_]{0,63}$/.test(left) || !/^(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})$/.test(right))
130
+ throw new PackageError('manifest', `dependency ${JSON.stringify(target)} must be an exact "name@MAJOR.MINOR.PATCH" or a module selector`, file);
131
+ return { kind: 'path', name: left, version: right };
132
+ }
133
+ const ref = parseModulePath(left, file);
134
+ return { kind: 'module', module: left, ref, selector: classifySelector(right, ref, file) };
135
+ }
136
+ function assertExact(req, file) {
137
+ if (req.kind !== 'module' || req.selector.kind === 'tag' || req.selector.kind === 'commit')
138
+ return;
139
+ const shown = req.selector.kind === 'branch' ? req.selector.name : req.selector.text;
140
+ throw new PackageError('branch', `selector ${JSON.stringify(shown)} is not an exact vX.Y.Z tag or 40-hex commit; branches and ranges resolve only through lotus-package-update`, file);
141
+ }
142
+ function cmp(a, b) { return a.major - b.major || a.minor - b.minor || a.patch - b.patch; }
143
+ function satisfies(version, op, base) {
144
+ if (cmp(version, base) < 0)
145
+ return false;
146
+ if (op === '~')
147
+ return version.major === base.major && version.minor === base.minor;
148
+ if (base.major > 0)
149
+ return version.major === base.major;
150
+ if (base.minor > 0)
151
+ return version.major === 0 && version.minor === base.minor;
152
+ return version.major === 0 && version.minor === 0 && version.patch === base.patch;
153
+ }
154
+ function selectorText(selector) {
155
+ if (selector.kind === 'tag')
156
+ return selector.semver.text;
157
+ if (selector.kind === 'commit')
158
+ return selector.commit;
159
+ if (selector.kind === 'range')
160
+ return selector.text;
161
+ return selector.name;
162
+ }
163
+ function quotedImports(info) {
164
+ const specs = [];
165
+ const entry = info.manifest.entry ? `${info.manifest.source}/${info.manifest.entry}.lotus` : undefined;
166
+ for (const file of info.files) {
167
+ if (!file.path.endsWith('.lotus'))
168
+ continue;
169
+ const display = posix(info.root, file.path);
170
+ let text;
171
+ try {
172
+ text = new TextDecoder('utf-8', { fatal: true }).decode(file.content);
173
+ }
174
+ catch {
175
+ throw new PackageError('manifest', 'file is not valid UTF-8', display);
176
+ }
177
+ let program;
178
+ try {
179
+ program = parseModuleSource(text, info.isRoot && file.path === entry, display);
180
+ }
181
+ catch (error) {
182
+ if (error instanceof CompileError)
183
+ throw error;
184
+ throw new PackageError('parse', error.message, display);
185
+ }
186
+ for (const decl of program.imports)
187
+ if (decl.target.includes('/'))
188
+ specs.push(decl.target);
189
+ }
190
+ return specs;
191
+ }
192
+ function collectSeeds(info) {
193
+ const seeds = [];
194
+ for (const spec of info.manifest.dependencies.values())
195
+ seeds.push({ spec, from: info.id, file: info.manifestFile });
196
+ for (const spec of quotedImports(info))
197
+ seeds.push({ spec, from: info.id, file: info.manifestFile });
198
+ for (const seed of seeds)
199
+ assertExact(classifyRequirement(seed.spec, seed.file), seed.file);
200
+ return seeds;
201
+ }
202
+ let templateDir;
203
+ let globalConfig;
204
+ function gitEnv() {
205
+ if (!templateDir)
206
+ templateDir = mkdtempSync(join(tmpdir(), 'lotus-git-template-'));
207
+ if (!globalConfig) {
208
+ const dir = mkdtempSync(join(tmpdir(), 'lotus-git-config-'));
209
+ globalConfig = join(dir, 'config');
210
+ writeFileSync(globalConfig, '');
211
+ }
212
+ return { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: globalConfig, GIT_TEMPLATE_DIR: templateDir,
213
+ GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: 'true', GIT_ATTR_NOSYSTEM: '1' };
214
+ }
215
+ function runGit(args) {
216
+ const result = spawnSync('git', [...GIT_FLAGS, ...args], { encoding: 'utf8', timeout: 60_000, env: gitEnv(), windowsHide: true });
217
+ if (result.error)
218
+ throw new PackageError('fetch', `git failed to start: ${result.error.message}`);
219
+ if (result.status !== 0) {
220
+ const detail = (result.stderr || result.stdout || '').trim().slice(0, 500);
221
+ throw new PackageError('fetch', `git ${args.filter(arg => !arg.startsWith('-')).slice(0, 3).join(' ')} failed${detail ? `: ${detail}` : ''}`);
222
+ }
223
+ return result.stdout;
224
+ }
225
+ function locatePackageDir(checkout, ref, prefix) {
226
+ const candidates = [];
227
+ if (ref.suffixMajor !== undefined)
228
+ candidates.push(prefix ? `${prefix}/v${ref.suffixMajor}` : `v${ref.suffixMajor}`);
229
+ candidates.push(prefix);
230
+ for (let index = 0; index < candidates.length; index++) {
231
+ const rel = candidates[index];
232
+ const manifestPath = join(checkout, ...(rel ? rel.split('/') : []), MANIFEST_FILE);
233
+ if (!existsSync(manifestPath))
234
+ continue;
235
+ // A vN/lotus.toml is the package root when it exists. Otherwise the repository
236
+ // (or explicit) directory is the root only when its manifest major matches.
237
+ if (ref.suffixMajor !== undefined && index === 0)
238
+ return rel;
239
+ const manifest = parseManifest(readFileSync(manifestPath, 'utf8'), rel ? `${rel}/${MANIFEST_FILE}` : MANIFEST_FILE);
240
+ const major = Number(manifest.version.split('.')[0]);
241
+ if (ref.suffixMajor !== undefined) {
242
+ if (major === ref.suffixMajor)
243
+ return rel;
244
+ continue;
245
+ }
246
+ if (major === 0 || major === 1)
247
+ return rel;
248
+ throw new PackageError('manifest', `version ${manifest.version} requires module path ${ref.module}/v${major}`, rel ? `${rel}/${MANIFEST_FILE}` : MANIFEST_FILE);
249
+ }
250
+ throw new PackageError('manifest', `no lotus.toml for ${ref.module} identifies its major version`);
251
+ }
252
+ function contained(parent, child) {
253
+ const base = parent.endsWith(sep) ? parent : parent + sep;
254
+ return child === parent || child.startsWith(base);
255
+ }
256
+ function checkIdentity(info, ref, selector) {
257
+ if (info.manifest.name !== ref.module)
258
+ throw new PackageError('manifest', `package name ${JSON.stringify(info.manifest.name)} does not match module path ${ref.module}`, info.manifestFile);
259
+ const major = Number(info.manifest.version.split('.')[0]);
260
+ if (ref.suffixMajor !== undefined && major !== ref.suffixMajor)
261
+ throw new PackageError('manifest', `module ${ref.module} requires major ${ref.suffixMajor}, found ${info.manifest.version}`, info.manifestFile);
262
+ if (ref.suffixMajor === undefined && major >= 2)
263
+ throw new PackageError('manifest', `version ${info.manifest.version} requires module path suffix /v${major}`, info.manifestFile);
264
+ if (selector.startsWith('v') && info.manifest.version !== selector.slice(1))
265
+ throw new PackageError('version-conflict', `tag ${selector} resolved to manifest version ${info.manifest.version}`, info.manifestFile);
266
+ if (info.manifest.kind !== 'library')
267
+ throw new PackageError('declaration-only', `dependency ${ref.module}@${selector} must be a library package`, info.manifestFile);
268
+ }
269
+ function fetchInto(project, cacheRoot, ref, selector, url, prefix) {
270
+ assertUrl(url);
271
+ const temp = mkdtempSync(join(tmpdir(), 'lotus-git-fetch-'));
272
+ try {
273
+ runGit(['init', '--template', templateDir ?? gitEnv().GIT_TEMPLATE_DIR, temp]);
274
+ runGit(['-C', temp, 'remote', 'add', 'origin', url]);
275
+ runGit(['-C', temp, 'fetch', '--depth=1', 'origin', selector]);
276
+ runGit(['-C', temp, 'checkout', '--detach', 'FETCH_HEAD']);
277
+ const commit = runGit(['-C', temp, 'rev-parse', 'HEAD']).trim();
278
+ const gitTree = runGit(['-C', temp, 'rev-parse', 'HEAD^{tree}']).trim();
279
+ if (!COMMIT.test(commit) || !COMMIT.test(gitTree))
280
+ throw new PackageError('fetch', 'git did not return a commit and tree id');
281
+ rmSync(join(temp, '.git'), { recursive: true, force: true });
282
+ const dir = locatePackageDir(temp, ref, prefix);
283
+ const selectorRel = posix(cacheRoot, ref.module, selector);
284
+ const checkoutRel = posix(selectorRel, commit);
285
+ const selectorAbs = join(project, ...selectorRel.split('/'));
286
+ rmSync(selectorAbs, { recursive: true, force: true });
287
+ mkdirSync(selectorAbs, { recursive: true });
288
+ const checkoutAbs = join(project, ...checkoutRel.split('/'));
289
+ try {
290
+ renameSync(temp, checkoutAbs);
291
+ }
292
+ catch (error) {
293
+ if (error.code !== 'EXDEV')
294
+ throw error;
295
+ cpSync(temp, checkoutAbs, { recursive: true });
296
+ rmSync(temp, { recursive: true, force: true });
297
+ }
298
+ const meta = { commit, gitTree, url, dir };
299
+ writeFileSync(join(selectorAbs, `${commit}.json`), JSON.stringify(meta) + '\n');
300
+ return { ...meta, checkoutRel };
301
+ }
302
+ catch (error) {
303
+ rmSync(temp, { recursive: true, force: true });
304
+ throw error;
305
+ }
306
+ }
307
+ function readMeta(project, module, selector) {
308
+ const hits = [];
309
+ for (const root of ['.lotus/deps', 'vendor']) {
310
+ const dir = join(project, ...posix(root, module, selector).split('/'));
311
+ if (!existsSync(dir))
312
+ continue;
313
+ for (const name of readdirSync(dir)) {
314
+ if (!/^[0-9a-f]{40}\.json$/.test(name))
315
+ continue;
316
+ const commit = name.slice(0, 40);
317
+ if (existsSync(join(dir, commit)))
318
+ hits.push({ root, commit });
319
+ }
320
+ }
321
+ const roots = new Set(hits.map(hit => hit.root));
322
+ if (hits.length === 0)
323
+ throw new PackageError('unfetched', `no cached ${module}@${selector}; run lotus-package-fetch (compile does not fetch)`);
324
+ if (roots.size > 1)
325
+ throw new PackageError('unfetched', `both .lotus/deps and vendor contain ${module}@${selector}; keep only one`);
326
+ if (hits.length !== 1)
327
+ throw new PackageError('unfetched', `cached ${module}@${selector} has more than one commit; run lotus-package-fetch`);
328
+ const hit = hits[0];
329
+ const selectorRel = posix(hit.root, module, selector);
330
+ let meta;
331
+ try {
332
+ meta = JSON.parse(readFileSync(join(project, ...selectorRel.split('/'), `${hit.commit}.json`), 'utf8'));
333
+ }
334
+ catch {
335
+ throw new PackageError('unfetched', `cached metadata for ${module}@${selector} is unreadable`);
336
+ }
337
+ if (meta.commit !== hit.commit || !COMMIT.test(meta.gitTree) || typeof meta.url !== 'string' || typeof meta.dir !== 'string')
338
+ throw new PackageError('unfetched', `cached metadata for ${module}@${selector} is not a fetch record`);
339
+ if (meta.dir)
340
+ relPath(meta.dir, 'cached dir', `${module}@${selector}`);
341
+ assertUrl(meta.url);
342
+ return { ...meta, checkoutRel: posix(selectorRel, hit.commit) };
343
+ }
344
+ function adopt(project, checkoutRel, dir, ref, selector, budget) {
345
+ const packageRel = dir ? posix(checkoutRel, dir) : checkoutRel;
346
+ const checkoutAbs = join(project, ...checkoutRel.split('/'));
347
+ const packageAbs = join(project, ...packageRel.split('/'));
348
+ if (!contained(realpathSync(checkoutAbs), realpathSync(packageAbs)))
349
+ throw new PackageError('symlink-escape', 'package root resolves outside the fetched repository', packageRel);
350
+ const info = scanPackage(project, packageRel, false, budget);
351
+ checkIdentity(info, ref, selector);
352
+ info.id = `${ref.module}@${selector}`;
353
+ info.selectedVersion = selector;
354
+ return info;
355
+ }
356
+ function derive(session, ref) {
357
+ const replacement = session.root.manifest.replace.get(ref.module);
358
+ if (replacement !== undefined && isGitLocator(replacement))
359
+ return { ...assertGitLocator(replacement, session.root.manifestFile), replaced: true };
360
+ if (!ref.forge) {
361
+ const pinned = session.root.manifest.sources.get(ref.module);
362
+ if (pinned === undefined)
363
+ throw new PackageError('locator', `no root [sources] locator for ${ref.module}; unknown hosts are not guessed and dependency locators are ignored`, session.root.manifestFile);
364
+ return { ...assertGitLocator(pinned, session.root.manifestFile), replaced: false };
365
+ }
366
+ const url = session.online?.resolveRepoUrl?.({ host: ref.host, owner: ref.owner ?? '', repo: ref.repo ?? '', module: ref.module })
367
+ ?? forgeGitUrl(ref.module, session.root.manifestFile);
368
+ assertUrl(url, session.root.manifestFile);
369
+ return { url, dir: '', replaced: false };
370
+ }
371
+ function prefixFor(ref, explicitDir, replaced) {
372
+ if (replaced || !ref.forge)
373
+ return explicitDir;
374
+ return ref.subdir;
375
+ }
376
+ function loadGit(session, ref, selector, replacedGit) {
377
+ const derived = replacedGit ?? derive(session, ref);
378
+ const located = session.online
379
+ ? fetchInto(session.project, session.online.vendor ? 'vendor' : '.lotus/deps', ref, selector, derived.url, prefixFor(ref, derived.dir, replacedGit !== undefined))
380
+ : readMeta(session.project, ref.module, selector);
381
+ const info = adopt(session.project, located.checkoutRel, located.dir, ref, selector, session.budget);
382
+ return { info, seeds: collectSeeds(info), override: replacedGit !== undefined, locator: { kind: 'git', url: located.url, dir: located.dir }, commit: located.commit, gitTree: located.gitTree };
383
+ }
384
+ function loadPathReplace(session, choice, path) {
385
+ relPath(path, `[replace] ${choice.module}`, session.root.manifestFile);
386
+ const info = scanPackage(session.project, path, false, session.budget);
387
+ if (info.manifest.name !== choice.module)
388
+ throw new PackageError('manifest', `replacement ${path} is ${info.id}, not ${choice.module}`, info.manifestFile);
389
+ const major = Number(info.manifest.version.split('.')[0]);
390
+ if (choice.ref.suffixMajor !== undefined && major !== choice.ref.suffixMajor)
391
+ throw new PackageError('manifest', `replacement ${path} has major ${major}, required ${choice.ref.suffixMajor}`, info.manifestFile);
392
+ if (choice.ref.suffixMajor === undefined && major >= 2)
393
+ throw new PackageError('manifest', `replacement version ${info.manifest.version} requires /v${major}`, info.manifestFile);
394
+ if (info.manifest.kind !== 'library')
395
+ throw new PackageError('declaration-only', `dependency ${choice.module} must be a library package`, info.manifestFile);
396
+ const selected = `v${info.manifest.version}`;
397
+ info.id = `${choice.module}@${selected}`;
398
+ info.selectedVersion = selected;
399
+ return { info, seeds: collectSeeds(info), override: true, locator: { kind: 'path', path } };
400
+ }
401
+ function loadPath(session, choice) {
402
+ const locator = session.root.manifest.sources.get(choice.name);
403
+ if (locator === undefined || isModulePath(choice.name))
404
+ throw new PackageError('manifest', `no [sources] locator for ${choice.name} in the root manifest`, session.root.manifestFile);
405
+ const info = scanPackage(session.project, locator, false, session.budget);
406
+ if (info.id !== `${choice.name}@${choice.version}`)
407
+ throw new PackageError('version-conflict', `locator ${locator} contains ${info.id}, expected ${choice.name}@${choice.version}`, info.manifestFile);
408
+ if (info.manifest.kind !== 'library')
409
+ throw new PackageError('declaration-only', `dependency ${info.id} must be a library package`, info.manifestFile);
410
+ return { info, seeds: collectSeeds(info), override: false, locator: { kind: 'path', path: locator } };
411
+ }
412
+ function semverOf(selected) {
413
+ const match = /^v(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})$/.exec(selected ?? '');
414
+ return match ? semver(match[1], match[2], match[3]) : undefined;
415
+ }
416
+ function selectorKey(choice) {
417
+ if (choice.tag)
418
+ return choice.tag.text;
419
+ const commit = choice.commits[0];
420
+ if (choice.commits.length === 1 && commit)
421
+ return commit;
422
+ throw new PackageError('manifest', `no version selected for ${choice.module}`);
423
+ }
424
+ function pushReq(list, pkg, required) {
425
+ if (!list.some(item => item.package === pkg && item.required === required))
426
+ list.push({ package: pkg, required });
427
+ }
428
+ /** Resolve module requirements from the root and selected manifests. Offline when `online` is omitted. */
429
+ export function resolveDistributedSources(project, root, limits, budget, online) {
430
+ const session = { project, root, limits, budget, ...(online ? { online } : {}) };
431
+ for (const [key, value] of root.manifest.replace) {
432
+ if (!isModulePath(key))
433
+ throw new PackageError('manifest', `[replace] key ${key} must be a module path`, root.manifestFile);
434
+ if (!isGitLocator(value))
435
+ relPath(value, `[replace] ${key}`, root.manifestFile);
436
+ else
437
+ assertGitLocator(value, root.manifestFile);
438
+ }
439
+ for (const [key, value] of root.manifest.sources)
440
+ if (isModulePath(key)) {
441
+ const ref = parseModulePath(key, root.manifestFile);
442
+ if (ref.forge)
443
+ throw new PackageError('manifest', `[sources] cannot override forge module ${key}; use [replace]`, root.manifestFile);
444
+ assertGitLocator(value, root.manifestFile);
445
+ }
446
+ // Go minimal version selection: the highest tag required by the root or by a
447
+ // selected version. Requirements of a version that lost the max are ignored.
448
+ // A raw commit is never bumped to a different object. Tag and commit agree only
449
+ // when that tag resolves to the commit.
450
+ const cache = new Map();
451
+ const selectedMods = new Map();
452
+ const selectedPaths = new Map();
453
+ const edgesFrom = () => {
454
+ const edges = [...collectSeeds(root)];
455
+ for (const item of selectedMods.values())
456
+ edges.push(...item.got.seeds);
457
+ for (const item of selectedPaths.values())
458
+ edges.push(...item.got.seeds);
459
+ return edges;
460
+ };
461
+ const buildChoices = (edges) => {
462
+ const choices = new Map();
463
+ const paths = new Map();
464
+ for (const seed of edges) {
465
+ const req = classifyRequirement(seed.spec, seed.file);
466
+ if (req.kind === 'path') {
467
+ if (req.name === root.manifest.name)
468
+ throw new PackageError('package-cycle', `${seed.from} depends on the root package ${root.id}`, seed.file);
469
+ const prior = paths.get(req.name);
470
+ if (prior && prior.version !== req.version)
471
+ prior.conflict = `${seed.from} requires ${req.name}@${req.version} but ${prior.version} is also required`;
472
+ const choice = prior ?? { name: req.name, version: req.version, requesters: [] };
473
+ if (!prior)
474
+ paths.set(req.name, choice);
475
+ pushReq(choice.requesters, seed.from, req.version);
476
+ continue;
477
+ }
478
+ if (req.module === root.manifest.name)
479
+ throw new PackageError('package-cycle', `${seed.from} depends on the root package ${root.id}`, seed.file);
480
+ const prior = choices.get(req.module);
481
+ const choice = prior ?? { module: req.module, ref: req.ref, commits: [], requesters: [] };
482
+ if (!prior)
483
+ choices.set(req.module, choice);
484
+ pushReq(choice.requesters, seed.from, selectorText(req.selector));
485
+ if (req.selector.kind === 'tag') {
486
+ if (!choice.tag || cmp(req.selector.semver, choice.tag) > 0)
487
+ choice.tag = req.selector.semver;
488
+ }
489
+ else if (req.selector.kind === 'commit' && !choice.commits.includes(req.selector.commit))
490
+ choice.commits.push(req.selector.commit);
491
+ }
492
+ return { choices, paths };
493
+ };
494
+ const loadChoice = (choice) => {
495
+ const replacement = root.manifest.replace.get(choice.module);
496
+ if (replacement !== undefined && !isGitLocator(replacement)) {
497
+ const key = `${choice.module}\0replace`;
498
+ const cached = cache.get(key);
499
+ if (cached)
500
+ return cached;
501
+ const got = loadPathReplace(session, choice, replacement);
502
+ cache.set(key, got);
503
+ return got;
504
+ }
505
+ const gitReplace = replacement !== undefined ? assertGitLocator(replacement, root.manifestFile) : undefined;
506
+ const key = `${choice.module}\0${gitReplace ? 'git-replace:' : ''}${selectorKey(choice)}`;
507
+ const cached = cache.get(key);
508
+ if (cached)
509
+ return cached;
510
+ const got = loadGit(session, choice.ref, selectorKey(choice), gitReplace);
511
+ cache.set(key, got);
512
+ return got;
513
+ };
514
+ const assertCovers = (got, choice) => {
515
+ if (choice.commits.length && got.locator.kind === 'path')
516
+ throw new PackageError('version-conflict', `path replacement for ${choice.module} cannot satisfy commit pin ${choice.commits.join(', ')}`, got.info.manifestFile);
517
+ const pinned = choice.commits[0];
518
+ if (choice.tag && choice.commits.length === 1 && pinned && got.commit !== pinned)
519
+ throw new PackageError('version-conflict', `tag ${choice.tag.text} of ${choice.module} resolves to ${got.commit ?? 'no commit'}, not ${pinned}`, got.info.manifestFile);
520
+ if (choice.tag && got.locator.kind === 'path') {
521
+ const [major, minor, patch] = got.info.manifest.version.split('.').map(Number);
522
+ const local = { major: major ?? 0, minor: minor ?? 0, patch: patch ?? 0, text: '' };
523
+ if (cmp(local, choice.tag) < 0)
524
+ throw new PackageError('version-conflict', `${got.info.id} is older than required ${choice.tag.text}`, got.info.manifestFile);
525
+ }
526
+ };
527
+ let stable = false;
528
+ for (let guard = 0; guard < limits.maxPackages * 8 + 8 && !stable; guard++) {
529
+ const { choices, paths } = buildChoices(edgesFrom());
530
+ if (choices.size + paths.size > limits.maxPackages)
531
+ throw new PackageError('limit', `package graph exceeds ${limits.maxPackages} packages`, root.manifestFile);
532
+ let upgraded = false;
533
+ for (const choice of choices.values()) {
534
+ const prev = selectedMods.get(choice.module);
535
+ if (!prev || !choice.tag)
536
+ continue;
537
+ if (prev.selector === choice.tag.text)
538
+ continue;
539
+ const loaded = semverOf(prev.selector);
540
+ if (loaded && cmp(choice.tag, loaded) <= 0)
541
+ continue;
542
+ selectedMods.set(choice.module, { selector: choice.tag.text, got: loadChoice(choice) });
543
+ upgraded = true;
544
+ }
545
+ if (upgraded)
546
+ continue;
547
+ let dropped = false;
548
+ for (const key of [...selectedMods.keys()])
549
+ if (!choices.has(key)) {
550
+ selectedMods.delete(key);
551
+ dropped = true;
552
+ }
553
+ for (const key of [...selectedPaths.keys()])
554
+ if (!paths.has(key)) {
555
+ selectedPaths.delete(key);
556
+ dropped = true;
557
+ }
558
+ if (dropped)
559
+ continue;
560
+ let moved = false;
561
+ for (const choice of choices.values()) {
562
+ if (choice.tag || choice.commits.length !== 1)
563
+ continue;
564
+ const prev = selectedMods.get(choice.module);
565
+ const only = choice.commits[0];
566
+ if (prev && prev.got.commit !== only) {
567
+ selectedMods.set(choice.module, { selector: only, got: loadChoice(choice) });
568
+ moved = true;
569
+ }
570
+ }
571
+ if (moved)
572
+ continue;
573
+ for (const choice of paths.values())
574
+ if (choice.conflict)
575
+ throw new PackageError('version-conflict', choice.conflict, root.manifestFile);
576
+ for (const choice of choices.values()) {
577
+ if (choice.commits.length > 1)
578
+ throw new PackageError('version-conflict', `${choice.module} is pinned to commits ${choice.commits.join(' and ')}`, root.manifestFile);
579
+ const prev = selectedMods.get(choice.module);
580
+ if (prev)
581
+ assertCovers(prev.got, choice);
582
+ }
583
+ let added = false;
584
+ for (const choice of choices.values()) {
585
+ if (selectedMods.has(choice.module))
586
+ continue;
587
+ selectedMods.set(choice.module, { selector: selectorKey(choice), got: loadChoice(choice) });
588
+ added = true;
589
+ }
590
+ for (const choice of paths.values()) {
591
+ if (selectedPaths.has(choice.name))
592
+ continue;
593
+ const key = `path\0${choice.name}`;
594
+ let got = cache.get(key);
595
+ if (!got) {
596
+ got = loadPath(session, choice);
597
+ cache.set(key, got);
598
+ }
599
+ selectedPaths.set(choice.name, { got });
600
+ added = true;
601
+ }
602
+ if (!added)
603
+ stable = true;
604
+ }
605
+ if (!stable)
606
+ throw new PackageError('limit', 'version selection did not converge', root.manifestFile);
607
+ const { choices, paths } = buildChoices(edgesFrom());
608
+ const packages = new Map();
609
+ const modules = new Map();
610
+ const winners = [];
611
+ const keep = new Set([root.id]);
612
+ for (const choice of choices.values()) {
613
+ const got = selectedMods.get(choice.module)?.got;
614
+ if (!got)
615
+ throw new PackageError('unfetched', `missing ${choice.module}@${selectorKey(choice)}`);
616
+ assertCovers(got, choice);
617
+ packages.set(got.info.manifest.name, got.info);
618
+ modules.set(choice.module, got.info);
619
+ keep.add(got.info.id);
620
+ winners.push({ harvested: got, requesters: choice.requesters });
621
+ }
622
+ for (const choice of paths.values()) {
623
+ if (choice.conflict)
624
+ throw new PackageError('version-conflict', choice.conflict, root.manifestFile);
625
+ const got = selectedPaths.get(choice.name)?.got;
626
+ if (!got)
627
+ throw new PackageError('manifest', `missing path package ${choice.name}`);
628
+ packages.set(got.info.manifest.name, got.info);
629
+ keep.add(got.info.id);
630
+ winners.push({ harvested: got, requesters: choice.requesters });
631
+ }
632
+ for (const key of root.manifest.sources.keys()) {
633
+ const used = isModulePath(key) ? choices.has(key) : paths.has(key);
634
+ if (!used)
635
+ throw new PackageError('manifest', `[sources] locator ${key} is not used by the dependency graph`, root.manifestFile);
636
+ }
637
+ for (const key of root.manifest.replace.keys())
638
+ if (!choices.has(key))
639
+ throw new PackageError('manifest', `[replace] ${key} is not used by the dependency graph`, root.manifestFile);
640
+ const state = new Map();
641
+ const visit = (info, chain) => {
642
+ if (state.get(info.id) === 'done')
643
+ return;
644
+ if (state.get(info.id) === 'active')
645
+ throw new PackageError('package-cycle', `package dependency cycle: ${[...chain, info.id].join(' -> ')}`, info.manifestFile);
646
+ state.set(info.id, 'active');
647
+ const winner = winners.find(item => item.harvested.info === info);
648
+ for (const seed of winner?.harvested.seeds ?? []) {
649
+ const req = classifyRequirement(seed.spec, seed.file);
650
+ const dep = req.kind === 'module' ? modules.get(req.module) : packages.get(req.name);
651
+ if (!dep)
652
+ throw new PackageError('manifest', `missing dependency ${seed.spec}`, info.manifestFile);
653
+ visit(dep, [...chain, info.id]);
654
+ }
655
+ state.set(info.id, 'done');
656
+ };
657
+ for (const info of packages.values())
658
+ visit(info, []);
659
+ const entries = winners.map(({ harvested: got, requesters }) => lockEntry(got, requesters.filter(item => keep.has(item.package))));
660
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : a.version < b.version ? -1 : a.version > b.version ? 1 : 0);
661
+ const replace = {};
662
+ for (const key of [...root.manifest.replace.keys()].sort())
663
+ replace[key] = replaceLocator(root.manifest.replace.get(key), root.manifestFile);
664
+ const lock = {
665
+ schema: LOCK_SCHEMA_V2,
666
+ root: { name: root.manifest.name, version: root.manifest.version,
667
+ ...(root.manifest.edition !== undefined ? { edition: root.manifest.edition } : {}),
668
+ ...(root.manifest.optimizer !== undefined ? { optimizer: root.manifest.optimizer } : {}),
669
+ dependencies: Object.fromEntries([...root.manifest.dependencies].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)),
670
+ ...(root.manifest.replace.size ? { replace } : {}) },
671
+ packages: entries,
672
+ };
673
+ return { packages, lockText: JSON.stringify(lock, null, 2) + '\n', modules };
674
+ }
675
+ function replaceLocator(value, file) {
676
+ if (isGitLocator(value)) {
677
+ const loc = assertGitLocator(value, file);
678
+ return { kind: 'git', url: loc.url, dir: loc.dir };
679
+ }
680
+ return { kind: 'path', path: relPath(value, '[replace]', file) };
681
+ }
682
+ function lockEntry(got, requesters) {
683
+ const requestersSorted = [...requesters].sort((a, b) => a.package < b.package ? -1 : a.package > b.package ? 1 : a.required < b.required ? -1 : a.required > b.required ? 1 : 0);
684
+ return { name: got.info.manifest.name, version: got.info.selectedVersion ?? got.info.manifest.version,
685
+ ...(got.commit ? { commit: got.commit } : {}), ...(got.gitTree ? { gitTree: got.gitTree } : {}),
686
+ locator: got.locator, override: got.override, requesters: requestersSorted, root: got.info.root,
687
+ dependencies: Object.fromEntries([...got.info.manifest.dependencies].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)),
688
+ files: got.info.files.map(file => ({ path: file.path, digest: hex(file.digest) })), treeDigest: hex(got.info.treeDigest) };
689
+ }
690
+ function listRefs(url) {
691
+ const out = runGit(['ls-remote', url, 'refs/tags/*', 'refs/heads/*']);
692
+ const tags = new Map();
693
+ const peeled = new Map();
694
+ const heads = new Map();
695
+ for (const line of out.split('\n')) {
696
+ if (!line.trim())
697
+ continue;
698
+ const [sha, ref] = line.split('\t');
699
+ if (!sha || !ref || !COMMIT.test(sha))
700
+ continue;
701
+ if (ref.startsWith('refs/heads/'))
702
+ heads.set(ref.slice('refs/heads/'.length), sha);
703
+ else if (ref.startsWith('refs/tags/') && ref.endsWith('^{}'))
704
+ peeled.set(ref.slice('refs/tags/'.length, -3), sha);
705
+ else if (ref.startsWith('refs/tags/'))
706
+ tags.set(ref.slice('refs/tags/'.length), sha);
707
+ }
708
+ const parsed = [];
709
+ for (const [name, sha] of tags) {
710
+ const match = TAG.exec(name);
711
+ if (!match)
712
+ continue;
713
+ parsed.push({ semver: semver(match[1], match[2], match[3]), commit: peeled.get(name) ?? sha });
714
+ }
715
+ return { tags: parsed, heads };
716
+ }
717
+ function resolveInexact(module, selector, manifest, options) {
718
+ const ref = parseModulePath(module, MANIFEST_FILE);
719
+ const classified = classifySelector(selector, ref, MANIFEST_FILE);
720
+ if (classified.kind === 'tag' || classified.kind === 'commit')
721
+ return `${module}@${selectorText(classified)}`;
722
+ const session = { project: '', root: { manifest }, limits: { maxPackages: 1, maxModules: 1, maxImportDepth: 1, maxImportBindings: 1, maxSourceBytes: 1 }, budget: { bytes: 0, limit: 1 }, online: options };
723
+ const url = derive(session, ref).url;
724
+ const refs = listRefs(url);
725
+ if (classified.kind === 'range') {
726
+ const matches = refs.tags.filter(tag => {
727
+ if (ref.suffixMajor !== undefined ? tag.semver.major !== ref.suffixMajor : tag.semver.major >= 2)
728
+ return false;
729
+ return satisfies(tag.semver, classified.op, classified.semver);
730
+ });
731
+ if (!matches.length)
732
+ throw new PackageError('fetch', `no tag of ${module} satisfies ${selector}`);
733
+ matches.sort((a, b) => cmp(a.semver, b.semver));
734
+ return `${module}@${matches[matches.length - 1].semver.text}`;
735
+ }
736
+ if (!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,127}$/.test(classified.name) || classified.name.split('/').includes('..'))
737
+ throw new PackageError('branch', `refusing branch name ${JSON.stringify(classified.name)}`);
738
+ const commit = refs.heads.get(classified.name);
739
+ if (!commit)
740
+ throw new PackageError('fetch', `branch ${JSON.stringify(classified.name)} was not found for ${module}`);
741
+ return `${module}@${commit}`;
742
+ }
743
+ function replaceAliasValue(text, alias, from, to) {
744
+ const escaped = from.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
745
+ const pattern = new RegExp(`(^|\\n)(${alias}[ \\t]*=[ \\t]*")${escaped}(")`);
746
+ const next = text.replace(pattern, `$1$2${to}$3`);
747
+ if (next === text)
748
+ throw new PackageError('manifest', `could not rewrite dependency ${alias}`, MANIFEST_FILE);
749
+ return next;
750
+ }
751
+ /** Fetch exact tags and commits into the cache and write `lotus.lock`. Branch names and ranges are rejected. */
752
+ export function fetchPackages(projectDir, options = {}) {
753
+ const workspace = resolveWorkspace(projectDir, { ...DEFAULT_PACKAGE_LIMITS, ...(options.limits ?? {}) }, options);
754
+ writeFileSync(join(projectDir, LOCK_FILE), workspace.lockText);
755
+ return workspace.lockText;
756
+ }
757
+ /**
758
+ * Resolve one root dependency that may be a branch or semver range (`^` / `~`), rewrite that
759
+ * manifest entry to an exact tag or commit, then fetch. This is the only command that may name a branch.
760
+ */
761
+ export function updatePackages(projectDir, spec, options = {}) {
762
+ const file = join(projectDir, MANIFEST_FILE);
763
+ const text = readFileSync(file, 'utf8');
764
+ const manifest = parseManifest(text, MANIFEST_FILE);
765
+ const at = spec.lastIndexOf('@');
766
+ const left = at < 0 ? spec : spec.slice(0, at);
767
+ const selector = at < 0 ? undefined : spec.slice(at + 1);
768
+ if (!left || left.startsWith('-'))
769
+ throw new PackageError('manifest', 'usage: lotus-package-update DIR SPEC [--vendor]');
770
+ let alias;
771
+ let module;
772
+ if (left.includes('/'))
773
+ module = left;
774
+ else
775
+ alias = left;
776
+ const entries = [...manifest.dependencies].map(([name, value]) => ({ name, value, req: classifyRequirement(value, MANIFEST_FILE) }));
777
+ const entry = alias ? entries.find(item => item.name === alias) : entries.find(item => item.req.kind === 'module' && item.req.module === module);
778
+ if (!entry || entry.req.kind !== 'module')
779
+ throw new PackageError('manifest', `update spec ${JSON.stringify(spec)} does not name a module dependency of the root package`, MANIFEST_FILE);
780
+ const currentSelector = selector ?? selectorText(entry.req.selector);
781
+ const resolved = resolveInexact(entry.req.module, currentSelector, manifest, options);
782
+ if (resolved !== entry.value)
783
+ writeFileSync(file, replaceAliasValue(text, entry.name, entry.value, resolved));
784
+ return fetchPackages(projectDir, options);
785
+ }