@openfairygui/cli 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -1,32 +1,93 @@
1
1
  import { createRequire } from "node:module";
2
- import { Command } from "commander";
3
- import { createNodeBackendRuntime } from "@openfairygui/backend/node";
2
+ import { Command, CommanderError, InvalidArgumentError } from "commander";
4
3
  import * as path$1 from "node:path";
5
4
  import path from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+ import { createNodeBackendRuntime } from "@openfairygui/backend/node";
6
7
  import * as fs$1 from "node:fs/promises";
7
8
  import fs from "node:fs/promises";
9
+ import { findInstalledDocumentation, getInstalledDocumentationIndex, getInstalledDocumentationVersion, readInstalledDocumentation } from "@openfairygui/backend/docs";
10
+ import { constants } from "node:fs";
11
+ import { tmpdir } from "node:os";
8
12
  //#region \0rolldown/runtime.js
9
13
  var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
10
14
  //#endregion
15
+ //#region src/utils/json-output.ts
16
+ const stdout = process.stdout.write.bind(process.stdout);
17
+ function wantsJson(argv) {
18
+ const args = argv.slice(2, argv.indexOf("--") < 0 ? void 0 : argv.indexOf("--"));
19
+ return args.includes("--json") && !args.some((arg) => [
20
+ "--help",
21
+ "-h",
22
+ "--version",
23
+ "-V"
24
+ ].includes(arg));
25
+ }
26
+ function configureJson(program) {
27
+ program.option("--json", "Print one JSON envelope (exit 0: success, 1: failure, 2: arguments, 3: incomplete)").exitOverride();
28
+ if (wantsJson(process.argv)) process.stdout.write = process.stderr.write.bind(process.stderr);
29
+ program.hook("preAction", (_root, command) => {
30
+ command.setOptionValue("json", command.optsWithGlobals().json);
31
+ });
32
+ }
33
+ function parsedCommand(program) {
34
+ const names = [];
35
+ let current = program;
36
+ for (;;) {
37
+ const next = current.commands.find((command) => command.name() === current.args[0]);
38
+ if (!next) break;
39
+ names.push(next.name());
40
+ current = next;
41
+ }
42
+ return names.join(" ") || "ofgui";
43
+ }
44
+ function printJson(command, result, error) {
45
+ stdout(`${JSON.stringify(error ? {
46
+ schemaVersion: 1,
47
+ command,
48
+ success: false,
49
+ error,
50
+ result
51
+ } : {
52
+ schemaVersion: 1,
53
+ command,
54
+ success: true,
55
+ result
56
+ })}\n`);
57
+ }
58
+ function printJsonError(command, error) {
59
+ stdout(`${JSON.stringify({
60
+ schemaVersion: 1,
61
+ command,
62
+ success: false,
63
+ error
64
+ })}\n`);
65
+ }
66
+ //#endregion
11
67
  //#region src/commands/backend-capabilities.ts
