@verentis/cli 0.2.25 → 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/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";
@@ -303,9 +304,8 @@ async function createApiClient(overrides) {
303
304
  body: JSON.stringify({
304
305
  audience: AUDIENCE,
305
306
  scopes: options.scopes,
306
- ...options.workspaceId ? { workspaceId: options.workspaceId } : {},
307
- ...options.accountId ? { accountId: options.accountId } : {},
308
- ...options.resourceId ? { resourceId: options.resourceId, resourceKind: options.resourceKind ?? "Node" } : {}
307
+ ...options.resourceId ?? options.workspaceId ?? options.accountId ? { resourceId: options.resourceId ?? options.workspaceId ?? options.accountId } : {},
308
+ ...options.resourceId && (options.resourceKind ?? "Node") === "Node" ? { resourceType: "Node", ...options.workspaceId ? { parentResourceId: options.workspaceId } : {} } : {}
309
309
  }),
310
310
  ...insecureFetchOptions(insecure)
311
311
  });
@@ -1073,6 +1073,10 @@ async function loadManifest(path) {
1073
1073
  }
1074
1074
  const launchKindError = validateLaunchManifestKind(kind, manifest.spec);
1075
1075
  if (launchKindError) throw new Error(`Invalid manifest at ${path}: ${launchKindError}.`);
1076
+ const collaborationErrors = validateNativeCollaborationSection(kind, manifest.spec);
1077
+ if (collaborationErrors.length > 0) {
1078
+ throw new Error(`Invalid manifest at ${path}: ${collaborationErrors.join(" ")}`);
1079
+ }
1076
1080
  const operationErrors = validateWopiOperationsSection(manifest.spec);
1077
1081
  if (operationErrors.length > 0) {
1078
1082
  throw new Error(`Invalid manifest at ${path}: ${operationErrors.join(" ")}`);
@@ -1139,6 +1143,19 @@ function validateHostedBackendDeclaration(kind, spec) {
1139
1143
  }
1140
1144
  return [];
1141
1145
  }
