@mostra/runtime 0.14.0 → 0.15.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.
Files changed (61) hide show
  1. package/dist/bin.js +1 -1
  2. package/dist/child-protocol-CPXR6pMu.js +13 -0
  3. package/dist/child-protocol-CPXR6pMu.js.map +1 -0
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +1 -1
  6. package/dist/{instance-CFTw3g-c.js → instance-Bw1BxctF.js} +2581 -189
  7. package/dist/instance-Bw1BxctF.js.map +1 -0
  8. package/dist/plugins/child/host.d.ts +1 -0
  9. package/dist/plugins/child/host.js +165 -0
  10. package/dist/plugins/child/host.js.map +1 -0
  11. package/dist/reference/cli.md +147 -5
  12. package/dist/reference/diagnostics.json +234 -0
  13. package/dist/reference/errors/MOSTRA_LICENSE_ACCEPT_INVALID.md +23 -0
  14. package/dist/reference/errors/MOSTRA_LICENSE_MISMATCH.md +23 -0
  15. package/dist/reference/errors/MOSTRA_LICENSE_UNACCEPTED.md +23 -0
  16. package/dist/reference/errors/MOSTRA_LICENSE_UNDECLARED.md +23 -0
  17. package/dist/reference/errors/MOSTRA_PACK_ADDRESS_INVALID.md +23 -0
  18. package/dist/reference/errors/MOSTRA_PACK_CSS_UNIMPORTED.md +23 -0
  19. package/dist/reference/errors/MOSTRA_PACK_FETCH_FAILED.md +23 -0
  20. package/dist/reference/errors/MOSTRA_PACK_FILE_EXISTS.md +23 -0
  21. package/dist/reference/errors/MOSTRA_PACK_ITEM_INVALID.md +23 -0
  22. package/dist/reference/errors/MOSTRA_PACK_ITEM_NOT_FOUND.md +23 -0
  23. package/dist/reference/errors/MOSTRA_PACK_NOT_APPLIED.md +23 -0
  24. package/dist/reference/errors/MOSTRA_PACK_OFFLINE.md +23 -0
  25. package/dist/reference/errors/MOSTRA_PACK_TARGET_INVALID.md +23 -0
  26. package/dist/reference/errors/MOSTRA_PLUGIN_CONFLICT.md +23 -0
  27. package/dist/reference/errors/MOSTRA_PLUGIN_CONTRACT_UNSUPPORTED.md +23 -0
  28. package/dist/reference/errors/MOSTRA_PLUGIN_ENTRY_INVALID.md +23 -0
  29. package/dist/reference/errors/MOSTRA_PLUGIN_EXPORTER_UNKNOWN.md +23 -0
  30. package/dist/reference/errors/MOSTRA_PLUGIN_FAILED.md +23 -0
  31. package/dist/reference/errors/MOSTRA_PLUGIN_MANIFEST_INVALID.md +23 -0
  32. package/dist/reference/errors/MOSTRA_PLUGIN_MANIFEST_WARNING.md +23 -0
  33. package/dist/reference/errors/MOSTRA_PLUGIN_NOT_A_PLUGIN.md +23 -0
  34. package/dist/reference/errors/MOSTRA_PLUGIN_NOT_INSTALLED.md +23 -0
  35. package/dist/reference/errors/MOSTRA_PLUGIN_OPTIONS_INVALID.md +23 -0
  36. package/dist/reference/errors/MOSTRA_PLUGIN_PLATFORM_UNSUPPORTED.md +23 -0
  37. package/dist/reference/errors/MOSTRA_PLUGIN_SCOPE_INVALID.md +23 -0
  38. package/dist/reference/errors/MOSTRA_PLUGIN_SHADOWED.md +23 -0
  39. package/dist/skill/SKILL.md +4 -2
  40. package/dist/skill/references/mcp.md +2 -2
  41. package/dist/skill/references/plugins.md +51 -0
  42. package/package.json +10 -7
  43. package/src/deps/index.ts +407 -90
  44. package/src/deps/installer.ts +53 -10
  45. package/src/deps/lock.ts +74 -2
  46. package/src/home/settings.ts +3 -0
  47. package/src/instance/index.ts +57 -0
  48. package/src/packs/index.ts +7 -0
  49. package/src/packs/methods.ts +49 -0
  50. package/src/packs/packs.ts +706 -0
  51. package/src/packs/read.ts +759 -0
  52. package/src/platform/index.ts +1 -0
  53. package/src/platform/shell.ts +14 -0
  54. package/src/plugins/child/host.ts +231 -0
  55. package/src/plugins/child-protocol.ts +68 -0
  56. package/src/plugins/index.ts +7 -0
  57. package/src/plugins/location.ts +109 -0
  58. package/src/plugins/methods.ts +269 -0
  59. package/src/plugins/plugins.ts +1396 -0
  60. package/src/publish/publisher.ts +71 -3
  61. package/dist/instance-CFTw3g-c.js.map +0 -1