12
68
  function registerBackendCapabilitiesCommand(program) {
13
- program.command("backend-capabilities").description("Open a backend session, print runtime capabilities, then close it").argument("<project-dir>", "Project root directory").action(async (projectDir) => {
69
+ program.command("backend-capabilities").description("Open a backend session, print runtime capabilities, then close it").argument("<project-dir>", "Project root directory").option("--json", "Print the machine-readable runtime capabilities after closing the session").action(async (projectDir, options) => {
14
70
  const runtime = createNodeBackendRuntime();
15
71
  const opened = await runtime.openSession({ projectPath: path.resolve(projectDir) });
16
72
  if (!opened.ok) throw new Error(`backend-capabilities: ${opened.error.message}`);
17
- const capabilities = runtime.getCapabilities();
18
- if (!capabilities.ok) {
19
- await runtime.closeSession({ sessionId: opened.data.sessionId });
20
- throw new Error("backend-capabilities: failed to read capabilities");
21
- }
22
- console.log(`Session: ${opened.data.sessionId}`);
23
- console.log(`Project: ${opened.data.canonicalProjectPath}`);
24
- console.log(`Revision: ${opened.data.revision}`);
25
- console.log(`Runtime owner: ${capabilities.data.runtimeOwner}`);
26
- console.log(`Transaction owner: ${capabilities.data.transactionKernelOwner}`);
27
- console.log(`App seam owner: ${capabilities.data.appSeamOwner}`);
28
- const closed = await runtime.closeSession({ sessionId: opened.data.sessionId });
73
+ let capabilities;
74
+ let closed;
75
+ try {
76
+ capabilities = runtime.getCapabilities();
77
+ if (!capabilities.ok) throw new Error("backend-capabilities: failed to read capabilities");
78
+ if (!options.json) {
79
+ console.log(`Session: ${opened.data.sessionId}`);
80
+ console.log(`Project: ${opened.data.canonicalProjectPath}`);
81
+ console.log(`Revision: ${opened.data.revision}`);
82
+ console.log(`Runtime owner: ${capabilities.data.runtimeOwner}`);
83
+ console.log(`Transaction owner: ${capabilities.data.transactionKernelOwner}`);
84
+ console.log(`App seam owner: ${capabilities.data.appSeamOwner}`);
85
+ }
86
+ } finally {
87
+ closed = await runtime.closeSession({ sessionId: opened.data.sessionId });
88
+ }
29
89
  if (!closed.ok) throw new Error(`backend-capabilities: ${closed.error.message}`);
90
+ if (options.json) printJson("backend-capabilities", capabilities.data);
30
91
  });
31
92
  }
32
93
  //#endregion
@@ -745,10 +806,10 @@ var Property = class extends GraphNode {
745
806
  return this.set("name", name);
746
807
  }
747
808
  getExtras() {
748
- return this.get("extras");
809
+ return structuredClone(this.get("extras"));
749
810
  }
750
811
  setExtras(extras) {
751
- return this.set("extras", extras);
812
+ return this.set("extras", structuredClone(extras));
752
813
  }
753
814
  clone() {
754
815
  const PropertyClass = this.constructor;
@@ -829,7 +890,7 @@ var ExtensibleProperty = class extends Property {
829
890
  };
830
891
  //#endregion
831
892
  //#region ../core/src/constants.ts
832
- const VERSION = `v0.3.0`;
893
+ const VERSION = `v0.4.0`;
833
894
  /** Binary package file magic number: "FGUI" as uint32. */
834
895
  const FGUI_MAGIC = 1179080009;
835
896
  /** Null string index in the binary string table. */
@@ -1219,10 +1280,10 @@ var Root = class extends ExtensibleProperty {
1219
1280
  return this.setBranches([...this.listBranches(), branch]);
1220
1281
  }
1221
1282
  getSettings() {
1222
- return this.get("settings");
1283
+ return structuredClone(this.get("settings"));
1223
1284
  }
1224
1285
  setSettings(settings) {
1225
- return this.set("settings", settings);
1286
+ return this.set("settings", structuredClone(settings));
1226
1287
  }
1227
1288
  /****** Extensions ******/
1228
1289
  listExtensionsUsed() {
@@ -2263,9 +2324,24 @@ var DragonBonesResource = class extends SkeletonResourceBase {
2263
2324
  * @category Properties
2264
2325
  */
2265
2326
  var Component = class extends ExtensibleProperty {
2327
+ _binaryDirty = true;
2266
2328
  init() {
2267
2329
  this.propertyType = PropertyType.COMPONENT;
2268
2330
  }
2331
+ /** @internal */
2332
+ _markBinaryClean() {
2333
+ this._binaryDirty = false;
2334
+ return this;
2335
+ }
2336
+ /** @internal */
2337
+ _markBinaryDirty() {
2338
+ this._binaryDirty = true;
2339
+ return this;
2340
+ }
2341
+ /** @internal */
2342
+ _isBinaryDirty() {
2343
+ return this._binaryDirty;
2344
+ }
2269
2345
  getDefaults() {
2270
2346
  return Object.assign(super.getDefaults(), {
2271
2347
  id: "",
@@ -6966,7 +7042,13 @@ var Gear = class extends Property {
6966
7042
  return this.get("gearType");
6967
7043
  }
6968
7044
  setGearType(v) {
6969
- return this.set("gearType", v);
7045
+ const stringValues = v === GearType.Text || v === GearType.Icon;
7046
+ if (stringValues === this.hasStringValues()) return this.set("gearType", v);
7047
+ const values = this.getValues();
7048
+ const pageValues = stringValues ? this.parseDelimitedValues(values) : {};
7049
+ this.set("gearType", v);
7050
+ this.set("values", stringValues ? "" : values);
7051
+ return this.set("pageValues", pageValues);
6970
7052
  }
6971
7053
  getController() {
6972
7054
  return this.getRef("controller");
@@ -6978,13 +7060,32 @@ var Gear = class extends Property {
6978
7060
  return this.get("pages");
6979
7061
  }
6980
7062
  setPages(v) {
6981
- return this.set("pages", v);
7063
+ this.set("pages", v);
7064
+ if (this.hasStringValues()) {
7065
+ const values = this.getPageValues();
7066
+ this.setPageValues(Object.fromEntries((v ? v.split(",") : []).map((page) => [page, values[page] ?? null])));
7067
+ }
7068
+ return this;
6982
7069
  }
7070
+ /** Delimited protocol values. Text/Icon states are owned by pageValues. */
6983
7071
  getValues() {
6984
- return this.get("values");
7072
+ if (!this.hasStringValues()) return this.get("values");
7073
+ const values = this.getPageValues();
7074
+ return (this.getPages() ? this.getPages().split(",") : []).map((page) => {
7075
+ const value = values[page];
7076
+ if (value === null || value === void 0 || value.includes("|")) throw new Error("Text/Icon gear states containing null or \"|\" require getPageValues().");
7077
+ return value;
7078
+ }).join("|");
6985
7079
  }
6986
7080
  setValues(v) {
6987
- return this.set("values", v);
7081
+ if (!this.hasStringValues()) return this.set("values", v);
7082
+ return this.setPageValues(this.parseDelimitedValues(v));
7083
+ }
7084
+ parseDelimitedValues(v) {
7085
+ const pages = this.getPages() ? this.getPages().split(",") : [];
7086
+ const values = v.split("|");
7087
+ if (v !== "" && values.length > pages.length) throw new Error("Text/Icon gear delimited values require a matching page for every value.");
7088
+ return Object.fromEntries(pages.map((page, index) => [page, values[index] ?? ""]));
6988
7089
  }
6989
7090
  getCondition() {
6990
7091
  return this.get("condition");
@@ -6999,21 +7100,25 @@ var Gear = class extends Property {
6999
7100
  return this.set("defaultValue", v);
7000
7101
  }
7001
7102
  getPageValues() {
7002
- return this.get("pageValues");
7103
+ return { ...this.get("pageValues") };
7003
7104
  }
7004
7105
  setPageValues(v) {
7005
- return this.set("pageValues", v);
7106
+ if (Object.values(v).some((value) => value !== null && typeof value !== "string")) throw new Error("Gear page values must be strings or null.");
7107
+ return this.set("pageValues", { ...v });
7006
7108
  }
7007
7109
  setPageValue(pageId, value) {
7008
7110
  const values = {
7009
7111
  ...this.getPageValues(),
7010
7112
  [pageId]: value
7011
7113
  };
7012
- return this.set("pageValues", values);
7114
+ return this.setPageValues(values);
7013
7115
  }
7014
7116
  getPageValue(pageId) {
7015
7117
  return this.getPageValues()[pageId] ?? this.getDefaultValue();
7016
7118
  }
7119
+ hasStringValues() {
7120
+ return this.getGearType() === GearType.Text || this.getGearType() === GearType.Icon;
7121
+ }
7017
7122
  getPositionsInPercent() {
7018
7123
  return this.get("positionsInPercent");
7019
7124
  }
@@ -15784,7 +15889,6 @@ const { Deflate, deflate, deflateRaw, gzip } = deflate_1$1;
15784
15889
  const { Inflate, inflate, inflateRaw, ungzip } = inflate_1$1;
15785
15890
  var deflateRaw_1 = deflateRaw;
15786
15891
  var Inflate_1 = Inflate;
15787
- var inflateRaw_1 = inflateRaw;
15788
15892
  //#endregion
15789
15893
  //#region ../core/src/utils/image-info.ts
15790
15894
  var import_jpeg_js = require_jpeg_js();
@@ -16180,6 +16284,99 @@ function probeRasterImageDimensions(data) {
16180
16284
  return readPngInfo(data, false) ?? readJpegInfo(data, false);
16181
16285
  }
16182
16286
  //#endregion
16287
+ //#region ../core/src/utils/svg-validation.ts
16288
+ const MAX_SVG_SOURCE_BYTES = 8 * 1024 * 1024;
16289
+ const MAX_SVG_NODES = 5e4;
16290
+ const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
16291
+ const XLINK_NAMESPACE = "http://www.w3.org/1999/xlink";
16292
+ const UNSAFE_SVG_ELEMENTS = new Set([
16293
+ "a",
16294
+ "animate",
16295
+ "animatecolor",
16296
+ "animatemotion",
16297
+ "animatetransform",
16298
+ "audio",
16299
+ "canvas",
16300
+ "discard",
16301
+ "embed",
16302
+ "feimage",
16303
+ "foreignobject",
16304
+ "iframe",
16305
+ "image",
16306
+ "object",
16307
+ "script",
16308
+ "set",
16309
+ "style",
16310
+ "video"
16311
+ ]);
16312
+ function invalidSvg(message) {
16313
+ throw new Error(`Invalid or unsafe SVG source (${message}).`);
16314
+ }
16315
+ function validateAttribute(name, value) {
16316
+ const normalizedName = name.toLowerCase();
16317
+ if (normalizedName === "xmlns") {
16318
+ if (value !== SVG_NAMESPACE) invalidSvg("the default namespace must be SVG");
16319
+ return;
16320
+ }
16321
+ if (normalizedName === "xmlns:xlink") {
16322
+ if (value !== XLINK_NAMESPACE) invalidSvg("the xlink namespace is invalid");
16323
+ return;
16324
+ }
16325
+ if (normalizedName.includes(":") && normalizedName !== "xlink:href" && normalizedName !== "xml:space") invalidSvg(`qualified attribute "${name}" is not allowed`);
16326
+ const localName = normalizedName.split(":").at(-1);
16327
+ const text = String(value);
16328
+ if (localName.startsWith("on")) invalidSvg(`event attribute "${name}" is not allowed`);
16329
+ if (localName === "style" || localName === "src") invalidSvg(`attribute "${name}" is not allowed`);
16330
+ if (localName === "href" && !/^#[A-Za-z_][\w:.-]*$/u.test(text)) invalidSvg(`external reference in "${name}" is not allowed`);
16331
+ if (/(?:^|[\s("'=])(?:https?:|file:|javascript:|data:|\/\/)/iu.test(text)) invalidSvg(`external URL in "${name}" is not allowed`);
16332
+ for (const match of text.matchAll(/url\s*\(([^)]*)\)/giu)) {
16333
+ const reference = (match[1] ?? "").trim().replace(/^(['"])(.*)\1$/u, "$2");
16334
+ if (!/^#[A-Za-z_][\w:.-]*$/u.test(reference)) invalidSvg(`external url() in "${name}" is not allowed`);
16335
+ }
16336
+ }
16337
+ /** Validate SVG bytes before handing them to a host image decoder. */
16338
+ function validateSafeSvgSource(bytes) {
16339
+ if (bytes.byteLength === 0 || bytes.byteLength > MAX_SVG_SOURCE_BYTES) invalidSvg("source size is unsupported");
16340
+ let source;
16341
+ try {
16342
+ source = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
16343
+ } catch {
16344
+ invalidSvg("source is not valid UTF-8");
16345
+ }
16346
+ if (/<!\s*(?:doctype|entity)\b|<\?xml-stylesheet\b/iu.test(source)) invalidSvg("DTD, entities, and stylesheets are not allowed");
16347
+ if (XMLValidator.validate(source, { allowBooleanAttributes: false }) !== true) invalidSvg("source is not well-formed XML");
16348
+ const roots = new XMLParser({
16349
+ preserveOrder: true,
16350
+ ignoreAttributes: false,
16351
+ attributeNamePrefix: "",
16352
+ parseAttributeValue: false,
16353
+ parseTagValue: false,
16354
+ processEntities: false,
16355
+ trimValues: false
16356
+ }).parse(source).flatMap((entry) => Object.keys(entry).filter((name) => name !== ":@" && !name.startsWith("#") && !name.startsWith("?")).map((name) => ({
16357
+ entry,
16358
+ name
16359
+ })));
16360
+ if (roots.length !== 1 || roots[0].name !== "svg") invalidSvg("a single unqualified <svg> root is required");
16361
+ if (roots[0].entry[":@"]?.xmlns !== SVG_NAMESPACE) invalidSvg("the SVG namespace is required");
16362
+ const pending = [roots[0].entry];
16363
+ let nodeCount = 0;
16364
+ while (pending.length > 0) {
16365
+ const current = pending.pop();
16366
+ for (const [name, value] of Object.entries(current)) {
16367
+ if (name === ":@" || name.startsWith("#") || name.startsWith("?")) continue;
16368
+ if (++nodeCount > MAX_SVG_NODES) invalidSvg("node count exceeds the supported limit");
16369
+ if (name.includes(":")) invalidSvg(`qualified element <${name}> is not allowed`);
16370
+ if (UNSAFE_SVG_ELEMENTS.has(name.toLowerCase())) invalidSvg(`element <${name}> is not allowed`);
16371
+ for (const [attributeName, attributeValue] of Object.entries(current[":@"] ?? {})) validateAttribute(attributeName, attributeValue);
16372
+ if (Array.isArray(value)) {
16373
+ for (const child of value) if (child && typeof child === "object" && !Array.isArray(child)) pending.push(child);
16374
+ }
16375
+ }
16376
+ }
16377
+ return source;
16378
+ }
16379
+ //#endregion
16183
16380
  //#region ../core/src/document.ts
16184
16381
  /**
16185
16382
  * Wraps a FairyGUI project and its resources for easier modification.
@@ -16206,12 +16403,32 @@ var Document = class Document {
16206
16403
  _root = new Root(this._graph);
16207
16404
  _logger = Logger.DEFAULT_INSTANCE;
16208
16405
  _projectDir = "";
16406
+ _hasBinaryComponents = false;
16209
16407
  static _GRAPH_DOCUMENTS = /* @__PURE__ */ new WeakMap();
16210
16408
  static fromGraph(graph) {
16211
16409
  return Document._GRAPH_DOCUMENTS.get(graph) || null;
16212
16410
  }
16213
16411
  constructor() {
16214
16412
  Document._GRAPH_DOCUMENTS.set(this._graph, this);
16413
+ this._graph.addEventListener("node:change", (event) => {
16414
+ if (!this._hasBinaryComponents) return;
16415
+ const pending = [event.target];
16416
+ const visited = /* @__PURE__ */ new Set();
16417
+ while (pending.length > 0) {
16418
+ const current = pending.pop();
16419
+ if (visited.has(current)) continue;
16420
+ visited.add(current);
16421
+ if (current instanceof Component) {
16422
+ current._markBinaryDirty();
16423
+ continue;
16424
+ }
16425
+ pending.push(...current.listParents());
16426
+ }
16427
+ });
16428
+ }
16429
+ /** @internal */
16430
+ _trackBinaryComponent() {
16431
+ this._hasBinaryComponents = true;
16215
16432
  }
16216
16433
  getRoot() {
16217
16434
  return this._root;
@@ -16431,6 +16648,12 @@ function isFiniteUamPoint(value) {
16431
16648
  const point = value;
16432
16649
  return typeof point.x === "number" && Number.isFinite(point.x) && typeof point.y === "number" && Number.isFinite(point.y);
16433
16650
  }
16651
+ function isValidUamXYGearValue(value, positionsInPercent) {
16652
+ if (!isFiniteUamPoint(value)) return false;
16653
+ const { px, py } = value;
16654
+ if (!positionsInPercent && px === void 0 && py === void 0) return true;
16655
+ return typeof px === "number" && Number.isFinite(px) && typeof py === "number" && Number.isFinite(py);
16656
+ }
16434
16657
  function isFiniteUamSize(value) {
16435
16658
  if (typeof value !== "object" || value === null) return false;
16436
16659
  const size = value;
@@ -16820,6 +17043,9 @@ function validateControllerAction(action, knownPageIds, knownChildIds, path, iss
16820
17043
  if (action.targetNodeId && !knownChildIds.has(action.targetNodeId)) pushIssue(issues, `${path}.targetNodeId`, `Unknown target node id "${action.targetNodeId}".`);
16821
17044
  }
16822
17045
  function validateGearBinding(gear, controllerMap, path, issues) {
17046
+ if (gear.kind === "xy") {
17047
+ for (const [valuePath, value] of [[`${path}.defaultValue`, gear.defaultValue], ...gear.states.filter((state) => state.value !== null).map((state) => [`${path}.states.${state.pageId}.value`, state.value])]) if (value !== null && !isValidUamXYGearValue(value, gear.positionsInPercent)) pushIssue(issues, valuePath, "XY gear values require finite x/y and paired finite px/py; percentage mode requires px/py.");
17048
+ }
16823
17049
  const controller = controllerMap.get(gear.controllerName);
16824
17050
  if (!controller) {
16825
17051
  pushIssue(issues, `${path}.controllerName`, `Unknown gear controller "${gear.controllerName}".`);
@@ -16966,7 +17192,12 @@ function validateDisplayNode(node, controllerMap, knownChildIds, knownGroupIds,
16966
17192
  if ("group" in node) pushIssue(issues, `${path}.group`, `${node.kind} display nodes must not declare a group reference.`);
16967
17193
  } else if (!("group" in node) || typeof node.group !== "string") pushIssue(issues, `${path}.group`, "Display node group must be a string.");
16968
17194
  else if (node.group && (node.group === node.id || !knownGroupIds.has(node.group))) pushIssue(issues, `${path}.group`, `Group reference "${node.group}" must target another group in the same component.`);
16969
- for (const [gearIndex, gear] of node.gears.entries()) validateGearBinding(gear, controllerMap, `${path}.gears[${gearIndex}]`, issues);
17195
+ const gearKinds = /* @__PURE__ */ new Set();
17196
+ for (const [gearIndex, gear] of node.gears.entries()) {
17197
+ if (gearKinds.has(gear.kind)) pushIssue(issues, `${path}.gears[${gearIndex}]`, `A display node may only have one ${gear.kind} gear.`);
17198
+ gearKinds.add(gear.kind);
17199
+ validateGearBinding(gear, controllerMap, `${path}.gears[${gearIndex}]`, issues);
17200
+ }
16970
17201
  for (const [relationIndex, relation] of node.relations.entries()) if (relation.targetNodeId && !knownChildIds.has(relation.targetNodeId)) pushIssue(issues, `${path}.relations[${relationIndex}]`, `Unknown relation target node id "${relation.targetNodeId}".`);
16971
17202
  }
16972
17203
  function validateUamProject(project) {
@@ -17212,16 +17443,8 @@ function sourceExtension(resource) {
17212
17443
  }
17213
17444
  function validSvg(bytes) {
17214
17445
  try {
17215
- if (bytes.byteLength === 0 || bytes.byteLength > 8 * 1024 * 1024) return false;
17216
- const source = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
17217
- if (XMLValidator.validate(source, { allowBooleanAttributes: false }) !== true) return false;
17218
- if (!/<svg(?:\s|>)/i.test(source)) return false;
17219
- if (/<!\s*(?:doctype|entity)\b|<\?xml-stylesheet\b/iu.test(source)) return false;
17220
- if (/<(?:a|animate|animatecolor|animatemotion|animatetransform|audio|canvas|discard|embed|feimage|foreignobject|iframe|image|object|script|set|style|video)(?:\s|>)/iu.test(source)) return false;
17221
- if (/\s(?:on[\w:-]*|style|src)\s*=/iu.test(source)) return false;
17222
- if (/\s(?:href|xlink:href)\s*=\s*['"](?!#[A-Za-z_][\w:.-]*['"])/iu.test(source)) return false;
17223
- const urlSource = source.replace(/\sxmlns\s*=\s*(['"])http:\/\/www\.w3\.org\/2000\/svg\1/giu, "");
17224
- return !/(?:https?:|file:|javascript:|data:|\/\/)|url\s*\(\s*(?!['"]?#[A-Za-z_])/iu.test(urlSource);
17446
+ validateSafeSvgSource(bytes);
17447
+ return true;
17225
17448
  } catch {
17226
17449
  return false;
17227
17450
  }
@@ -17325,12 +17548,18 @@ function parseLookGearValue(value) {
17325
17548
  };
17326
17549
  }
17327
17550
  function parseGenericGearValue(kind, value) {
17551
+ if (kind === "text") return value === null ? null : { text: value };
17552
+ if (kind === "icon") return value === null ? null : { icon: value };
17328
17553
  if (!value || value === "-") return null;
17329
17554
  const parts = value.split(",");
17330
17555
  switch (kind) {
17331
17556
  case "xy": return {
17332
17557
  x: parseNumber(parts[0], 0),
17333
- y: parseNumber(parts[1], 0)
17558
+ y: parseNumber(parts[1], 0),
17559
+ ...parts.length > 2 ? {
17560
+ px: Number(parts[2]),
17561
+ py: Number(parts[3])
17562
+ } : {}
17334
17563
  };
17335
17564
  case "size": return {
17336
17565
  width: parseNumber(parts[0], 0),
@@ -17348,8 +17577,6 @@ function parseGenericGearValue(kind, value) {
17348
17577
  animationName: parts[2] ?? "",
17349
17578
  skinName: parts[3] ?? ""
17350
17579
  };
17351
- case "text": return { text: value };
17352
- case "icon": return { icon: value };
17353
17580
  case "fontSize": return { fontSize: parseNumber(parts[0], 12) };
17354
17581
  }
17355
17582
  }
@@ -17606,16 +17833,18 @@ function liftGears(gears) {
17606
17833
  [GearType.FontSize, "fontSize"]
17607
17834
  ]).get(gear.getGearType());
17608
17835
  if (!kind) throw new Error(`UAM lift does not support gear type "${gear.getGearType()}" in Gate A.`);
17609
- const values = gear.getValues() ? gear.getValues().split("|") : [];
17610
- const defaultValue = `${gear.getDefaultValue() ?? ""}`;
17836
+ const stringValues = kind === "text" || kind === "icon";
17837
+ const pageValues = gear.getPageValues();
17838
+ const values = stringValues ? [] : gear.getValues() ? gear.getValues().split("|") : [];
17839
+ const defaultValue = gear.getDefaultValue() === null ? null : `${gear.getDefaultValue()}`;
17611
17840
  const base = {
17612
17841
  name: gear.getName(),
17613
17842
  controllerName: gear.getController()?.getName() ?? "",
17614
17843
  states: pages.map((pageId, index) => ({
17615
17844
  pageId,
17616
- value: parseGenericGearValue(kind, values[index] ?? null)
17845
+ value: parseGenericGearValue(kind, stringValues ? pageValues[pageId] ?? null : values[index] ?? null)
17617
17846
  })),
17618
- defaultValue: parseGenericGearValue(kind, defaultValue) ?? defaultGenericGearValue(kind),
17847
+ defaultValue: parseGenericGearValue(kind, defaultValue) ?? (stringValues || kind === "xy" ? null : defaultGenericGearValue(kind)),
17619
17848
  condition: gear.getCondition(),
17620
17849
  positionsInPercent: gear.getPositionsInPercent(),
17621
17850
  tween: gear.getTween(),
@@ -20272,7 +20501,7 @@ function parseGear(_ctx, doc, obj, gearTag, attrs, localControllers) {
20272
20501
  const pages = readXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.pages);
20273
20502
  if (pages) gear.setPages(pages);
20274
20503
  const values = readXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.values);
20275
- if (values) gear.setValues(values);
20504
+ if (gearType === GearType.Text || gearType === GearType.Icon || values) gear.setValues(values ?? "");
20276
20505
  const defaultValue = readXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.default);
20277
20506
  if (defaultValue !== void 0) gear.setDefaultValue(defaultValue);
20278
20507
  const condition = readXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.condition);
@@ -22877,6 +23106,7 @@ function serializeChild(obj) {
22877
23106
  const objectProtocol = DISPLAY_OBJECT_PROTOCOL_BY_TYPE[type] ?? PROJECT_XML_PROTOCOL.componentInstance;
22878
23107
  writeCommonDisplayState(attrs, typedObj, objectProtocol);
22879
23108
  const gearChildNameSet = getProtocolGearChildNameSet(objectProtocol);
23109
+ assertDisplayObjectGearXmlValues(obj);
22880
23110
  for (const gear of obj.listGears()) {
22881
23111
  const gearTag = GEAR_TAG[gear.getGearType()];
22882
23112
  if (!gearTag || !gearChildNameSet.has(gearTag)) continue;
@@ -22904,12 +23134,36 @@ function serializeChild(obj) {
22904
23134
  if (extensionChildName && extensionValue !== void 0) attrs[extensionChildName] = extensionValue;
22905
23135
  return attrs;
22906
23136
  }
23137
+ function assertDisplayObjectGearXmlValues(obj) {
23138
+ const types = /* @__PURE__ */ new Set();
23139
+ for (const gear of obj.listGears()) {
23140
+ const type = gear.getGearType();
23141
+ if (types.has(type)) throw new Error(`Display node "${obj.getId()}" has duplicate ${GEAR_TAG[type] ?? type} bindings.`);
23142
+ types.add(type);
23143
+ assertTextGearXmlValues(gear);
23144
+ }
23145
+ }
23146
+ function assertTextGearXmlValues(gear) {
23147
+ if (gear.getGearType() !== GearType.Text && gear.getGearType() !== GearType.Icon) return;
23148
+ const values = gear.getPageValues();
23149
+ for (const page of gear.getPages() ? gear.getPages().split(",") : []) if (values[page]?.includes("|")) throw new Error(`Project XML cannot represent "|" in Text/Icon gear page "${page}"; no verified delimiter escape is available.`);
23150
+ }
22907
23151
  function serializeGear(gear, ownerType, ownerName) {
22908
23152
  const ctrl = gear.getController();
22909
23153
  const attrs = {};
22910
23154
  if (ctrl) writeXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.controller, ctrl.getName());
22911
- if (gear.getPages()) writeXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.pages, gear.getPages());
22912
- if (gear.getValues()) writeXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.values, normalizeGearXmlValue(gear.getGearType(), gear.getValues(), ownerType, ownerName ?? void 0, gear));
23155
+ if (gear.getGearType() === GearType.Text || gear.getGearType() === GearType.Icon) {
23156
+ assertTextGearXmlValues(gear);
23157
+ const values = gear.getPageValues();
23158
+ const pages = (gear.getPages() ? gear.getPages().split(",") : []).filter((page) => values[page] != null);
23159
+ if (pages.length > 0) {
23160
+ writeXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.pages, pages.join(","));
23161
+ writeXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.values, pages.map((page) => values[page]).join("|"));
23162
+ }
23163
+ } else {
23164
+ if (gear.getPages()) writeXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.pages, gear.getPages());
23165
+ if (gear.getValues()) writeXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.values, normalizeGearXmlValue(gear.getGearType(), gear.getValues(), ownerType, ownerName ?? void 0, gear));
23166
+ }
22913
23167
  if (gear.getDefaultValue() !== null) writeXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.default, normalizeGearXmlValue(gear.getGearType(), gear.getDefaultValue(), ownerType, ownerName ?? void 0, gear));
22914
23168
  if (gear.getTween()) {
22915
23169
  writeXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.tween, "true");
@@ -23300,7 +23554,10 @@ var ProjectWriter = class {
23300
23554
  const staleSourceFilePaths = new Set((options.staleSourceFiles ?? []).map((source) => this._projectSourceFilePath(basePath, source)));
23301
23555
  const staleBranchDirectoryPaths = new Set((options.staleBranchDirectories ?? []).map((directory) => this._projectBranchDirectoryPath(basePath, directory)));
23302
23556
  if (staleBranchDirectoryPaths.size > 0 && !fs.rmdir) throw new Error("Project branch cleanup requires a FileSystem.rmdir() implementation.");
23303
- for (const pkg of root.listPackages()) this._assertPackageOutputTargets(pkg);
23557
+ for (const pkg of root.listPackages()) {
23558
+ this._assertPackageOutputTargets(pkg);
23559
+ for (const component of pkg.listComponents()) for (const child of component.listChildren()) assertDisplayObjectGearXmlValues(child);
23560
+ }
23304
23561
  const settings = root.getSettings?.() ?? {};
23305
23562
  const settingsPath = fs.join(basePath, "settings");
23306
23563
  const staleOptionalSettings = [];
@@ -23309,7 +23566,11 @@ var ProjectWriter = class {
23309
23566
  if (settings[key] === void 0 && await fs.exists(filePath)) staleOptionalSettings.push(filePath);
23310
23567
  }
23311
23568
  if (staleOptionalSettings.length > 0 && !fs.unlink) throw new Error("Project settings cleanup requires a FileSystem.unlink() implementation.");
23312
- const fairyXml = `<?xml version="1.0" encoding="utf-8"?>\n<projectDescription id="${root.getProjectId()}" type="${this._projectTypeName(root.getProjectType())}" version="${root.getVersion() || "3.0"}"/>\n`;
23569
+ const fairyXml = `<?xml version="1.0" encoding="utf-8"?>\n<projectDescription${renderXmlAttrs({
23570
+ id: root.getProjectId(),
23571
+ type: this._projectTypeName(root.getProjectType()),
23572
+ version: root.getVersion() || "3.0"
23573
+ })}/>\n`;
23313
23574
  await fs.writeFile(projectPath, fairyXml);
23314
23575
  await fs.mkdir(settingsPath);
23315
23576
  for (const [fileName, key] of Object.entries({
@@ -24742,9 +25003,10 @@ function decodeChildBlock2(doc, resource, child, childBuf) {
24742
25003
  for (let pageIndex = 0; pageIndex < pageCount; pageIndex += 1) {
24743
25004
  if (remainingBytes(childBuf) < 2) break;
24744
25005
  const rawPageId = childBuf.readS();
25006
+ if (rawPageId === null && (gearType === GearType.Text || gearType === GearType.Icon)) continue;
24745
25007
  const pageId = rawPageId ?? controllerPages[pageIndex]?.getId() ?? "";
24746
25008
  pages.push(pageId);
24747
- if (rawPageId === null && gearType !== GearType.Text && gearType !== GearType.Icon) {
25009
+ if (rawPageId === null) {
24748
25010
  values.push("-");
24749
25011
  continue;
24750
25012
  }
@@ -24794,7 +25056,8 @@ function decodeChildBlock2(doc, resource, child, childBuf) {
24794
25056
  }
24795
25057
  }
24796
25058
  if (pages.length > 0) gear.setPages(pages.join(","));
24797
- if (values.length > 0) gear.setValues(values.join("|"));
25059
+ if (gearType === GearType.Text || gearType === GearType.Icon) gear.setPageValues(Object.fromEntries(pages.map((page, index) => [page, values[index] ?? null])));
25060
+ else if (values.length > 0) gear.setValues(values.join("|"));
24798
25061
  gear.setDefaultValue(defaultValue);
24799
25062
  child.addGear(gear);
24800
25063
  childBuf.pos = nextPos;
@@ -24858,6 +25121,41 @@ function decodeComponentDefinition(resource, rawData, extensionTypeCode, doc) {
24858
25121
  }
24859
25122
  //#endregion
24860
25123
  //#region ../core/src/io/binary-reader.ts
25124
+ const DEFAULT_BINARY_READ_LIMITS = {
25125
+ maxCompressedBytes: 64 * 1024 * 1024,
25126
+ maxDecompressedBytes: 256 * 1024 * 1024,
25127
+ maxCompressionRatio: 200
25128
+ };
25129
+ function readLimits(options) {
25130
+ const limits = {
25131
+ ...DEFAULT_BINARY_READ_LIMITS,
25132
+ ...options.limits
25133
+ };
25134
+ for (const [name, value] of Object.entries(limits)) if (!Number.isFinite(value) || value <= 0) throw new RangeError(`${name} must be a positive finite number.`);
25135
+ return limits;
25136
+ }
25137
+ function inflateRawWithLimits(input, limits) {
25138
+ if (input.byteLength > limits.maxCompressedBytes) throw new Error(`FairyGUI binary compressed data exceeds ${limits.maxCompressedBytes} bytes.`);
25139
+ const maxOutputBytes = Math.min(limits.maxDecompressedBytes, Math.floor(input.byteLength * limits.maxCompressionRatio));
25140
+ const chunks = [];
25141
+ let outputLength = 0;
25142
+ const inflater = new Inflate_1({ raw: true });
25143
+ inflater.onData = (chunk) => {
25144
+ if (!(chunk instanceof Uint8Array)) throw new Error("FairyGUI binary inflate returned non-binary data.");
25145
+ outputLength += chunk.byteLength;
25146
+ if (outputLength > maxOutputBytes) throw new Error(`FairyGUI binary decompressed data exceeds the configured ${maxOutputBytes} byte budget.`);
25147
+ chunks.push(chunk);
25148
+ };
25149
+ inflater.push(input, true);
25150
+ if (inflater.err !== 0) throw new Error(`Invalid compressed FairyGUI binary data: ${inflater.msg}`);
25151
+ const output = new Uint8Array(outputLength);
25152
+ let offset = 0;
25153
+ for (const chunk of chunks) {
25154
+ output.set(chunk, offset);
25155
+ offset += chunk.byteLength;
25156
+ }
25157
+ return output;
25158
+ }
24861
25159
  /**
24862
25160
  * Binary item type codes as used in the .fui format.
24863
25161
  * @internal
@@ -24958,7 +25256,7 @@ function decodeFontGlyphs(doc, resource, buf) {
24958
25256
  for (let index = 0; index < glyphCount; index += 1) {
24959
25257
  const chunkSize = buf.getInt16();
24960
25258
  const nextPos = buf.pos + chunkSize;
24961
- const charId = buf.getInt16();
25259
+ const charId = buf.getUint16();
24962
25260
  const glyph = doc.createFontGlyph(`${resource.getId()}_${charId || index}`);
24963
25261
  glyph.setCharId(charId).setChar(decodeChar(charId)).setImg(buf.readS() ?? "").setX(buf.getInt32()).setY(buf.getInt32()).setXOffset(buf.getInt32()).setYOffset(buf.getInt32()).setWidth(buf.getInt32()).setHeight(buf.getInt32()).setAdvance(buf.getInt32()).setChannel(buf.getUint8());
24964
25262
  resource.addGlyph(glyph);
@@ -24977,8 +25275,10 @@ function decodeFontGlyphs(doc, resource, buf) {
24977
25275
  */
24978
25276
  var BinaryReader = class {
24979
25277
  _fs;
24980
- constructor(fs) {
25278
+ _limits;
25279
+ constructor(fs, options = {}) {
24981
25280
  this._fs = fs;
25281
+ this._limits = readLimits(options);
24982
25282
  }
24983
25283
  async read(filePath) {
24984
25284
  const doc = new Document();
@@ -25004,9 +25304,12 @@ var BinaryReader = class {
25004
25304
  outer.skip(20);
25005
25305
  let buf;
25006
25306
  if (compressed) {
25007
- const decompressed = inflateRaw_1(new Uint8Array(outer.buffer, outer.byteOffset + outer.pos, outer.byteLength - outer.pos));
25307
+ const decompressed = inflateRawWithLimits(new Uint8Array(outer.buffer, outer.byteOffset + outer.pos, outer.byteLength - outer.pos), this._limits);
25008
25308
  buf = new ByteBuffer(decompressed.buffer, 0, decompressed.byteLength);
25009
- } else buf = outer;
25309
+ } else {
25310
+ if (outer.byteLength - outer.pos > this._limits.maxDecompressedBytes) throw new Error(`FairyGUI binary data exceeds ${this._limits.maxDecompressedBytes} bytes.`);
25311
+ buf = outer;
25312
+ }
25010
25313
  buf.version = outer.version;
25011
25314
  const indexTablePos = buf.pos;
25012
25315
  const ver2 = buf.version >= 2;
@@ -25135,6 +25438,8 @@ var BinaryReader = class {
25135
25438
  ...getComponentExtras(res),
25136
25439
  _rawBinary: toRawBinarySlice(rawData)
25137
25440
  });
25441
+ res._markBinaryClean();
25442
+ doc._trackBinaryComponent();
25138
25443
  pkg.addResource(res);
25139
25444
  createdResource = res;
25140
25445
  break;
@@ -25286,7 +25591,7 @@ var BinaryReader = class {
25286
25591
  *
25287
25592
  * @internal
25288
25593
  */
25289
- var WriteBuffer = class {
25594
+ var WriteBuffer = class WriteBuffer {
25290
25595
  _buf;
25291
25596
  _view;
25292
25597
  _pos = 0;
@@ -25296,6 +25601,9 @@ var WriteBuffer = class {
25296
25601
  _strings;
25297
25602
  /** Raw custom strings written to block 5, keyed by string table index. */
25298
25603
  _customStrings;
25604
+ static _assertInteger(value, min, max, type) {
25605
+ if (!Number.isSafeInteger(value) || value < min || value > max) throw new RangeError(`${type} value is out of range: ${value}`);
25606
+ }
25299
25607
  constructor(initialSize = 4096, parent) {
25300
25608
  this._buf = new ArrayBuffer(initialSize);
25301
25609
  this._view = new DataView(this._buf);
@@ -25330,34 +25638,41 @@ var WriteBuffer = class {
25330
25638
  this._view = new DataView(this._buf);
25331
25639
  }
25332
25640
  writeUint8(v) {
25641
+ WriteBuffer._assertInteger(v, 0, 255, "uint8");
25333
25642
  this._ensure(1);
25334
25643
  this._view.setUint8(this._pos++, v);
25335
25644
  }
25336
25645
  writeInt8(v) {
25646
+ WriteBuffer._assertInteger(v, -128, 127, "int8");
25337
25647
  this._ensure(1);
25338
25648
  this._view.setInt8(this._pos++, v);
25339
25649
  }
25340
25650
  writeUint16(v) {
25651
+ WriteBuffer._assertInteger(v, 0, 65535, "uint16");
25341
25652
  this._ensure(2);
25342
25653
  this._view.setUint16(this._pos, v, false);
25343
25654
  this._pos += 2;
25344
25655
  }
25345
25656
  writeInt16(v) {
25657
+ WriteBuffer._assertInteger(v, -32768, 32767, "int16");
25346
25658
  this._ensure(2);
25347
25659
  this._view.setInt16(this._pos, v, false);
25348
25660
  this._pos += 2;
25349
25661
  }
25350
25662
  writeUint32(v) {
25663
+ WriteBuffer._assertInteger(v, 0, 4294967295, "uint32");
25351
25664
  this._ensure(4);
25352
25665
  this._view.setUint32(this._pos, v, false);
25353
25666
  this._pos += 4;
25354
25667
  }
25355
25668
  writeInt32(v) {
25669
+ WriteBuffer._assertInteger(v, -2147483648, 2147483647, "int32");
25356
25670
  this._ensure(4);
25357
25671
  this._view.setInt32(this._pos, v, false);
25358
25672
  this._pos += 4;
25359
25673
  }
25360
25674
  writeFloat32(v) {
25675
+ if (!Number.isFinite(v)) throw new RangeError(`float32 value must be finite: ${v}`);
25361
25676
  this._ensure(4);
25362
25677
  this._view.setFloat32(this._pos, v, false);
25363
25678
  this._pos += 4;
@@ -25368,6 +25683,7 @@ var WriteBuffer = class {
25368
25683
  /** Write a uint16-prefixed UTF-8 string. */
25369
25684
  writeUTFString(s) {
25370
25685
  const encoded = new TextEncoder().encode(s);
25686
+ if (encoded.byteLength > 65535) throw new RangeError(`UTF string exceeds uint16 byte length: ${encoded.byteLength}`);
25371
25687
  this.writeUint16(encoded.byteLength);
25372
25688
  this._ensure(encoded.byteLength);
25373
25689
  new Uint8Array(this._buf, this._pos, encoded.byteLength).set(encoded);
@@ -25394,6 +25710,7 @@ var WriteBuffer = class {
25394
25710
  const existing = this._stringMap.get(s);
25395
25711
  if (existing !== void 0) return existing;
25396
25712
  const index = this._strings.length;
25713
+ if (index >= 65533) throw new RangeError(`String table exceeds protocol index limit: ${index + 1}`);
25397
25714
  this._strings.push(s);
25398
25715
  this._stringMap.set(s, index);
25399
25716
  return index;
@@ -25430,6 +25747,7 @@ var WriteBuffer = class {
25430
25747
  if (!noCache) this.writeUint16(this.addString(s));
25431
25748
  else {
25432
25749
  const index = this._strings.length;
25750
+ if (index >= 65533) throw new RangeError(`String table exceeds protocol index limit: ${index + 1}`);
25433
25751
  this._strings.push(s);
25434
25752
  this.writeUint16(index);
25435
25753
  }
@@ -25727,7 +26045,7 @@ function _writeControllers(buf, comp) {
25727
26045
  }
25728
26046
  /** Map property type to GObject type index used in binary format. */
25729
26047
  function _writeComponentRelations(buf, comp) {
25730
- _writeRelations(buf, comp, _createChildIndexMap(comp));
26048
+ _writeRelations(buf, comp, getRuntimeChildIndexMap(comp));
25731
26049
  }
25732
26050
  function _writeRelations(buf, obj, childIndexById) {
25733
26051
  const relationDefs = obj.getRelations?.() ?? [];
@@ -25751,15 +26069,6 @@ function _writeRelations(buf, obj, childIndexById) {
25751
26069
  }
25752
26070
  }
25753
26071
  }
25754
- function _createChildIndexMap(comp) {
25755
- const childIndexById = /* @__PURE__ */ new Map();
25756
- const children = comp.listChildren();
25757
- for (const [index, child] of children.entries()) {
25758
- const childId = child.getId?.();
25759
- if (childId) childIndexById.set(childId, index);
25760
- }
25761
- return childIndexById;
25762
- }
25763
26072
  function _resolveRelationTargetIndex(target, childIndexById) {
25764
26073
  if (!target) return -1;
25765
26074
  const mappedIndex = childIndexById?.get(target);
@@ -26046,8 +26355,8 @@ function _writeTransitionValue(buf, item, value, version) {
26046
26355
  break;
26047
26356
  }
26048
26357
  case "Scale":
26049
- buf.writeFloat32(parseFloat(parts[0]) || 1);
26050
- buf.writeFloat32(parseFloat(parts[1]) || 1);
26358
+ buf.writeFloat32(_numberToken(parts[0], 1));
26359
+ buf.writeFloat32(_numberToken(parts[1], 1));
26051
26360
  break;
26052
26361
  case "Alpha":
26053
26362
  case "Rotation":
@@ -26074,11 +26383,11 @@ function _writeTransitionValue(buf, item, value, version) {
26074
26383
  break;
26075
26384
  case "Sound":
26076
26385
  buf.writeSEx(parts[0] || null, false, false);
26077
- buf.writeFloat32((parseInt(parts[1], 10) || 100) / 100);
26386
+ buf.writeFloat32(Math.trunc(_numberToken(parts[1], 100)) / 100);
26078
26387
  break;
26079
26388
  case "Transition":
26080
26389
  buf.writeSEx(parts[0] || null, false, false);
26081
- buf.writeInt32(parseInt(parts[1], 10) || 1);
26390
+ buf.writeInt32(Math.trunc(_numberToken(parts[1], 1)));
26082
26391
  break;
26083
26392
  case "Shake":
26084
26393
  buf.writeFloat32(parseFloat(parts[0]) || 0);
@@ -26109,10 +26418,12 @@ function _writeGear(buf, gear, gearType, comp, version) {
26109
26418
  const ctrlIndex = ctrl ? controllers.indexOf(ctrl) : -1;
26110
26419
  buf.writeInt16(ctrlIndex >= 0 ? ctrlIndex : 0);
26111
26420
  const pagesStr = _strVal(gear.getPages?.()) ?? "";
26112
- const valuesStr = _strVal(gear.getValues?.()) ?? "";
26113
- const defaultStr = _strVal(gear.getDefaultValue?.()) ?? "";
26421
+ const stringValues = gearType === 6 || gearType === 7;
26422
+ const defaultValue = gear.getDefaultValue?.();
26423
+ const defaultStr = _strVal(defaultValue) ?? "";
26114
26424
  const pages = pagesStr ? pagesStr.split(",") : [];
26115
- const values = valuesStr ? valuesStr.split("|") : [];
26425
+ const pageValues = gear.getPageValues();
26426
+ const values = stringValues ? pages.map((page) => pageValues[page] ?? null) : (_strVal(gear.getValues?.()) ?? "").split("|");
26116
26427
  const pageCount = pages.length;
26117
26428
  if (gearType === 0 || gearType === 8) {
26118
26429
  buf.writeInt16(pages.length);
@@ -26120,15 +26431,15 @@ function _writeGear(buf, gear, gearType, comp, version) {
26120
26431
  } else {
26121
26432
  buf.writeInt16(pageCount);
26122
26433
  for (let i = 0; i < pageCount; i++) {
26123
- const value = values[i] ?? "";
26124
- if (_shouldWriteNullGearPage(gearType, value)) {
26434
+ const value = values[i] ?? null;
26435
+ if (value === null || _shouldWriteNullGearPage(gearType, value)) {
26125
26436
  buf.writeS(null);
26126
26437
  continue;
26127
26438
  }
26128
26439
  buf.writeS(pages[i] ?? null);
26129
26440
  _writeGearStatus(buf, gearType, value, version);
26130
26441
  }
26131
- const hasDefault = defaultStr !== "";
26442
+ const hasDefault = stringValues ? defaultValue !== null && defaultValue !== void 0 : defaultStr !== "";
26132
26443
  buf.writeBool(hasDefault);
26133
26444
  if (hasDefault) _writeGearStatus(buf, gearType, defaultStr, version);
26134
26445
  }
@@ -26190,8 +26501,8 @@ function _writeGearStatus(buf, gearType, valueStr, _version) {
26190
26501
  case 2:
26191
26502
  buf.writeInt32(parseInt(parts[0], 10) || 0);
26192
26503
  buf.writeInt32(parseInt(parts[1], 10) || 0);
26193
- buf.writeFloat32(parseFloat(parts[2]) || 1);
26194
- buf.writeFloat32(parseFloat(parts[3]) || 1);
26504
+ buf.writeFloat32(_numberToken(parts[2], 1));
26505
+ buf.writeFloat32(_numberToken(parts[3], 1));
26195
26506
  break;
26196
26507
  case 3:
26197
26508
  buf.writeFloat32(_numberToken(parts[0], 1));
@@ -26373,7 +26684,7 @@ function _writeDisplayList(buf, comp, _doc, pkg, version) {
26373
26684
  buf.pos = saved;
26374
26685
  }
26375
26686
  const cb3 = buf.pos - childIndexPos;
26376
- _writeRelations(buf, child, _createChildIndexMap(comp));
26687
+ _writeRelations(buf, child, childIndexMap);
26377
26688
  let cb4 = 0;
26378
26689
  const isCompOrList = childType === "GComponent" || childType === "GList" || childType === "GTree" || childType === "GButton" || childType === "GLabel" || childType === "GComboBox" || childType === "GProgressBar" || childType === "GSlider" || childType === "GScrollBar";
26379
26690
  const isTextInput = childType === "GTextInput";
@@ -27236,7 +27547,7 @@ var BinaryWriter = class {
27236
27547
  const compExtras = res.getExtras();
27237
27548
  const extType = res.getExtensionType?.() ?? compExtras.extensionType;
27238
27549
  data.writeUint8(extType ? extTypeMap[extType] ?? 0 : 0);
27239
- if (compExtras?._rawBinary) data.writeBuffer(toUint8Array(compExtras._rawBinary));
27550
+ if (compExtras?._rawBinary && !res._isBinaryDirty()) data.writeBuffer(toUint8Array(compExtras._rawBinary));
27240
27551
  else {
27241
27552
  const encoded = encodeComponent(res, doc, pkg, version, data);
27242
27553
  data.writeBuffer(encoded);
@@ -27525,7 +27836,7 @@ function _encodeFontGlyphs(fntData, parentBuf) {
27525
27836
  for (const glyph of fntData.glyphs) {
27526
27837
  const glyphStart = buf.pos;
27527
27838
  buf.writeInt16(0);
27528
- buf.writeInt16(glyph.charId);
27839
+ buf.writeUint16(glyph.charId);
27529
27840
  buf.writeS(glyph.img);
27530
27841
  buf.writeInt32(glyph.x);
27531
27842
  buf.writeInt32(glyph.y);
@@ -27659,8 +27970,8 @@ var PlatformIO = class {
27659
27970
  async writeProject(doc, projectPath, options) {
27660
27971
  return new ProjectWriter(this.createFileSystem()).write(doc, projectPath, options);
27661
27972
  }
27662
- async readBinary(filePath) {
27663
- return new BinaryReader(this.createFileSystem()).read(filePath);
27973
+ async readBinary(filePath, options) {
27974
+ return new BinaryReader(this.createFileSystem(), options).read(filePath);
27664
27975
  }
27665
27976
  async writeBinary(doc, filePath, options) {
27666
27977
  return new BinaryWriter(this.createFileSystem()).write(doc, filePath, options);
@@ -27798,12 +28109,14 @@ function collectComponentReferences(target, ownerPackageId, component) {
27798
28109
  }
27799
28110
  addUnknownReferences(target, ownerPackageId, child.getPropertyOverrides?.().map((property) => property.value));
27800
28111
  for (const gear of child.listGears?.() ?? []) {
27801
- addUnknownReferences(target, ownerPackageId, gear.getValues?.());
28112
+ addUnknownReferences(target, ownerPackageId, gear.getGearType() === GearType.Text || gear.getGearType() === GearType.Icon ? Object.values(gear.getPageValues()) : gear.getValues());
27802
28113
  addUnknownReferences(target, ownerPackageId, gear.getDefaultValue?.());
27803
28114
  }
27804
28115
  }
27805
28116
  addFontReferences(target, ownerPackageId, referenceComponent.getFont?.());
27806
28117
  for (const reference of [
28118
+ referenceComponent.getAddedToStageSound?.(),
28119
+ referenceComponent.getRemovedFromStageSound?.(),
27807
28120
  referenceComponent.getDropdown?.(),
27808
28121
  referenceComponent.getHeaderRes?.(),
27809
28122
  referenceComponent.getFooterRes?.(),
@@ -29578,9 +29891,15 @@ async function writeAtlasPageImage(pkg, inputs, page, atlasFileName, encoder, op
29578
29891
  if (options.extractAlpha) {
29579
29892
  const atlasBuffer = await atlasPipeline.png().toBuffer();
29580
29893
  await encoder(atlasBuffer).removeAlpha().png().toFile(outputFile);
29894
+ options.onFileWritten?.(outputFile);
29581
29895
  const alphaBuffer = await encoder(atlasBuffer).extractChannel("alpha").png().toBuffer();
29582
- await encoder(alphaBuffer).joinChannel([alphaBuffer, alphaBuffer]).png().toFile(`${options.outputPath}/${insertFileNameSuffix(atlasFileName, "!a")}`);
29583
- } else await atlasPipeline.toFile(outputFile);
29896
+ const alphaFile = `${options.outputPath}/${insertFileNameSuffix(atlasFileName, "!a")}`;
29897
+ await encoder(alphaBuffer).joinChannel([alphaBuffer, alphaBuffer]).png().toFile(alphaFile);
29898
+ options.onFileWritten?.(alphaFile);
29899
+ } else {
29900
+ await atlasPipeline.toFile(outputFile);
29901
+ options.onFileWritten?.(outputFile);
29902
+ }
29584
29903
  logger.info(`atlas: Generated ${atlasFileName} (${page.width}x${page.height}, ${page.outputRects.length} sprites)`);
29585
29904
  }
29586
29905
  function inputToCompatRect(input, index) {
@@ -29685,6 +30004,7 @@ async function emitDirectImageOutput(doc, pkg, input, encoder, options, logger,
29685
30004
  top: 0
29686
30005
  }]).png().toFile(outputFile);
29687
30006
  }
30007
+ options.onFileWritten?.(outputFile);
29688
30008
  } catch {
29689
30009
  const message = `atlas: Could not write direct-output atlas "${atlasFileName}".`;
29690
30010
  if (options.strictOutput) throw new Error(message);
@@ -29882,9 +30202,8 @@ async function resolveEditorCompatibleResourceOrder(pkg, allResources, options)
29882
30202
  await addResource(resourceMap.get(resourceId));
29883
30203
  }
29884
30204
  async function addGearIconResources(gear) {
29885
- if (gear.getGearType?.() !== GearType.Icon) return;
29886
- const values = gear.getValues?.();
29887
- if (typeof values === "string" && values) for (const value of values.split("|")) await addResourceByLocalUiUrl(value.trim());
30205
+ if (gear.getGearType() !== GearType.Icon) return;
30206
+ for (const value of Object.values(gear.getPageValues())) await addResourceByLocalUiUrl(value);
29888
30207
  const defaultValue = gear.getDefaultValue?.();
29889
30208
  if (typeof defaultValue === "string") await addResourceByLocalUiUrl(defaultValue);
29890
30209
  }
@@ -30107,6 +30426,9 @@ const FGUI_TYPESCRIPT_BINDER_TEMPLATE = `{{generatedMark}}
30107
30426
  function formatPluginError(error) {
30108
30427
  return error instanceof Error ? error.message : String(error);
30109
30428
  }
30429
+ function shouldAbortPluginFailure(plugin) {
30430
+ return plugin.failureMode !== "warn";
30431
+ }
30110
30432
  //#endregion
30111
30433
  //#region ../functions/src/path-utils.ts
30112
30434
  function trimTrailingSlashes(value) {
@@ -30192,7 +30514,9 @@ async function publishCodeGeneration(doc, options) {
30192
30514
  handled = true;
30193
30515
  logger.info(`publish: Generated code using plugin "${plugin.name}"`);
30194
30516
  } catch (error) {
30195
- logger.warn(`publish: Code generation plugin "${plugin.name}" failed: ${formatPluginError(error)}`);
30517
+ const message = `publish: Code generation plugin "${plugin.name}" failed: ${formatPluginError(error)}`;
30518
+ if (shouldAbortPluginFailure(plugin)) throw new Error(message);
30519
+ logger.warn(message);
30196
30520
  }
30197
30521
  }
30198
30522
  if (handled) return;
@@ -31574,7 +31898,9 @@ async function runPublishPluginHook(plugins, hook, doc, options) {
31574
31898
  try {
31575
31899
  await fn(doc, options);
31576
31900
  } catch (error) {
31577
- logger.warn(`publish: Plugin "${plugin.name}" ${hook} failed: ${formatPluginError(error)}`);
31901
+ const message = `publish: Plugin "${plugin.name}" ${hook} failed: ${formatPluginError(error)}`;
31902
+ if (shouldAbortPluginFailure(plugin)) throw new Error(message);
31903
+ logger.warn(message);
31578
31904
  }
31579
31905
  }
31580
31906
  }
@@ -31720,6 +32046,7 @@ function publish(options) {
31720
32046
  basePath: options.basePath,
31721
32047
  outputPath: options.fs ? plan.outputDir : void 0,
31722
32048
  mkdir: options.fs ? options.fs.mkdir : void 0,
32049
+ onFileWritten: options.atlas?.onFileWritten,
31723
32050
  readFileRaw: options.atlas?.readFileRaw ?? options.fs?.readFileRaw,
31724
32051
  strictOutput: options.fs !== void 0,
31725
32052
  preparedMovieClips,
@@ -31866,15 +32193,9 @@ var NodeIO = class extends PlatformIO {
31866
32193
  },
31867
32194
  async readdir(dirPath) {
31868
32195
  const entries = await fs$1.readdir(dirPath, { withFileTypes: true });
31869
- return (await Promise.all(entries.map(async (entry) => {
31870
- if (entry.isDirectory()) return entry.name;
31871
- if (!entry.isSymbolicLink()) return null;
31872
- try {
31873
- return (await fs$1.stat(path$1.join(dirPath, entry.name))).isDirectory() ? entry.name : null;
31874
- } catch {
31875
- return null;
31876
- }
31877
- }))).filter((entry) => entry !== null);
32196
+ const symlink = entries.find((entry) => entry.isSymbolicLink());
32197
+ if (symlink) throw new Error(`Symbolic links are not supported in project directories: ${path$1.join(dirPath, symlink.name)}`);
32198
+ return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
31878
32199
  },
31879
32200
  async exists(filePath) {
31880
32201
  try {
@@ -31917,10 +32238,14 @@ async function resolveFairyPath(input) {
31917
32238
  //#endregion
31918
32239
  //#region src/commands/inspect.ts
31919
32240
  function registerInspectCommand(program) {
31920
- program.command("inspect").description("Show project contents report").argument("<project-dir>", "Project root directory or .fairy file").action(async (projectDir) => {
32241
+ program.command("inspect").description("Show project contents report").argument("<project-dir>", "Project root directory or .fairy file").option("--json", "Print the machine-readable inspection report").action(async (projectDir, options) => {
31921
32242
  const fairyPath = await resolveFairyPath(projectDir);
31922
- console.log(`Project: ${fairyPath}\n`);
31923
- printReport(inspect(await new NodeIO().readProject(fairyPath)));
32243
+ const report = inspect(await new NodeIO().readProject(fairyPath));
32244
+ if (options.json) printJson("inspect", report);
32245
+ else {
32246
+ console.log(`Project: ${fairyPath}\n`);
32247
+ printReport(report);
32248
+ }
31924
32249
  });
31925
32250
  }
31926
32251
  function printReport(report) {
@@ -31959,16 +32284,33 @@ async function loadPlugins(doc, pluginsDir) {
31959
32284
  for (const entry of entries) {
31960
32285
  if (!entry.isDirectory()) continue;
31961
32286
  const pluginDir = path.join(pluginsDir, entry.name);
32287
+ let manifest;
32288
+ try {
32289
+ manifest = await readPluginManifest(fs, path, pluginDir);
32290
+ } catch (error) {
32291
+ doc.getLogger().warn(`publish: Plugin "${entry.name}" was skipped: ${formatPluginError(error)}`);
32292
+ continue;
32293
+ }
32294
+ if (!manifest) continue;
32295
+ if (!manifest.main) {
32296
+ const error = /* @__PURE__ */ new Error(`Codegen plugin "${manifest.name}" is missing package.json main.`);
32297
+ if (manifest.required) throw error;
32298
+ doc.getLogger().warn(`publish: Plugin "${manifest.name}" was skipped: ${error.message}`);
32299
+ continue;
32300
+ }
31962
32301
  try {
31963
- const manifest = await readPluginManifest(fs, path, pluginDir);
31964
- if (!manifest) continue;
31965
32302
  const plugin = await loadPlugin(resolvePluginMain(path, pluginDir, manifest));
31966
32303
  plugins.push({
31967
32304
  name: manifest.name,
31968
- plugin
32305
+ plugin,
32306
+ failureMode: manifest.required ? "abort" : manifest.failureMode
31969
32307
  });
31970
32308
  } catch (error) {
31971
- doc.getLogger().warn(`publish: Plugin "${entry.name}" was skipped: ${formatPluginError(error)}`);
32309
+ if (!manifest.required && manifest.failureMode === "warn") {
32310
+ doc.getLogger().warn(`publish: Plugin "${manifest.name}" was skipped: ${formatPluginError(error)}`);
32311
+ continue;
32312
+ }
32313
+ throw new Error(`publish: Failed to load plugin "${manifest.name}": ${formatPluginError(error)}`);
31972
32314
  }
31973
32315
  }
31974
32316
  return plugins;
@@ -31978,7 +32320,6 @@ async function readPluginManifest(fs, path, pluginDir) {
31978
32320
  const content = await fs.readFile(manifestPath, "utf-8");
31979
32321
  const manifest = JSON.parse(content);
31980
32322
  if (!manifest.name) throw new Error(`Codegen plugin at ${pluginDir} is missing package.json name.`);
31981
- if (!manifest.main) throw new Error(`Codegen plugin "${manifest.name}" is missing package.json main.`);
31982
32323
  return manifest;
31983
32324
  }
31984
32325
  function resolvePluginMain(path, pluginDir, manifest) {
@@ -31999,7 +32340,7 @@ function isObject(value) {
31999
32340
  //#endregion
32000
32341
  //#region ../functions/src/adapters/node/publish.ts
32001
32342
  const importNative$2 = new Function("id", "return import(id)");
32002
- async function createNodePublishFileSystem() {
32343
+ async function createNodePublishFileSystem(files) {
32003
32344
  const [fs, path] = await Promise.all([importNative$2("node:fs/promises"), importNative$2("node:path")]);
32004
32345
  return {
32005
32346
  async readFileRaw(filePath) {
@@ -32009,6 +32350,7 @@ async function createNodePublishFileSystem() {
32009
32350
  async writeFileRaw(filePath, data) {
32010
32351
  await fs.mkdir(path.dirname(filePath), { recursive: true });
32011
32352
  await fs.writeFile(filePath, data);
32353
+ files.add(path.resolve(filePath));
32012
32354
  },
32013
32355
  async mkdir(dirPath) {
32014
32356
  await fs.mkdir(dirPath, { recursive: true });
@@ -32018,6 +32360,7 @@ async function createNodePublishFileSystem() {
32018
32360
  },
32019
32361
  async deleteFile(filePath) {
32020
32362
  await fs.rm(filePath, { force: true });
32363
+ files.delete(path.resolve(filePath));
32021
32364
  },
32022
32365
  join(...paths) {
32023
32366
  return path.join(...paths);
@@ -32043,6 +32386,77 @@ async function loadNodePublishPlugins(document, assetsPath) {
32043
32386
  if (!projectDir) return [];
32044
32387
  return loadPlugins(document, (await importNative$2("node:path")).join(projectDir, "plugins"));
32045
32388
  }
32389
+ async function publishToStagedOutput(output, run) {
32390
+ const [fs, path, { randomUUID }] = await Promise.all([
32391
+ importNative$2("node:fs/promises"),
32392
+ importNative$2("node:path"),
32393
+ importNative$2("node:crypto")
32394
+ ]);
32395
+ const target = path.resolve(output);
32396
+ const parent = path.dirname(target);
32397
+ const name = path.basename(target);
32398
+ const staging = path.join(parent, `.${name}.publish-${randomUUID()}`);
32399
+ const backup = path.join(parent, `.${name}.publish-backup-${randomUUID()}`);
32400
+ await fs.mkdir(parent, { recursive: true });
32401
+ let existed = false;
32402
+ try {
32403
+ const stat = await fs.lstat(target);
32404
+ if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error(`publishNode: output must be a regular directory: ${target}`);
32405
+ await assertNoSymlinks(fs, path, target);
32406
+ existed = true;
32407
+ } catch (error) {
32408
+ if (error.code !== "ENOENT") throw error;
32409
+ }
32410
+ try {
32411
+ if (existed) await fs.cp(target, staging, {
32412
+ recursive: true,
32413
+ errorOnExist: true,
32414
+ force: false
32415
+ });
32416
+ else await fs.mkdir(staging);
32417
+ } catch (error) {
32418
+ await fs.rm(staging, {
32419
+ recursive: true,
32420
+ force: true
32421
+ });
32422
+ throw error;
32423
+ }
32424
+ try {
32425
+ await run(staging);
32426
+ } catch (error) {
32427
+ await fs.rm(staging, {
32428
+ recursive: true,
32429
+ force: true
32430
+ });
32431
+ throw error;
32432
+ }
32433
+ if (!existed) {
32434
+ await fs.rename(staging, target);
32435
+ return;
32436
+ }
32437
+ await fs.rename(target, backup);
32438
+ try {
32439
+ await fs.rename(staging, target);
32440
+ } catch (error) {
32441
+ await fs.rename(backup, target);
32442
+ await fs.rm(staging, {
32443
+ recursive: true,
32444
+ force: true
32445
+ });
32446
+ throw error;
32447
+ }
32448
+ await fs.rm(backup, {
32449
+ recursive: true,
32450
+ force: true
32451
+ }).catch(() => void 0);
32452
+ }
32453
+ async function assertNoSymlinks(fs, path, directory) {
32454
+ for (const entry of await fs.readdir(directory, { withFileTypes: true })) {
32455
+ const entryPath = path.join(directory, entry.name);
32456
+ if (entry.isSymbolicLink()) throw new Error(`publishNode: symbolic links are not supported in output directories: ${entryPath}`);
32457
+ if (entry.isDirectory()) await assertNoSymlinks(fs, path, entryPath);
32458
+ }
32459
+ }
32046
32460
  /**
32047
32461
  * Publish a FairyGUI project through the standard Node host adapter.
32048
32462
  *
@@ -32052,20 +32466,40 @@ async function loadNodePublishPlugins(document, assetsPath) {
32052
32466
  */
32053
32467
  async function publishNode(options) {
32054
32468
  const { document, assetsPath: configuredAssetsPath, atlas, encoder: configuredEncoder, plugins: configuredPlugins, ...publishOptions } = options;
32055
- const [fileSystem, assetsPath] = await Promise.all([createNodePublishFileSystem(), resolveNodeAssetsPath(document, configuredAssetsPath)]);
32469
+ const files = /* @__PURE__ */ new Set();
32470
+ const [fs, path] = await Promise.all([importNative$2("node:fs/promises"), importNative$2("node:path")]);
32471
+ const [fileSystem, assetsPath] = await Promise.all([createNodePublishFileSystem(files), resolveNodeAssetsPath(document, configuredAssetsPath)]);
32056
32472
  const [encoder, plugins] = await Promise.all([configuredEncoder === void 0 ? loadSharpBackend() : Promise.resolve(configuredEncoder), configuredPlugins === void 0 ? loadNodePublishPlugins(document, assetsPath) : Promise.resolve(configuredPlugins)]);
32057
32473
  if (!encoder) throw new Error("publishNode: Sharp is required for a complete publish. Install sharp or provide an encoder.");
32058
- await document.transform(publish({
32059
- ...publishOptions,
32060
- basePath: assetsPath,
32061
- encoder,
32062
- atlas: {
32063
- ...atlas,
32064
- readFileRaw: fileSystem.readFileRaw
32065
- },
32066
- fs: fileSystem,
32067
- plugins
32068
- }));
32474
+ const result = { files: [] };
32475
+ const run = async (output) => {
32476
+ await document.transform(publish({
32477
+ ...publishOptions,
32478
+ output,
32479
+ basePath: assetsPath,
32480
+ encoder,
32481
+ atlas: {
32482
+ ...atlas,
32483
+ readFileRaw: fileSystem.readFileRaw,
32484
+ onFileWritten(file) {
32485
+ files.add(path.resolve(file));
32486
+ atlas?.onFileWritten?.(file);
32487
+ }
32488
+ },
32489
+ fs: fileSystem,
32490
+ plugins
32491
+ }));
32492
+ result.files = await Promise.all([...files].sort().map(async (file) => {
32493
+ const relative = output ? path.relative(output, file) : null;
32494
+ return {
32495
+ path: relative !== null && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative) ? path.resolve(publishOptions.output, relative) : file,
32496
+ size: (await fs.stat(file)).size
32497
+ };
32498
+ }));
32499
+ };
32500
+ if (publishOptions.output) await publishToStagedOutput(publishOptions.output, run);
32501
+ else await run(void 0);
32502
+ return result;
32069
32503
  }
32070
32504
  //#endregion
32071
32505
  //#region ../functions/src/adapters/node/restore.ts
@@ -32292,7 +32726,7 @@ function parseProjectType(value) {
32292
32726
  //#endregion
32293
32727
  //#region src/commands/publish.ts
32294
32728
  function registerPublishCommand(program) {
32295
- program.command("publish").description("Publish project to binary outputs and configured generated code").argument("<project-dir>", "Project root directory or .fairy file").option("-o, --output <dir>", "Override project or package publish output directory").option("-c, --compressed", "Compress binary data (overrides project setting)").option("-p, --packages <a,b,c>", "Only publish specific packages (comma-separated)").option("-b, --branch <name>", "Active branch used by \"主干合并活跃分支\"; omit for main branch").option("-t, --project-type <name|id>", "Override project type (for example: unity, layabox, cocoscreator, 0, 4, 3)").action(async (projectDir, options) => {
32729
+ program.command("publish").description("Publish project to binary outputs and configured generated code").argument("<project-dir>", "Project root directory or .fairy file").option("--json", "Print one JSON result or error (exit 0: success, 1: workflow failure, 2: invalid arguments)").option("-o, --output <dir>", "Override project or package publish output directory").option("-c, --compressed", "Compress binary data (overrides project setting)").option("-p, --packages <a,b,c>", "Only publish specific packages (comma-separated)").option("-b, --branch <name>", "Active branch used by \"主干合并活跃分支\"; omit for main branch").option("-t, --project-type <name|id>", "Override project type (for example: unity, layabox, cocoscreator, 0, 4, 3)").action(async (projectDir, options) => {
32296
32730
  const fairyPath = await resolveFairyPath(projectDir);
32297
32731
  const projectRootDir = path.dirname(fairyPath);
32298
32732
  const outputDir = options.output ? path.resolve(options.output) : void 0;
@@ -32308,7 +32742,7 @@ function registerPublishCommand(program) {
32308
32742
  });
32309
32743
  console.log(`Settings: ext=${resolved.fileExtension}, compressed=${resolved.compressed}`);
32310
32744
  if (options.branch) console.log(`Active branch: ${options.branch}`);
32311
- await publishNode({
32745
+ const result = await publishNode({
32312
32746
  document: doc,
32313
32747
  output: outputDir,
32314
32748
  compressed: resolved.compressed,
@@ -32318,13 +32752,17 @@ function registerPublishCommand(program) {
32318
32752
  atlas: resolved.atlas,
32319
32753
  branch: options.branch
32320
32754
  });
32755
+ if (options.json) {
32756
+ printJson("publish", result);
32757
+ return;
32758
+ }
32321
32759
  console.log(`\nDone!${outputDir ? ` Output override: ${outputDir}` : ""}`);
32322
32760
  });
32323
32761
  }
32324
32762
  //#endregion
32325
32763
  //#region src/commands/restore.ts
32326
32764
  function registerRestoreCommand(program) {
32327
- program.command("restore").description("Recover a project directory from trusted local published artifacts").argument("<release-dir>", "Published release directory").requiredOption("-o, --output <dir>", "Output project directory").option("-p, --packages <a,b,c>", "Only restore specific packages (comma-separated)").option("-f, --force", "Replace a non-empty output directory only after a complete staged restore").option("-t, --project-type <name|id>", "Override restored project type; default is unity").action(async (releaseDir, options) => {
32765
+ program.command("restore").description("Recover a project directory from trusted local published artifacts").argument("<release-dir>", "Published release directory").option("--json", "Print one JSON result or error (exit 0: success, 1: workflow failure, 2: invalid arguments)").requiredOption("-o, --output <dir>", "Output project directory").option("-p, --packages <a,b,c>", "Only restore specific packages (comma-separated)").option("-f, --force", "Replace a non-empty output directory only after a complete staged restore").option("-t, --project-type <name|id>", "Override restored project type; default is unity").action(async (releaseDir, options) => {
32328
32766
  const inputDir = path.resolve(releaseDir);
32329
32767
  const outputDir = path.resolve(options.output);
32330
32768
  const pkgFilter = options.packages ? options.packages.split(",").map((value) => value.trim()).filter(Boolean) : void 0;
@@ -32338,6 +32776,17 @@ function registerRestoreCommand(program) {
32338
32776
  projectType
32339
32777
  });
32340
32778
  const packages = result.document.getRoot().listPackages();
32779
+ if (options.json) {
32780
+ printJson("restore", {
32781
+ projectPath: result.projectPath,
32782
+ packages: packages.map((pkg) => ({
32783
+ id: pkg.getId(),
32784
+ name: pkg.getName()
32785
+ })),
32786
+ warnings: result.warnings
32787
+ });
32788
+ return;
32789
+ }
32341
32790
  console.log(`\nDone! Output: ${result.projectPath}`);
32342
32791
  console.log(`Packages: ${packages.map((pkg) => pkg.getName()).join(", ")}`);
32343
32792
  for (const warning of result.warnings) console.warn(`Warning: ${warning}`);
@@ -32349,7 +32798,10 @@ function registerValidateCommand(program) {
32349
32798
  program.command("validate").description("Validate project structure, references, and source files").argument("<project-dir>", "Project root directory or .fairy file").option("--json", "Print the machine-readable validation report").action(async (projectDir, options) => {
32350
32799
  const fairyPath = await resolveFairyPath(projectDir);
32351
32800
  const report = await validateProjectNode(fairyPath);
32352
- if (options.json) console.log(JSON.stringify(report, null, 2));
32801
+ if (options.json) printJson("validate", report, report.status === "valid" ? void 0 : {
32802
+ code: report.status === "invalid" ? "validation_failed" : "validation_incomplete",
32803
+ message: `Project validation is ${report.status}; inspect result.diagnostics.`
32804
+ });
32353
32805
  else {
32354
32806
  console.log(`${report.status.toUpperCase()}: ${fairyPath}`);
32355
32807
  for (const diagnostic of report.diagnostics) {
@@ -32357,14 +32809,14 @@ function registerValidateCommand(program) {
32357
32809
  console.log(`${diagnostic.severity.toUpperCase()} ${diagnostic.code} ${diagnostic.path}${source}: ${diagnostic.message}`);
32358
32810
  }
32359
32811
  }
32360
- process.exitCode = report.status === "valid" ? 0 : report.status === "invalid" ? 1 : 2;
32812
+ process.exitCode = report.status === "valid" ? 0 : report.status === "invalid" ? 1 : 3;
32361
32813
  });
32362
32814
  }
32363
32815
  //#endregion
32364
32816
  //#region src/utils/package-version.ts
32365
32817
  const require$1 = createRequire(import.meta.url);
32366
32818
  function getInjectedPackageVersion() {
32367
- const version = "0.3.0";
32819
+ const version = "0.4.0";
32368
32820
  return typeof version === "string" && true ? version : null;
32369
32821
  }
32370
32822
  function readPackageVersion() {
@@ -32377,16 +32829,181 @@ function readPackageVersion() {
32377
32829
  return "0.0.0-dev";
32378
32830
  }
32379
32831
  //#endregion
32832
+ //#region src/commands/docs.ts
32833
+ function registerDocsCommand(program) {
32834
+ const docs = program.command("docs").description("Read version-bound installed documentation offline (no download or repository required)");
32835
+ function print(command, options, read) {
32836
+ const version = getInstalledDocumentationVersion();
32837
+ try {
32838
+ if (version.packageVersion !== readPackageVersion()) throw new Error("CLI and installed documentation versions differ; ask the host to reconcile the installation.");
32839
+ const result = read();
32840
+ if (options.json) printJson(command, result);
32841
+ else {
32842
+ console.log(`${version.packageName}@${version.packageVersion} | contract ${version.BACKEND_CONTRACT_VERSION} | schema ${version.BACKEND_CAPABILITY_SCHEMA_VERSION}`);
32843
+ console.log("text" in result ? result.text : result.documents.map((entry) => `${entry.id}\t${entry.title}`).join("\n"));
32844
+ }
32845
+ } catch (error) {
32846
+ const message = error instanceof Error ? error.message : String(error);
32847
+ if (options.json) printJsonError(command, {
32848
+ code: "documentation_unavailable",
32849
+ message
32850
+ });
32851
+ else console.error(message);
32852
+ process.exitCode = 1;
32853
+ }
32854
+ }
32855
+ docs.command("ls").description("List installed document IDs, URIs and version").option("--json", "Print JSON").action((options) => print("docs ls", options, getInstalledDocumentationIndex));
32856
+ docs.command("find <query>").description("Search only the installed corpus").option("--json", "Print JSON").action((query, options) => print("docs find", options, () => findInstalledDocumentation(query)));
32857
+ docs.command("cat <id>").description("Read an exact ID from docs ls, not a filesystem path").option("--json", "Print JSON").action((id, options) => print("docs cat", options, () => readInstalledDocumentation(id)));
32858
+ docs.command("diagnostic <code>").description("Read a diagnostic recovery guide; never execute repairs").option("--json", "Print JSON").action((code, options) => print("docs diagnostic", options, () => readInstalledDocumentation(`diagnostics/${code}`)));
32859
+ docs.command("schema <kind>").description("Read a self-contained operation schema or cli/<command> output schema").option("--json", "Print JSON").action((kind, options) => print("docs schema", options, () => readInstalledDocumentation(kind.startsWith("cli/") ? kind : `operations/${kind}`)));
32860
+ }
32861
+ //#endregion
32862
+ //#region src/commands/doctor.ts
32863
+ async function inspectNativeImages() {
32864
+ try {
32865
+ const sharp = (await import("sharp")).default;
32866
+ for (const format of ["png", "jpeg"]) {
32867
+ const { data, info } = await sharp(await sharp({ create: {
32868
+ width: 1,
32869
+ height: 1,
32870
+ channels: 3,
32871
+ background: "#204060"
32872
+ } }).toFormat(format).toBuffer()).raw().toBuffer({ resolveWithObject: true });
32873
+ if (info.width !== 1 || info.height !== 1 || info.channels !== 3 || data.length !== 3) throw new Error(`${format} pixel decoding returned unexpected dimensions.`);
32874
+ }
32875
+ return {
32876
+ id: "native-images",
32877
+ status: "ok",
32878
+ version: sharp.versions.sharp,
32879
+ message: "In-memory PNG/JPEG encoding and pixel decoding passed."
32880
+ };
32881
+ } catch (error) {
32882
+ return {
32883
+ id: "native-images",
32884
+ status: "incomplete",
32885
+ message: `Native image capability unavailable or failed; ask the host to check Sharp before publishing/restoring. ${error instanceof Error ? error.message : String(error)}`
32886
+ };
32887
+ }
32888
+ }
32889
+ async function inspectDirectory(id, requested) {
32890
+ const check = {
32891
+ id,
32892
+ status: "error",
32893
+ path: path.resolve(requested),
32894
+ inspectedPath: path.resolve(requested),
32895
+ exists: null,
32896
+ message: ""
32897
+ };
32898
+ try {
32899
+ for (;;) {
32900
+ try {
32901
+ await fs.lstat(check.inspectedPath);
32902
+ } catch (error) {
32903
+ if (error.code !== "ENOENT") throw error;
32904
+ if (check.inspectedPath === check.path) check.exists = false;
32905
+ const parent = path.dirname(check.inspectedPath);
32906
+ if (id === "temp-directory" || parent === check.inspectedPath) throw error;
32907
+ check.inspectedPath = parent;
32908
+ continue;
32909
+ }
32910
+ if (check.inspectedPath === check.path) check.exists = true;
32911
+ check.inspectedPath = await fs.realpath(check.inspectedPath);
32912
+ if (!(await fs.stat(check.inspectedPath)).isDirectory()) throw new Error("The inspected path is not a directory.");
32913
+ await fs.access(check.inspectedPath, constants.R_OK | constants.W_OK | constants.X_OK);
32914
+ check.status = "ok";
32915
+ check.message = check.exists ? "Directory access flags passed; no files written." : "Target absent; only the nearest existing ancestor passed access flags. Nothing created.";
32916
+ break;
32917
+ }
32918
+ } catch (error) {
32919
+ check.message = error instanceof Error ? error.message : String(error);
32920
+ }
32921
+ return check;
32922
+ }
32923
+ function registerDoctorCommand(program) {
32924
+ program.command("doctor").description("Diagnose versions, native images and directory access; optionally validate a project; never write or repair").argument("[project-dir]", "Optional project directory or .fairy file for Node validation").option("--output-dir <directory>", "Check output directory access (or its existing ancestor), without creating it", (value) => {
32925
+ if (!value) throw new InvalidArgumentError("Output directory must not be empty.");
32926
+ return value;
32927
+ }).option("--json", "Print the complete machine-readable product diagnosis").action(async (projectDir, options) => {
32928
+ const version = getInstalledDocumentationVersion();
32929
+ const errors = [];
32930
+ const cliVersion = readPackageVersion();
32931
+ if (cliVersion !== version.packageVersion) errors.push({
32932
+ code: "installed_version_mismatch",
32933
+ message: "CLI and documentation versions differ; ask the host to reconcile the installation."
32934
+ });
32935
+ const minimumMajor = /^>=(\d+)$/u.exec(version.nodeEngine)?.[1];
32936
+ if (!minimumMajor || Number(process.versions.node.split(".")[0]) < Number(minimumMajor)) errors.push({
32937
+ code: "unsupported_node_version",
32938
+ message: `Installed package requires Node ${version.nodeEngine}.`
32939
+ });
32940
+ const capabilities = createNodeBackendRuntime().getCapabilities();
32941
+ const checks = await Promise.all([
32942
+ inspectNativeImages(),
32943
+ inspectDirectory("temp-directory", tmpdir()),
32944
+ ...options.outputDir === void 0 ? [] : [inspectDirectory("output-directory", options.outputDir)]
32945
+ ]);
32946
+ let project = null;
32947
+ let projectPath = null;
32948
+ if (projectDir) try {
32949
+ projectPath = await resolveFairyPath(projectDir);
32950
+ project = await validateProjectNode(projectPath);
32951
+ } catch (error) {
32952
+ errors.push({
32953
+ code: "project_check_failed",
32954
+ message: error instanceof Error ? error.message : String(error)
32955
+ });
32956
+ }
32957
+ const status = errors.length || !capabilities.ok || project?.status === "invalid" || checks.some((check) => check.status === "error") ? "error" : project?.status === "incomplete" || checks.some((check) => check.status === "incomplete") ? "incomplete" : "ready";
32958
+ const report = {
32959
+ scope: "installed-product",
32960
+ ...version,
32961
+ cliVersion,
32962
+ nodeVersion: process.versions.node,
32963
+ status,
32964
+ errors,
32965
+ checks,
32966
+ capabilities,
32967
+ projectPath,
32968
+ project,
32969
+ limits: [
32970
+ "No installation, configuration changes, probe writes, session opening or repair.",
32971
+ "Without a project, project source bytes are not tested; native images use only an in-memory PNG/JPEG sample.",
32972
+ "Directory access flags do not prove effective ACL permissions, available space, later writes, rename/rollback or continued access. Missing output directories are not created.",
32973
+ "Capabilities are declarations, not proof of publish/restore or runtime rendering. Project plugins and configured output destinations are not executed or checked; only an explicit --output-dir is inspected."
32974
+ ]
32975
+ };
32976
+ if (options.json) printJson("doctor", report, status === "ready" ? void 0 : {
32977
+ code: status === "error" ? "doctor_failed" : "doctor_incomplete",
32978
+ message: `Product diagnosis is ${status}; inspect result.checks, result.errors and result.project.`
32979
+ });
32980
+ else {
32981
+ console.log(`${status.toUpperCase()}: OpenFairyGUI ${cliVersion} (documentation ${version.packageVersion}, Node ${report.nodeVersion})`);
32982
+ for (const error of errors) console.log(`${error.code}: ${error.message}`);
32983
+ for (const check of checks) console.log(`${check.status} ${check.id}${"path" in check ? ` ${check.path} (inspected ${check.inspectedPath})` : ""}: ${check.message}`);
32984
+ if (project) {
32985
+ console.log(`Project ${project.status}: ${projectPath}`);
32986
+ for (const diagnostic of project.diagnostics) console.log(`${diagnostic.severity} ${diagnostic.code} ${diagnostic.path}: ${diagnostic.message}`);
32987
+ }
32988
+ console.log(report.limits.join("\n"));
32989
+ }
32990
+ process.exitCode = status === "ready" ? 0 : status === "error" ? 1 : 3;
32991
+ });
32992
+ }
32993
+ //#endregion
32380
32994
  //#region src/cli.ts
32381
32995
  const PACKAGE_VERSION = readPackageVersion();
32382
32996
  function createProgram() {
32383
32997
  const program = new Command("ofgui");
32998
+ configureJson(program);
32384
32999
  program.description("FairyGUI Headless Authoring CLI").version(PACKAGE_VERSION).showHelpAfterError();
32385
33000
  registerInspectCommand(program);
32386
33001
  registerPublishCommand(program);
32387
33002
  registerRestoreCommand(program);
32388
33003
  registerValidateCommand(program);
32389
33004
  registerBackendCapabilitiesCommand(program);
33005
+ registerDocsCommand(program);
33006
+ registerDoctorCommand(program);
32390
33007
  program.addHelpText("after", [
32391
33008
  "",
32392
33009
  "Alias:",
@@ -32397,12 +33014,19 @@ function createProgram() {
32397
33014
  ].join("\n"));
32398
33015
  return program;
32399
33016
  }
32400
- async function main() {
32401
- await createProgram().parseAsync(process.argv);
33017
+ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
33018
+ const program = createProgram();
33019
+ program.parseAsync(process.argv).catch((err) => {
33020
+ if (err instanceof CommanderError && err.exitCode === 0) return;
33021
+ const command = parsedCommand(program);
33022
+ const message = err instanceof Error ? err.message : String(err);
33023
+ if (wantsJson(process.argv)) printJsonError(command, {
33024
+ code: err instanceof CommanderError ? "invalid_arguments" : command === "publish" || command === "restore" ? `${command}_failed` : "command_failed",
33025
+ message
33026
+ });
33027
+ else console.error(message);
33028
+ process.exitCode = err instanceof CommanderError ? 2 : 1;
33029
+ });
32402
33030
  }
32403
- main().catch((err) => {
32404
- console.error(err instanceof Error ? err.message : String(err));
32405
- process.exit(1);
32406
- });
32407
33031
  //#endregion
32408
- export {};
33032
+ export { createProgram };