@verentis/cli 0.2.26 → 0.2.27

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/README.md CHANGED
@@ -415,6 +415,52 @@ The hero does not count toward that gallery limit, but it does count toward the
415
415
  unique presentation images. README and changelog Markdown files are each limited to 1 MiB.
416
416
  `verentis validate` checks these paths, formats and limits before publishing.
417
417
 
418
+ ### Manifest icons
419
+
420
+ Icon fields (`metadata.icon`, `spec.entry-points[].icon`, `spec.entry-points[].mime-types[].icon`,
421
+ `spec.mime-types[].icon`, `spec.file-types[].icon`) accept:
422
+
423
+ - a relative SVG file path, resolved against the manifest directory (it must end in `.svg` and may not
424
+ escape the package directory): `icon: ./icons/app.svg`
425
+ - a reference into an optional top-level `icons:` map: `icon: "#doc"`
426
+ - inline SVG markup: `icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">…</svg>'`
427
+
428
+ ```yaml
429
+ icons:
430
+ doc: ./icons/document.svg # file path or inline <svg> markup
431
+ spec:
432
+ file-types:
433
+ - pattern: "*.docx"
434
+ icon: "#doc"
435
+ ```
436
+
437
+ SVGs must be UTF-8 with an `<svg>` root (an `<?xml ?>` declaration and comments may precede it), end
438
+ with `</svg>`, stay within 32 KiB each and 256 KiB of distinct markup per manifest, and must not contain
439
+ numeric character references (`&#`), `<!DOCTYPE>`/`<!ENTITY>`, `script`/`foreignObject`/`iframe`/
440
+ `object`/`embed`/`audio`/`video` elements, `on*=` handlers, `javascript:`/`vbscript:`/`data:text/html`
441
+ URLs, or external `href`/`xlink:href`/`url(...)` references. Declare a `viewBox` and prefer
442
+ `currentColor` without fixed width/height — icons render at 16–40px. When `metadata.icon` is absent
443
+ and `marketplace.logo` is a valid SVG, the logo is used as the app icon.
444
+
445
+ `verentis validate` and `verentis pack` report problems with the field path, for example
446
+ `spec.file-types[2].icon: ./icons/x.svg not found`. Iconify identifiers (`lucide:file-text`, `shapes`)
447
+ are legacy and only produce a warning; convert them with:
448
+
449
+ ```bash
450
+ verentis icons migrate [dir] # *.app.yaml, *.engine.yaml and manifest.yaml in dir
451
+ verentis icons migrate --file my.app.yaml --dry-run
452
+ verentis icons migrate --iconify-api https://icons.internal.example # self-hosted Iconify API
453
+ ```
454
+
455
+ `icons migrate` resolves each id (bare names map to `lucide:<name>`) from a locally installed
456
+ `@iconify-json/<prefix>` package when present, otherwise from the Iconify API
457
+ (`https://api.iconify.design`, override with `--iconify-api <url>` or `VERENTIS_ICONIFY_API`), and writes
458
+ it as a standalone SVG to `icons/<prefix>-<name>.svg` next to the manifest and rewrites the field to that path, preserving
459
+ the rest of the YAML. Ids that do not exist (e.g. `lucide:checklist`) are reported as errors, left
460
+ unchanged and make the command exit non-zero — replace them with your own SVG. Network failures
461
+ are reported per field in the same way. `verentis init` scaffolds `icons/app.svg` and references it
462
+ from `metadata.icon`.
463
+
418
464
  ## The `.vpkg` format
419
465
 
420
466
  A gzip tarball: `manifest.yaml` + `files/**` payload + optional plaintext `catalog/**` presentation
@@ -452,6 +498,10 @@ Packing behaviour:
452
498
  overrides the packed manifest version, and `--bump-version` increments the authored patch version.
453
499
  `publish` without a file selects the highest-version `.vpkg` in the current directory. `validate`
454
500
  accepts the same overlay selectors.
501
+ - Icons are inlined into the packed `manifest.yaml`: the top-level `icons:` map holds the validated SVG
502
+ markup keyed by the first 12 hex characters of its sha256, and every icon field becomes `"#<key>"`.
503
+ Legacy Iconify ids are left as-is. Source files are not modified; digests and signatures cover the
504
+ rewritten manifest.
455
505
  - Marketplace files are selected independently of `packaging.files` and written to deterministic,
456
506
  content-addressed `catalog/assets/**` and `catalog/docs/**` entries described by
457
507
  `catalog/index.json` (schema version 1).
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command, Option } from 'commander';
3
- import { mkdir, stat, writeFile, readFile, readdir, glob, realpath, mkdtemp, rm } from 'fs/promises';
3
+ import { mkdir, stat, writeFile, readFile, readdir, glob, realpath, mkdtemp, rm, access } from 'fs/promises';
4
4
  import { tmpdir, homedir } from 'os';
5
5
  import { resolve, basename, dirname, posix, join, isAbsolute, relative, sep, extname } from 'path';