@@ -0,0 +1,759 @@
1
+ /**
2
+ * Reading source pack items (D30, EX-03): shadcn registry items, by any of shadcn's address forms,
3
+ * with their registry dependencies, read before anything is written. Every remote read is bounded
4
+ * (30 s, 8 MiB), `https:` (or `http:` to this machine), and offline fails at once.
5
+ *
6
+ * - a URL: the item's JSON;
7
+ * - a file: a local item, its files' `path`s read beside it when they carry no `content`;
8
+ * - GitHub (`owner/repo/item[#ref]`): the ref resolved to a commit, the repository's root
9
+ * `registry.json` (and its `include`s) at that commit, the item found by name, each file read
10
+ * at that commit; anonymously, or with `GH_TOKEN` or `GITHUB_TOKEN` for a repository that isn't
11
+ * public, sent only to GitHub's API;
12
+ * - `@namespace/item`: through the artifact's `components.json` `registries`, a URL template
13
+ * (`{name}`, `{style}`) or `{ url, params, headers }` with `${VAR}` read from the environment;
14
+ * - a bare name (in `registryDependencies`): shadcn's own registry (`REGISTRY_URL`, as shadcn
15
+ * reads it, else `https://ui.shadcn.com/r`), at the style `components.json` names
16
+ * (`new-york-v4` when it names none);
17
+ * - `plugin:<package>/<item>`: a pack an installed plugin carries (`contributes.packs`).
18
+ */
19
+ import { realpathSync } from "node:fs";
20
+ import { readFile } from "node:fs/promises";
21
+ import { dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
22
+ import { createDiagnostic, RpcError } from "@mostra/protocol";
23
+ import {
24
+ type PackAddress,
25
+ parsePackAddress,
26
+ type Registry,
27
+ type RegistryItem,
28
+ RegistryItemSchema,
29
+ RegistrySchema,
30
+ } from "@mostra/protocol/plugin";
31
+ import { EnvHttpProxyAgent, fetch as undiciFetch } from "undici";
32
+ import type { Environment } from "../log.ts";
33
+
34
+ /** How long one read may take. */
35
+ export const FETCH_TIMEOUT_MS: number = 30_000;
36
+
37
+ /** The most one read may return. */
38
+ export const FETCH_LIMIT_BYTES: number = 8 * 1024 * 1024;
39
+
40
+ /** The most items one `mostra add` may install, its registry dependencies included. */
41
+ const ITEM_LIMIT = 200;
42
+
43
+ /** An item as it was read, with where it came from and how its files' contents are read. */
44
+ export interface ReadItem {
45
+ readonly item: RegistryItem;
46
+ /** The address it was asked for by. */
47
+ readonly address: string;
48
+ /** Where it was read: a URL, or a file. */
49
+ readonly source: string;
50
+ /** The item whose `registryDependencies` named it. */
51
+ readonly requiredBy?: string;
52
+ /** Each file's content, in the item's order. */
53
+ readonly contents: readonly string[];
54
+ }
55
+
56
+ /** What reading needs of the artifact and the instance. */
57
+ export interface ReadContext {
58
+ /** The artifact's `components.json`, when it has one. */
59
+ readonly components?: ComponentsJson;
60
+ readonly env: Environment;
61
+ readonly offline: boolean;
62
+ /** An installed plugin's pack item file, for `plugin:` addresses. */
63
+ readonly pluginItem: (pkg: string, item: string) => Promise<string | undefined>;
64
+ /** Where GitHub's API and raw files are (tests point them at a local fake). */
65
+ readonly github?: { readonly api: string; readonly raw: string };
66
+ }
67
+
68
+ /** The parts of a `components.json` Mostra reads. */
69
+ export interface ComponentsJson {
70
+ readonly style?: string;
71
+ readonly tailwind?: { readonly css?: string };
72
+ readonly aliases?: Readonly<Record<string, string>>;
73
+ readonly registries?: Readonly<
74
+ Record<
75
+ string,
76
+ | string
77
+ | {
78
+ readonly url: string;
79
+ readonly params?: Readonly<Record<string, string>>;
80
+ readonly headers?: Readonly<Record<string, string>>;
81
+ }
82
+ >
83
+ >;
84
+ }
85
+
86
+ /** An address as reading follows it: a pack address, or a GitHub item's relative dependency. */
87
+ type Address =
88
+ | PackAddress
89
+ | {
90
+ readonly kind: "repo-file";
91
+ readonly owner: string;
92
+ readonly repo: string;
93
+ readonly sha: string;
94
+ readonly path: string;
95
+ };
96
+
97
+ /** Where an item was read, for its relative dependencies. */
98
+ interface From {
99
+ /** A local item's directory. */
100
+ readonly base?: string;
101
+ /** A GitHub item's repository and commit, and the directory of its registry entry. */
102
+ readonly github?: { readonly owner: string; readonly repo: string; readonly sha: string };
103
+ readonly githubBase?: string;
104
+ /** A URL item's URL. */
105
+ readonly url?: string;
106
+ }
107
+
108
+ /**
109
+ * `text` without the slashes it ends in. A loop, not `/\/+$/`, which backtracks polynomially on a
110
+ * string of many slashes (CodeQL js/polynomial-redos), and a registry's URL comes from the caller.
111
+ */
112
+ export function withoutTrailingSlashes(text: string): string {
113
+ let end = text.length;
114
+ while (end > 0 && text[end - 1] === "/") end -= 1;
115
+ return text.slice(0, end);
116
+ }
117
+
118
+ /** `inner` is `outer` or inside it (both real paths), by whole segments. */
119
+ function isInside(outer: string, inner: string): boolean {
120
+ const from = relative(outer, inner);
121
+ return from === "" || (from !== ".." && !from.startsWith(`..${sep}`) && !isAbsolute(from));
122
+ }
123
+
124
+ const SHADCN_REGISTRY = "https://ui.shadcn.com/r";
125
+ const DEFAULT_STYLE = "new-york-v4";
126
+
127
+ const fail = (code: Parameters<typeof createDiagnostic>[0], message: string): RpcError =>
128
+ new RpcError(createDiagnostic(code, { message }));
129
+
130
+ /** Whether a URL names this machine. */
131
+ function isLoopback(url: URL): boolean {
132
+ return (
133
+ url.hostname === "localhost" ||
134
+ url.hostname === "[::1]" ||
135
+ /^127(?:\.\d{1,3}){3}$/.test(url.hostname)
136
+ );
137
+ }
138
+
139
+ /** Whether a URL may be read: `https:`, or `http:` to this machine. */
140
+ function readable(url: URL): boolean {
141
+ if (url.protocol === "https:") return true;
142
+ return url.protocol === "http:" && isLoopback(url);
143
+ }
144
+
145
+ /**
146
+ * Whether a read of `first` may follow a redirect to `next`: `next` is readable, and a registry
147
+ * elsewhere never sends a read to this machine (WP-16 review, R01's addendum): only an address
148
+ * the caller named on this machine leads to another one here.
149
+ */
150
+ export function mayFollow(first: URL, next: URL): boolean {
151
+ return readable(next) && (!isLoopback(next) || isLoopback(first));
152
+ }
153
+
154
+ const agents = new Map<string, EnvHttpProxyAgent>();
155
+
156
+ /** The proxy agent for the environment's `HTTPS_PROXY`, `HTTP_PROXY` and `NO_PROXY`. */
157
+ function agentFor(env: Environment): EnvHttpProxyAgent {
158
+ const pick = (name: string): string | undefined => env[name.toLowerCase()] ?? env[name];
159
+ const httpsProxy = pick("HTTPS_PROXY");
160
+ const httpProxy = pick("HTTP_PROXY");
161
+ const noProxy = pick("NO_PROXY");
162
+ const key = JSON.stringify([httpsProxy, httpProxy, noProxy]);
163
+ let agent = agents.get(key);
164
+ if (agent === undefined) {
165
+ agent = new EnvHttpProxyAgent({
166
+ ...(httpsProxy !== undefined ? { httpsProxy } : {}),
167
+ ...(httpProxy !== undefined ? { httpProxy } : {}),
168
+ ...(noProxy !== undefined ? { noProxy } : {}),
169
+ });
170
+ agents.set(key, agent);
171
+ }
172
+ return agent;
173
+ }
174
+
175
+ /** Reads a URL's text, bounded; 404 is `undefined`, anything else that fails throws. */
176
+ export async function readUrl(
177
+ text: string,
178
+ context: ReadContext,
179
+ headers: Readonly<Record<string, string>> = {},
180
+ ): Promise<string | undefined> {
181
+ let url: URL;
182
+ try {
183
+ url = new URL(text);
184
+ } catch {
185
+ throw fail("MOSTRA_PACK_ADDRESS_INVALID", `"${text}" isn't a URL.`);
186
+ }
187
+ if (!readable(url)) {
188
+ throw fail(
189
+ "MOSTRA_PACK_ADDRESS_INVALID",
190
+ `${url.origin} isn't https: Mostra reads registry items over https, or http from this machine.`,
191
+ );
192
+ }
193
+ if (context.offline) {
194
+ throw fail("MOSTRA_PACK_OFFLINE", `Mostra is offline, so it can't read ${redactUrl(url)}.`);
195
+ }
196
+ // Redirects are followed here, at most five, each target checked before it is asked, and the
197
+ // caller's headers (a registry's token, GitHub's) kept only while the origin stays the same:
198
+ // a registry that redirects elsewhere never hands its credentials on.
199
+ const deadline = AbortSignal.timeout(FETCH_TIMEOUT_MS);
200
+ let response: Awaited<ReturnType<typeof undiciFetch>>;
201
+ let current = url;
202
+ for (let hop = 0; ; hop += 1) {
203
+ try {
204
+ response = await undiciFetch(current, {
205
+ headers: {
206
+ accept: "application/json, text/plain;q=0.9, */*;q=0.1",
207
+ ...(current.origin === url.origin ? headers : {}),
208
+ },
209
+ signal: deadline,
210
+ redirect: "manual",
211
+ dispatcher: agentFor(context.env),
212
+ });
213
+ } catch (error) {
214
+ throw fail(
215
+ "MOSTRA_PACK_FETCH_FAILED",
216
+ `Reading ${redactUrl(current)} failed: ${reasonOf(error)}.`,
217
+ );
218
+ }
219
+ const location = response.headers.get("location");
220
+ if (response.status < 300 || response.status >= 400 || location === null) break;
221
+ await response.body?.cancel();
222
+ const next = new URL(location, current);
223
+ if (!mayFollow(url, next)) {
224
+ throw fail(
225
+ "MOSTRA_PACK_FETCH_FAILED",
226
+ `${redactUrl(url)} redirected to ${isLoopback(next) ? "this machine" : "an address that isn't https"}, which Mostra doesn't follow.`,
227
+ );
228
+ }
229
+ if (hop >= 4) {
230
+ throw fail("MOSTRA_PACK_FETCH_FAILED", `${redactUrl(url)} redirected more than five times.`);
231
+ }
232
+ current = next;
233
+ }
234
+ if (response.status === 404) {
235
+ await response.body?.cancel();
236
+ return undefined;
237
+ }
238
+ if (!response.ok) {
239
+ await response.body?.cancel();
240
+ throw fail(
241
+ "MOSTRA_PACK_FETCH_FAILED",
242
+ `${redactUrl(url)} answered ${response.status} ${response.statusText}.`,
243
+ );
244
+ }
245
+ const declared = Number(response.headers.get("content-length") ?? "0");
246
+ if (declared > FETCH_LIMIT_BYTES) {
247
+ await response.body?.cancel();
248
+ throw fail("MOSTRA_PACK_FETCH_FAILED", `${redactUrl(url)} is larger than 8 MiB.`);
249
+ }
250
+ const chunks: Uint8Array[] = [];
251
+ let size = 0;
252
+ try {
253
+ for await (const chunk of response.body ?? []) {
254
+ size += chunk.byteLength;
255
+ if (size > FETCH_LIMIT_BYTES) {
256
+ throw fail("MOSTRA_PACK_FETCH_FAILED", `${redactUrl(url)} sent more than 8 MiB.`);
257
+ }
258
+ chunks.push(chunk);
259
+ }
260
+ } catch (error) {
261
+ if (error instanceof RpcError) throw error;
262
+ // The deadline, or the connection, ended the body part-way.
263
+ throw fail("MOSTRA_PACK_FETCH_FAILED", `Reading ${redactUrl(url)} failed: ${reasonOf(error)}.`);
264
+ }
265
+ return Buffer.concat(chunks).toString("utf8");
266
+ }
267
+
268
+ /** Why a request failed, in words. */
269
+ function reasonOf(error: unknown): string {
270
+ if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) {
271
+ return `it didn't answer within ${FETCH_TIMEOUT_MS / 1000} s`;
272
+ }
273
+ if (error instanceof Error) {
274
+ return error.cause instanceof Error ? error.cause.message : error.message;
275
+ }
276
+ return String(error);
277
+ }
278
+
279
+ /** A URL without its credentials or query, for messages. */
280
+ function redactUrl(url: URL): string {
281
+ return `${url.origin}${url.pathname}`;
282
+ }
283
+
284
+ /** Parses an item's JSON, refusing anything shadcn's schema (and Mostra's block) refuses. */
285
+ export function parseItem(text: string, where: string): RegistryItem {
286
+ let data: unknown;
287
+ try {
288
+ data = JSON.parse(text);
289
+ } catch {
290
+ throw fail("MOSTRA_PACK_ITEM_INVALID", `${where} isn't JSON.`);
291
+ }
292
+ const parsed = RegistryItemSchema.safeParse(data);
293
+ if (!parsed.success) {
294
+ const first = parsed.error.issues[0];
295
+ throw fail(
296
+ "MOSTRA_PACK_ITEM_INVALID",
297
+ `${where} isn't a registry item: ${first ? `${first.path.join(".") || "(top)"}: ${first.message}` : "its shape is wrong"}.`,
298
+ );
299
+ }
300
+ for (const [index, file] of (parsed.data.files ?? []).entries()) {
301
+ if (
302
+ (file.type === "registry:file" || file.type === "registry:page") &&
303
+ file.target === undefined
304
+ ) {
305
+ throw fail(
306
+ "MOSTRA_PACK_ITEM_INVALID",
307
+ `${where}: files[${index}] is a ${file.type}, which needs a target.`,
308
+ );
309
+ }
310
+ }
311
+ return parsed.data;
312
+ }
313
+
314
+ /** `${VAR}` in `text`, from the environment (shadcn's registry headers and params). */
315
+ function expand(text: string, env: Environment): string {
316
+ return text.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name: string) => env[name] ?? "");
317
+ }
318
+
319
+ /**
320
+ * Reads every item `specs` name, with their registry dependencies, depth first, each once (by
321
+ * address), dependencies before the items that need them.
322
+ */
323
+ export async function readItems(
324
+ specs: readonly string[],
325
+ context: ReadContext,
326
+ cwd: string,
327
+ ): Promise<ReadItem[]> {
328
+ const done = new Map<string, ReadItem>();
329
+ const order: ReadItem[] = [];
330
+ const visiting = new Set<string>();
331
+ const github = context.github ?? {
332
+ api: "https://api.github.com",
333
+ raw: "https://raw.githubusercontent.com",
334
+ };
335
+ const shas = new Map<string, string>();
336
+ const registries = new Map<string, Promise<{ item: unknown; base: string }[]>>();
337
+
338
+ const githubToken = (): string | undefined =>
339
+ context.env["GH_TOKEN"] || context.env["GITHUB_TOKEN"] || undefined;
340
+
341
+ /** A ref of a repository as its commit SHA (a full SHA as it is). */
342
+ const commitOf = async (
343
+ owner: string,
344
+ repo: string,
345
+ ref: string | undefined,
346
+ ): Promise<string> => {
347
+ if (ref !== undefined && /^[0-9a-f]{40}$/.test(ref)) return ref;
348
+ const key = `${owner}/${repo}#${ref ?? ""}`;
349
+ const known = shas.get(key);
350
+ if (known !== undefined) return known;
351
+ const token = githubToken();
352
+ const answer = await readUrl(
353
+ `${github.api}/repos/${owner}/${repo}/commits/${encodeURIComponent(ref ?? "HEAD")}`,
354
+ context,
355
+ {
356
+ accept: "application/vnd.github.sha",
357
+ ...(token !== undefined ? { authorization: `Bearer ${token}` } : {}),
358
+ },
359
+ ).catch((error: unknown) => {
360
+ // GitHub answers 422 for a ref that names no commit.
361
+ if (error instanceof RpcError && /answered 422/.test(error.diagnostic.message))
362
+ return undefined;
363
+ throw error;
364
+ });
365
+ const sha = answer?.trim();
366
+ if (sha === undefined || !/^[0-9a-f]{40}$/.test(sha)) {
367
+ throw fail(
368
+ "MOSTRA_PACK_ITEM_NOT_FOUND",
369
+ `GitHub has no ${ref === undefined ? "default branch" : `ref "${ref}"`} in ${owner}/${repo}${token === undefined ? " that it shows without a token (set GH_TOKEN for a repository that isn't public)" : ""}.`,
370
+ );
371
+ }
372
+ shas.set(key, sha);
373
+ return sha;
374
+ };
375
+
376
+ /** A file of a repository at a commit: raw anonymously, else the API with a token. */
377
+ const repoFile = async (
378
+ owner: string,
379
+ repo: string,
380
+ sha: string,
381
+ path: string,
382
+ ): Promise<string | undefined> => {
383
+ const clean = posix.normalize(path).replace(/^\/+/, "");
384
+ if (clean.startsWith("..")) {
385
+ throw fail("MOSTRA_PACK_ITEM_INVALID", `${path} leaves ${owner}/${repo}.`);
386
+ }
387
+ const encoded = clean.split("/").map(encodeURIComponent).join("/");
388
+ const anonymous = await readUrl(`${github.raw}/${owner}/${repo}/${sha}/${encoded}`, context);
389
+ if (anonymous !== undefined) return anonymous;
390
+ const token = githubToken();
391
+ if (token === undefined) return undefined;
392
+ return readUrl(`${github.api}/repos/${owner}/${repo}/contents/${encoded}?ref=${sha}`, context, {
393
+ accept: "application/vnd.github.raw+json",
394
+ authorization: `Bearer ${token}`,
395
+ });
396
+ };
397
+
398
+ /**
399
+ * A repository's registry, its `include`s read in, each item with the directory it came from;
400
+ * read once per commit for every item of the call.
401
+ */
402
+ const registryOf = (
403
+ owner: string,
404
+ repo: string,
405
+ sha: string,
406
+ ): Promise<{ item: unknown; base: string }[]> => {
407
+ const key = `${owner}/${repo}@${sha}`;
408
+ let known = registries.get(key);
409
+ if (known === undefined) {
410
+ known = readRegistry(owner, repo, sha);
411
+ registries.set(key, known);
412
+ }
413
+ return known;
414
+ };
415
+ const readRegistry = async (
416
+ owner: string,
417
+ repo: string,
418
+ sha: string,
419
+ ): Promise<{ item: unknown; base: string }[]> => {
420
+ const found: { item: unknown; base: string }[] = [];
421
+ const seen = new Set<string>();
422
+ const visit = async (path: string): Promise<void> => {
423
+ if (seen.has(path) || seen.size > 50) return;
424
+ seen.add(path);
425
+ const text = await repoFile(owner, repo, sha, path);
426
+ if (text === undefined) {
427
+ if (path === "registry.json") {
428
+ throw fail(
429
+ "MOSTRA_PACK_ITEM_NOT_FOUND",
430
+ `${owner}/${repo} has no registry.json at its root (commit ${sha.slice(0, 12)}).`,
431
+ );
432
+ }
433
+ throw fail("MOSTRA_PACK_ITEM_NOT_FOUND", `${owner}/${repo}'s ${path} isn't there.`);
434
+ }
435
+ let data: unknown;
436
+ try {
437
+ data = JSON.parse(text);
438
+ } catch {
439
+ throw fail("MOSTRA_PACK_ITEM_INVALID", `${owner}/${repo}'s ${path} isn't JSON.`);
440
+ }
441
+ const registry = RegistrySchema.safeParse(data);
442
+ if (!registry.success) {
443
+ throw fail("MOSTRA_PACK_ITEM_INVALID", `${owner}/${repo}'s ${path} isn't a registry.`);
444
+ }
445
+ const base = posix.dirname(path);
446
+ for (const raw of (data as { items?: unknown[] }).items ?? [])
447
+ found.push({ item: raw, base });
448
+ for (const include of (registry.data as Registry).include ?? []) {
449
+ await visit(posix.join(base, include));
450
+ }
451
+ };
452
+ await visit("registry.json");
453
+ return found;
454
+ };
455
+
456
+ /** Reads one address into an item and its files' contents. */
457
+ const read = async (
458
+ address: Address,
459
+ text: string,
460
+ from: From | undefined,
461
+ ): Promise<{ item: RegistryItem; source: string; contents: string[]; context?: From }> => {
462
+ if (address.kind === "file") {
463
+ const path = isAbsolute(address.path)
464
+ ? address.path
465
+ : from?.base !== undefined
466
+ ? resolve(from.base, address.path)
467
+ : resolve(cwd, address.path);
468
+ let body: string;
469
+ try {
470
+ body = await readFile(path, "utf8");
471
+ } catch {
472
+ throw fail("MOSTRA_PACK_ITEM_NOT_FOUND", `There's no item at ${path}.`);
473
+ }
474
+ const item = parseItem(body, path);
475
+ const contents: string[] = [];
476
+ // A local item's files are read from its own directory, never from elsewhere on the
477
+ // machine (WP-16 review R03 finding 10): their content is copied into a published source.
478
+ const dir = realpathSync(dirname(path));
479
+ for (const file of item.files ?? []) {
480
+ if (file.content !== undefined) contents.push(file.content);
481
+ else {
482
+ let real: string;
483
+ try {
484
+ real = realpathSync(resolve(dir, file.path));
485
+ } catch {
486
+ throw fail(
487
+ "MOSTRA_PACK_ITEM_INVALID",
488
+ `${path}'s file ${file.path} has no content and isn't beside the item.`,
489
+ );
490
+ }
491
+ if (!isInside(dir, real)) {
492
+ throw fail(
493
+ "MOSTRA_PACK_ITEM_INVALID",
494
+ `${path}'s file ${file.path} is outside the item's directory, which Mostra doesn't read from.`,
495
+ );
496
+ }
497
+ contents.push(await readFile(real, "utf8"));
498
+ }
499
+ }
500
+ return { item, source: path, contents, context: { base: dirname(path) } };
501
+ }
502
+ if (address.kind === "plugin") {
503
+ const file = await context.pluginItem(address.package, address.item);
504
+ if (file === undefined) {
505
+ throw fail(
506
+ "MOSTRA_PACK_ITEM_NOT_FOUND",
507
+ `No installed plugin ${address.package} carries a pack "${address.item}".`,
508
+ );
509
+ }
510
+ return read({ kind: "file", path: file }, file, undefined);
511
+ }
512
+ if (address.kind === "repo-file") {
513
+ // A GitHub item's relative dependency: an item file of the same repository, at its commit.
514
+ const body = await repoFile(address.owner, address.repo, address.sha, address.path);
515
+ const where = `${address.owner}/${address.repo}/${address.path}@${address.sha.slice(0, 12)}`;
516
+ if (body === undefined) {
517
+ throw fail("MOSTRA_PACK_ITEM_NOT_FOUND", `There's no item ${where}.`);
518
+ }
519
+ const item = parseItem(body, where);
520
+ const contents: string[] = [];
521
+ for (const file of item.files ?? []) {
522
+ if (file.content !== undefined) {
523
+ contents.push(file.content);
524
+ continue;
525
+ }
526
+ const fileBody = await repoFile(
527
+ address.owner,
528
+ address.repo,
529
+ address.sha,
530
+ posix.join(posix.dirname(address.path), file.path),
531
+ );
532
+ if (fileBody === undefined) {
533
+ throw fail("MOSTRA_PACK_ITEM_INVALID", `${where}: ${file.path} isn't in the repository.`);
534
+ }
535
+ contents.push(fileBody);
536
+ }
537
+ return {
538
+ item,
539
+ source: `https://github.com/${address.owner}/${address.repo}/blob/${address.sha}/${address.path}`,
540
+ contents,
541
+ context: {
542
+ github: { owner: address.owner, repo: address.repo, sha: address.sha },
543
+ githubBase: posix.dirname(address.path),
544
+ },
545
+ };
546
+ }
547
+ if (address.kind === "github") {
548
+ const sha = await commitOf(address.owner, address.repo, address.ref);
549
+ const entries = await registryOf(address.owner, address.repo, sha);
550
+ const entry = entries.find(
551
+ (candidate) =>
552
+ typeof candidate.item === "object" &&
553
+ candidate.item !== null &&
554
+ (candidate.item as { name?: unknown }).name === address.item,
555
+ );
556
+ if (entry === undefined) {
557
+ throw fail(
558
+ "MOSTRA_PACK_ITEM_NOT_FOUND",
559
+ `${address.owner}/${address.repo}'s registry has no item "${address.item}" (commit ${sha.slice(0, 12)}).`,
560
+ );
561
+ }
562
+ const where = `${address.owner}/${address.repo}/${address.item}@${sha.slice(0, 12)}`;
563
+ const item = parseItem(JSON.stringify(entry.item), where);
564
+ const contents: string[] = [];
565
+ for (const file of item.files ?? []) {
566
+ if (file.content !== undefined) {
567
+ contents.push(file.content);
568
+ continue;
569
+ }
570
+ const body = await repoFile(
571
+ address.owner,
572
+ address.repo,
573
+ sha,
574
+ posix.join(entry.base, file.path),
575
+ );
576
+ if (body === undefined) {
577
+ throw fail("MOSTRA_PACK_ITEM_INVALID", `${where}: ${file.path} isn't in the repository.`);
578
+ }
579
+ contents.push(body);
580
+ }
581
+ return {
582
+ item,
583
+ source: `https://github.com/${address.owner}/${address.repo}/tree/${sha}`,
584
+ contents,
585
+ context: {
586
+ github: { owner: address.owner, repo: address.repo, sha },
587
+ githubBase: entry.base,
588
+ },
589
+ };
590
+ }
591
+ // url, namespace and name read one item's JSON from a URL.
592
+ let url: string;
593
+ let headers: Record<string, string> = {};
594
+ if (address.kind === "url") url = address.url;
595
+ else if (address.kind === "namespace") {
596
+ const registry = context.components?.registries?.[address.namespace];
597
+ if (registry === undefined) {
598
+ throw fail(
599
+ "MOSTRA_PACK_ADDRESS_INVALID",
600
+ `The artifact's components.json registers no ${address.namespace} registry; add it to "registries" ("${address.namespace}": "https://…/{name}.json").`,
601
+ );
602
+ }
603
+ const template = typeof registry === "string" ? registry : registry.url;
604
+ // A variable names a credential or a parameter, never where the request goes: one in the
605
+ // URL's scheme or host could send the others anywhere (WP-16 review, R01's addendum).
606
+ const origin = /^[a-z][a-z0-9+.-]*:\/\/[^/?#]*/i.exec(template)?.[0] ?? template;
607
+ if (origin.includes("${")) {
608
+ throw fail(
609
+ "MOSTRA_PACK_ADDRESS_INVALID",
610
+ `The artifact's components.json names the ${address.namespace} registry's host through a variable (${origin}); write the host itself, and keep variables to its params and headers.`,
611
+ );
612
+ }
613
+ const style = context.components?.style ?? DEFAULT_STYLE;
614
+ const target = new URL(
615
+ expand(template, context.env)
616
+ .replaceAll("{name}", address.item)
617
+ .replaceAll("{style}", style),
618
+ );
619
+ if (typeof registry !== "string") {
620
+ for (const [name, value] of Object.entries(registry.params ?? {})) {
621
+ target.searchParams.set(name, expand(value, context.env));
622
+ }
623
+ headers = Object.fromEntries(
624
+ Object.entries(registry.headers ?? {}).map(([name, value]) => [
625
+ name,
626
+ expand(value, context.env),
627
+ ]),
628
+ );
629
+ }
630
+ url = target.href;
631
+ } else {
632
+ const style = context.components?.style ?? DEFAULT_STYLE;
633
+ const base = withoutTrailingSlashes(context.env["REGISTRY_URL"] || SHADCN_REGISTRY);
634
+ url = `${base}/styles/${encodeURIComponent(style)}/${encodeURIComponent(address.name)}.json`;
635
+ }
636
+ const body = await readUrl(url, context, headers);
637
+ if (body === undefined) {
638
+ throw fail(
639
+ "MOSTRA_PACK_ITEM_NOT_FOUND",
640
+ `There's no item ${text} (${new URL(url).origin}${new URL(url).pathname} answered 404).`,
641
+ );
642
+ }
643
+ const item = parseItem(body, text);
644
+ const contents: string[] = [];
645
+ for (const file of item.files ?? []) {
646
+ if (file.content === undefined) {
647
+ throw fail(
648
+ "MOSTRA_PACK_ITEM_INVALID",
649
+ `${text}: ${file.path} has no content; an item read from a URL carries its files' content.`,
650
+ );
651
+ }
652
+ contents.push(file.content);
653
+ }
654
+ // Where it was read, without the query a registry's params (a token) may fill.
655
+ return { item, source: redactUrl(new URL(url)), contents, context: { url } };
656
+ };
657
+
658
+ /**
659
+ * A registry dependency's address, read as shadcn reads it. A relative item file is relative to
660
+ * the item that names it: beside a local item, in a GitHub item's repository at its commit,
661
+ * under a URL item's URL. A remote item never names a file on this machine.
662
+ */
663
+ const dependencyAddress = (text: string, from: From | undefined): Address => {
664
+ const parsed = parsePackAddress(text);
665
+ if (parsed !== undefined) {
666
+ if (parsed.kind === "file" && (from?.github !== undefined || from?.url !== undefined)) {
667
+ if (isAbsolute(parsed.path)) {
668
+ throw fail(
669
+ "MOSTRA_PACK_ADDRESS_INVALID",
670
+ `A remote item names "${text}", a file on this machine, which Mostra doesn't read for it.`,
671
+ );
672
+ }
673
+ if (from.github !== undefined) {
674
+ const path = posix.normalize(posix.join(from.githubBase ?? ".", parsed.path));
675
+ if (path.startsWith("..")) {
676
+ throw fail("MOSTRA_PACK_ADDRESS_INVALID", `"${text}" leaves the item's repository.`);
677
+ }
678
+ return { kind: "repo-file", ...from.github, path };
679
+ }
680
+ return { kind: "url", url: new URL(parsed.path, from.url).href };
681
+ }
682
+ // A dependency of a local item names a sibling item file relative to it.
683
+ if (parsed.kind === "file" && from?.base !== undefined && !isAbsolute(parsed.path)) {
684
+ return { kind: "file", path: resolve(from.base, parsed.path) };
685
+ }
686
+ return parsed;
687
+ }
688
+ if (/^[a-z0-9][a-z0-9._-]*$/i.test(text)) return { kind: "name", name: text };
689
+ throw fail("MOSTRA_PACK_ADDRESS_INVALID", `"${text}" isn't a registry item address.`);
690
+ };
691
+
692
+ const visit = async (
693
+ text: string,
694
+ address: Address,
695
+ requiredBy: string | undefined,
696
+ from: From | undefined,
697
+ ): Promise<void> => {
698
+ const key =
699
+ address.kind === "file"
700
+ ? `file:${address.path}`
701
+ : address.kind === "repo-file"
702
+ ? `repo-file:${address.owner}/${address.repo}@${address.sha}/${address.path}`
703
+ : address.kind === "url"
704
+ ? `url:${address.url}`
705
+ : `${address.kind}:${text}`;
706
+ if (done.has(key) || visiting.has(key)) return;
707
+ if (done.size >= ITEM_LIMIT) {
708
+ throw fail(
709
+ "MOSTRA_PACK_ITEM_INVALID",
710
+ `More than ${ITEM_LIMIT} items: their registry dependencies don't end.`,
711
+ );
712
+ }
713
+ visiting.add(key);
714
+ const read_ = await read(address, text, from);
715
+ for (const dependency of read_.item.registryDependencies ?? []) {
716
+ await visit(
717
+ dependency,
718
+ dependencyAddress(dependency, read_.context),
719
+ read_.item.name,
720
+ read_.context,
721
+ );
722
+ }
723
+ visiting.delete(key);
724
+ const entry: ReadItem = {
725
+ item: read_.item,
726
+ address: text,
727
+ source: read_.source,
728
+ ...(requiredBy !== undefined ? { requiredBy } : {}),
729
+ contents: read_.contents,
730
+ };
731
+ done.set(key, entry);
732
+ order.push(entry);
733
+ };
734
+
735
+ for (const spec of specs) {
736
+ const address = parsePackAddress(spec);
737
+ if (address === undefined) {
738
+ throw fail("MOSTRA_PACK_ADDRESS_INVALID", `"${spec}" isn't a registry item address.`);
739
+ }
740
+ await visit(spec, address, undefined, undefined);
741
+ }
742
+ return order;
743
+ }
744
+
745
+ /** The artifact's `components.json`, when it has one Mostra can read. */
746
+ export async function readComponentsJson(root: string): Promise<ComponentsJson | undefined> {
747
+ let text: string;
748
+ try {
749
+ text = await readFile(join(root, "components.json"), "utf8");
750
+ } catch {
751
+ return undefined;
752
+ }
753
+ try {
754
+ const data = JSON.parse(text) as ComponentsJson;
755
+ return typeof data === "object" && data !== null ? data : undefined;
756
+ } catch {
757
+ throw fail("MOSTRA_PACK_ITEM_INVALID", `${join(root, "components.json")} isn't JSON.`);
758
+ }
759
+ }