@crossberryweb/mozhi 3.5.0 → 3.7.1

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.
Binary file
Binary file
package/bin/mozhi.js CHANGED
@@ -16,8 +16,8 @@
16
16
  * natively by this launcher (lib/) without starting the interpreter —
17
17
  * see `mz help pkg`.
18
18
  *
19
- * Bundled official release binaries (v3.3.0 line, static builds with
20
- * SQLite vendored):
19
+ * Bundled official release binaries (v3.6.0 line, static builds with
20
+ * SQLite and the RFC 6234 SHA sources vendored):
21
21
  * bin/mozhi-linux-x86_64
22
22
  * bin/mozhi-linux-arm64
23
23
  *
@@ -74,7 +74,7 @@ if (argv.length && PKG_COMMANDS.has(argv[0])) {
74
74
 
75
75
  if (!fs.existsSync(bin)) {
76
76
  console.error('[mozhi] No bundled interpreter for ' + process.platform + '-' + process.arch + '.');
77
- console.error('[mozhi] This package ships official v3.3.0 binaries for:');
77
+ console.error('[mozhi] This package ships official v3.6.0 binaries for:');
78
78
  console.error('[mozhi] linux-x86_64, linux-arm64 (fully static — works on glibc, Alpine, Termux)');
79
79
  console.error('[mozhi] For macOS, Windows and other platforms use the installer:');
80
80
  console.error('[mozhi] curl -fsSL https://github.com/crossberry-in/mozhi-doc/raw/main/install.sh | bash');
@@ -1,6 +1,6 @@
1
- 96f331365ca5672429fcac3ea3e71b35e6f7bae741d2e726a1133d9dd966c64a mozhi-interpreter-alpine-arm64
2
- fd7a18453e1496d53a5114596c432591707928ae8b7f0f1830c70fcf72e23fdb mozhi-interpreter-alpine-x86_64
3
- 56dd0579f860b65cb648e99a5c48743a49ad5fbee30e11712cdd5a55fc9a30f0 mozhi-interpreter-linux-arm64
4
- 7c0933dccd0c48cae20d050ac4aab0699fc2eea24f19c28676a80aa8da96d033 mozhi-interpreter-linux-x86_64
5
- 0eafca5e3c54604ea0db809a1fa8a4601018a4fb09e99dbc4bcdff3c9c564236 mozhi-interpreter-macos-arm64
6
- 38b77dc57b35b6234868819392f70c2ff34956840ad14e08c683f28de9c497e7 mozhi-interpreter-macos-x86_64
1
+ dbb0c6a28587c0574a230b2bea5d037b6c64152d02feba91d1fc125bf251e11c mozhi-interpreter-alpine-arm64
2
+ fd3f4558821648c3ebc6f71d4c0d354e4f3de99ca6417d8466aac6aceb18890f mozhi-interpreter-alpine-x86_64
3
+ a15b858168d21a5b459e264cd904f490fd54cae6ca077d9522d95db1136d7885 mozhi-interpreter-linux-arm64
4
+ 3d903735c716bebfdba950fe6f345a8729b8f3749276cd90c4d38d71eb4ee1fb mozhi-interpreter-linux-x86_64
5
+ eb1f7fd7d32b71657ee7001cd42c84f82064734f4c3c7aec6cee836f190f5274 mozhi-interpreter-macos-arm64
6
+ a4a31288b0dc624cd80904fa1748f2c73832055f647760e3cbeb9e5ea840b445 mozhi-interpreter-macos-x86_64
package/lib/cli.js CHANGED
@@ -8,9 +8,11 @@
8
8
 
9
9
  const fs = require('fs');
10
10
  const path = require('path');
11
+ const { spawnSync } = require('child_process');
11
12
  const pkgman = require('./pkgman');
12
13
  const scaffold = require('./scaffold');
13
14
  const reg = require('./registry');
15
+ const publish = require('./publish');
14
16
 
15
17
  function out(msg) { process.stdout.write(msg + '\n'); }
16
18
  function err(msg) { process.stderr.write(msg + '\n'); }
@@ -22,7 +24,7 @@ function pad(s, n) {
22
24
 
23
25
  function usage() {
24
26
  out('usage:');
25
- out(' mz install <name> install a package from the Mozhi registry');
27
+ out(' mz install <name> install a package from the Mozhi registry (resolves dependencies)');
26
28
  out(' mz install <name>@<tag> install a specific release tag');
27
29
  out(' mz install @user/repo install from any Git repo release');
28
30
  out(' mz install @user/repo@tag install a specific repo release tag');
@@ -31,14 +33,26 @@ function usage() {
31
33
  out(' mz uninstall <name> remove an installed package');
32
34
  out(' mz list list installed packages');
33
35
  out(' mz search [query] search the package registry');
34
- out(' mz pkg new <name> scaffold a new package (with release workflow)');
36
+ out(' mz pkg init [name|dir] scaffold a new package (with release workflow)');
35
37
  out(' mz pkg check [dir] verify a package directory structure');
36
- out(' mz pkg zip [dir] build <name>.mz.pkg.zip from a package dir');
38
+ out(' mz pkg build [dir] build <name>.mz.pkg.zip from a package dir');
39
+ out(' mz pkg test [dir] run the package test suite (tests/)');
40
+ out(' mz pkg info [dir|name] show manifest, origin and dependency info');
41
+ out(' mz pkg install <spec> same as mz install');
42
+ out(' mz pkg search [query] same as mz search');
43
+ out(' mz pkg update [name] update installed packages to the newest release');
44
+ out(' mz pkg remove <name> same as mz uninstall');
45
+ out(' mz pkg publish [dir] release the package (GitHub release + checksums)');
46
+ out(' mz pkg new <name> same as mz pkg init <name>');
47
+ out(' mz pkg zip [dir] same as mz pkg build');
37
48
  out('');
38
49
  out('options:');
39
50
  out(' --local install into ./.mozhi/pkg instead of ~/.mozhi/pkg');
51
+ out(' --no-deps skip installing declared dependencies');
52
+ out(' --dry-run (publish) validate and report without releasing');
53
+ out(' --allow-dirty (publish) release even with uncommitted changes');
40
54
  out('');
41
- out('package layout: package.toml + src/mod.mz; releases carry <name>.mz.pkg.zip');
55
+ out('package layout: mozhi.toml (or legacy package.toml) + src/mod.mz; releases carry <name>.mz.pkg.zip');
42
56
  out('registry: ' + reg.DEFAULT_REGISTRY_URL);
43
57
  }
44
58
 
@@ -97,29 +111,167 @@ async function cmdSearch(args) {
97
111
  out('registry packages (' + (q ? 'matching "' + q + '"' : 'all') + ') — source: ' + source);
98
112
  out('');
99
113
  for (const p of hits) {
114
+ const versions = p.versions ? Object.keys(p.versions).length + ' version(s)' : 'v' + (p.version || '?');
100
115
  const dist = p.repo ? p.repo : 'mozhi-doc libs';
101
- out(' ' + pad(p.name, 20) + pad('v' + (p.version || '?'), 10) + pad(dist, 34));
116
+ out(' ' + pad(p.name, 20) + pad(versions, 16) + pad(dist, 34));
102
117
  if (p.description) out(' ' + pad('', 20) + p.description);
103
118
  }
104
119
  if (!hits.length) out(' (no matches)');
105
120
  return 0;
106
121
  }
107
122
 
123
+ /* Locate the interpreter binary for mz pkg test: the launcher env var
124
+ * wins, then PATH, then the bundled bin/ copy. */
125
+ function findMozhiBinary() {
126
+ if (process.env.MOZHI_BIN) return process.env.MOZHI_BIN;
127
+ const fromPath = spawnSync('sh', ['-c', 'command -v mozhi || command -v mz'], { encoding: 'utf8' });
128
+ if (fromPath.status === 0 && fromPath.stdout.trim()) return fromPath.stdout.trim();
129
+ const arch = process.arch === 'x64' ? 'x86_64' : process.arch;
130
+ const bundled = path.join(__dirname, '..', 'bin', 'mozhi-' + process.platform + '-' + arch);
131
+ if (fs.existsSync(bundled)) return bundled;
132
+ return null;
133
+ }
134
+
135
+ function cmdPkgTest(args) {
136
+ const dir = path.resolve(args[0] || '.');
137
+ const mf = pkgman.MANIFESTS.map((m) => path.join(dir, m)).find((p) => fs.existsSync(p));
138
+ if (!mf) {
139
+ err('mz pkg test: no mozhi.toml/package.toml in ' + dir);
140
+ return 1;
141
+ }
142
+ const manifest = pkgman.parseManifest(fs.readFileSync(mf, 'utf8'));
143
+ const testsDir = path.join(dir, (manifest.test_dir || 'tests'));
144
+ if (!fs.existsSync(testsDir)) {
145
+ out('no tests/ directory — nothing to run');
146
+ return 0;
147
+ }
148
+ const files = fs.readdirSync(testsDir).filter((f) => /\.test\.mz$/.test(f)).sort();
149
+ if (!files.length) {
150
+ out('no *.test.mz files in ' + testsDir + ' — nothing to run');
151
+ return 0;
152
+ }
153
+ const bin = findMozhiBinary();
154
+ if (!bin) {
155
+ err('mz pkg test: cannot find a mozhi interpreter (set MOZHI_BIN or install @crossberryweb/mozhi)');
156
+ return 1;
157
+ }
158
+ // Import path: test files import the package entry via relative path,
159
+ // mirroring the scaffold layout (import <name> from "../src/mod.mz").
160
+ let failed = 0;
161
+ for (const f of files) {
162
+ process.stdout.write(' ' + f + ' ');
163
+ const r = spawnSync(bin, ['run', path.join(testsDir, f)], { cwd: dir, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8' });
164
+ if (r.status === 0) {
165
+ out('PASS');
166
+ } else {
167
+ failed++;
168
+ out('FAIL');
169
+ if (r.stdout) process.stdout.write(r.stdout + '\n');
170
+ if (r.stderr) process.stderr.write(r.stderr + '\n');
171
+ }
172
+ }
173
+ out('');
174
+ out((files.length - failed) + ' passed, ' + failed + ' failed');
175
+ return failed ? 1 : 0;
176
+ }
177
+
178
+ function cmdPkgInfo(args) {
179
+ const target = args[0] || '.';
180
+ // 1. as a directory
181
+ const abs = path.resolve(target);
182
+ if (fs.existsSync(abs) && fs.statSync(abs).isDirectory()) {
183
+ const mf = pkgman.MANIFESTS.map((m) => path.join(abs, m)).find((p) => fs.existsSync(p));
184
+ if (mf) {
185
+ const manifest = pkgman.parseManifest(fs.readFileSync(mf, 'utf8'));
186
+ out(pad('name', 14) + (manifest.name || '-'));
187
+ out(pad('version', 14) + (manifest.version || '-'));
188
+ out(pad('description', 14) + (manifest.description || '-'));
189
+ out(pad('license', 14) + (manifest.license || '-'));
190
+ out(pad('entry', 14) + (manifest.entry || '-'));
191
+ out(pad('manifest', 14) + path.basename(mf));
192
+ const deps = manifest.dependencies || {};
193
+ const names = Object.keys(deps);
194
+ out(pad('dependencies', 14) + (names.length ? names.map((n) => n + ' ' + (deps[n] || '*')).join(', ') : '(none)'));
195
+ return 0;
196
+ }
197
+ }
198
+ // 2. as an installed package name
199
+ const info = pkgman.info(target);
200
+ if (!info) {
201
+ err('mz pkg info: "' + target + '" is neither a package directory nor an installed package');
202
+ return 1;
203
+ }
204
+ out(pad('name', 14) + info.name);
205
+ out(pad('version', 14) + (info.version || '-'));
206
+ out(pad('installed at', 14) + info.path);
207
+ out(pad('source', 14) + info.source);
208
+ if (info.installedAt) out(pad('installed on', 14) + info.installedAt);
209
+ if (info.manifest) {
210
+ out(pad('manifest', 14) + (info.manifestFile || '-'));
211
+ const deps = info.manifest.dependencies || {};
212
+ const names = Object.keys(deps);
213
+ out(pad('dependencies', 14) + (names.length ? names.map((n) => n + ' ' + (deps[n] || '*')).join(', ') : '(none)'));
214
+ if (info.manifest.description) out(pad('description', 14) + info.manifest.description);
215
+ }
216
+ return 0;
217
+ }
218
+
219
+ async function cmdPkgUpdate(args, opts) {
220
+ const name = args[0] || null;
221
+ out('updating ' + (name || 'all installed packages') + ' ...');
222
+ const results = await pkgman.update(name, opts);
223
+ let changed = 0;
224
+ for (const r of results) {
225
+ if (r.changed) {
226
+ changed++;
227
+ out(' updated: ' + r.name + ' ' + (r.from || '?') + ' -> ' + (r.to || '?'));
228
+ } else {
229
+ out(' current: ' + r.name + ' ' + (r.to || '?'));
230
+ }
231
+ }
232
+ out(changed + ' updated, ' + (results.length - changed) + ' already current');
233
+ return 0;
234
+ }
235
+
236
+ async function cmdPkgPublish(args, opts) {
237
+ const dir = args[0] || '.';
238
+ const res = await publish.publishDir(dir, { dryRun: !!opts.dryRun, allowDirty: !!opts.allowDirty });
239
+ if (res.dryRun) {
240
+ out('dry run — package is publishable:');
241
+ out(' repo: ' + res.repo);
242
+ out(' tag: ' + res.tag);
243
+ out(' artifact: ' + res.zipName + ' (' + res.size + ' bytes, ' + res.files + ' files)');
244
+ out(' sha256: ' + res.sha256);
245
+ out(' run without --dry-run to create the GitHub release');
246
+ return 0;
247
+ }
248
+ out('published ' + res.manifest.name + ' v' + res.manifest.version + ':');
249
+ out(' release: ' + (res.releaseUrl || res.repo + ' tag ' + res.tag));
250
+ out(' artifact: ' + res.zipName + ' (' + res.size + ' bytes)');
251
+ out(' sha256: ' + res.sha256);
252
+ out(' verified: re-downloaded and checksum-matched');
253
+ out('');
254
+ out('to list it in the public registry, open a PR adding this entry to mozhi-registry.json:');
255
+ out(JSON.stringify(res.registryEntry, null, 2));
256
+ return 0;
257
+ }
258
+
108
259
  function cmdPkg(args) {
109
260
  const sub = args[0] || 'help';
110
- if (sub === 'new') {
261
+ if (sub === 'new' || sub === 'init') {
111
262
  const name = args[1];
112
- if (!name) { err("mz: 'pkg new' needs a package name — usage: mz pkg new <name> [dir]"); return 1; }
263
+ if (!name) { err("mz: 'pkg " + sub + "' needs a package name — usage: mz pkg " + sub + " <name> [dir]"); return 1; }
113
264
  const res = scaffold.scaffold(name, args[2]);
114
265
  out('created package ' + name + ' in ' + res.root + ' (' + res.files + ' files)');
115
266
  out('');
116
267
  out(' next steps:');
117
268
  out(' cd ' + name);
118
- out(' mozhi test # run the sample test');
269
+ out(' mz pkg test # run the sample test');
119
270
  out(' mz pkg check # verify structure');
120
271
  out(' git init && git add -A && git commit -m "initial import"');
121
272
  out(' git remote add origin git@github.com:<you>/' + name + '.git && git push -u origin main');
122
273
  out(' git tag v0.1.0 && git push origin v0.1.0 # auto-release workflow builds the zip');
274
+ out(' or release directly: GITHUB_TOKEN=... mz pkg publish');
123
275
  out('');
124
276
  out(' others install it with: mz install @<you>/' + name);
125
277
  return 0;
@@ -128,28 +280,43 @@ function cmdPkg(args) {
128
280
  const info = pkgman.checkDir(args[1] || '.');
129
281
  out('package structure OK: ' + info.manifest.name +
130
282
  (info.manifest.version ? ' v' + info.manifest.version : '') +
131
- ' — entry: ' + info.manifest.entry + ' (' + info.files + ' files)');
283
+ ' — entry: ' + info.manifest.entry + ' (' + info.files + ' files, manifest: ' + info.manifestFile + ')');
132
284
  if (!info.manifest.version) {
133
- err('mz: warning: package.toml has no version field');
285
+ err('mz: warning: manifest has no version field');
286
+ }
287
+ const depNames = Object.keys(info.manifest.dependencies || {});
288
+ if (depNames.length) {
289
+ out('dependencies: ' + depNames.map((n) => n + ' ' + info.manifest.dependencies[n]).join(', '));
134
290
  }
135
291
  return 0;
136
292
  }
137
- if (sub === 'zip') {
293
+ if (sub === 'zip' || sub === 'build') {
138
294
  const res = pkgman.zipDir(args[1] || '.');
139
295
  out('built ' + res.out + ' (' + res.name + (res.version ? ' v' + res.version : '') + ', ' + res.count + ' files)');
140
- out('attach it to a GitHub release, or let the release workflow do it on tag push.');
296
+ out('sha256: ' + res.sha256);
297
+ out('attach it to a GitHub release, let the release workflow do it on tag push, or run: mz pkg publish');
141
298
  return 0;
142
299
  }
143
- usage();
144
- return sub === 'help' || sub === '--help' ? 0 : 1;
300
+ if (sub === 'test') {
301
+ return cmdPkgTest(args.slice(1));
302
+ }
303
+ if (sub === 'info') {
304
+ return cmdPkgInfo(args.slice(1));
305
+ }
306
+ return null; // handled by async router (install/search/update/remove/publish)
145
307
  }
146
308
 
147
309
  /* Entry point. Returns process exit code. */
148
310
  async function run(argv) {
149
311
  const cmd = argv[0];
150
312
  const args = argv.slice(1);
151
- const opts = { local: args.includes('--local') };
152
- const rest = args.filter((a) => a !== '--local');
313
+ const opts = {
314
+ local: args.includes('--local'),
315
+ noDeps: args.includes('--no-deps'),
316
+ dryRun: args.includes('--dry-run'),
317
+ allowDirty: args.includes('--allow-dirty'),
318
+ };
319
+ const rest = args.filter((a) => !['--local', '--no-deps', '--dry-run', '--allow-dirty'].includes(a));
153
320
 
154
321
  try {
155
322
  switch (cmd) {
@@ -165,8 +332,18 @@ async function run(argv) {
165
332
  case 'search':
166
333
  return await cmdSearch(rest);
167
334
  case 'pkg':
168
- case 'package':
169
- return cmdPkg(rest);
335
+ case 'package': {
336
+ const sync = cmdPkg(rest);
337
+ if (sync !== null) return sync;
338
+ const sub = rest[0];
339
+ if (sub === 'install') return await cmdInstall(rest.slice(1), opts);
340
+ if (sub === 'search') return await cmdSearch(rest.slice(1));
341
+ if (sub === 'update') return await cmdPkgUpdate(rest.slice(1), opts);
342
+ if (sub === 'remove') return await cmdUninstall(rest.slice(1), opts);
343
+ if (sub === 'publish') return await cmdPkgPublish(rest.slice(1), opts);
344
+ usage();
345
+ return sub === 'help' || sub === '--help' ? 0 : 1;
346
+ }
170
347
  case 'help':
171
348
  case '--help':
172
349
  case '-h':
package/lib/gh.js CHANGED
@@ -106,4 +106,59 @@ async function downloadAsset(asset) {
106
106
  return buf;
107
107
  }
108
108
 
109
- module.exports = { apiBase, latestRelease, releaseByTag, pickAsset, downloadAsset, validRepo };
109
+ /* ---------------- publish-side helpers (author actions) ---------------- */
110
+
111
+ function publishToken() {
112
+ return process.env.GITHUB_TOKEN || process.env.MOZHI_GH_TOKEN || null;
113
+ }
114
+
115
+ /* Create a release. Returns the release JSON (includes upload_url). */
116
+ async function createRelease(repo, tag, title, body) {
117
+ if (!validRepo(repo)) throw new Error('invalid repository: ' + repo);
118
+ const token = publishToken();
119
+ if (!token) {
120
+ throw new Error('publishing requires a GitHub token — set GITHUB_TOKEN (repo scope: contents:write)');
121
+ }
122
+ const res = await fetch(apiBase() + '/repos/' + repo + '/releases', {
123
+ method: 'POST',
124
+ signal: AbortSignal.timeout(20000),
125
+ headers: {
126
+ 'user-agent': UA,
127
+ accept: 'application/vnd.github+json',
128
+ authorization: 'Bearer ' + token,
129
+ 'content-type': 'application/json',
130
+ },
131
+ body: JSON.stringify({ tag_name: tag, name: title || tag, body: body || '', draft: false, prerelease: false }),
132
+ });
133
+ if (!res.ok) {
134
+ const detail = await res.text().catch(() => '');
135
+ throw new Error('release creation failed (HTTP ' + res.status + '): ' + detail.slice(0, 300));
136
+ }
137
+ return res.json();
138
+ }
139
+
140
+ /* Upload one asset to a release upload_url. Returns the asset JSON. */
141
+ async function uploadAsset(release, filename, buf, contentType = 'application/zip') {
142
+ const token = publishToken();
143
+ if (!token) throw new Error('publishing requires GITHUB_TOKEN');
144
+ const base = (release && release.upload_url || '').replace(/\{\?name,label\}$/, '');
145
+ if (!base) throw new Error('release has no upload_url');
146
+ const res = await fetch(base + '?name=' + encodeURIComponent(filename), {
147
+ method: 'POST',
148
+ signal: AbortSignal.timeout(60000),
149
+ headers: {
150
+ 'user-agent': UA,
151
+ authorization: 'Bearer ' + token,
152
+ 'content-type': contentType,
153
+ 'content-length': String(buf.length),
154
+ },
155
+ body: buf,
156
+ });
157
+ if (!res.ok) {
158
+ const detail = await res.text().catch(() => '');
159
+ throw new Error('asset upload failed (HTTP ' + res.status + '): ' + detail.slice(0, 300));
160
+ }
161
+ return res.json();
162
+ }
163
+
164
+ module.exports = { apiBase, latestRelease, releaseByTag, pickAsset, downloadAsset, validRepo, createRelease, uploadAsset, publishToken };
package/lib/pkgman.js CHANGED
@@ -20,12 +20,18 @@
20
20
  const fs = require('fs');
21
21
  const path = require('path');
22
22
  const os = require('os');
23
+ const crypto = require('crypto');
23
24
  const { readZip, writeZip } = require('./zip');
24
25
  const reg = require('./registry');
25
26
  const gh = require('./gh');
27
+ const semver = require('./semver');
26
28
 
27
- const MANIFEST = 'package.toml';
29
+ /* mozhi.toml is the canonical manifest name; package.toml remains
30
+ * accepted for compatibility with packages published before v3.6. */
31
+ const MANIFEST = 'mozhi.toml';
32
+ const MANIFESTS = ['mozhi.toml', 'package.toml'];
28
33
  const ORIGIN_FILE = '.mozhi-pkg.json';
34
+ const MAX_DEP_DEPTH = 10;
29
35
 
30
36
  /* ------------------------------------------------------------------ */
31
37
  /* helpers */
@@ -42,15 +48,37 @@ function libsRoot(global_ = true) {
42
48
  }
43
49
 
44
50
  /* Lenient manifest scan — mirrors the interpreter's mz_pkg.c parser:
45
- * any `key = "value"` line wins regardless of section headers. */
51
+ * any `key = "value"` line wins regardless of section headers, except
52
+ * that [dependencies] collects `name = "constraint"` pairs instead.
53
+ * Returns { name, version, ..., dependencies: {pkg: constraint} }. */
46
54
  function parseManifest(text) {
47
- const out = {};
48
- const re = /^[ \t]*([A-Za-z_][A-Za-z0-9_-]*)[ \t]*=[ \t]*"([^"]*)"/gm;
49
- let m;
50
- while ((m = re.exec(text)) !== null) {
51
- if (!(m[1] in out)) out[m[1]] = m[2];
55
+ const fields = {};
56
+ const dependencies = {};
57
+ let section = '';
58
+ const depKey = /^[ \t]*([A-Za-z_][A-Za-z0-9_-]*)[ \t]*=[ \t]*"([^"]*)"/;
59
+ for (const rawLine of String(text).split(/\r?\n/)) {
60
+ // strip comments, but only # characters outside quoted strings
61
+ let stripped = '';
62
+ let inQuote = false;
63
+ for (const ch of rawLine) {
64
+ if (ch === '"') inQuote = !inQuote;
65
+ if (ch === '#' && !inQuote) break;
66
+ stripped += ch;
67
+ }
68
+ const line = stripped.trim();
69
+ if (!line) continue;
70
+ const sec = /^\[+\s*([^\]\s]+)\s*\]+$/.exec(line);
71
+ if (sec) { section = sec[1].toLowerCase(); continue; }
72
+ const m = depKey.exec(line);
73
+ if (!m) continue;
74
+ if (section === 'dependencies') {
75
+ dependencies[m[1]] = m[2];
76
+ } else if (!(m[1] in fields)) {
77
+ fields[m[1]] = m[2];
78
+ }
52
79
  }
53
- return out;
80
+ fields.dependencies = dependencies;
81
+ return fields;
54
82
  }
55
83
 
56
84
  /* Default entry probing, same order as the interpreter. */
@@ -67,10 +95,11 @@ function resolveEntry(manifest, files, prefix) {
67
95
  return null;
68
96
  }
69
97
 
70
- /* Locate package.toml inside a zip file map: zip root or a single
98
+ /* Locate a manifest inside a zip file map: zip root or a single
71
99
  * top-level directory (git-archive style). Returns prefix ('' or 'dir/'). */
72
100
  function findManifestPrefix(files) {
73
- if (files.has(MANIFEST)) return '';
101
+ const has = (p) => MANIFESTS.some((m) => files.has(p + m));
102
+ if (has('')) return '';
74
103
  const tops = new Set();
75
104
  for (const name of files.keys()) {
76
105
  const slash = name.indexOf('/');
@@ -78,19 +107,28 @@ function findManifestPrefix(files) {
78
107
  }
79
108
  if (tops.size === 1) {
80
109
  const prefix = Array.from(tops)[0] + '/';
81
- if (files.has(prefix + MANIFEST)) return prefix;
110
+ if (has(prefix)) return prefix;
82
111
  }
83
112
  throw new Error(
84
- 'package structure invalid: ' + MANIFEST + ' not found at zip root or in a single top-level directory'
113
+ 'package structure invalid: ' + MANIFEST + ' (or package.toml) not found at zip root or in a single top-level directory'
85
114
  );
86
115
  }
87
116
 
88
- /* Verify a zip's package structure. Returns {manifest, prefix, entry, files}. */
117
+ function readManifestFrom(files, prefix) {
118
+ for (const m of MANIFESTS) {
119
+ const f = files.get(prefix + m);
120
+ if (f !== undefined) return { name: m, text: f.toString('utf8') };
121
+ }
122
+ return null;
123
+ }
124
+
125
+ /* Verify a zip's package structure. Returns {manifestFile, manifest, prefix, entry, files}. */
89
126
  function verifyZip(files, expectedName) {
90
127
  const prefix = findManifestPrefix(files);
91
- const manifest = parseManifest(files.get(prefix + MANIFEST).toString('utf8'));
128
+ const mf = readManifestFrom(files, prefix);
129
+ const manifest = parseManifest(mf.text);
92
130
  if (!manifest.name) {
93
- throw new Error('package structure invalid: ' + MANIFEST + ' has no "name" field');
131
+ throw new Error('package structure invalid: ' + mf.name + ' has no "name" field');
94
132
  }
95
133
  if (expectedName && manifest.name !== expectedName) {
96
134
  throw new Error(
@@ -105,7 +143,7 @@ function verifyZip(files, expectedName) {
105
143
  .filter(Boolean).join(', ') + ')'
106
144
  );
107
145
  }
108
- return { manifest, prefix, entry, files };
146
+ return { manifestFile: mf.name, manifest, prefix, entry, files };
109
147
  }
110
148
 
111
149
  function writeOrigin(dir, origin) {
@@ -140,20 +178,56 @@ function extractTo(pkg, root, origin) {
140
178
  return dest;
141
179
  }
142
180
 
181
+ /* ------------------------------------------------------------------ */
182
+ /* checksums */
183
+ /* ------------------------------------------------------------------ */
184
+
185
+ function sha256hex(buf) {
186
+ return crypto.createHash('sha256').update(buf).digest('hex');
187
+ }
188
+
189
+ /* Verify a downloaded zip against an expected sha256. Throws on mismatch. */
190
+ function assertChecksum(buf, expected, what) {
191
+ if (!expected) return;
192
+ const actual = sha256hex(buf);
193
+ if (actual.toLowerCase() !== String(expected).toLowerCase()) {
194
+ throw new Error(
195
+ 'integrity check failed for ' + what + ': sha256 ' + actual + ' != expected ' + expected +
196
+ ' — the artifact does not match the published checksum and was NOT installed'
197
+ );
198
+ }
199
+ }
200
+
201
+ /* Look for a checksums-sha256.txt asset in a release and return the
202
+ * checksum recorded for `assetName`, or null when absent. */
203
+ function findReleaseChecksum(release, assetName) {
204
+ const assets = (release && release.assets) || [];
205
+ const cs = assets.find((a) => /^checksums-sha256\.txt$/i.test(a.name));
206
+ if (!cs) return null;
207
+ return downloadAsset(cs)
208
+ .then((buf) => {
209
+ const line = buf.toString('utf8').split(/\r?\n/)
210
+ .find((l) => l.trim().endsWith(' ' + assetName) || l.trim().split(/\s+/)[1] === assetName);
211
+ return line ? line.trim().split(/\s+/)[0] : null;
212
+ })
213
+ .catch(() => null);
214
+ }
215
+
143
216
  /* ------------------------------------------------------------------ */
144
217
  /* install */
145
218
  /* ------------------------------------------------------------------ */
146
219
 
147
220
  async function installFromZipBuffer(buf, origin) {
221
+ assertChecksum(buf, origin.sha256, origin.asset || origin.file || 'package zip');
148
222
  const files = readZip(buf);
149
223
  const pkg = verifyZip(files, origin.expectedName);
150
- const root = pkgRoot(origin.local !== false);
224
+ const root = pkgRoot(origin.local !== true);
151
225
  const dest = extractTo(pkg, root, {
152
226
  name: pkg.manifest.name,
153
227
  version: pkg.manifest.version || null,
154
228
  ...origin,
155
229
  });
156
- return { manifest: pkg.manifest, dest };
230
+ return { manifest: pkg.manifest, dest, manifestFile: pkg.manifestFile };
157
231
  }
158
232
 
159
233
  async function installFromGit(repo, tag, opts = {}) {
@@ -176,13 +250,20 @@ async function installFromGit(repo, tag, opts = {}) {
176
250
  ' — found: ' + ((release.assets || []).map((a) => a.name).join(', ') || 'none')
177
251
  );
178
252
  }
179
- const buf = await gh.downloadAsset(asset);
180
253
  const expected = asset.name.replace(/\.mz\.pkg\.zip$/, '');
254
+ // integrity: prefer an explicit expected checksum, else the release
255
+ // checksums-sha256.txt manifest when present
256
+ let wantSha = opts.sha256 || null;
257
+ if (!wantSha) {
258
+ wantSha = await findReleaseChecksum(release, asset.name);
259
+ }
260
+ const buf = await gh.downloadAsset(asset);
181
261
  const res = await installFromZipBuffer(buf, {
182
262
  kind: 'git',
183
263
  repo,
184
264
  tag: release.tag_name || tag || null,
185
265
  asset: asset.name,
266
+ sha256: wantSha,
186
267
  expectedName: opts.strictName ? expected : undefined,
187
268
  });
188
269
  return { ...res, release, asset };
@@ -206,8 +287,45 @@ function libsLedgerWrite(global_, data) {
206
287
  }
207
288
 
208
289
  async function installFromRegistry(entry, nameSpec, opts = {}) {
290
+ // Registry v2: per-version dist info with tags + checksums. Resolve the
291
+ // best version matching opts.constraint (or an exact tag when given).
292
+ if (entry.versions && typeof entry.versions === 'object') {
293
+ const available = Object.keys(entry.versions);
294
+ let chosen = null;
295
+ if (opts.tag) {
296
+ chosen = available.find((v) => entry.versions[v].tag === opts.tag) || null;
297
+ if (!chosen) throw new Error('package "' + entry.name + '" has no version with tag ' + opts.tag + ' (published: ' + available.join(', ') + ')');
298
+ } else {
299
+ chosen = semver.bestMatch(available, opts.constraint || '*');
300
+ if (!chosen) {
301
+ throw new Error(
302
+ 'no version of "' + entry.name + '" satisfies constraint "' + (opts.constraint || '*') + '"' +
303
+ ' (published: ' + available.join(', ') + ')'
304
+ );
305
+ }
306
+ }
307
+ const vinfo = entry.versions[chosen];
308
+ const dist = vinfo.dist || {};
309
+ if (entry.repo) {
310
+ const res = await installFromGit(entry.repo, vinfo.tag || null, { local: opts.local, sha256: dist.sha256 || null });
311
+ return { ...res, resolvedVersion: chosen };
312
+ }
313
+ if (dist.url) {
314
+ const r = await fetch(dist.url, { signal: AbortSignal.timeout(30000) });
315
+ if (!r.ok) throw new Error('download failed (HTTP ' + r.status + '): ' + dist.url);
316
+ const buf = Buffer.from(await r.arrayBuffer());
317
+ const res = await installFromZipBuffer(buf, {
318
+ kind: 'registry', name: entry.name, version: chosen, asset: dist.asset || dist.url,
319
+ sha256: dist.sha256 || null, local: opts.local,
320
+ expectedName: entry.name,
321
+ });
322
+ return { ...res, resolvedVersion: chosen };
323
+ }
324
+ throw new Error('registry entry "' + entry.name + '" version ' + chosen + ' has no usable dist (repo or dist.url)');
325
+ }
326
+ // v1 fallback: entry-level repo or legacy single-file lib
209
327
  if (entry.repo) {
210
- return installFromGit(entry.repo, opts.tag, { strictName: false });
328
+ return installFromGit(entry.repo, opts.tag, { local: opts.local, strictName: false });
211
329
  }
212
330
  // Legacy single-file library hosted in the mozhi-doc repo
213
331
  const src = entry.source || entry.install;
@@ -235,22 +353,24 @@ async function installFromRegistry(entry, nameSpec, opts = {}) {
235
353
  };
236
354
  }
237
355
 
238
- async function installFromLocalZip(file) {
356
+ async function installFromLocalZip(file, opts = {}) {
239
357
  const buf = fs.readFileSync(file);
240
358
  const res = await installFromZipBuffer(buf, {
241
359
  kind: 'local-zip',
242
360
  file: path.resolve(file),
361
+ local: !!opts.local,
243
362
  expectedName: undefined,
244
363
  });
245
364
  return res;
246
365
  }
247
366
 
248
- async function installFromLocalDir(dir) {
367
+ async function installFromLocalDir(dir, opts = {}) {
249
368
  const abs = path.resolve(dir);
250
- const manifestPath = path.join(abs, MANIFEST);
251
- if (!fs.existsSync(manifestPath)) {
252
- throw new Error('not a package directory (missing ' + MANIFEST + '): ' + abs);
369
+ const mfName = MANIFESTS.find((m) => fs.existsSync(path.join(abs, m)));
370
+ if (!mfName) {
371
+ throw new Error('not a package directory (missing ' + MANIFEST + ' or package.toml): ' + abs);
253
372
  }
373
+ const manifestPath = path.join(abs, mfName);
254
374
  const manifest = parseManifest(fs.readFileSync(manifestPath, 'utf8'));
255
375
  if (!manifest.name) throw new Error(MANIFEST + ' has no "name" field');
256
376
  const files = new Map();
@@ -265,9 +385,9 @@ async function installFromLocalDir(dir) {
265
385
  walk(abs, '');
266
386
  const pkg = verifyZip(files, undefined);
267
387
  if (!pkg) throw new Error('package verification failed');
268
- const root = pkgRoot(true);
269
- const dest = extractTo({ ...pkg, prefix: '' }, root, { kind: 'local-dir', file: abs });
270
- return { manifest, dest };
388
+ const root = pkgRoot(opts.local !== true);
389
+ const dest = extractTo({ ...pkg, prefix: '' }, root, { kind: 'local-dir', file: abs, local: !!opts.local });
390
+ return { manifest, dest, manifestFile: pkg.manifestFile };
271
391
  }
272
392
 
273
393
  /* Install a spec string. Returns a result object; throws on failure. */
@@ -277,17 +397,18 @@ async function install(spec, opts = {}) {
277
397
 
278
398
  // local zip file
279
399
  if (/\.mz\.pkg\.zip$/.test(spec) || (fs.existsSync(spec) && fs.statSync(spec).isFile() && spec.endsWith('.zip'))) {
280
- return installFromLocalZip(spec);
400
+ return finishInstall(await installFromLocalZip(spec, { local }), { local, noDeps: opts.noDeps, depth: opts.depth || 0, seen: opts.seen });
281
401
  }
282
402
  // local directory
283
403
  if (fs.existsSync(spec) && fs.statSync(spec).isDirectory()) {
284
- return installFromLocalDir(spec);
404
+ return finishInstall(await installFromLocalDir(spec, { local }), { local, noDeps: opts.noDeps, depth: opts.depth || 0, seen: opts.seen });
285
405
  }
286
406
  // @user/repo[@tag]
287
407
  if (spec.startsWith('@')) {
288
408
  const m = spec.match(/^@([^/@]+)\/([^/@]+)(?:@(.+))?$/);
289
409
  if (!m) throw new Error('invalid Git package spec: ' + spec + ' (expected @user/repo or @user/repo@tag)');
290
- return installFromGit(m[1] + '/' + m[2], m[3] || null, { local });
410
+ const res = await installFromGit(m[1] + '/' + m[2], m[3] || null, { local });
411
+ return finishInstall(res, { local, noDeps: opts.noDeps, depth: opts.depth || 0, seen: opts.seen });
291
412
  }
292
413
  // registry name[@tag]
293
414
  const nm = spec.match(/^([^@]+)(?:@(.+))?$/);
@@ -303,8 +424,38 @@ async function install(spec, opts = {}) {
303
424
  ' search the registry: mz search ' + name
304
425
  );
305
426
  }
306
- const res = await installFromRegistry(entry, name, { local, tag });
307
- return { ...res, registrySource: source };
427
+ const res = await installFromRegistry(entry, name, { local, tag, constraint: opts.constraint });
428
+ return finishInstall(res, { local, noDeps: opts.noDeps, depth: opts.depth || 0, seen: opts.seen, registrySource: source });
429
+ }
430
+
431
+ /* Install the [dependencies] declared by a freshly installed package.
432
+ * Cycles and depth are bounded; already-installed versions that satisfy
433
+ * the constraint are left alone. */
434
+ async function finishInstall(res, ctx) {
435
+ const deps = (res.manifest && res.manifest.dependencies) || {};
436
+ const names = Object.keys(deps);
437
+ if (!names.length || ctx.noDeps || ctx.depth >= MAX_DEP_DEPTH) {
438
+ if (ctx.depth >= MAX_DEP_DEPTH && names.length) {
439
+ process.stderr.write('mz: warning: dependency chain deeper than ' + MAX_DEP_DEPTH + ' — remaining deps not installed\n');
440
+ }
441
+ return res;
442
+ }
443
+ const installed = [];
444
+ for (const depName of names) {
445
+ const constraint = deps[depName];
446
+ const have = listInstalled().find((p) => p.name === depName);
447
+ if (have && have.version && semver.satisfies(have.version, constraint)) {
448
+ installed.push({ name: depName, version: have.version, skipped: true });
449
+ continue;
450
+ }
451
+ const sub = await install(depName, {
452
+ local: ctx.local, constraint, noDeps: false,
453
+ depth: ctx.depth + 1,
454
+ seen: ctx.seen,
455
+ });
456
+ installed.push({ name: depName, version: sub.manifest ? sub.manifest.version : null, skipped: false });
457
+ }
458
+ return { ...res, dependencies: installed };
308
459
  }
309
460
 
310
461
  /* ------------------------------------------------------------------ */
@@ -348,9 +499,15 @@ function uninstall(name, opts = {}) {
348
499
  }
349
500
 
350
501
  function readManifestDir(dir) {
351
- const mp = path.join(dir, MANIFEST);
352
- if (!fs.existsSync(mp)) return null;
353
- return parseManifest(fs.readFileSync(mp, 'utf8'));
502
+ /* Try every supported manifest name — legacy packages ship
503
+ * package.toml, current scaffolds write mozhi.toml. Without the
504
+ * fallback, `mz list` silently hid legacy packages after the
505
+ * mozhi.toml migration. */
506
+ for (const m of MANIFESTS) {
507
+ const mp = path.join(dir, m);
508
+ if (fs.existsSync(mp)) return parseManifest(fs.readFileSync(mp, 'utf8'));
509
+ }
510
+ return null;
354
511
  }
355
512
 
356
513
  function listInstalled() {
@@ -393,6 +550,61 @@ function listInstalled() {
393
550
  return rows;
394
551
  }
395
552
 
553
+ /* ------------------------------------------------------------------ */
554
+ /* update */
555
+ /* ------------------------------------------------------------------ */
556
+
557
+ /* Re-resolve and reinstall registry packages. `name` updates one package;
558
+ * with no name, every installed package whose origin came from the
559
+ * registry (or a git repo) is updated to the newest satisfying release. */
560
+ async function update(name, opts = {}) {
561
+ const rows = listInstalled().filter((r) => r.source !== 'libs (single-file)');
562
+ const targets = name ? rows.filter((r) => r.name === name) : rows;
563
+ if (name && !targets.length) {
564
+ throw new Error('package "' + name + '" is not installed — nothing to update');
565
+ }
566
+ const results = [];
567
+ for (const t of targets) {
568
+ const res = await install(t.name, { local: !!opts.local, noDeps: true, depth: MAX_DEP_DEPTH });
569
+ const newVer = res.manifest ? res.manifest.version : null;
570
+ results.push({ name: t.name, from: t.version, to: newVer, changed: newVer !== t.version });
571
+ }
572
+ return results;
573
+ }
574
+
575
+ /* ------------------------------------------------------------------ */
576
+ /* info */
577
+ /* ------------------------------------------------------------------ */
578
+
579
+ /* Details about an installed package: manifest fields, origin, deps. */
580
+ function info(name, opts = {}) {
581
+ const rows = listInstalled();
582
+ const row = rows.find((r) => r.name === name);
583
+ if (!row) return null;
584
+ const dir = row.path;
585
+ const origin = readOrigin(dir) || {};
586
+ let manifest = null;
587
+ let manifestFile = null;
588
+ for (const m of MANIFESTS) {
589
+ const p = path.join(dir, m);
590
+ if (fs.existsSync(p)) {
591
+ manifestFile = m;
592
+ manifest = parseManifest(fs.readFileSync(p, 'utf8'));
593
+ break;
594
+ }
595
+ }
596
+ return {
597
+ name: row.name,
598
+ version: row.version || (manifest && manifest.version) || null,
599
+ path: dir,
600
+ source: row.source,
601
+ origin,
602
+ manifestFile,
603
+ manifest,
604
+ installedAt: origin.installed_at || null,
605
+ };
606
+ }
607
+
396
608
  /* ------------------------------------------------------------------ */
397
609
  /* author-side: pkg check / pkg zip */
398
610
  /* ------------------------------------------------------------------ */
@@ -412,7 +624,7 @@ function checkDir(dir) {
412
624
  };
413
625
  walk(abs, '');
414
626
  const pkg = verifyZip(files, undefined);
415
- return { manifest: { ...pkg.manifest, entry: pkg.entry }, fileMap: files, files: files.size, abs };
627
+ return { manifest: { ...pkg.manifest, entry: pkg.entry }, fileMap: files, files: files.size, abs, manifestFile: pkg.manifestFile };
416
628
  }
417
629
 
418
630
  /* Build <name>.mz.pkg.zip from a package directory. Returns output path. */
@@ -423,11 +635,11 @@ function zipDir(dir, outPath) {
423
635
  const buf = writeZip(files);
424
636
  const out = path.resolve(outPath || path.join(process.cwd(), info.manifest.name + '.mz.pkg.zip'));
425
637
  fs.writeFileSync(out, buf);
426
- return { out, name: info.manifest.name, version: info.manifest.version, count: info.files };
638
+ return { out, name: info.manifest.name, version: info.manifest.version, count: info.files, sha256: sha256hex(buf) };
427
639
  }
428
640
 
429
641
  module.exports = {
430
- install, uninstall, listInstalled, checkDir, zipDir,
642
+ install, uninstall, listInstalled, update, info, checkDir, zipDir,
431
643
  parseManifest, verifyZip, findManifestPrefix, resolveEntry,
432
- pkgRoot, libsRoot, MANIFEST, ORIGIN_FILE,
644
+ pkgRoot, libsRoot, MANIFEST, MANIFESTS, ORIGIN_FILE, sha256hex,
433
645
  };
package/lib/publish.js ADDED
@@ -0,0 +1,115 @@
1
+ 'use strict';
2
+ /*
3
+ * Mozhi package manager — `mz pkg publish`.
4
+ *
5
+ * What publish does (all steps real, verifiable):
6
+ * 1. validate the package directory (mz pkg check rules)
7
+ * 2. verify the git working tree is committed and the remote matches
8
+ * 3. build <name>.mz.pkg.zip in memory (same bytes `mz pkg zip` writes)
9
+ * 4. create a GitHub release for tag v<version> on the origin repo
10
+ * (requires GITHUB_TOKEN with contents:write)
11
+ * 5. upload the zip + a checksums-sha256.txt asset
12
+ * 6. re-download the asset and verify the checksum round-trip
13
+ * 7. print the registry.json entry to add in a mozhi-doc PR
14
+ * (the registry is version-controlled; entries change through PRs
15
+ * so every listing stays auditable — publish does NOT touch it)
16
+ *
17
+ * What publish deliberately does NOT do:
18
+ * - it never pushes git tags (you tag, it releases)
19
+ * - it never edits the registry file (you open the PR)
20
+ */
21
+
22
+ const { execFileSync } = require('child_process');
23
+ const crypto = require('crypto');
24
+ const path = require('path');
25
+ const pkgman = require('./pkgman');
26
+ const gh = require('./gh');
27
+ const { writeZip } = require('./zip');
28
+
29
+ function sh(cmd, args, opts = {}) {
30
+ return execFileSync(cmd, args, { encoding: 'utf8', ...opts }).trim();
31
+ }
32
+
33
+ function git(args, opts = {}) {
34
+ try {
35
+ return sh('git', args, opts);
36
+ } catch (e) {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ function parseOriginRemote(dir) {
42
+ const url = git(['-C', dir, 'remote', 'get-url', 'origin']);
43
+ if (!url) return null;
44
+ const m = /github\.com[:/]([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?$/.exec(url);
45
+ if (!m) return null;
46
+ return m[1] + '/' + m[2];
47
+ }
48
+
49
+ /* Publish a package directory. Returns a result summary. */
50
+ async function publishDir(dir, opts = {}) {
51
+ const abs = path.resolve(dir || '.');
52
+ const dryRun = !!opts.dryRun;
53
+
54
+ const info = pkgman.checkDir(abs); // throws on invalid structure
55
+ const { manifest } = info;
56
+ if (!manifest.version) throw new Error('manifest has no version — set one before publishing');
57
+
58
+ const repo = parseOriginRemote(abs);
59
+ if (!repo) {
60
+ throw new Error('cannot determine the GitHub repo — add a git remote: git remote add origin git@github.com:<you>/' +
61
+ manifest.name + '.git');
62
+ }
63
+ const head = git(['-C', abs, 'rev-parse', 'HEAD']);
64
+ const dirty = git(['-C', abs, 'status', '--porcelain']);
65
+ if (!head || (dirty && dirty.length && !opts.allowDirty)) {
66
+ throw new Error('working tree has uncommitted changes — commit first (or pass --allow-dirty)');
67
+ }
68
+
69
+ // Build the zip in memory (same bytes pkg zip would write).
70
+ const files = new Map();
71
+ for (const [rel, data] of info.fileMap) files.set(manifest.name + '/' + rel, data);
72
+ const zipBuf = writeZip(files);
73
+ const zipName = manifest.name + '.mz.pkg.zip';
74
+ const sha256 = crypto.createHash('sha256').update(zipBuf).digest('hex');
75
+ const checksumBody = sha256 + ' ' + zipName + '\n';
76
+
77
+ const tag = 'v' + manifest.version;
78
+ if (dryRun) {
79
+ return { dryRun: true, repo, tag, zipName, sha256, size: zipBuf.length, files: info.files, manifest };
80
+ }
81
+
82
+ const release = await gh.createRelease(repo, tag,
83
+ manifest.name + ' ' + tag,
84
+ 'Mozhi package release. Install with: mz install @' + repo);
85
+ await gh.uploadAsset(release, zipName, zipBuf);
86
+ await gh.uploadAsset(release, 'checksums-sha256.txt', Buffer.from(checksumBody, 'utf8'), 'text/plain');
87
+
88
+ // Round-trip verification: download what we just published.
89
+ const check = await gh.releaseByTag(repo, tag);
90
+ const asset = gh.pickAsset(check, manifest.name);
91
+ if (!asset) throw new Error('published release has no ' + zipName + ' asset — upload failed');
92
+ const back = await gh.downloadAsset(asset);
93
+ const backSha = crypto.createHash('sha256').update(back).digest('hex');
94
+ if (backSha !== sha256) {
95
+ throw new Error('checksum mismatch after publish (' + backSha + ' != ' + sha256 + ')');
96
+ }
97
+
98
+ const registryEntry = {
99
+ name: manifest.name,
100
+ version: manifest.version,
101
+ description: manifest.description || '',
102
+ license: manifest.license || 'MIT',
103
+ category: manifest.category || 'general',
104
+ repo,
105
+ official: false,
106
+ versions: { [manifest.version]: { tag, dist: { asset: zipName, sha256 } } },
107
+ };
108
+
109
+ return {
110
+ repo, tag, zipName, sha256, releaseUrl: check.html_url || null,
111
+ registryEntry, files: info.files, size: zipBuf.length, manifest,
112
+ };
113
+ }
114
+
115
+ module.exports = { publishDir, parseOriginRemote };
package/lib/scaffold.js CHANGED
@@ -34,14 +34,14 @@ jobs:
34
34
  - name: Read package metadata
35
35
  id: meta
36
36
  run: |
37
- NAME=$(sed -n 's/^name[[:space:]]*=[[:space:]]*"\\([^"]*\\)".*/\\1/p' package.toml | head -1)
38
- VERSION=$(sed -n 's/^version[[:space:]]*=[[:space:]]*"\\([^"]*\\)".*/\\1/p' package.toml | head -1)
37
+ NAME=$(sed -n 's/^name[[:space:]]*=[[:space:]]*"\\([^"]*\\)".*/\\1/p' mozhi.toml | head -1)
38
+ VERSION=$(sed -n 's/^version[[:space:]]*=[[:space:]]*"\\([^"]*\\)".*/\\1/p' mozhi.toml | head -1)
39
39
  if [ -z "$NAME" ] || [ -z "$VERSION" ]; then
40
- echo "package.toml must define name and version" >&2
40
+ echo "mozhi.toml must define name and version" >&2
41
41
  exit 1
42
42
  fi
43
43
  if [ "\${GITHUB_REF_NAME#v}" != "$VERSION" ]; then
44
- echo "tag \${GITHUB_REF_NAME} does not match package.toml version $VERSION" >&2
44
+ echo "tag \${GITHUB_REF_NAME} does not match mozhi.toml version $VERSION" >&2
45
45
  exit 1
46
46
  fi
47
47
  echo "name=$NAME" >> "$GITHUB_OUTPUT"
@@ -49,7 +49,7 @@ jobs:
49
49
 
50
50
  - name: Verify package structure
51
51
  run: |
52
- test -f package.toml
52
+ test -f mozhi.toml
53
53
  test -f src/mod.mz
54
54
  echo "package structure OK: \${{ steps.meta.outputs.name }} v\${{ steps.meta.outputs.version }}"
55
55
 
@@ -84,18 +84,26 @@ function scaffold(name, dir) {
84
84
  }
85
85
  const year = new Date().getFullYear();
86
86
  const files = new Map([
87
- ['package.toml', `# ${name} — Mozhi package manifest
87
+ ['mozhi.toml', `# ${name} — Mozhi package manifest
88
88
  [package]
89
89
  name = "${name}"
90
90
  version = "0.1.0"
91
91
  description = "TODO: one-line description of ${name}"
92
92
  license = "MIT"
93
93
  category = "general"
94
- edition = "2024"
95
94
 
96
95
  [module]
97
96
  # The file the interpreter loads for 'import ${name}'.
98
97
  entry = "src/mod.mz"
98
+
99
+ # Declare dependencies on registry packages here; 'mz install'
100
+ # resolves them recursively (semver ranges: "1.2.3", ">=1.0.0 <2.0.0",
101
+ # "^1.2.3", "~1.2.3", "*").
102
+ [dependencies]
103
+
104
+ [test]
105
+ # directory 'mz pkg test' scans for *.test.mz files
106
+ tests = "tests"
99
107
  `],
100
108
  ['src/mod.mz', `# ${name} v0.1.0 — entry module
101
109
  #
@@ -117,7 +125,7 @@ import ${name}
117
125
  echo(${name}.hello("Mozhi"))
118
126
  echo("version: " + ${name}.version())
119
127
  `],
120
- ['tests/' + name + '.test.mz', `# Run with: mozhi test
128
+ ['tests/' + name + '.test.mz', `# Run with: mz pkg test
121
129
  import ${name} from "../src/mod.mz"
122
130
 
123
131
  assert_eq(${name}.hello("x"), "hello, x!")
@@ -148,13 +156,14 @@ echo(${name}.hello("Mozhi"))
148
156
  mozhi test # run tests/
149
157
  mozhi run examples/demo.mz
150
158
  mz pkg check # verify package structure
151
- mz pkg zip # build ${name}.mz.pkg.zip locally
159
+ mz pkg test # run tests/
160
+ mz pkg build # build ${name}.mz.pkg.zip locally
152
161
  \`\`\`
153
162
 
154
163
  ## Release
155
164
 
156
165
  \`\`\`bash
157
- # 1. set the version in package.toml
166
+ # 1. set the version in mozhi.toml
158
167
  # 2. commit and tag — GitHub Actions builds the release zip automatically
159
168
  git commit -am "release 0.1.0"
160
169
  git tag v0.1.0
package/lib/semver.js ADDED
@@ -0,0 +1,104 @@
1
+ 'use strict';
2
+ /*
3
+ * Mozhi package manager — minimal semantic-version handling for
4
+ * [dependencies] constraints in mozhi.toml manifests.
5
+ *
6
+ * Supported range syntax (a whitespace-separated list = AND):
7
+ * 1.2.3 exact version
8
+ * >=1.2.0 greater or equal
9
+ * >1.2.0 <2.0.0 bounded range
10
+ * ^1.2.3 same major (>=1.2.3 <2.0.0)
11
+ * ~1.2.3 same minor (>=1.2.3 <1.3.0)
12
+ * * any version
13
+ *
14
+ * Deliberately NOT supported: prerelease tags, build metadata,
15
+ * node-style "1.x" ranges. Unknown syntax fails loudly (install aborts)
16
+ * instead of silently resolving to something the author did not ask for.
17
+ */
18
+
19
+ function parseVersion(v) {
20
+ const m = /^(\d+)\.(\d+)\.(\d+)$/.exec(String(v || '').trim());
21
+ if (!m) return null;
22
+ return { major: +m[1], minor: +m[2], patch: +m[3] };
23
+ }
24
+
25
+ function cmpVersions(a, b) {
26
+ const A = parseVersion(a), B = parseVersion(b);
27
+ if (!A || !B) return NaN;
28
+ if (A.major !== B.major) return A.major - B.major;
29
+ if (A.minor !== B.minor) return A.minor - B.minor;
30
+ return A.patch - B.patch;
31
+ }
32
+
33
+ function cmpOp(op, a, b) {
34
+ const c = cmpVersions(a, b);
35
+ switch (op) {
36
+ case '>=': return c >= 0;
37
+ case '>': return c > 0;
38
+ case '<=': return c <= 0;
39
+ case '<': return c < 0;
40
+ case '=': return c === 0;
41
+ default: return false;
42
+ }
43
+ }
44
+
45
+ /* Parse one constraint clause into {op, version} or {any:true}. */
46
+ function parseClause(clause) {
47
+ const c = String(clause).trim();
48
+ if (c === '' || c === '*') return { any: true };
49
+ let m = /^\^(\d+)\.(\d+)\.(\d+)$/.exec(c);
50
+ if (m) {
51
+ return { range: [{ op: '>=', version: `${m[1]}.${m[2]}.${m[3]}` }, { op: '<', version: `${+m[1] + 1}.0.0` }] };
52
+ }
53
+ m = /^~(\d+)\.(\d+)\.(\d+)$/.exec(c);
54
+ if (m) {
55
+ return { range: [{ op: '>=', version: `${m[1]}.${m[2]}.${m[3]}` }, { op: '<', version: `${m[1]}.${+m[2] + 1}.0` }] };
56
+ }
57
+ m = /^(>=|<=|>|<|=)?\s*(\d+\.\d+\.\d+)$/.exec(c);
58
+ if (m) {
59
+ const op = m[1] || '=';
60
+ if (op === '=') return { exact: m[2] };
61
+ return { range: [{ op, version: m[2] }] };
62
+ }
63
+ throw new Error(`unsupported version constraint "${clause}" (supported: 1.2.3, >=1.2.3, <2.0.0, ^1.2.3, ~1.2.3, *)`);
64
+ }
65
+
66
+ /* Parse a whole constraint string ("1.2.3", ">=1.0.0 <2.0.0", "^1.2.3"). */
67
+ function parseRange(range) {
68
+ const clauses = String(range || '*').trim().split(/\s+/).filter(Boolean);
69
+ if (!clauses.length) clauses.push('*');
70
+ const parsed = clauses.map(parseClause);
71
+ // collapse {range:[...]} entries into a flat comparator list
72
+ const comps = [];
73
+ let exact = null;
74
+ for (const p of parsed) {
75
+ if (p.any) continue;
76
+ if (p.exact) { exact = p.exact; continue; }
77
+ comps.push(...p.range);
78
+ }
79
+ return { comps, exact, raw: range };
80
+ }
81
+
82
+ function satisfies(version, range) {
83
+ const v = parseVersion(version);
84
+ if (!v) return false;
85
+ const r = typeof range === 'string' ? parseRange(range) : range;
86
+ if (r.exact) return cmpVersions(version, r.exact) === 0;
87
+ for (const c of r.comps) {
88
+ if (!cmpOp(c.op, version, c.version)) return false;
89
+ }
90
+ return true;
91
+ }
92
+
93
+ /* Pick the highest version in `available` that satisfies `range`.
94
+ * Returns the version string or null. */
95
+ function bestMatch(available, range) {
96
+ const r = typeof range === 'string' ? parseRange(range) : range;
97
+ const sorted = available.slice().sort(cmpVersions);
98
+ for (let i = sorted.length - 1; i >= 0; i--) {
99
+ if (satisfies(sorted[i], r)) return sorted[i];
100
+ }
101
+ return null;
102
+ }
103
+
104
+ module.exports = { parseVersion, parseRange, satisfies, bestMatch, cmpVersions };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crossberryweb/mozhi",
3
- "version": "3.5.0",
3
+ "version": "3.7.1",
4
4
  "description": "Mozhi programming language interpreter \u2014 native web, JSON, fs, math, SQLite, templates \u2014 with the built-in package manager (`mz install`). Install once, get both commands: `mozhi` and the short alias `mz` (identical behavior).",
5
5
  "license": "MIT",
6
6
  "repository": {