@openfairygui/cli 0.3.1 → 0.5.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
@@ -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.1`;
893
+ const VERSION = `v0.5.0-alpha.1`;
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. */
@@ -6981,7 +7042,13 @@ var Gear = class extends Property {
6981
7042
  return this.get("gearType");
6982
7043
  }
6983
7044
  setGearType(v) {
6984
- 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);
6985
7052
  }
6986
7053
  getController() {
6987
7054
  return this.getRef("controller");
@@ -6993,13 +7060,32 @@ var Gear = class extends Property {
6993
7060
  return this.get("pages");
6994
7061
  }
6995
7062
  setPages(v) {
6996
- 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;
6997
7069
  }
7070
+ /** Delimited protocol values. Text/Icon states are owned by pageValues. */
6998
7071
  getValues() {
6999
- 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("|");
7000
7079
  }
7001
7080
  setValues(v) {
7002
- 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] ?? ""]));
7003
7089
  }
7004
7090
  getCondition() {
7005
7091
  return this.get("condition");
@@ -7014,21 +7100,25 @@ var Gear = class extends Property {
7014
7100
  return this.set("defaultValue", v);
7015
7101
  }
7016
7102
  getPageValues() {
7017
- return this.get("pageValues");
7103
+ return { ...this.get("pageValues") };
7018
7104
  }
7019
7105
  setPageValues(v) {
7020
- 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 });
7021
7108
  }
7022
7109
  setPageValue(pageId, value) {
7023
7110
  const values = {
7024
7111
  ...this.getPageValues(),
7025
7112
  [pageId]: value
7026
7113
  };
7027
- return this.set("pageValues", values);
7114
+ return this.setPageValues(values);
7028
7115
  }
7029
7116
  getPageValue(pageId) {
7030
7117
  return this.getPageValues()[pageId] ?? this.getDefaultValue();
7031
7118
  }
7119
+ hasStringValues() {
7120
+ return this.getGearType() === GearType.Text || this.getGearType() === GearType.Icon;
7121
+ }
7032
7122
  getPositionsInPercent() {
7033
7123
  return this.get("positionsInPercent");
7034
7124
  }
@@ -16558,6 +16648,12 @@ function isFiniteUamPoint(value) {
16558
16648
  const point = value;
16559
16649
  return typeof point.x === "number" && Number.isFinite(point.x) && typeof point.y === "number" && Number.isFinite(point.y);
16560
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
+ }
16561
16657
  function isFiniteUamSize(value) {
16562
16658
  if (typeof value !== "object" || value === null) return false;
16563
16659
  const size = value;
@@ -16947,6 +17043,9 @@ function validateControllerAction(action, knownPageIds, knownChildIds, path, iss
16947
17043
  if (action.targetNodeId && !knownChildIds.has(action.targetNodeId)) pushIssue(issues, `${path}.targetNodeId`, `Unknown target node id "${action.targetNodeId}".`);
16948
17044
  }
16949
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
+ }
16950
17049
  const controller = controllerMap.get(gear.controllerName);
16951
17050
  if (!controller) {
16952
17051
  pushIssue(issues, `${path}.controllerName`, `Unknown gear controller "${gear.controllerName}".`);
@@ -17093,7 +17192,12 @@ function validateDisplayNode(node, controllerMap, knownChildIds, knownGroupIds,
17093
17192
  if ("group" in node) pushIssue(issues, `${path}.group`, `${node.kind} display nodes must not declare a group reference.`);
17094
17193
  } else if (!("group" in node) || typeof node.group !== "string") pushIssue(issues, `${path}.group`, "Display node group must be a string.");
17095
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.`);
17096
- 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
+ }
17097
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}".`);
17098
17202
  }
17099
17203
  function validateUamProject(project) {
@@ -17444,12 +17548,18 @@ function parseLookGearValue(value) {
17444
17548
  };
17445
17549
  }
17446
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 };
17447
17553
  if (!value || value === "-") return null;
17448
17554
  const parts = value.split(",");
17449
17555
  switch (kind) {
17450
17556
  case "xy": return {
17451
17557
  x: parseNumber(parts[0], 0),
17452
- 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
+ } : {}
17453
17563
  };