6
6
  import { execFile, spawn, spawnSync } from 'child_process';
@@ -8,10 +8,11 @@ import { promisify, TextDecoder as TextDecoder$1 } from 'util';
8
8
  import * as tar from 'tar';
9
9
  import { extract } from 'tar';
10
10
  import { generateKeyPairSync, createHash, randomUUID, randomBytes, createCipheriv, createPublicKey, verify, diffieHellman, hkdfSync, sign, createPrivateKey } from 'crypto';
11
- import { parse, stringify, parseDocument } from 'yaml';
11
+ import { parse, parseDocument, isScalar, stringify, Document, YAMLMap, Scalar } from 'yaml';
12
12
  import { createWriteStream, readFileSync, createReadStream } from 'fs';
13
13
  import { Readable } from 'stream';
14
14
  import { pipeline } from 'stream/promises';
15
+ import { createRequire } from 'module';
15
16
  import { fileURLToPath } from 'url';
16
17
 
17
18
  function insecureFetchOptions(insecure) {
@@ -139,7 +140,7 @@ async function refreshIdentityToken(apiUrl, refreshToken, insecure) {
139
140
  `Session could not be renewed${payload?.error ? ` (${payload.error})` : ` (${res.status})`}. Run \`verentis login\` again.`
140
141
  );
141
142
  }
142
- var sleep = (ms) => new Promise((resolve13) => setTimeout(resolve13, ms));
143
+ var sleep = (ms) => new Promise((resolve15) => setTimeout(resolve15, ms));
143
144
 
144
145
  // src/auth/githubActions.ts
145
146
  var JWT_BEARER_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer";
@@ -2014,7 +2015,7 @@ async function followExecution(api, workspaceId, executionId, json) {
2014
2015
  if (exec.status !== "Completed") process.exitCode = 1;
2015
2016
  return;
2016
2017
  }
2017
- await new Promise((resolve13) => setTimeout(resolve13, 1e3));
2018
+ await new Promise((resolve15) => setTimeout(resolve15, 1e3));
2018
2019
  }
2019
2020
  console.error("Timed out waiting for a terminal status \u2014 check `verentis exec get`.");
2020
2021
  process.exitCode = 1;
@@ -2155,6 +2156,427 @@ async function uploadDirectory(api, workspaceId, localDir, remoteBase, branch) {
2155
2156
  }
2156
2157
  return count;
2157
2158
  }
