@crossberryweb/mozhi 3.2.1 → 3.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/pkgman.js ADDED
@@ -0,0 +1,433 @@
1
+ 'use strict';
2
+ /*
3
+ * Mozhi package manager — install / uninstall / list / verify.
4
+ *
5
+ * Package layout (inside a release zip):
6
+ * package.toml manifest: name, version, entry, description...
7
+ * src/mod.mz entry module (default)
8
+ * examples/ tests/ optional
9
+ *
10
+ * Install targets:
11
+ * ~/.mozhi/pkg/<name>/ global (default) — resolved by the interpreter
12
+ * ./.mozhi/pkg/<name>/ project (--local)
13
+ * ~/.mozhi/libs/... legacy single-file registry libs
14
+ *
15
+ * Every install is verified before it lands: the zip must contain a
16
+ * package.toml, the manifest must name the package and resolve to an
17
+ * existing entry file, and entry names may not escape the package.
18
+ */
19
+
20
+ const fs = require('fs');
21
+ const path = require('path');
22
+ const os = require('os');
23
+ const { readZip, writeZip } = require('./zip');
24
+ const reg = require('./registry');
25
+ const gh = require('./gh');
26
+
27
+ const MANIFEST = 'package.toml';
28
+ const ORIGIN_FILE = '.mozhi-pkg.json';
29
+
30
+ /* ------------------------------------------------------------------ */
31
+ /* helpers */
32
+ /* ------------------------------------------------------------------ */
33
+
34
+ function pkgRoot(global_ = true) {
35
+ if (global_) return path.join(os.homedir(), '.mozhi', 'pkg');
36
+ return path.join(process.cwd(), '.mozhi', 'pkg');
37
+ }
38
+
39
+ function libsRoot(global_ = true) {
40
+ if (global_) return path.join(os.homedir(), '.mozhi', 'libs');
41
+ return path.join(process.cwd(), '.mozhi', 'libs');
42
+ }
43
+
44
+ /* Lenient manifest scan — mirrors the interpreter's mz_pkg.c parser:
45
+ * any `key = "value"` line wins regardless of section headers. */
46
+ 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];
52
+ }
53
+ return out;
54
+ }
55
+
56
+ /* Default entry probing, same order as the interpreter. */
57
+ function resolveEntry(manifest, files, prefix) {
58
+ const candidates = [];
59
+ if (manifest.entry) candidates.push(manifest.entry);
60
+ const name = manifest.name || 'mod';
61
+ candidates.push('src/mod.mz', 'src/' + name + '.mz', name + '.mz', 'mod.mz', 'main.mz', 'index.mz');
62
+ for (const c of candidates) {
63
+ if (!c || c.startsWith('/') || c.includes('..') || /[\\]/.test(c)) continue;
64
+ if (!/\.(mz|mozhi)$/.test(c)) continue;
65
+ if (files.has(prefix + c)) return c;
66
+ }
67
+ return null;
68
+ }
69
+
70
+ /* Locate package.toml inside a zip file map: zip root or a single
71
+ * top-level directory (git-archive style). Returns prefix ('' or 'dir/'). */
72
+ function findManifestPrefix(files) {
73
+ if (files.has(MANIFEST)) return '';
74
+ const tops = new Set();
75
+ for (const name of files.keys()) {
76
+ const slash = name.indexOf('/');
77
+ if (slash > 0) tops.add(name.slice(0, slash));
78
+ }
79
+ if (tops.size === 1) {
80
+ const prefix = Array.from(tops)[0] + '/';
81
+ if (files.has(prefix + MANIFEST)) return prefix;
82
+ }
83
+ throw new Error(
84
+ 'package structure invalid: ' + MANIFEST + ' not found at zip root or in a single top-level directory'
85
+ );
86
+ }
87
+
88
+ /* Verify a zip's package structure. Returns {manifest, prefix, entry, files}. */
89
+ function verifyZip(files, expectedName) {
90
+ const prefix = findManifestPrefix(files);
91
+ const manifest = parseManifest(files.get(prefix + MANIFEST).toString('utf8'));
92
+ if (!manifest.name) {
93
+ throw new Error('package structure invalid: ' + MANIFEST + ' has no "name" field');
94
+ }
95
+ if (expectedName && manifest.name !== expectedName) {
96
+ throw new Error(
97
+ 'package structure invalid: manifest name "' + manifest.name + '" does not match expected "' + expectedName + '"'
98
+ );
99
+ }
100
+ const entry = resolveEntry(manifest, files, prefix);
101
+ if (!entry) {
102
+ throw new Error(
103
+ 'package structure invalid: entry module not found (looked for ' +
104
+ [manifest.entry, 'src/mod.mz', 'src/' + manifest.name + '.mz', manifest.name + '.mz']
105
+ .filter(Boolean).join(', ') + ')'
106
+ );
107
+ }
108
+ return { manifest, prefix, entry, files };
109
+ }
110
+
111
+ function writeOrigin(dir, origin) {
112
+ fs.writeFileSync(path.join(dir, ORIGIN_FILE), JSON.stringify(origin, null, 2) + '\n');
113
+ }
114
+
115
+ function readOrigin(dir) {
116
+ try {
117
+ return JSON.parse(fs.readFileSync(path.join(dir, ORIGIN_FILE), 'utf8'));
118
+ } catch {
119
+ return null;
120
+ }
121
+ }
122
+
123
+ /* Extract a verified package map into <root>/<name> (replacing any old copy). */
124
+ function extractTo(pkg, root, origin) {
125
+ const dest = path.join(root, pkg.manifest.name);
126
+ const staging = dest + '.tmp-' + process.pid;
127
+ fs.rmSync(staging, { recursive: true, force: true });
128
+ fs.mkdirSync(staging, { recursive: true });
129
+ for (const [name, data] of pkg.files) {
130
+ if (!name.startsWith(pkg.prefix) || name === pkg.prefix + ORIGIN_FILE) continue;
131
+ const rel = name.slice(pkg.prefix.length);
132
+ const target = path.join(staging, rel);
133
+ fs.mkdirSync(path.dirname(target), { recursive: true });
134
+ fs.writeFileSync(target, data);
135
+ }
136
+ writeOrigin(staging, origin);
137
+ fs.rmSync(dest, { recursive: true, force: true });
138
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
139
+ fs.renameSync(staging, dest);
140
+ return dest;
141
+ }
142
+
143
+ /* ------------------------------------------------------------------ */
144
+ /* install */
145
+ /* ------------------------------------------------------------------ */
146
+
147
+ async function installFromZipBuffer(buf, origin) {
148
+ const files = readZip(buf);
149
+ const pkg = verifyZip(files, origin.expectedName);
150
+ const root = pkgRoot(origin.local !== false);
151
+ const dest = extractTo(pkg, root, {
152
+ name: pkg.manifest.name,
153
+ version: pkg.manifest.version || null,
154
+ ...origin,
155
+ });
156
+ return { manifest: pkg.manifest, dest };
157
+ }
158
+
159
+ async function installFromGit(repo, tag, opts = {}) {
160
+ const repoName = repo.split('/')[1];
161
+ const release = tag ? await gh.releaseByTag(repo, tag) : await gh.latestRelease(repo);
162
+ if (!release) {
163
+ throw new Error(
164
+ 'no release found in ' + repo + (tag ? ' for tag ' + tag : '') +
165
+ ' — packages install from tagged releases carrying <name>.mz.pkg.zip assets'
166
+ );
167
+ }
168
+ // pkg name: try repo name first, then any single .mz.pkg.zip asset
169
+ let asset = gh.pickAsset(release, repoName);
170
+ if (!asset) {
171
+ asset = gh.pickAsset(release, null);
172
+ }
173
+ if (!asset) {
174
+ throw new Error(
175
+ 'release ' + (release.tag_name || '') + ' in ' + repo + ' has no <name>.mz.pkg.zip asset' +
176
+ ' — found: ' + ((release.assets || []).map((a) => a.name).join(', ') || 'none')
177
+ );
178
+ }
179
+ const buf = await gh.downloadAsset(asset);
180
+ const expected = asset.name.replace(/\.mz\.pkg\.zip$/, '');
181
+ const res = await installFromZipBuffer(buf, {
182
+ kind: 'git',
183
+ repo,
184
+ tag: release.tag_name || tag || null,
185
+ asset: asset.name,
186
+ expectedName: opts.strictName ? expected : undefined,
187
+ });
188
+ return { ...res, release, asset };
189
+ }
190
+
191
+ /* Legacy single-file libs install into ~/.mozhi/libs/<path from the
192
+ * registry>. A small ledger records where each one went so uninstall
193
+ * and list work without re-fetching the registry. */
194
+ function libsLedgerPath(global_ = true) {
195
+ return path.join(libsRoot(global_), '.mozhi-libs.json');
196
+ }
197
+
198
+ function libsLedgerRead(global_ = true) {
199
+ try { return JSON.parse(fs.readFileSync(libsLedgerPath(global_), 'utf8')); }
200
+ catch { return {}; }
201
+ }
202
+
203
+ function libsLedgerWrite(global_, data) {
204
+ fs.mkdirSync(libsRoot(global_), { recursive: true });
205
+ fs.writeFileSync(libsLedgerPath(global_), JSON.stringify(data, null, 2) + '\n');
206
+ }
207
+
208
+ async function installFromRegistry(entry, nameSpec, opts = {}) {
209
+ if (entry.repo) {
210
+ return installFromGit(entry.repo, opts.tag, { strictName: false });
211
+ }
212
+ // Legacy single-file library hosted in the mozhi-doc repo
213
+ const src = entry.source || entry.install;
214
+ if (!src) throw new Error('registry entry "' + entry.name + '" has neither "repo" nor "install"');
215
+ const libsBase = (process.env.MOZHI_LIBS_URL ||
216
+ 'https://raw.githubusercontent.com/crossberry-in/mozhi-doc/main/libs/').replace(/\/+$/, '/');
217
+ const url = libsBase + src.replace(/^\/+/, '');
218
+ const res = await fetch(url, { signal: AbortSignal.timeout(15000) });
219
+ if (!res.ok) throw new Error('download failed (HTTP ' + res.status + '): ' + url);
220
+ const body = await res.text();
221
+ if (body.length < 10) throw new Error('downloaded library looks empty: ' + url);
222
+
223
+ const root = libsRoot(opts.local !== true);
224
+ const rel = src.replace(/^\/+/, '');
225
+ const dest = path.join(root, rel);
226
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
227
+ fs.writeFileSync(dest, body);
228
+ const ledger = libsLedgerRead(opts.local !== true);
229
+ ledger[entry.name] = { path: rel, version: entry.version || null, installed_at: new Date().toISOString() };
230
+ libsLedgerWrite(opts.local !== true, ledger);
231
+ return {
232
+ manifest: { name: entry.name, version: entry.version || null, description: entry.description },
233
+ dest,
234
+ legacy: true,
235
+ };
236
+ }
237
+
238
+ async function installFromLocalZip(file) {
239
+ const buf = fs.readFileSync(file);
240
+ const res = await installFromZipBuffer(buf, {
241
+ kind: 'local-zip',
242
+ file: path.resolve(file),
243
+ expectedName: undefined,
244
+ });
245
+ return res;
246
+ }
247
+
248
+ async function installFromLocalDir(dir) {
249
+ 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);
253
+ }
254
+ const manifest = parseManifest(fs.readFileSync(manifestPath, 'utf8'));
255
+ if (!manifest.name) throw new Error(MANIFEST + ' has no "name" field');
256
+ const files = new Map();
257
+ const walk = (d, rel) => {
258
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
259
+ if (e.name === '.git' || e.name === ORIGIN_FILE) continue;
260
+ const r = rel ? rel + '/' + e.name : e.name;
261
+ if (e.isDirectory()) walk(path.join(d, e.name), r);
262
+ else files.set(r, fs.readFileSync(path.join(d, e.name)));
263
+ }
264
+ };
265
+ walk(abs, '');
266
+ const pkg = verifyZip(files, undefined);
267
+ 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 };
271
+ }
272
+
273
+ /* Install a spec string. Returns a result object; throws on failure. */
274
+ async function install(spec, opts = {}) {
275
+ if (!spec) throw new Error('nothing to install — usage: mz install <name|@user/repo|file.mz.pkg.zip|dir>');
276
+ const local = !!opts.local;
277
+
278
+ // local zip file
279
+ if (/\.mz\.pkg\.zip$/.test(spec) || (fs.existsSync(spec) && fs.statSync(spec).isFile() && spec.endsWith('.zip'))) {
280
+ return installFromLocalZip(spec);
281
+ }
282
+ // local directory
283
+ if (fs.existsSync(spec) && fs.statSync(spec).isDirectory()) {
284
+ return installFromLocalDir(spec);
285
+ }
286
+ // @user/repo[@tag]
287
+ if (spec.startsWith('@')) {
288
+ const m = spec.match(/^@([^/@]+)\/([^/@]+)(?:@(.+))?$/);
289
+ 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 });
291
+ }
292
+ // registry name[@tag]
293
+ const nm = spec.match(/^([^@]+)(?:@(.+))?$/);
294
+ if (!nm) throw new Error('invalid package spec: ' + spec);
295
+ const name = nm[1];
296
+ const tag = nm[2] || null;
297
+ const { registry, source } = await reg.fetchRegistry();
298
+ const entry = reg.findPackage(registry, name);
299
+ if (!entry) {
300
+ throw new Error(
301
+ 'package "' + name + '" is not in the Mozhi registry.\n' +
302
+ ' install from any Git repo: mz install @username/repo\n' +
303
+ ' search the registry: mz search ' + name
304
+ );
305
+ }
306
+ const res = await installFromRegistry(entry, name, { local, tag });
307
+ return { ...res, registrySource: source };
308
+ }
309
+
310
+ /* ------------------------------------------------------------------ */
311
+ /* uninstall / list */
312
+ /* ------------------------------------------------------------------ */
313
+
314
+ function uninstall(name, opts = {}) {
315
+ const removed = [];
316
+ // 1. ledger-recorded legacy lib
317
+ const ledger = libsLedgerRead(opts.local !== true);
318
+ if (ledger[name] && ledger[name].path) {
319
+ const p = path.join(libsRoot(opts.local !== true), ledger[name].path);
320
+ if (fs.existsSync(p)) {
321
+ fs.rmSync(p, { recursive: true, force: true });
322
+ removed.push(p);
323
+ }
324
+ delete ledger[name];
325
+ libsLedgerWrite(opts.local !== true, ledger);
326
+ }
327
+ // 2. package dir
328
+ const dir = path.join(pkgRoot(opts.local !== true), name);
329
+ if (fs.existsSync(dir)) {
330
+ fs.rmSync(dir, { recursive: true, force: true });
331
+ removed.push(dir);
332
+ }
333
+ // 3. conventional libs locations
334
+ const libFile = path.join(libsRoot(opts.local !== true), name + '.mz');
335
+ if (fs.existsSync(libFile)) {
336
+ fs.rmSync(libFile, { force: true });
337
+ removed.push(libFile);
338
+ }
339
+ const libDir = path.join(libsRoot(opts.local !== true), name);
340
+ if (fs.existsSync(libDir) && fs.statSync(libDir).isDirectory()) {
341
+ fs.rmSync(libDir, { recursive: true, force: true });
342
+ removed.push(libDir);
343
+ }
344
+ if (!removed.length) {
345
+ throw new Error('package "' + name + '" is not installed');
346
+ }
347
+ return removed;
348
+ }
349
+
350
+ function readManifestDir(dir) {
351
+ const mp = path.join(dir, MANIFEST);
352
+ if (!fs.existsSync(mp)) return null;
353
+ return parseManifest(fs.readFileSync(mp, 'utf8'));
354
+ }
355
+
356
+ function listInstalled() {
357
+ const rows = [];
358
+ const root = pkgRoot(true);
359
+ if (fs.existsSync(root)) {
360
+ for (const e of fs.readdirSync(root, { withFileTypes: true })) {
361
+ if (!e.isDirectory()) continue;
362
+ const dir = path.join(root, e.name);
363
+ const m = readManifestDir(dir);
364
+ if (!m) continue;
365
+ const origin = readOrigin(dir) || {};
366
+ rows.push({
367
+ name: m.name || e.name,
368
+ version: m.version || null,
369
+ source: origin.kind === 'git' ? (origin.repo + (origin.tag ? '@' + origin.tag : ''))
370
+ : origin.kind === 'local-zip' ? 'zip: ' + (origin.file || '?')
371
+ : origin.kind === 'local-dir' ? 'dir: ' + (origin.file || '?')
372
+ : 'unknown',
373
+ path: dir,
374
+ });
375
+ }
376
+ }
377
+ const libs = libsRoot(true);
378
+ const ledger = libsLedgerRead(true);
379
+ if (fs.existsSync(libs)) {
380
+ for (const e of fs.readdirSync(libs, { withFileTypes: true })) {
381
+ if (e.isFile() && e.name.endsWith('.mz')) {
382
+ rows.push({ name: e.name.slice(0, -3), version: null, source: 'libs (single-file)', path: path.join(libs, e.name) });
383
+ } else if (e.isDirectory() && fs.existsSync(path.join(libs, e.name, e.name + '.mz'))) {
384
+ rows.push({ name: e.name, version: null, source: 'libs (directory)', path: path.join(libs, e.name) });
385
+ }
386
+ }
387
+ for (const [name, rec] of Object.entries(ledger)) {
388
+ if (rows.some((r) => r.path === path.join(libs, rec.path))) continue;
389
+ rows.push({ name, version: rec.version, source: 'libs (registry)', path: path.join(libs, rec.path) });
390
+ }
391
+ }
392
+ rows.sort((a, b) => a.name.localeCompare(b.name));
393
+ return rows;
394
+ }
395
+
396
+ /* ------------------------------------------------------------------ */
397
+ /* author-side: pkg check / pkg zip */
398
+ /* ------------------------------------------------------------------ */
399
+
400
+ /* Validate a package directory. Returns manifest + file map. Throws when invalid. */
401
+ function checkDir(dir) {
402
+ const abs = path.resolve(dir || '.');
403
+ const manifest = parseManifest(fs.readFileSync(path.join(abs, MANIFEST), 'utf8'));
404
+ const files = new Map();
405
+ const walk = (d, rel) => {
406
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
407
+ if (['.git', '.github', 'node_modules', ORIGIN_FILE].includes(e.name)) continue;
408
+ const r = rel ? rel + '/' + e.name : e.name;
409
+ if (e.isDirectory()) walk(path.join(d, e.name), r);
410
+ else files.set(r, fs.readFileSync(path.join(d, e.name)));
411
+ }
412
+ };
413
+ walk(abs, '');
414
+ const pkg = verifyZip(files, undefined);
415
+ return { manifest: { ...pkg.manifest, entry: pkg.entry }, fileMap: files, files: files.size, abs };
416
+ }
417
+
418
+ /* Build <name>.mz.pkg.zip from a package directory. Returns output path. */
419
+ function zipDir(dir, outPath) {
420
+ const info = checkDir(dir); // verifies before packaging
421
+ const files = new Map();
422
+ for (const [rel, data] of info.fileMap) files.set(info.manifest.name + '/' + rel, data);
423
+ const buf = writeZip(files);
424
+ const out = path.resolve(outPath || path.join(process.cwd(), info.manifest.name + '.mz.pkg.zip'));
425
+ fs.writeFileSync(out, buf);
426
+ return { out, name: info.manifest.name, version: info.manifest.version, count: info.files };
427
+ }
428
+
429
+ module.exports = {
430
+ install, uninstall, listInstalled, checkDir, zipDir,
431
+ parseManifest, verifyZip, findManifestPrefix, resolveEntry,
432
+ pkgRoot, libsRoot, MANIFEST, ORIGIN_FILE,
433
+ };
@@ -0,0 +1,112 @@
1
+ 'use strict';
2
+ /*
3
+ * Mozhi package manager — registry client.
4
+ *
5
+ * The registry is a version-controlled JSON file in the public mozhi-doc
6
+ * repository, so every registry change is auditable through git history:
7
+ *
8
+ * https://raw.githubusercontent.com/crossberry-in/mozhi-doc/main/mozhi-registry.json
9
+ *
10
+ * Resolution order: $MOZHI_REGISTRY_URL (http/https/file) → remote with
11
+ * timeout → ~/.mozhi/cache/registry.json (last good copy) → bundled
12
+ * snapshot shipped inside the npm package.
13
+ */
14
+
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+ const os = require('os');
18
+
19
+ const DEFAULT_REGISTRY_URL =
20
+ 'https://raw.githubusercontent.com/crossberry-in/mozhi-doc/main/mozhi-registry.json';
21
+
22
+ function registryUrl() {
23
+ return process.env.MOZHI_REGISTRY_URL || DEFAULT_REGISTRY_URL;
24
+ }
25
+
26
+ function cachePath() {
27
+ return path.join(os.homedir(), '.mozhi', 'cache', 'registry.json');
28
+ }
29
+
30
+ function bundledSnapshotPath() {
31
+ return path.join(__dirname, '..', 'registry.json');
32
+ }
33
+
34
+ function parseRegistry(text) {
35
+ const data = JSON.parse(text);
36
+ if (!data || !Array.isArray(data.packages)) {
37
+ throw new Error('registry JSON has no "packages" array');
38
+ }
39
+ return data;
40
+ }
41
+
42
+ async function fetchRegistry(timeoutMs = 8000) {
43
+ const url = registryUrl();
44
+ const errors = [];
45
+
46
+ // 1. explicit override (http/https via fetch, file:// via fs)
47
+ if (url.startsWith('file://')) {
48
+ const p = url.slice('file://'.length);
49
+ return { registry: parseRegistry(fs.readFileSync(p, 'utf8')), source: 'file://' + p };
50
+ }
51
+
52
+ // 2. remote
53
+ try {
54
+ const res = await fetch(url, {
55
+ signal: AbortSignal.timeout(timeoutMs),
56
+ headers: { 'user-agent': 'mozhi-pkg/3.3 (+https://github.com/crossberry-in/mozhi)' },
57
+ });
58
+ if (!res.ok) throw new Error('HTTP ' + res.status);
59
+ const text = await res.text();
60
+ const registry = parseRegistry(text);
61
+ try {
62
+ fs.mkdirSync(path.dirname(cachePath()), { recursive: true });
63
+ fs.writeFileSync(cachePath(), text);
64
+ } catch { /* cache write is best-effort */ }
65
+ return { registry, source: url };
66
+ } catch (e) {
67
+ errors.push('remote (' + url + '): ' + e.message);
68
+ }
69
+
70
+ // 3. last good cached copy
71
+ try {
72
+ const text = fs.readFileSync(cachePath(), 'utf8');
73
+ return { registry: parseRegistry(text), source: 'cache: ' + cachePath() };
74
+ } catch (e) {
75
+ errors.push('cache: ' + e.message);
76
+ }
77
+
78
+ // 4. bundled snapshot
79
+ try {
80
+ const text = fs.readFileSync(bundledSnapshotPath(), 'utf8');
81
+ return { registry: parseRegistry(text), source: 'bundled snapshot' };
82
+ } catch (e) {
83
+ errors.push('bundled: ' + e.message);
84
+ }
85
+
86
+ throw new Error('cannot load package registry:\n ' + errors.join('\n '));
87
+ }
88
+
89
+ /* Find a package entry by exact name or import_as. */
90
+ function findPackage(registry, name) {
91
+ const pkgs = registry.packages || [];
92
+ for (const p of pkgs) {
93
+ if (p.name === name) return p;
94
+ }
95
+ for (const p of pkgs) {
96
+ if (p.import_as === name && p.repo) return p; // alias only for repo-distributed pkgs
97
+ }
98
+ return null;
99
+ }
100
+
101
+ /* Search entries by substring across name/description/keywords/category. */
102
+ function searchPackages(registry, query) {
103
+ const q = String(query || '').toLowerCase();
104
+ return (registry.packages || []).filter((p) => {
105
+ if (!q) return true;
106
+ const hay = [p.name, p.description, p.category, ...(p.keywords || [])]
107
+ .filter(Boolean).join(' ').toLowerCase();
108
+ return hay.includes(q);
109
+ });
110
+ }
111
+
112
+ module.exports = { registryUrl, fetchRegistry, findPackage, searchPackages, DEFAULT_REGISTRY_URL };