17454
17564
  case "size": return {
17455
17565
  width: parseNumber(parts[0], 0),
@@ -17467,8 +17577,6 @@ function parseGenericGearValue(kind, value) {
17467
17577
  animationName: parts[2] ?? "",
17468
17578
  skinName: parts[3] ?? ""
17469
17579
  };
17470
- case "text": return { text: value };
17471
- case "icon": return { icon: value };
17472
17580
  case "fontSize": return { fontSize: parseNumber(parts[0], 12) };
17473
17581
  }
17474
17582
  }
@@ -17725,16 +17833,18 @@ function liftGears(gears) {
17725
17833
  [GearType.FontSize, "fontSize"]
17726
17834
  ]).get(gear.getGearType());
17727
17835
  if (!kind) throw new Error(`UAM lift does not support gear type "${gear.getGearType()}" in Gate A.`);
17728
- const values = gear.getValues() ? gear.getValues().split("|") : [];
17729
- 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()}`;
17730
17840
  const base = {
17731
17841
  name: gear.getName(),
17732
17842
  controllerName: gear.getController()?.getName() ?? "",
17733
17843
  states: pages.map((pageId, index) => ({
17734
17844
  pageId,
17735
- value: parseGenericGearValue(kind, values[index] ?? null)
17845
+ value: parseGenericGearValue(kind, stringValues ? pageValues[pageId] ?? null : values[index] ?? null)
17736
17846
  })),
17737
- defaultValue: parseGenericGearValue(kind, defaultValue) ?? defaultGenericGearValue(kind),
17847
+ defaultValue: parseGenericGearValue(kind, defaultValue) ?? (stringValues || kind === "xy" ? null : defaultGenericGearValue(kind)),
17738
17848
  condition: gear.getCondition(),
17739
17849
  positionsInPercent: gear.getPositionsInPercent(),
17740
17850
  tween: gear.getTween(),
@@ -20391,7 +20501,7 @@ function parseGear(_ctx, doc, obj, gearTag, attrs, localControllers) {
20391
20501
  const pages = readXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.pages);
20392
20502
  if (pages) gear.setPages(pages);
20393
20503
  const values = readXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.values);
20394
- if (values) gear.setValues(values);
20504
+ if (gearType === GearType.Text || gearType === GearType.Icon || values) gear.setValues(values ?? "");
20395
20505
  const defaultValue = readXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.default);
20396
20506
  if (defaultValue !== void 0) gear.setDefaultValue(defaultValue);
20397
20507
  const condition = readXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.condition);
@@ -22996,6 +23106,7 @@ function serializeChild(obj) {
22996
23106
  const objectProtocol = DISPLAY_OBJECT_PROTOCOL_BY_TYPE[type] ?? PROJECT_XML_PROTOCOL.componentInstance;
22997
23107
  writeCommonDisplayState(attrs, typedObj, objectProtocol);
22998
23108
  const gearChildNameSet = getProtocolGearChildNameSet(objectProtocol);
23109
+ assertDisplayObjectGearXmlValues(obj);
22999
23110
  for (const gear of obj.listGears()) {
23000
23111
  const gearTag = GEAR_TAG[gear.getGearType()];
23001
23112
  if (!gearTag || !gearChildNameSet.has(gearTag)) continue;
@@ -23023,12 +23134,36 @@ function serializeChild(obj) {
23023
23134
  if (extensionChildName && extensionValue !== void 0) attrs[extensionChildName] = extensionValue;
23024
23135
  return attrs;
23025
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
+ }
23026
23151
  function serializeGear(gear, ownerType, ownerName) {
23027
23152
  const ctrl = gear.getController();
23028
23153
  const attrs = {};
23029
23154
  if (ctrl) writeXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.controller, ctrl.getName());
23030
- if (gear.getPages()) writeXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.pages, gear.getPages());
23031
- 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
+ }
23032
23167
  if (gear.getDefaultValue() !== null) writeXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.default, normalizeGearXmlValue(gear.getGearType(), gear.getDefaultValue(), ownerType, ownerName ?? void 0, gear));
23033
23168
  if (gear.getTween()) {
23034
23169
  writeXmlAttr(attrs, PROJECT_XML_PROTOCOL.gear.attrs.tween, "true");
@@ -23419,7 +23554,10 @@ var ProjectWriter = class {
23419
23554
  const staleSourceFilePaths = new Set((options.staleSourceFiles ?? []).map((source) => this._projectSourceFilePath(basePath, source)));
23420
23555
  const staleBranchDirectoryPaths = new Set((options.staleBranchDirectories ?? []).map((directory) => this._projectBranchDirectoryPath(basePath, directory)));
23421
23556
  if (staleBranchDirectoryPaths.size > 0 && !fs.rmdir) throw new Error("Project branch cleanup requires a FileSystem.rmdir() implementation.");
23422
- 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
+ }
23423
23561
  const settings = root.getSettings?.() ?? {};
23424
23562
  const settingsPath = fs.join(basePath, "settings");
23425
23563
  const staleOptionalSettings = [];
@@ -24865,9 +25003,10 @@ function decodeChildBlock2(doc, resource, child, childBuf) {
24865
25003
  for (let pageIndex = 0; pageIndex < pageCount; pageIndex += 1) {
24866
25004
  if (remainingBytes(childBuf) < 2) break;
24867
25005
  const rawPageId = childBuf.readS();
25006
+ if (rawPageId === null && (gearType === GearType.Text || gearType === GearType.Icon)) continue;
24868
25007
  const pageId = rawPageId ?? controllerPages[pageIndex]?.getId() ?? "";
24869
25008
  pages.push(pageId);
24870
- if (rawPageId === null && gearType !== GearType.Text && gearType !== GearType.Icon) {
25009
+ if (rawPageId === null) {
24871
25010
  values.push("-");
24872
25011
  continue;
24873
25012
  }
@@ -24917,7 +25056,8 @@ function decodeChildBlock2(doc, resource, child, childBuf) {
24917
25056
  }
24918
25057
  }
24919
25058
  if (pages.length > 0) gear.setPages(pages.join(","));
24920
- 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("|"));
24921
25061
  gear.setDefaultValue(defaultValue);
24922
25062
  child.addGear(gear);
24923
25063
  childBuf.pos = nextPos;
@@ -25905,7 +26045,7 @@ function _writeControllers(buf, comp) {
25905
26045
  }
25906
26046
  /** Map property type to GObject type index used in binary format. */
25907
26047
  function _writeComponentRelations(buf, comp) {
25908
- _writeRelations(buf, comp, _createChildIndexMap(comp));
26048
+ _writeRelations(buf, comp, getRuntimeChildIndexMap(comp));
25909
26049
  }
25910
26050
  function _writeRelations(buf, obj, childIndexById) {
25911
26051
  const relationDefs = obj.getRelations?.() ?? [];
@@ -25929,15 +26069,6 @@ function _writeRelations(buf, obj, childIndexById) {
25929
26069
  }
25930
26070
  }
25931
26071
  }
25932
- function _createChildIndexMap(comp) {
25933
- const childIndexById = /* @__PURE__ */ new Map();
25934
- const children = comp.listChildren();
25935
- for (const [index, child] of children.entries()) {
25936
- const childId = child.getId?.();
25937
- if (childId) childIndexById.set(childId, index);
25938
- }
25939
- return childIndexById;
25940
- }
25941
26072
  function _resolveRelationTargetIndex(target, childIndexById) {
25942
26073
  if (!target) return -1;
25943
26074
  const mappedIndex = childIndexById?.get(target);
@@ -26224,8 +26355,8 @@ function _writeTransitionValue(buf, item, value, version) {
26224
26355
  break;
26225
26356
  }
26226
26357
  case "Scale":
26227
- buf.writeFloat32(parseFloat(parts[0]) || 1);
26228
- buf.writeFloat32(parseFloat(parts[1]) || 1);
26358
+ buf.writeFloat32(_numberToken(parts[0], 1));
26359
+ buf.writeFloat32(_numberToken(parts[1], 1));
26229
26360
  break;
26230
26361
  case "Alpha":
26231
26362
  case "Rotation":
@@ -26252,11 +26383,11 @@ function _writeTransitionValue(buf, item, value, version) {
26252
26383
  break;
26253
26384
  case "Sound":
26254
26385
  buf.writeSEx(parts[0] || null, false, false);
26255
- buf.writeFloat32((parseInt(parts[1], 10) || 100) / 100);
26386
+ buf.writeFloat32(Math.trunc(_numberToken(parts[1], 100)) / 100);
26256
26387
  break;
26257
26388
  case "Transition":
26258
26389
  buf.writeSEx(parts[0] || null, false, false);
26259
- buf.writeInt32(parseInt(parts[1], 10) || 1);
26390
+ buf.writeInt32(Math.trunc(_numberToken(parts[1], 1)));
26260
26391
  break;
26261
26392
  case "Shake":
26262
26393
  buf.writeFloat32(parseFloat(parts[0]) || 0);
@@ -26287,10 +26418,12 @@ function _writeGear(buf, gear, gearType, comp, version) {
26287
26418
  const ctrlIndex = ctrl ? controllers.indexOf(ctrl) : -1;
26288
26419
  buf.writeInt16(ctrlIndex >= 0 ? ctrlIndex : 0);
26289
26420
  const pagesStr = _strVal(gear.getPages?.()) ?? "";
26290
- const valuesStr = _strVal(gear.getValues?.()) ?? "";
26291
- const defaultStr = _strVal(gear.getDefaultValue?.()) ?? "";
26421
+ const stringValues = gearType === 6 || gearType === 7;
26422
+ const defaultValue = gear.getDefaultValue?.();
26423
+ const defaultStr = _strVal(defaultValue) ?? "";
26292
26424
  const pages = pagesStr ? pagesStr.split(",") : [];
26293
- const values = valuesStr ? valuesStr.split("|") : [];
26425
+ const pageValues = gear.getPageValues();
26426
+ const values = stringValues ? pages.map((page) => pageValues[page] ?? null) : (_strVal(gear.getValues?.()) ?? "").split("|");
26294
26427
  const pageCount = pages.length;
26295
26428
  if (gearType === 0 || gearType === 8) {
26296
26429
  buf.writeInt16(pages.length);
@@ -26298,15 +26431,15 @@ function _writeGear(buf, gear, gearType, comp, version) {
26298
26431
  } else {
26299
26432
  buf.writeInt16(pageCount);
26300
26433
  for (let i = 0; i < pageCount; i++) {
26301
- const value = values[i] ?? "";
26302
- if (_shouldWriteNullGearPage(gearType, value)) {
26434
+ const value = values[i] ?? null;
26435
+ if (value === null || _shouldWriteNullGearPage(gearType, value)) {
26303
26436
  buf.writeS(null);
26304
26437
  continue;
26305
26438
  }
26306
26439
  buf.writeS(pages[i] ?? null);
26307
26440
  _writeGearStatus(buf, gearType, value, version);
26308
26441
  }
26309
- const hasDefault = defaultStr !== "";
26442
+ const hasDefault = stringValues ? defaultValue !== null && defaultValue !== void 0 : defaultStr !== "";
26310
26443
  buf.writeBool(hasDefault);
26311
26444
  if (hasDefault) _writeGearStatus(buf, gearType, defaultStr, version);
26312
26445
  }
@@ -26368,8 +26501,8 @@ function _writeGearStatus(buf, gearType, valueStr, _version) {
26368
26501
  case 2:
26369
26502
  buf.writeInt32(parseInt(parts[0], 10) || 0);
26370
26503
  buf.writeInt32(parseInt(parts[1], 10) || 0);
26371
- buf.writeFloat32(parseFloat(parts[2]) || 1);
26372
- buf.writeFloat32(parseFloat(parts[3]) || 1);
26504
+ buf.writeFloat32(_numberToken(parts[2], 1));
26505
+ buf.writeFloat32(_numberToken(parts[3], 1));
26373
26506
  break;
26374
26507
  case 3:
26375
26508
  buf.writeFloat32(_numberToken(parts[0], 1));
@@ -26551,7 +26684,7 @@ function _writeDisplayList(buf, comp, _doc, pkg, version) {
26551
26684
  buf.pos = saved;
26552
26685
  }
26553
26686
  const cb3 = buf.pos - childIndexPos;
26554
- _writeRelations(buf, child, _createChildIndexMap(comp));
26687
+ _writeRelations(buf, child, childIndexMap);
26555
26688
  let cb4 = 0;
26556
26689
  const isCompOrList = childType === "GComponent" || childType === "GList" || childType === "GTree" || childType === "GButton" || childType === "GLabel" || childType === "GComboBox" || childType === "GProgressBar" || childType === "GSlider" || childType === "GScrollBar";
26557
26690
  const isTextInput = childType === "GTextInput";
@@ -27976,12 +28109,14 @@ function collectComponentReferences(target, ownerPackageId, component) {
27976
28109
  }
27977
28110
  addUnknownReferences(target, ownerPackageId, child.getPropertyOverrides?.().map((property) => property.value));
27978
28111
  for (const gear of child.listGears?.() ?? []) {
27979
- addUnknownReferences(target, ownerPackageId, gear.getValues?.());
28112
+ addUnknownReferences(target, ownerPackageId, gear.getGearType() === GearType.Text || gear.getGearType() === GearType.Icon ? Object.values(gear.getPageValues()) : gear.getValues());
27980
28113
  addUnknownReferences(target, ownerPackageId, gear.getDefaultValue?.());
27981
28114
  }
27982
28115
  }
27983
28116
  addFontReferences(target, ownerPackageId, referenceComponent.getFont?.());
27984
28117
  for (const reference of [
28118
+ referenceComponent.getAddedToStageSound?.(),
28119
+ referenceComponent.getRemovedFromStageSound?.(),
27985
28120
  referenceComponent.getDropdown?.(),
27986
28121
  referenceComponent.getHeaderRes?.(),
27987
28122
  referenceComponent.getFooterRes?.(),
@@ -29756,9 +29891,15 @@ async function writeAtlasPageImage(pkg, inputs, page, atlasFileName, encoder, op
29756
29891
  if (options.extractAlpha) {
29757
29892
  const atlasBuffer = await atlasPipeline.png().toBuffer();
29758
29893
  await encoder(atlasBuffer).removeAlpha().png().toFile(outputFile);
29894
+ options.onFileWritten?.(outputFile);
29759
29895
  const alphaBuffer = await encoder(atlasBuffer).extractChannel("alpha").png().toBuffer();
29760
- await encoder(alphaBuffer).joinChannel([alphaBuffer, alphaBuffer]).png().toFile(`${options.outputPath}/${insertFileNameSuffix(atlasFileName, "!a")}`);
29761
- } 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
+ }
29762
29903
  logger.info(`atlas: Generated ${atlasFileName} (${page.width}x${page.height}, ${page.outputRects.length} sprites)`);
29763
29904
  }
29764
29905
  function inputToCompatRect(input, index) {
@@ -29863,6 +30004,7 @@ async function emitDirectImageOutput(doc, pkg, input, encoder, options, logger,
29863
30004
  top: 0
29864
30005
  }]).png().toFile(outputFile);
29865
30006
  }
30007
+ options.onFileWritten?.(outputFile);
29866
30008
  } catch {
29867
30009
  const message = `atlas: Could not write direct-output atlas "${atlasFileName}".`;
29868
30010
  if (options.strictOutput) throw new Error(message);
@@ -30060,9 +30202,8 @@ async function resolveEditorCompatibleResourceOrder(pkg, allResources, options)
30060
30202
  await addResource(resourceMap.get(resourceId));
30061
30203
  }
30062
30204
  async function addGearIconResources(gear) {
30063
- if (gear.getGearType?.() !== GearType.Icon) return;
30064
- const values = gear.getValues?.();
30065
- 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);
30066
30207
  const defaultValue = gear.getDefaultValue?.();
30067
30208
  if (typeof defaultValue === "string") await addResourceByLocalUiUrl(defaultValue);
30068
30209
  }
@@ -31905,6 +32046,7 @@ function publish(options) {
31905
32046
  basePath: options.basePath,
31906
32047
  outputPath: options.fs ? plan.outputDir : void 0,
31907
32048
  mkdir: options.fs ? options.fs.mkdir : void 0,
32049
+ onFileWritten: options.atlas?.onFileWritten,
31908
32050
  readFileRaw: options.atlas?.readFileRaw ?? options.fs?.readFileRaw,
31909
32051
  strictOutput: options.fs !== void 0,
31910
32052
  preparedMovieClips,
@@ -32096,10 +32238,14 @@ async function resolveFairyPath(input) {
32096
32238
  //#endregion
32097
32239
  //#region src/commands/inspect.ts
32098
32240
  function registerInspectCommand(program) {
32099
- 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) => {
32100
32242
  const fairyPath = await resolveFairyPath(projectDir);
32101
- console.log(`Project: ${fairyPath}\n`);
32102
- 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
+ }
32103
32249
  });
32104
32250
  }
32105
32251
  function printReport(report) {
@@ -32194,7 +32340,7 @@ function isObject(value) {
32194
32340
  //#endregion
32195
32341
  //#region ../functions/src/adapters/node/publish.ts
32196
32342
  const importNative$2 = new Function("id", "return import(id)");
32197
- async function createNodePublishFileSystem() {
32343
+ async function createNodePublishFileSystem(files) {
32198
32344
  const [fs, path] = await Promise.all([importNative$2("node:fs/promises"), importNative$2("node:path")]);
32199
32345
  return {
32200
32346
  async readFileRaw(filePath) {
@@ -32204,6 +32350,7 @@ async function createNodePublishFileSystem() {
32204
32350
  async writeFileRaw(filePath, data) {
32205
32351
  await fs.mkdir(path.dirname(filePath), { recursive: true });
32206
32352
  await fs.writeFile(filePath, data);
32353
+ files.add(path.resolve(filePath));
32207
32354
  },
32208
32355
  async mkdir(dirPath) {
32209
32356
  await fs.mkdir(dirPath, { recursive: true });
@@ -32213,6 +32360,7 @@ async function createNodePublishFileSystem() {
32213
32360
  },
32214
32361
  async deleteFile(filePath) {
32215
32362
  await fs.rm(filePath, { force: true });
32363
+ files.delete(path.resolve(filePath));
32216
32364
  },
32217
32365
  join(...paths) {
32218
32366
  return path.join(...paths);
@@ -32318,9 +32466,12 @@ async function assertNoSymlinks(fs, path, directory) {
32318
32466
  */
32319
32467
  async function publishNode(options) {
32320
32468
  const { document, assetsPath: configuredAssetsPath, atlas, encoder: configuredEncoder, plugins: configuredPlugins, ...publishOptions } = options;
32321
- 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)]);
32322
32472
  const [encoder, plugins] = await Promise.all([configuredEncoder === void 0 ? loadSharpBackend() : Promise.resolve(configuredEncoder), configuredPlugins === void 0 ? loadNodePublishPlugins(document, assetsPath) : Promise.resolve(configuredPlugins)]);
32323
32473
  if (!encoder) throw new Error("publishNode: Sharp is required for a complete publish. Install sharp or provide an encoder.");
32474
+ const result = { files: [] };
32324
32475
  const run = async (output) => {
32325
32476
  await document.transform(publish({
32326
32477
  ...publishOptions,
@@ -32329,17 +32480,26 @@ async function publishNode(options) {
32329
32480
  encoder,
32330
32481
  atlas: {
32331
32482
  ...atlas,
32332
- readFileRaw: fileSystem.readFileRaw
32483
+ readFileRaw: fileSystem.readFileRaw,
32484
+ onFileWritten(file) {
32485
+ files.add(path.resolve(file));
32486
+ atlas?.onFileWritten?.(file);
32487
+ }
32333
32488
  },
32334
32489
  fs: fileSystem,
32335
32490
  plugins
32336
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
+ }));
32337
32499
  };
32338
- if (publishOptions.output) {
32339
- await publishToStagedOutput(publishOptions.output, run);
32340
- return;
32341
- }
32342
- await run(void 0);
32500
+ if (publishOptions.output) await publishToStagedOutput(publishOptions.output, run);
32501
+ else await run(void 0);
32502
+ return result;
32343
32503
  }
32344
32504
  //#endregion
32345
32505
  //#region ../functions/src/adapters/node/restore.ts
@@ -32566,7 +32726,7 @@ function parseProjectType(value) {
32566
32726
  //#endregion
32567
32727
  //#region src/commands/publish.ts
32568
32728
  function registerPublishCommand(program) {
32569
- 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) => {
32570
32730
  const fairyPath = await resolveFairyPath(projectDir);
32571
32731
  const projectRootDir = path.dirname(fairyPath);
32572
32732
  const outputDir = options.output ? path.resolve(options.output) : void 0;
@@ -32582,7 +32742,7 @@ function registerPublishCommand(program) {
32582
32742
  });
32583
32743
  console.log(`Settings: ext=${resolved.fileExtension}, compressed=${resolved.compressed}`);
32584
32744
  if (options.branch) console.log(`Active branch: ${options.branch}`);
32585
- await publishNode({
32745
+ const result = await publishNode({
32586
32746
  document: doc,
32587
32747
  output: outputDir,
32588
32748
  compressed: resolved.compressed,
@@ -32592,13 +32752,17 @@ function registerPublishCommand(program) {
32592
32752
  atlas: resolved.atlas,
32593
32753
  branch: options.branch
32594
32754
  });
32755
+ if (options.json) {
32756
+ printJson("publish", result);
32757
+ return;
32758
+ }
32595
32759
  console.log(`\nDone!${outputDir ? ` Output override: ${outputDir}` : ""}`);
32596
32760
  });
32597
32761
  }
32598
32762
  //#endregion
32599
32763
  //#region src/commands/restore.ts
32600
32764
  function registerRestoreCommand(program) {
32601
- 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) => {
32602
32766
  const inputDir = path.resolve(releaseDir);
32603
32767
  const outputDir = path.resolve(options.output);
32604
32768
  const pkgFilter = options.packages ? options.packages.split(",").map((value) => value.trim()).filter(Boolean) : void 0;
@@ -32612,6 +32776,17 @@ function registerRestoreCommand(program) {
32612
32776
  projectType
32613
32777
  });
32614
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
+ }
32615
32790
  console.log(`\nDone! Output: ${result.projectPath}`);
32616
32791
  console.log(`Packages: ${packages.map((pkg) => pkg.getName()).join(", ")}`);
32617
32792
  for (const warning of result.warnings) console.warn(`Warning: ${warning}`);
@@ -32623,7 +32798,10 @@ function registerValidateCommand(program) {
32623
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) => {
32624
32799
  const fairyPath = await resolveFairyPath(projectDir);
32625
32800
  const report = await validateProjectNode(fairyPath);
32626
- 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
+ });
32627
32805
  else {
32628
32806
  console.log(`${report.status.toUpperCase()}: ${fairyPath}`);
32629
32807
  for (const diagnostic of report.diagnostics) {
@@ -32631,14 +32809,14 @@ function registerValidateCommand(program) {
32631
32809
  console.log(`${diagnostic.severity.toUpperCase()} ${diagnostic.code} ${diagnostic.path}${source}: ${diagnostic.message}`);
32632
32810
  }
32633
32811
  }
32634
- process.exitCode = report.status === "valid" ? 0 : report.status === "invalid" ? 1 : 2;
32812
+ process.exitCode = report.status === "valid" ? 0 : report.status === "invalid" ? 1 : 3;
32635
32813
  });
32636
32814
  }
32637
32815
  //#endregion
32638
32816
  //#region src/utils/package-version.ts
32639
32817
  const require$1 = createRequire(import.meta.url);
32640
32818
  function getInjectedPackageVersion() {
32641
- const version = "0.3.1";
32819
+ const version = "0.5.0-alpha.1";
32642
32820
  return typeof version === "string" && true ? version : null;
32643
32821
  }
32644
32822
  function readPackageVersion() {
@@ -32651,16 +32829,181 @@ function readPackageVersion() {
32651
32829
  return "0.0.0-dev";
32652
32830
  }
32653
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
32654
32994
  //#region src/cli.ts
32655
32995
  const PACKAGE_VERSION = readPackageVersion();
32656
32996
  function createProgram() {
32657
32997
  const program = new Command("ofgui");
32998
+ configureJson(program);
32658
32999
  program.description("FairyGUI Headless Authoring CLI").version(PACKAGE_VERSION).showHelpAfterError();
32659
33000
  registerInspectCommand(program);
32660
33001
  registerPublishCommand(program);
32661
33002
  registerRestoreCommand(program);
32662
33003
  registerValidateCommand(program);
32663
33004
  registerBackendCapabilitiesCommand(program);
33005
+ registerDocsCommand(program);
33006
+ registerDoctorCommand(program);
32664
33007
  program.addHelpText("after", [
32665
33008
  "",
32666
33009
  "Alias:",
@@ -32671,12 +33014,19 @@ function createProgram() {
32671
33014
  ].join("\n"));
32672
33015
  return program;
32673
33016
  }
32674
- async function main() {
32675
- 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
+ });
32676
33030
  }
32677
- main().catch((err) => {
32678
- console.error(err instanceof Error ? err.message : String(err));
32679
- process.exit(1);
32680
- });
32681
33031
  //#endregion
32682
- export {};
33032
+ export { createProgram };