2159
+ var MAX_ICON_BYTES = 32 * 1024;
2160
+ var MAX_TOTAL_ICON_BYTES = 256 * 1024;
2161
+ var LEGACY_ICON_PATTERN = /^[a-z0-9-]+(:[a-z0-9-]+)?$/;
2162
+ var SVG_START = /^(?:<\?xml[\s\S]*?\?>\s*)?(?:<!--[\s\S]*?-->\s*)*<svg\b/i;
2163
+ var SVG_END_CLOSING = /<\/svg>\s*$/i;
2164
+ var SVG_END_SELF_CLOSING = /<svg\b[\s\S]*\/>\s*$/i;
2165
+ var SVG_REJECTIONS = [
2166
+ [/&#/i, "numeric character references (&#) are not allowed"],
2167
+ [/<!DOCTYPE|<!ENTITY/i, "<!DOCTYPE>/<!ENTITY> declarations are not allowed"],
2168
+ [/<(?:script|foreignObject|iframe|object|embed|audio|video)\b/i, "script, foreignObject, iframe, object, embed, audio and video elements are not allowed"],
2169
+ [/\son[a-z]+\s*=/i, "event handler (on*=) attributes are not allowed"],
2170
+ [/(?:javascript|vbscript)\s*:/i, "javascript:/vbscript: URLs are not allowed"],
2171
+ [/data\s*:\s*text\/html/i, "data:text/html URLs are not allowed"],
2172
+ [/(?:xlink:href|href)\s*=\s*["']?\s*(?:https?:|ftp:|\/\/)/i, "external href/xlink:href references are not allowed"],
2173
+ [/url\(\s*["']?\s*(?:https?:|\/\/)/i, "external url(...) references are not allowed"]
2174
+ ];
2175
+ function validateSvgIcon(text) {
2176
+ if (Buffer.byteLength(text, "utf8") > MAX_ICON_BYTES) return `SVG exceeds the ${MAX_ICON_BYTES / 1024} KiB icon limit`;
2177
+ const markup = canonicalizeSvg(text);
2178
+ if (!SVG_START.test(markup)) return "SVG must have an <svg> root element (only an <?xml ?> declaration and comments may precede it)";
2179
+ if (!SVG_END_CLOSING.test(markup) && !SVG_END_SELF_CLOSING.test(markup)) return "SVG must end with </svg>";
2180
+ for (const [pattern, reason] of SVG_REJECTIONS) {
2181
+ if (pattern.test(markup)) return reason;
2182
+ }
2183
+ return null;
2184
+ }
2185
+ function canonicalizeSvg(text) {
2186
+ return text.replace(/^\uFEFF+/, "").trim();
2187
+ }
2188
+ function decodeUtf8(bytes) {
2189
+ try {
2190
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
2191
+ } catch {
2192
+ return null;
2193
+ }
2194
+ }
2195
+ function classifyIconValue(value) {
2196
+ const trimmed = value.trim();
2197
+ if (trimmed.startsWith("<")) return "inline";
2198
+ if (trimmed.startsWith("#")) return "ref";
2199
+ if (/\.svg$/i.test(trimmed)) return "path";
2200
+ if (LEGACY_ICON_PATTERN.test(trimmed)) return "legacy";
2201
+ return "invalid";
2202
+ }
2203
+ function collectIconFields(manifest) {
2204
+ const fields = [];
2205
+ if (!isRecord(manifest)) return fields;
2206
+ const add = (path, value) => {
2207
+ if (value !== void 0) fields.push({ path, label: formatPath(path), value });
2208
+ };
2209
+ const bindings = (container, path) => {
2210
+ if (!Array.isArray(container)) return;
2211
+ container.forEach((item, index) => {
2212
+ if (isRecord(item)) add([...path, index, "icon"], item.icon);
2213
+ });
2214
+ };
2215
+ if (isRecord(manifest.metadata)) add(["metadata", "icon"], manifest.metadata.icon);
2216
+ const spec = manifest.spec;
2217
+ if (!isRecord(spec)) return fields;
2218
+ if (Array.isArray(spec["entry-points"])) {
2219
+ spec["entry-points"].forEach((entryPoint, index) => {
2220
+ if (!isRecord(entryPoint)) return;
2221
+ add(["spec", "entry-points", index, "icon"], entryPoint.icon);
2222
+ bindings(entryPoint["mime-types"], ["spec", "entry-points", index, "mime-types"]);
2223
+ });
2224
+ }
2225
+ bindings(spec["mime-types"], ["spec", "mime-types"]);
2226
+ bindings(spec["file-types"], ["spec", "file-types"]);
2227
+ return fields;
2228
+ }
2229
+ async function resolveManifestIcons(manifest, manifestDir) {
2230
+ const errors = [];
2231
+ const warnings = [];
2232
+ const fields = [];
2233
+ const root = resolve(manifestDir);
2234
+ const distinct = /* @__PURE__ */ new Set();
2235
+ const resolveSvg = async (label, value, allowLegacy) => {
2236
+ const kind = classifyIconValue(value);
2237
+ if (kind === "inline") return checkMarkup(label, value.trim(), "inline SVG");
2238
+ if (kind === "path") {
2239
+ const loaded = await readIconFile(root, value.trim());
2240
+ if ("error" in loaded) {
2241
+ errors.push(`${label}: ${loaded.error}`);
2242
+ return void 0;
2243
+ }
2244
+ return checkMarkup(label, loaded.text, value.trim());
2245
+ }
2246
+ if (kind === "legacy" && allowLegacy) return void 0;
2247
+ errors.push(allowLegacy ? `${label}: '${value}' is not a relative .svg path, "#key" reference, inline <svg> markup or Iconify id` : `${label}: '${value}' must be a relative .svg path or inline <svg> markup`);
2248
+ return void 0;
2249
+ };
2250
+ const checkMarkup = (label, text, source) => {
2251
+ const problem = validateSvgIcon(text);
2252
+ if (problem) {
2253
+ errors.push(`${label}: ${source}: ${problem}`);
2254
+ return void 0;
2255
+ }
2256
+ const markup = canonicalizeSvg(text);
2257
+ distinct.add(markup);
2258
+ return markup;
2259
+ };
2260
+ const map = /* @__PURE__ */ new Map();
2261
+ const iconsSection = isRecord(manifest) ? manifest.icons : void 0;
2262
+ if (iconsSection !== void 0) {
2263
+ if (!isRecord(iconsSection)) {
2264
+ errors.push("icons must be a map of key -> SVG file path or inline <svg> markup");
2265
+ } else {
2266
+ for (const [key, value] of Object.entries(iconsSection)) {
2267
+ const label = `icons.${key}`;
2268
+ if (typeof value !== "string" || value.trim().length === 0) {
2269
+ errors.push(`${label} must be a non-empty string`);
2270
+ map.set(key, void 0);
2271
+ continue;
2272
+ }
2273
+ map.set(key, await resolveSvg(label, value, false));
2274
+ }
2275
+ }
2276
+ }
2277
+ for (const field of collectIconFields(manifest)) {
2278
+ if (typeof field.value !== "string" || field.value.trim().length === 0) {
2279
+ errors.push(`${field.label} must be a non-empty string`);
2280
+ continue;
2281
+ }
2282
+ const value = field.value;
2283
+ const kind = classifyIconValue(value);
2284
+ if (kind === "legacy") {
2285
+ warnings.push(`${field.label}: '${value}' is a legacy Iconify icon; run \`verentis icons migrate\` to convert it to SVG`);
2286
+ fields.push({ ...field, value, legacy: true });
2287
+ continue;
2288
+ }
2289
+ if (kind === "ref") {
2290
+ const key = value.trim().slice(1);
2291
+ if (!map.has(key)) {
2292
+ errors.push(`${field.label}: ${value.trim()} does not match a key in the top-level icons map`);
2293
+ continue;
2294
+ }
2295
+ const markup2 = map.get(key);
2296
+ if (markup2 !== void 0) fields.push({ ...field, value, markup: markup2, legacy: false });
2297
+ continue;
2298
+ }
2299
+ const markup = await resolveSvg(field.label, value, true);
2300
+ if (markup !== void 0) fields.push({ ...field, value, markup, legacy: false });
2301
+ }
2302
+ let logoIcon;
2303
+ const metadata = isRecord(manifest) && isRecord(manifest.metadata) ? manifest.metadata : void 0;
2304
+ const marketplace2 = isRecord(manifest) && isRecord(manifest.marketplace) ? manifest.marketplace : void 0;
2305
+ if (metadata && metadata.icon === void 0 && typeof marketplace2?.logo === "string" && /\.svg$/i.test(marketplace2.logo.trim())) {
2306
+ const loaded = await readIconFile(root, marketplace2.logo.trim());
2307
+ const problem = "error" in loaded ? loaded.error : validateSvgIcon(loaded.text);
2308
+ if (problem || "error" in loaded) {
2309
+ warnings.push(`marketplace.logo cannot be used as the app icon (metadata.icon fallback): ${problem}`);
2310
+ } else {
2311
+ logoIcon = canonicalizeSvg(loaded.text);
2312
+ distinct.add(logoIcon);
2313
+ }
2314
+ }
2315
+ const total = [...distinct].reduce((sum, markup) => sum + Buffer.byteLength(markup, "utf8"), 0);
2316
+ if (total > MAX_TOTAL_ICON_BYTES) {
2317
+ errors.push(`icons: total distinct SVG markup is ${(total / 1024).toFixed(1)} KiB, exceeding the ${MAX_TOTAL_ICON_BYTES / 1024} KiB per-manifest limit`);
2318
+ }
2319
+ const needsInlining = logoIcon !== void 0 || iconsSection !== void 0 || fields.some((field) => !field.legacy);
2320
+ return { errors, warnings, fields, logoIcon, needsInlining };
2321
+ }
2322
+ async function readIconFile(root, source) {
2323
+ if (isAbsolute(source) || /^[a-z][a-z0-9+.-]*:/i.test(source) || source.includes("\\")) {
2324
+ return { error: `${source} must be a path relative to the manifest directory` };
2325
+ }
2326
+ const candidate = resolve(root, source);
2327
+ if (escapes(root, candidate)) return { error: `${source} escapes the package directory` };
2328
+ let actual;
2329
+ let realRoot;
2330
+ try {
2331
+ actual = await realpath(candidate);
2332
+ realRoot = await realpath(root);
2333
+ } catch {
2334
+ return { error: `${source} not found` };
2335
+ }
2336
+ if (escapes(realRoot, actual)) return { error: `${source} escapes the package directory` };
2337
+ let bytes;
2338
+ try {
2339
+ bytes = await readFile(actual);
2340
+ } catch {
2341
+ return { error: `${source} could not be read (is it a file?)` };
2342
+ }
2343
+ if (bytes.length > MAX_ICON_BYTES) return { error: `${source}: SVG exceeds the ${MAX_ICON_BYTES / 1024} KiB icon limit` };
2344
+ const text = decodeUtf8(bytes);
2345
+ if (text === null) return { error: `${source} is not valid UTF-8` };
2346
+ return { text };
2347
+ }
2348
+ function escapes(root, candidate) {
2349
+ const fromRoot = relative(root, candidate);
2350
+ return fromRoot === "" || fromRoot === ".." || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot);
2351
+ }
2352
+ function iconKey(markup) {
2353
+ return createHash("sha256").update(markup, "utf8").digest("hex").slice(0, 12);
2354
+ }
2355
+ function inlineIconsIntoDocument(document, resolution) {
2356
+ const icons = /* @__PURE__ */ new Map();
2357
+ const quoted = (text) => Object.assign(new Scalar(text), { type: Scalar.QUOTE_DOUBLE });
2358
+ for (const field of resolution.fields) {
2359
+ if (field.markup === void 0) continue;
2360
+ const key = iconKey(field.markup);
2361
+ icons.set(key, field.markup);
2362
+ document.setIn(field.path, quoted(`#${key}`));
2363
+ }
2364
+ if (resolution.logoIcon !== void 0) {
2365
+ const key = iconKey(resolution.logoIcon);
2366
+ icons.set(key, resolution.logoIcon);
2367
+ document.setIn(["metadata", "icon"], quoted(`#${key}`));
2368
+ }
2369
+ if (icons.size === 0) {
2370
+ if (document.has("icons")) document.delete("icons");
2371
+ return;
2372
+ }
2373
+ const node = new YAMLMap();
2374
+ for (const [key, markup] of [...icons.entries()].sort(([a], [b]) => a.localeCompare(b))) {
2375
+ node.set(key, Object.assign(new Scalar(markup), { type: Scalar.BLOCK_LITERAL }));
2376
+ }
2377
+ document.set("icons", node);
2378
+ }
2379
+ function formatPath(path) {
2380
+ return path.reduce((text, segment) => typeof segment === "number" ? `${text}[${segment}]` : text ? `${text}.${segment}` : segment, "");
2381
+ }
2382
+ function isRecord(value) {
2383
+ return !!value && typeof value === "object" && !Array.isArray(value);
2384
+ }
2385
+
2386
+ // src/vpkg/iconMigration.ts
2387
+ var DEFAULT_ICONIFY_API = "https://api.iconify.design";
2388
+ function createIconSetLoader(options = {}) {
2389
+ const apiBase = (options.apiBase ?? process.env.VERENTIS_ICONIFY_API ?? DEFAULT_ICONIFY_API).replace(/\/+$/, "");
2390
+ const fetchImpl = options.fetch ?? globalThis.fetch;
2391
+ const loadLocal = options.loadLocal ?? loadLocalCollection;
2392
+ const local = /* @__PURE__ */ new Map();
2393
+ return async (prefix, name) => {
2394
+ let collection = local.get(prefix);
2395
+ if (!collection) {
2396
+ collection = loadLocal(prefix);
2397
+ local.set(prefix, collection);
2398
+ }
2399
+ const installed = await collection;
2400
+ if (installed) return installed;
2401
+ const url = `${apiBase}/${encodeURIComponent(prefix)}.json?icons=${encodeURIComponent(name)}`;
2402
+ let response;
2403
+ try {
2404
+ response = await fetchImpl(url);
2405
+ } catch (error) {
2406
+ return { error: `could not reach the Iconify API (${url}): ${error instanceof Error ? error.message : String(error)}` };
2407
+ }
2408
+ if (response.status === 404) return { error: `unknown Iconify icon set '${prefix}'` };
2409
+ if (!response.ok) return { error: `Iconify API request failed (${url}): HTTP ${response.status}` };
2410
+ let body;
2411
+ try {
2412
+ body = await response.json();
2413
+ } catch {
2414
+ return { error: `Iconify API returned an invalid response (${url})` };
2415
+ }
2416
+ if (body === 404 || !body || typeof body !== "object" || !("icons" in body)) {
2417
+ return { error: `unknown Iconify icon set '${prefix}'` };
2418
+ }
2419
+ return body;
2420
+ };
2421
+ }
2422
+ async function loadLocalCollection(prefix) {
2423
+ const specifier = `@iconify-json/${prefix}/icons.json`;
2424
+ for (const base of [join(process.cwd(), "noop.js"), import.meta.url]) {
2425
+ try {
2426
+ const path = createRequire(base).resolve(specifier);
2427
+ return JSON.parse(await readFile(path, "utf8"));
2428
+ } catch {
2429
+ }
2430
+ }
2431
+ return null;
2432
+ }
2433
+ async function findIconManifests(dir) {
2434
+ const entries = await readdir(dir);
2435
+ const matches = entries.filter((name) => /\.(app|engine)\.ya?ml$/.test(name) || name === "manifest.yaml").sort().map((name) => join(dir, name));
2436
+ const files2 = [];
2437
+ for (const path of matches) {
2438
+ if ((await stat(path)).isFile()) files2.push(path);
2439
+ }
2440
+ return files2;
2441
+ }
2442
+ async function migrateManifestIcons(manifestPath, options = {}) {
2443
+ const loader = options.loader ?? createIconSetLoader();
2444
+ const text = await readFile(manifestPath, "utf8");
2445
+ const document = parseDocument(text);
2446
+ if (document.errors.length > 0) {
2447
+ throw new Error(`Failed to parse ${manifestPath}: ${document.errors.map((error) => error.message).join(" ")}`);
2448
+ }
2449
+ const manifest = document.toJS();
2450
+ const targets = [];
2451
+ for (const field of collectIconFields(manifest)) {
2452
+ if (typeof field.value === "string" && classifyIconValue(field.value) === "legacy") {
2453
+ targets.push({ path: field.path, label: field.label, value: field.value });
2454
+ }
2455
+ }
2456
+ const icons = manifest && typeof manifest === "object" ? manifest.icons : void 0;
2457
+ if (icons && typeof icons === "object" && !Array.isArray(icons)) {
2458
+ for (const [key, value] of Object.entries(icons)) {
2459
+ if (typeof value === "string" && classifyIconValue(value) === "legacy") {
2460
+ targets.push({ path: ["icons", key], label: formatPath(["icons", key]), value });
2461
+ }
2462
+ }
2463
+ }
2464
+ const result = { manifestPath, changes: [], errors: [], written: [], updated: false };
2465
+ const iconDir = join(dirname(manifestPath), "icons");
2466
+ const splices = [];
2467
+ const pending = /* @__PURE__ */ new Map();
2468
+ for (const target of targets) {
2469
+ const id = target.value.trim();
2470
+ const [prefix, name] = id.includes(":") ? id.split(":") : ["lucide", id];
2471
+ const svg = await renderIconifySvg(prefix, name, loader);
2472
+ if (typeof svg !== "string") {
2473
+ result.errors.push(`${target.label}: ${svg.error}; left as '${target.value}'`);
2474
+ continue;
2475
+ }
2476
+ const node = document.getIn(target.path, true);
2477
+ if (!isScalar(node) || !node.range) {
2478
+ result.errors.push(`${target.label}: could not locate the value in the YAML source; left as '${target.value}'`);
2479
+ continue;
2480
+ }
2481
+ const fileName = `${prefix}-${name}.svg`;
2482
+ const replacementValue = `./icons/${fileName}`;
2483
+ const file = join(iconDir, fileName);
2484
+ pending.set(file, svg);
2485
+ splices.push({ start: node.range[0], end: node.range[1], replacement: formatScalar(replacementValue, node.type) });
2486
+ result.changes.push({ field: target.label, from: target.value, to: replacementValue, file });
2487
+ }
2488
+ if (options.dryRun || result.changes.length === 0) return result;
2489
+ for (const [file, svg] of pending) {
2490
+ if (await exists2(file)) continue;
2491
+ await mkdir(iconDir, { recursive: true });
2492
+ await writeFile(file, `${svg}
2493
+ `);
2494
+ result.written.push(file);
2495
+ }
2496
+ let updated = text;
2497
+ for (const splice of splices.sort((a, b) => b.start - a.start)) {
2498
+ updated = updated.slice(0, splice.start) + splice.replacement + updated.slice(splice.end);
2499
+ }
2500
+ await writeFile(manifestPath, updated);
2501
+ result.updated = true;
2502
+ return result;
2503
+ }
2504
+ async function renderIconifySvg(prefix, name, loader = createIconSetLoader()) {
2505
+ const id = `${prefix}:${name}`;
2506
+ if (!/^[a-z0-9-]+$/.test(prefix) || !/^[a-z0-9-]+$/.test(name)) return { error: `invalid Iconify id '${id}'` };
2507
+ const icons = await loader(prefix, name);
2508
+ if ("error" in icons && typeof icons.error === "string") return { error: `${icons.error} (for '${id}')` };
2509
+ const { getIconData, iconToSVG, iconToHTML } = await import('@iconify/utils');
2510
+ const data = getIconData(icons, name);
2511
+ if (!data) return { error: `unknown Iconify icon '${id}'` };
2512
+ const rendered = iconToSVG(data);
2513
+ const svg = iconToHTML(rendered.body, { viewBox: rendered.attributes.viewBox });
2514
+ const problem = validateSvgIcon(svg);
2515
+ if (problem) return { error: `Iconify icon '${id}' does not satisfy the SVG icon rules: ${problem}` };
2516
+ return svg;
2517
+ }
2518
+ function formatScalar(value, type) {
2519
+ if (type === "QUOTE_SINGLE") return `'${value}'`;
2520
+ if (type === "QUOTE_DOUBLE") return `"${value}"`;
2521
+ return value;
2522
+ }
2523
+ async function exists2(path) {
2524
+ try {
2525
+ await access(path);
2526
+ return true;
2527
+ } catch {
2528
+ return false;
2529
+ }
2530
+ }
2531
+
2532
+ // src/commands/icons.ts
2533
+ function registerIcons(program2) {
2534
+ const icons = program2.command("icons").description("Manage manifest icons");
2535
+ icons.command("migrate [dir]").description("Convert legacy Iconify icon ids in manifests to local SVG files (icons/<prefix>-<name>.svg)").option("--file <path>", "migrate this manifest (repeatable; default: *.app.yaml, *.engine.yaml and manifest.yaml in dir)", collect, []).option("--dry-run", "report the changes without writing files").option("--iconify-api <url>", `Iconify API base URL when @iconify-json/<prefix> is not installed (default: VERENTIS_ICONIFY_API or ${DEFAULT_ICONIFY_API})`).action(async (dir, options) => {
2536
+ const manifests = options.file.length > 0 ? options.file.map((file) => resolve(file)) : await findIconManifests(resolve(dir ?? "."));
2537
+ if (manifests.length === 0) {
2538
+ throw new Error(`No manifests found in ${resolve(dir ?? ".")} (expected *.app.yaml, *.engine.yaml or manifest.yaml; use --file).`);
2539
+ }
2540
+ const loader = createIconSetLoader({ apiBase: options.iconifyApi });
2541
+ let errorCount = 0;
2542
+ for (const manifestPath of manifests) {
2543
+ if (!(await stat(manifestPath).catch(() => null))?.isFile()) throw new Error(`${manifestPath} does not exist.`);
2544
+ const result = await migrateManifestIcons(manifestPath, { dryRun: options.dryRun, loader });
2545
+ const verb = options.dryRun ? "would migrate" : "migrated";
2546
+ console.log(`${manifestPath}: ${verb} ${result.changes.length} icon(s)${result.errors.length ? `, ${result.errors.length} error(s)` : ""}`);
2547
+ for (const change of result.changes) console.log(` ${change.field}: ${change.from} -> ${change.to}`);
2548
+ for (const file of result.written) console.log(` wrote ${file}`);
2549
+ for (const error of result.errors) console.error(` error: ${error}`);
2550
+ errorCount += result.errors.length;
2551
+ }
2552
+ if (errorCount > 0) {
2553
+ console.error(`${errorCount} icon(s) could not be migrated; replace them with your own SVG files.`);
2554
+ process.exitCode = 1;
2555
+ }
2556
+ });
2557
+ }
2558
+ function collect(value, previous) {
2559
+ return [...previous, value];
2560
+ }
2561
+ var APP_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
2562
+ <rect x="2" y="2" width="28" height="28" rx="7" fill="#475569"/>
2563
+ <rect x="8" y="8" width="7" height="7" rx="1.5" fill="#f8fafc"/>
2564
+ <rect x="17" y="8" width="7" height="7" rx="1.5" fill="#f8fafc"/>
2565
+ <rect x="8" y="17" width="7" height="7" rx="1.5" fill="#f8fafc"/>
2566
+ <rect x="17" y="17" width="7" height="7" rx="1.5" fill="#cbd5e1"/>
2567
+ </svg>
2568
+ `;
2569
+ var ENGINE_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
2570
+ <rect x="2" y="2" width="28" height="28" rx="7" fill="#334155"/>
2571
+ <path d="M9 11l5 5-5 5" fill="none" stroke="#f8fafc" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/>
2572
+ <path d="M16 21h7" fill="none" stroke="#f8fafc" stroke-width="2.5" stroke-linecap="round"/>
2573
+ </svg>
2574
+ `;
2575
+ var TEMPLATE_FILES = {
2576
+ application: { "icons/app.svg": APP_ICON_SVG },
2577
+ engine: { "icons/app.svg": ENGINE_ICON_SVG },
2578
+ bundle: {}
2579
+ };
2158
2580
  var TEMPLATES = {
2159
2581
  application: (name) => `api-version: verentis.io/v1
2160
2582
  kind: Application
@@ -2164,7 +2586,7 @@ metadata:
2164
2586
  package-id: ${name}
2165
2587
  display-name: ${titleCase(name)}
2166
2588
  description: ""
2167
- icon: layout-dashboard
2589
+ icon: ./icons/app.svg
2168
2590
  version: 0.1.0
2169
2591
  author: ""
2170
2592
 
@@ -2216,7 +2638,7 @@ metadata:
2216
2638
  package-id: ${name}
2217
2639
  display-name: ${titleCase(name)}
2218
2640
  description: ""
2219
- icon: lucide:terminal
2641
+ icon: ./icons/app.svg
2220
2642
  version: 0.1.0
2221
2643
  author: ""
2222
2644
 
@@ -2287,13 +2709,20 @@ function registerInit(program2) {
2287
2709
  await mkdir(targetDir, { recursive: true });
2288
2710
  const name = (options.name ?? targetDir.split("/").pop() ?? "my-package").toLowerCase().replace(/[^a-z0-9-]/g, "-");
2289
2711
  const manifestPath = join(targetDir, "manifest.yaml");
2290
- if (await exists2(manifestPath)) throw new Error(`${manifestPath} already exists.`);
2712
+ if (await exists3(manifestPath)) throw new Error(`${manifestPath} already exists.`);
2291
2713
  await writeFile(manifestPath, template(name));
2292
2714
  console.log(`Created ${manifestPath} (kind: ${options.kind}).`);
2715
+ for (const [relativePath, content] of Object.entries(TEMPLATE_FILES[options.kind.toLowerCase()] ?? {})) {
2716
+ const path = join(targetDir, relativePath);
2717
+ if (await exists3(path)) continue;
2718
+ await mkdir(dirname(path), { recursive: true });
2719
+ await writeFile(path, content);
2720
+ console.log(`Created ${path}.`);
2721
+ }
2293
2722
  console.log("Fill in packaging.publisher and packaging.files, then run `verentis pack`.");
2294
2723
  });
2295
2724
  }
2296
- async function exists2(path) {
2725
+ async function exists3(path) {
2297
2726
  try {
2298
2727
  await stat(path);
2299
2728
  return true;
@@ -3145,9 +3574,18 @@ async function pack(options) {
3145
3574
  const catalog = manifest.marketplace ? await buildCatalog(projectDir, manifest.marketplace) : void 0;
3146
3575
  const packedManifest = stripTemplatePackagingFields(manifest);
3147
3576
  const manifestSanitized = packedManifest !== manifest;
3577
+ const icons = await resolveManifestIcons(packedManifest, projectDir);
3578
+ if (icons.errors.length > 0) throw new Error(`Invalid icons:
3579
+ ${icons.errors.join("\n ")}`);
3148
3580
  const staging = await mkdtemp(join(tmpdir(), "vpkg-"));
3149
3581
  try {
3150
- const manifestText = overrideApplied || manifestSanitized ? stringify(packedManifest) : await readFile(manifestPath, "utf8");
3582
+ const embedObject = overrideApplied || manifestSanitized;
3583
+ let manifestText = embedObject ? stringify(packedManifest) : await readFile(manifestPath, "utf8");
3584
+ if (icons.needsInlining) {
3585
+ const document = embedObject ? new Document(packedManifest) : parseDocument(manifestText);
3586
+ inlineIconsIntoDocument(document, icons);
3587
+ manifestText = document.toString();
3588
+ }
3151
3589
  await writeFile(join(staging, "manifest.yaml"), manifestText);
3152
3590
  const encrypt = (options.encryptFor?.length ?? 0) > 0;
3153
3591
  const contentKey = encrypt ? generateContentKey() : null;
@@ -3227,7 +3665,8 @@ async function pack(options) {
3227
3665
  catalogFiles: catalog ? ["index.json", ...catalog.entries.map((entry) => entry.path.replace(/^catalog\//, ""))] : [],
3228
3666
  treeDigest: sha256Hex(Buffer.from(digestsJson, "utf8")),
3229
3667
  signed,
3230
- encrypted: encrypt
3668
+ encrypted: encrypt,
3669
+ warnings: icons.warnings
3231
3670
  };
3232
3671
  } finally {
3233
3672
  await rm(staging, { recursive: true, force: true });
@@ -3372,6 +3811,7 @@ function registerPack(program2) {
3372
3811
  signingKey,
3373
3812
  encryptFor
3374
3813
  });
3814
+ for (const warning of result.warnings) console.warn(`Warning: ${warning}`);
3375
3815
  console.log(`Packed ${result.publisher}/${result.packageId}@${result.version} (${result.kind})`);
3376
3816
  console.log(` ${result.outFile}`);
3377
3817
  console.log(` ${result.files.length} payload file(s), tree digest ${result.treeDigest.slice(0, 16)}\u2026, ${result.signed ? "signed" : "UNSIGNED"}${result.encrypted ? ", ENCRYPTED" : ""}`);
@@ -4049,11 +4489,11 @@ function getCliVersion() {
4049
4489
  }
4050
4490
  function readVersion() {
4051
4491
  const candidates = ["../package.json", "../../package.json"];
4052
- for (const relative4 of candidates) {
4492
+ for (const relative5 of candidates) {
4053
4493
  try {
4054
- const raw = readFileSync(fileURLToPath(new URL(relative4, import.meta.url)), "utf8");
4494
+ const raw = readFileSync(fileURLToPath(new URL(relative5, import.meta.url)), "utf8");
4055
4495
  const pkg = JSON.parse(raw);
4056
- if (pkg.version && (relative4 === "../package.json" || pkg.name === PACKAGE_NAME)) return pkg.version;
4496
+ if (pkg.version && (relative5 === "../package.json" || pkg.name === PACKAGE_NAME)) return pkg.version;
4057
4497
  } catch {
4058
4498
  }
4059
4499
  }
@@ -4370,6 +4810,9 @@ function registerValidate(program2) {
4370
4810
  } catch (error) {
4371
4811
  issues.push({ level: "error", message: error instanceof Error ? error.message : String(error) });
4372
4812
  }
4813
+ const icons = await resolveManifestIcons(manifest, dirname(manifestPath));
4814
+ issues.push(...icons.errors.filter((message) => !issues.some((issue) => issue.message === message)).map((message) => ({ level: "error", message })));
4815
+ issues.push(...icons.warnings.map((message) => ({ level: "warning", message })));
4373
4816
  if (manifest.marketplace && !issues.some((issue) => issue.level === "error" && issue.message.startsWith("marketplace"))) {
4374
4817
  try {
4375
4818
  await buildCatalog(dirname(manifestPath), manifest.marketplace);
@@ -4488,6 +4931,7 @@ registerExec(program);
4488
4931
  registerPolicy(program);
4489
4932
  registerDev(program);
4490
4933
  registerValidate(program);
4934
+ registerIcons(program);
4491
4935
  registerCreate(program);
4492
4936
  registerPublisher(program);
4493
4937
  registerKeygen(program);