1146
+ function validateNativeCollaborationSection(kind, spec) {
1147
+ if (!spec || typeof spec !== "object" || Array.isArray(spec) || !Object.prototype.hasOwnProperty.call(spec, "collaboration")) return [];
1148
+ if (kind !== "Application") return ["spec.collaboration is only supported for Application manifests."];
1149
+ const applicationSpec = spec;
1150
+ const declaration = applicationSpec.collaboration;
1151
+ if (!declaration || typeof declaration !== "object" || Array.isArray(declaration) || Object.keys(declaration).length !== 1 || !Object.prototype.hasOwnProperty.call(declaration, "mode") || declaration.mode !== "native-scene-v1") {
1152
+ return ["spec.collaboration must be exactly { mode: native-scene-v1 }."];
1153
+ }
1154
+ if (Object.prototype.hasOwnProperty.call(applicationSpec, "wopi") || Array.isArray(applicationSpec.capabilities) && applicationSpec.capabilities.includes("wopi")) {
1155
+ return ["Native collaboration and WOPI must use separate application declarations."];
1156
+ }
1157
+ return [];
1158
+ }
1142
1159
  function validateWopiOperationsSection(spec) {
1143
1160
  if (!spec || typeof spec !== "object" || Array.isArray(spec)) return [];
1144
1161
  const wopi = spec.wopi;
@@ -1337,6 +1354,7 @@ function validateManifest(manifest) {
1337
1354
  for (const message of validateWopiOperationsSection(spec)) error(message);
1338
1355
  for (const message of validateHostedBackendDeclaration(kind, spec)) error(message);
1339
1356
  for (const message of validateDependencies(spec)) error(message);
1357
+ for (const message of validateNativeCollaborationSection(kind, spec)) error(message);
1340
1358
  if (kind === "ExecutionEngine") {
1341
1359
  const runtimes = spec.runtimes ?? {};
1342
1360
  if (Object.keys(runtimes).length === 0) {
@@ -1997,7 +2015,7 @@ async function followExecution(api, workspaceId, executionId, json) {
1997
2015
  if (exec.status !== "Completed") process.exitCode = 1;
1998
2016
  return;
1999
2017
  }
2000
- await new Promise((resolve13) => setTimeout(resolve13, 1e3));
2018
+ await new Promise((resolve15) => setTimeout(resolve15, 1e3));
2001
2019
  }
2002
2020
  console.error("Timed out waiting for a terminal status \u2014 check `verentis exec get`.");
2003
2021
  process.exitCode = 1;
@@ -2138,6 +2156,427 @@ async function uploadDirectory(api, workspaceId, localDir, remoteBase, branch) {
2138
2156
  }
2139
2157
  return count;
2140
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
+ };
2141
2580
  var TEMPLATES = {
2142
2581
  application: (name) => `api-version: verentis.io/v1
2143
2582
  kind: Application
@@ -2147,7 +2586,7 @@ metadata:
2147
2586
  package-id: ${name}
2148
2587
  display-name: ${titleCase(name)}
2149
2588
  description: ""
2150
- icon: layout-dashboard
2589
+ icon: ./icons/app.svg
2151
2590
  version: 0.1.0
2152
2591
  author: ""
2153
2592
 
@@ -2199,7 +2638,7 @@ metadata:
2199
2638
  package-id: ${name}
2200
2639
  display-name: ${titleCase(name)}
2201
2640
  description: ""
2202
- icon: lucide:terminal
2641
+ icon: ./icons/app.svg
2203
2642
  version: 0.1.0
2204
2643
  author: ""
2205
2644
 
@@ -2270,13 +2709,20 @@ function registerInit(program2) {
2270
2709
  await mkdir(targetDir, { recursive: true });
2271
2710
  const name = (options.name ?? targetDir.split("/").pop() ?? "my-package").toLowerCase().replace(/[^a-z0-9-]/g, "-");
2272
2711
  const manifestPath = join(targetDir, "manifest.yaml");
2273
- if (await exists2(manifestPath)) throw new Error(`${manifestPath} already exists.`);
2712
+ if (await exists3(manifestPath)) throw new Error(`${manifestPath} already exists.`);
2274
2713
  await writeFile(manifestPath, template(name));
2275
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
+ }
2276
2722
  console.log("Fill in packaging.publisher and packaging.files, then run `verentis pack`.");
2277
2723
  });
2278
2724
  }
2279
- async function exists2(path) {
2725
+ async function exists3(path) {
2280
2726
  try {
2281
2727
  await stat(path);
2282
2728
  return true;
@@ -3128,9 +3574,18 @@ async function pack(options) {
3128
3574
  const catalog = manifest.marketplace ? await buildCatalog(projectDir, manifest.marketplace) : void 0;
3129
3575
  const packedManifest = stripTemplatePackagingFields(manifest);
3130
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 ")}`);
3131
3580
  const staging = await mkdtemp(join(tmpdir(), "vpkg-"));
3132
3581
  try {
3133
- 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
+ }
3134
3589
  await writeFile(join(staging, "manifest.yaml"), manifestText);
3135
3590
  const encrypt = (options.encryptFor?.length ?? 0) > 0;
3136
3591
  const contentKey = encrypt ? generateContentKey() : null;
@@ -3210,7 +3665,8 @@ async function pack(options) {
3210
3665
  catalogFiles: catalog ? ["index.json", ...catalog.entries.map((entry) => entry.path.replace(/^catalog\//, ""))] : [],
3211
3666
  treeDigest: sha256Hex(Buffer.from(digestsJson, "utf8")),
3212
3667
  signed,
3213
- encrypted: encrypt
3668
+ encrypted: encrypt,
3669
+ warnings: icons.warnings
3214
3670
  };
3215
3671
  } finally {
3216
3672
  await rm(staging, { recursive: true, force: true });
@@ -3355,6 +3811,7 @@ function registerPack(program2) {
3355
3811
  signingKey,
3356
3812
  encryptFor
3357
3813
  });
3814
+ for (const warning of result.warnings) console.warn(`Warning: ${warning}`);
3358
3815
  console.log(`Packed ${result.publisher}/${result.packageId}@${result.version} (${result.kind})`);
3359
3816
  console.log(` ${result.outFile}`);
3360
3817
  console.log(` ${result.files.length} payload file(s), tree digest ${result.treeDigest.slice(0, 16)}\u2026, ${result.signed ? "signed" : "UNSIGNED"}${result.encrypted ? ", ENCRYPTED" : ""}`);
@@ -4032,11 +4489,11 @@ function getCliVersion() {
4032
4489
  }
4033
4490
  function readVersion() {
4034
4491
  const candidates = ["../package.json", "../../package.json"];
4035
- for (const relative4 of candidates) {
4492
+ for (const relative5 of candidates) {
4036
4493
  try {
4037
- const raw = readFileSync(fileURLToPath(new URL(relative4, import.meta.url)), "utf8");
4494
+ const raw = readFileSync(fileURLToPath(new URL(relative5, import.meta.url)), "utf8");
4038
4495
  const pkg = JSON.parse(raw);
4039
- 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;
4040
4497
  } catch {
4041
4498
  }
4042
4499
  }
@@ -4353,6 +4810,9 @@ function registerValidate(program2) {
4353
4810
  } catch (error) {
4354
4811
  issues.push({ level: "error", message: error instanceof Error ? error.message : String(error) });
4355
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 })));
4356
4816
  if (manifest.marketplace && !issues.some((issue) => issue.level === "error" && issue.message.startsWith("marketplace"))) {
4357
4817
  try {
4358
4818
  await buildCatalog(dirname(manifestPath), manifest.marketplace);
@@ -4471,6 +4931,7 @@ registerExec(program);
4471
4931
  registerPolicy(program);
4472
4932
  registerDev(program);
4473
4933
  registerValidate(program);
4934
+ registerIcons(program);
4474
4935
  registerCreate(program);
4475
4936
  registerPublisher(program);
4476
4937
  registerKeygen(program);