@taptap/maker 0.0.37-beta.1 → 0.0.37-beta.10

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.
@@ -0,0 +1,289 @@
1
+ -- Maker NanoVG data adapter. No Lua source is stored in UI documents.
2
+ -- capture() is an explicit, synchronous development operation; hooks never survive it.
3
+ local M = {}
4
+ local unpack = table.unpack or unpack
5
+ local active = false
6
+ local signatures = {
7
+ save = "", restore = "", beginPath = "", closePath = "", fill = "", stroke = "",
8
+ moveTo = "nn", lineTo = "nn", bezierTo = "nnnnnn", quadTo = "nnnn", arcTo = "nnnnn",
9
+ rect = "nnnn", roundedRect = "nnnnn", roundedRectVarying = "nnnnnnnn",
10
+ circle = "nnn", ellipse = "nnnn", arc = "nnnnnn",
11
+ translate = "nn", scale = "nn", rotate = "n", skewX = "n", skewY = "n", transform = "nnnnnn",
12
+ scissor = "nnnn", intersectScissor = "nnnn",
13
+ fillColor = "c", strokeColor = "c", fillPaint = "p", strokePaint = "p",
14
+ strokeWidth = "n", miterLimit = "n", lineCap = "n", lineJoin = "n", globalAlpha = "n",
15
+ fontSize = "n", fontFace = "s", textAlign = "n", textLetterSpacing = "n", text = "nns", textBox = "nnns",
16
+ }
17
+ local paints = { linearGradient = "nnnncc", radialGradient = "nnnncc", imagePattern = "nnnnnsn" }
18
+
19
+ local function finite(n) return type(n) == "number" and n == n and math.abs(n) < math.huge end
20
+ local function color(value)
21
+ if type(value) == "string" then
22
+ assert((#value == 7 or #value == 9) and value:match("^#%x+$"), "Invalid NanoVG color")
23
+ return { tonumber(value:sub(2, 3), 16), tonumber(value:sub(4, 5), 16),
24
+ tonumber(value:sub(6, 7), 16), #value == 9 and tonumber(value:sub(8, 9), 16) or 255 }
25
+ end
26
+ assert(type(value) == "table" and #value == 4, "Expected RGBA color")
27
+ for i = 1, 4 do assert(finite(value[i]) and value[i] >= 0 and value[i] <= 255, "Invalid color channel") end
28
+ return value
29
+ end
30
+
31
+ local function validateArgs(args, sig)
32
+ assert(type(args) == "table" and #args == #sig, "Invalid NanoVG argument count")
33
+ for i = 1, #sig do
34
+ local kind, value = sig:sub(i, i), args[i]
35
+ if kind == "n" then assert(finite(value), "Expected finite NanoVG number")
36
+ elseif kind == "s" then assert(type(value) == "string", "Expected NanoVG string")
37
+ elseif kind == "c" then color(value)
38
+ else
39
+ assert(type(value) == "table" and paints[value.kind], "Unsupported NanoVG paint")
40
+ validateArgs(value.args, paints[value.kind])
41
+ end
42
+ end
43
+ end
44
+
45
+ local function validate(node)
46
+ assert(type(node) == "table" and node.type == "NanoVG", "Expected NanoVG node")
47
+ validateArgs(node.viewBox, "nnnn")
48
+ assert(node.viewBox[3] > 0 and node.viewBox[4] > 0, "Invalid NanoVG viewBox")
49
+ assert(type(node.commands) == "table" and #node.commands <= 20000, "Too many NanoVG commands")
50
+ local depth = 0
51
+ for _, cmd in ipairs(node.commands) do
52
+ assert(type(cmd) == "table" and signatures[cmd[1]], "Unsupported NanoVG command: " .. tostring(cmd[1]))
53
+ local args = {}; for i = 2, #cmd do args[#args + 1] = cmd[i] end
54
+ validateArgs(args, signatures[cmd[1]])
55
+ if cmd[1] == "textBox" then assert(args[3] > 0, "Text box width must be positive") end
56
+ if cmd[1] == "save" then depth = depth + 1 end
57
+ if cmd[1] == "restore" then depth = depth - 1 end
58
+ assert(depth >= 0 and depth <= 32, "Unbalanced NanoVG state stack (layer limit: 32)")
59
+ end
60
+ assert(depth == 0, "Unbalanced NanoVG state stack")
61
+ end
62
+ M.validate = validate
63
+
64
+ -- opts.images maps existing native image handles to assets-relative resource paths.
65
+ -- opts.fonts maps existing font IDs to names. Unknown APIs/opaque paints fail capture.
66
+ function M.capture(ctx, opts, draw)
67
+ assert(not active, "Nested NanoVG capture is not supported; capture separate named layers")
68
+ assert(type(opts) == "table" and type(draw) == "function", "capture requires options and a draw function")
69
+ local node = { type = "NanoVG", id = opts.id, position = "absolute", left = opts.left or 0,
70
+ top = opts.top or 0, width = opts.width, height = opts.height,
71
+ viewBox = opts.viewBox or { 0, 0, opts.width, opts.height }, commands = {} }
72
+ local originals, colors, paintValues = {}, {}, {}
73
+ local images, fonts = opts.images or {}, opts.fonts or {}
74
+ local depth, failure = 0, nil
75
+ local function remember(op, args)
76
+ assert(#node.commands < 20000, "NanoVG command limit exceeded")
77
+ local cmd = { op }; for _, value in ipairs(args) do cmd[#cmd + 1] = value end
78
+ node.commands[#node.commands + 1] = cmd
79
+ end
80
+ local function capturedColor(value)
81
+ assert(colors[value], "Color was created outside capture; create it inside the draw callback")
82
+ return colors[value]
83
+ end
84
+ local function wrap(name, fn)
85
+ if originals[name] then
86
+ _G[name] = function(...)
87
+ local result = { pcall(fn, ...) }
88
+ if not result[1] then failure = tostring(result[2]); error(failure) end
89
+ return unpack(result, 2)
90
+ end
91
+ end
92
+ end
93
+ for name, fn in pairs(_G) do
94
+ if type(fn) == "function" and name:match("^nvg[A-Z]") then originals[name] = fn end
95
+ end
96
+ assert(originals.nvgSave and originals.nvgRestore and originals.nvgReset, "NanoVG context is unavailable")
97
+ originals.nvgSave(ctx)
98
+ active = true
99
+ -- Refuse unrecorded drawing instead of returning a visually incomplete success.
100
+ for name in pairs(originals) do
101
+ local api = name
102
+ _G[api] = function()
103
+ failure = "Unsupported NanoVG capture API: " .. api
104
+ error(failure)
105
+ end
106
+ end
107
+ for op, sig in pairs(signatures) do
108
+ local operation, signature = op, sig
109
+ local name = "nvg" .. op:sub(1, 1):upper() .. op:sub(2)
110
+ wrap(name, function(vg, ...)
111
+ assert(vg == ctx, "A capture may only use its own NanoVG context")
112
+ local args = { ... }
113
+ for i = 1, #signature do
114
+ local kind = signature:sub(i, i)
115
+ if kind == "c" then args[i] = capturedColor(args[i])
116
+ elseif kind == "p" then
117
+ assert(paintValues[args[i]], "Paint was created outside capture")
118
+ args[i] = paintValues[args[i]]
119
+ end
120
+ end
121
+ validateArgs(args, signature)
122
+ if operation == "save" then assert(depth < 32, "NanoVG stack limit") end
123
+ if operation == "restore" then assert(depth > 0, "Unbalanced NanoVG restore") end
124
+ remember(operation, args)
125
+ local result = originals[name](vg, ...)
126
+ if operation == "save" then depth = depth + 1 end
127
+ if operation == "restore" then depth = depth - 1 end
128
+ return result
129
+ end)
130
+ end
131
+ for _, name in ipairs({ "nvgRGB", "nvgRGBA", "nvgRGBf", "nvgRGBAf" }) do
132
+ local api = name
133
+ wrap(api, function(...)
134
+ local a = { ... }; local factor = api:sub(-1) == "f" and 255 or 1
135
+ local rgba = { a[1] * factor, a[2] * factor, a[3] * factor, a[4] and a[4] * factor or 255 }
136
+ color(rgba)
137
+ local result = originals[api](...); colors[result] = rgba; return result
138
+ end)
139
+ end
140
+ for kind, sig in pairs(paints) do
141
+ local paintKind, signature = kind, sig
142
+ local name = "nvg" .. kind:sub(1, 1):upper() .. kind:sub(2)
143
+ wrap(name, function(vg, ...)
144
+ assert(vg == ctx, "NanoVG context mismatch")
145
+ local args = { ... }
146
+ if paintKind == "imagePattern" then
147
+ assert(images[args[6]], "Image handle requires opts.images mapping")
148
+ args[6] = images[args[6]]
149
+ else args[5] = capturedColor(args[5]); args[6] = capturedColor(args[6]) end
150
+ validateArgs(args, signature)
151
+ local result = originals[name](vg, ...)
152
+ paintValues[result] = { kind = paintKind, args = args }
153
+ return result
154
+ end)
155
+ end
156
+ wrap("nvgFontFaceId", function(vg, id)
157
+ assert(vg == ctx and fonts[id], "Font ID requires opts.fonts mapping")
158
+ remember("fontFace", { fonts[id] }); return originals.nvgFontFaceId(vg, id)
159
+ end)
160
+ for _, name in ipairs({ "nvgImageSize", "nvgTextBounds", "nvgTextMetrics" }) do
161
+ if originals[name] then _G[name] = originals[name] end
162
+ end
163
+ local ok, err = xpcall(function()
164
+ originals.nvgReset(ctx)
165
+ originals.nvgBeginPath(ctx)
166
+ draw()
167
+ assert(not failure, failure)
168
+ validate(node)
169
+ end, function(e) return tostring(e) end)
170
+ for name, fn in pairs(originals) do _G[name] = fn end
171
+ for _ = 1, depth do originals.nvgRestore(ctx) end
172
+ originals.nvgRestore(ctx)
173
+ active = false
174
+ if not ok then error(err) end
175
+ return node
176
+ end
177
+
178
+ local function nativeColor(value) return nvgRGBA(unpack(color(value))) end
179
+ local function multiply(a, b)
180
+ return { a[1]*b[1]+a[3]*b[2], a[2]*b[1]+a[4]*b[2], a[1]*b[3]+a[3]*b[4],
181
+ a[2]*b[3]+a[4]*b[4], a[1]*b[5]+a[3]*b[6]+a[5], a[2]*b[5]+a[4]*b[6]+a[6] }
182
+ end
183
+ local function inverse(m)
184
+ local d = m[1]*m[4]-m[2]*m[3]
185
+ if math.abs(d) < 1e-12 then return nil end
186
+ return { m[4]/d, -m[2]/d, -m[3]/d, m[1]/d,
187
+ (m[3]*m[6]-m[4]*m[5])/d, (m[2]*m[5]-m[1]*m[6])/d }
188
+ end
189
+
190
+ -- Draw a leaf inside the caller's active NanoVG frame. Layout belongs to the caller.
191
+ -- resolveImage(path, ctx) returns a cached native handle; this module owns no resources.
192
+ function M.draw(ctx, node, x, y, width, height, resolveImage, opacity)
193
+ validate(node)
194
+ local view, depth = node.viewBox, 0
195
+ local matrix, clips, stack = { 1, 0, 0, 1, 0, 0 }, {}, {}
196
+ nvgSave(ctx)
197
+ local ok, err = xpcall(function()
198
+ nvgTranslate(ctx, x or node.left or 0, y or node.top or 0)
199
+ nvgScale(ctx, (width or node.width or view[3]) / view[3], (height or node.height or view[4]) / view[4])
200
+ nvgTranslate(ctx, -view[1], -view[2])
201
+ nvgFillColor(ctx, nvgRGBA(255, 255, 255, 255)); nvgStrokeColor(ctx, nvgRGBA(0, 0, 0, 255))
202
+ nvgStrokeWidth(ctx, 1); nvgMiterLimit(ctx, 10); nvgLineCap(ctx, 0); nvgLineJoin(ctx, 4)
203
+ nvgFontSize(ctx, 16); nvgFontFace(ctx, "sans"); nvgTextAlign(ctx, 65)
204
+ nvgTextLetterSpacing(ctx, 0)
205
+ if opacity then nvgGlobalAlpha(ctx, opacity) end
206
+ nvgBeginPath(ctx)
207
+ local function clipped(fn, args)
208
+ if #clips == 0 then fn(ctx, unpack(args)); return end
209
+ local inv = inverse(matrix)
210
+ if not inv then return end
211
+ -- Apply layer scissors at paint time so replacing a local scissor cannot
212
+ -- discard an enclosing Widget/ScrollView clip.
213
+ nvgSave(ctx)
214
+ local painted, problem = pcall(function()
215
+ nvgTransform(ctx, unpack(inv))
216
+ for _, clip in ipairs(clips) do
217
+ local back = inverse(clip.matrix)
218
+ if not back then return end
219
+ nvgTransform(ctx, unpack(clip.matrix))
220
+ nvgIntersectScissor(ctx, unpack(clip.args))
221
+ nvgTransform(ctx, unpack(back))
222
+ end
223
+ nvgTransform(ctx, unpack(matrix))
224
+ fn(ctx, unpack(args))
225
+ end)
226
+ nvgRestore(ctx)
227
+ if not painted then error(problem) end
228
+ end
229
+ for _, cmd in ipairs(node.commands) do
230
+ local op, args = cmd[1], {}
231
+ for i = 2, #cmd do args[#args + 1] = cmd[i] end
232
+ if op == "fillColor" or op == "strokeColor" then args[1] = nativeColor(args[1]) end
233
+ if op == "globalAlpha" then args[1] = args[1] * (opacity or 1) end
234
+ if op == "fillPaint" or op == "strokePaint" then
235
+ local p, a = args[1], {}; for i, value in ipairs(args[1].args) do a[i] = value end
236
+ if p.kind == "imagePattern" then
237
+ assert(resolveImage, "Image paint requires resolveImage(path, ctx)")
238
+ a[6] = resolveImage(a[6], ctx)
239
+ assert(type(a[6]) == "number" and a[6] > 0, "NanoVG image could not be resolved")
240
+ else a[5] = nativeColor(a[5]); a[6] = nativeColor(a[6]) end
241
+ args[1] = _G["nvg" .. p.kind:sub(1, 1):upper() .. p.kind:sub(2)](ctx, unpack(a))
242
+ end
243
+ local fn = _G["nvg" .. op:sub(1, 1):upper() .. op:sub(2)]
244
+ assert(type(fn) == "function", "NanoVG runtime API missing: " .. op)
245
+ if op == "scissor" or op == "intersectScissor" then
246
+ local nextClips = {}
247
+ if op == "intersectScissor" then for i, clip in ipairs(clips) do nextClips[i] = clip end end
248
+ nextClips[#nextClips + 1] = { matrix = matrix, args = args }; clips = nextClips
249
+ elseif op == "fill" or op == "stroke" or op == "text" or op == "textBox" then clipped(fn, args)
250
+ else fn(ctx, unpack(args)) end
251
+ if op == "save" then depth = depth + 1; stack[depth] = { matrix = matrix, clips = clips } end
252
+ if op == "restore" then matrix = stack[depth].matrix; clips = stack[depth].clips; stack[depth] = nil; depth = depth - 1 end
253
+ local t
254
+ if op == "transform" then t = args
255
+ elseif op == "translate" then t = { 1, 0, 0, 1, args[1], args[2] }
256
+ elseif op == "scale" then t = { args[1], 0, 0, args[2], 0, 0 }
257
+ elseif op == "rotate" then
258
+ local c, s = math.cos(args[1]), math.sin(args[1]); t = { c, s, -s, c, 0, 0 }
259
+ elseif op == "skewX" then t = { 1, 0, math.tan(args[1]), 1, 0, 0 }
260
+ elseif op == "skewY" then t = { 1, math.tan(args[1]), 0, 1, 0, 0 } end
261
+ if t then matrix = multiply(matrix, t) end
262
+ end
263
+ end, function(e) return tostring(e) end)
264
+ for _ = 1, depth do nvgRestore(ctx) end
265
+ nvgRestore(ctx)
266
+ if not ok then error(err) end
267
+ end
268
+
269
+ -- Register the node before UI.LoadJSON; reuse the engine's layout, input and transforms.
270
+ function M.register(UI, resolveImage)
271
+ assert(not UI.NanoVG, "UI.NanoVG is already registered")
272
+ local Widget = require("urhox-libs/UI/Core/Widget")
273
+ local Vector = Widget:Extend("NanoVG")
274
+ function Vector:Render(ctx)
275
+ local layout = self:GetAbsoluteLayout()
276
+ local data = { type = "NanoVG", commands = self.props.commands, viewBox = self.props.viewBox }
277
+ local opacity, widget = 1, self
278
+ while widget do
279
+ local a = widget.renderProps_ and widget.renderProps_.opacity or widget.props.opacity or 1
280
+ opacity = opacity * math.max(0, math.min(1, a))
281
+ widget = widget.parent
282
+ end
283
+ M.draw(ctx, data, layout.x, layout.y, layout.w, layout.h, resolveImage, opacity)
284
+ end
285
+ UI.NanoVG = Vector
286
+ return Vector
287
+ end
288
+
289
+ return M
@@ -0,0 +1,148 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { checkDocument } = require("./ui-json-check.cjs");
6
+
7
+ function inside(root, file) {
8
+ const rel = path.relative(root, file);
9
+ return rel === "" || (!rel.startsWith(".." + path.sep) && rel !== ".." && !path.isAbsolute(rel));
10
+ }
11
+ function readProjectConfig(root) {
12
+ const source = ".project/project.json";
13
+ const file = path.join(root, source);
14
+ try {
15
+ const raw = JSON.parse(fs.readFileSync(file, "utf8").replace(/^\uFEFF/, ""));
16
+ const publish = raw && typeof raw.taptap_publish === "object" ? raw.taptap_publish : raw;
17
+ const orientation = publish && (publish.screen_orientation || publish.orientation);
18
+ return { orientation: orientation === "landscape" || orientation === "portrait" ? orientation : null, source };
19
+ } catch (error) {
20
+ if (error.code === "ENOENT") return { orientation: null, source, missing: true };
21
+ return { orientation: null, source, error: error.message };
22
+ }
23
+ }
24
+ function checkExportManifest(root, assets, files, diagnostics) {
25
+ const relative = "assets/ui/ui-export-manifest.ui.json";
26
+ const file = path.join(assets, "ui", "ui-export-manifest.ui.json");
27
+ if (!fs.existsSync(file)) return;
28
+ let manifest;
29
+ try {
30
+ manifest = JSON.parse(fs.readFileSync(file, "utf8").replace(/^\uFEFF/, ""));
31
+ } catch (error) {
32
+ diagnostics.push({ code: "UI_MANIFEST_PARSE", severity: "error", file: relative, pointer: "",
33
+ message: error.message });
34
+ return;
35
+ }
36
+ const categories = ["pages", "components", "templates"];
37
+ const actual = new Set(files.map(item => path.relative(assets, item).split(path.sep).join("/")));
38
+ categories.forEach(kind => {
39
+ const listed = Array.isArray(manifest[kind]) ? manifest[kind].filter(item => typeof item === "string") : [];
40
+ const listedSet = new Set(listed);
41
+ const actualFiles = [...actual].filter(item => item.startsWith("ui/" + kind + "/"));
42
+ const missing = listed.filter(item => !actual.has(item));
43
+ const unlisted = actualFiles.filter(item => !listedSet.has(item));
44
+ if (missing.length) diagnostics.push({ code: "UI_MANIFEST_MISSING_FILE", severity: "error",
45
+ file: relative, pointer: "/" + kind, message: "导出清单登记了不存在的文件:" + missing.join(", ") });
46
+ if (unlisted.length) diagnostics.push({ code: "UI_MANIFEST_STALE", severity: "warning",
47
+ file: relative, pointer: "/" + kind, message: "目录中有 " + unlisted.length +
48
+ " 个 " + kind + " 文件未登记,清单可能来自旧导出:" + unlisted.slice(0, 5).join(", ") +
49
+ (unlisted.length > 5 ? " …" : "") });
50
+ });
51
+ }
52
+ function main(argv) {
53
+ if (argv.includes("--help")) {
54
+ console.log("node check-ui.cjs --project <game-root> [--file assets/ui/page.ui.json] [--format json|text]");
55
+ return 0;
56
+ }
57
+ const args = {};
58
+ for (let i = 0; i < argv.length; i += 2) {
59
+ if (!["--project", "--file", "--format"].includes(argv[i]) || !argv[i + 1] || argv[i + 1].startsWith("--")) {
60
+ throw new Error("Unknown or incomplete argument: " + argv[i]);
61
+ }
62
+ args[argv[i]] = argv[i + 1];
63
+ }
64
+ if (!args["--project"]) throw new Error("--project is required");
65
+ const format = args["--format"] || "text";
66
+ if (!["json", "text"].includes(format)) throw new Error("--format must be json or text");
67
+ const root = fs.realpathSync(args["--project"]);
68
+ const assets = fs.realpathSync(path.join(root, "assets"));
69
+ if (!inside(root, assets)) throw new Error("assets must be inside the project");
70
+ const files = [], scanDiagnostics = [];
71
+ function scan(dir) {
72
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
73
+ if ([".git", "node_modules"].includes(entry.name)) continue;
74
+ const file = path.join(dir, entry.name);
75
+ if (entry.isSymbolicLink()) {
76
+ scanDiagnostics.push({ code: "UI_SCAN_SYMLINK", severity: "warning",
77
+ file: path.relative(root, file), pointer: "", message: "未递归扫描符号链接,请检查其目标。" });
78
+ } else if (entry.isDirectory()) scan(file);
79
+ else if (/\.ui\.json$/i.test(entry.name)) files.push(file);
80
+ }
81
+ }
82
+ if (args["--file"]) {
83
+ const target = path.resolve(root, args["--file"]);
84
+ if (!inside(assets, target) || !/\.ui\.json$/i.test(target)) throw new Error("--file must be a .ui.json inside assets");
85
+ const real = fs.realpathSync(target);
86
+ if (!inside(assets, real)) throw new Error("--file symlink escapes assets");
87
+ files.push(real);
88
+ } else scan(assets);
89
+ const projectConfig = readProjectConfig(root);
90
+ const report = { version: 1, files: files.length, errors: 0, warnings: 0,
91
+ projectConfig,
92
+ diagnostics: scanDiagnostics, skipped: [] };
93
+ checkExportManifest(root, assets, files, report.diagnostics);
94
+ if (projectConfig.error) report.diagnostics.push({ code: "UI_PROJECT_CONFIG_PARSE", severity: "error",
95
+ file: projectConfig.source, pointer: "", message: projectConfig.error });
96
+ else if (projectConfig.missing) report.diagnostics.push({ code: "UI_PROJECT_CONFIG_MISSING", severity: "warning",
97
+ file: projectConfig.source, pointer: "", message: "未找到项目屏幕方向配置;页面预览可能使用错误的横竖屏设备。" });
98
+ const skipped = new Set();
99
+ function resourceExists(ref) {
100
+ const file = path.resolve(assets, ref);
101
+ if (!inside(assets, file)) return false;
102
+ try {
103
+ const real = fs.realpathSync(file);
104
+ if (!inside(assets, real)) return false;
105
+ fs.accessSync(real, fs.constants.R_OK);
106
+ return fs.statSync(real).isFile();
107
+ } catch (_) { return false; }
108
+ }
109
+ for (const file of files) {
110
+ const relative = path.relative(root, file).split(path.sep).join("/");
111
+ let tree;
112
+ try {
113
+ if (fs.statSync(file).size > 4 * 1024 * 1024) throw new Error("File exceeds 4 MiB");
114
+ tree = JSON.parse(fs.readFileSync(file, "utf8").replace(/^\uFEFF/, ""));
115
+ } catch (error) {
116
+ report.diagnostics.push({ code: "UI_JSON_PARSE", severity: "error",
117
+ file: relative, pointer: "", message: error.message });
118
+ continue;
119
+ }
120
+ const result = checkDocument({ file: relative, tree, resourceExists });
121
+ report.diagnostics.push(...result.diagnostics);
122
+ if (projectConfig.orientation && /assets\/ui\/pages\//i.test(relative) &&
123
+ typeof tree.width === "number" && typeof tree.height === "number") {
124
+ const landscape = tree.width >= tree.height;
125
+ if ((projectConfig.orientation === "landscape") !== landscape) {
126
+ report.diagnostics.push({ code: "UI_DESIGN_ORIENTATION", severity: "error", file: relative,
127
+ pointer: "/width", message: "页面根尺寸 " + tree.width + "×" + tree.height +
128
+ " 与项目配置的 " + projectConfig.orientation + " 方向不一致。" });
129
+ }
130
+ }
131
+ result.skipped.forEach(item => skipped.add(item));
132
+ }
133
+ if (!files.length) report.diagnostics.push({ code: "UI_NO_FILES", severity: "error",
134
+ file: "assets", pointer: "", message: "未找到 .ui.json;先确认项目根目录,或使用 lua-ui-to-json 提取。" });
135
+ report.errors = report.diagnostics.filter(d => d.severity === "error").length;
136
+ report.warnings = report.diagnostics.filter(d => d.severity === "warning").length;
137
+ report.skipped = [...skipped];
138
+ if (format === "json") console.log(JSON.stringify(report, null, 2));
139
+ else {
140
+ console.log(`${report.files} files, ${report.errors} errors, ${report.warnings} warnings`);
141
+ for (const d of report.diagnostics) console.log(`[${d.severity}] ${d.code} ${d.file}${d.pointer}: ${d.message}`);
142
+ console.log("Not verified: " + (report.skipped.join(", ") || "No documents checked"));
143
+ console.log("Static checks do not prove runtime or visual equivalence.");
144
+ }
145
+ return report.errors ? 1 : 0;
146
+ }
147
+ try { process.exitCode = main(process.argv.slice(2)); }
148
+ catch (error) { console.error(error.message); process.exitCode = 2; }
@@ -0,0 +1,206 @@
1
+ (function (root) {
2
+ "use strict";
3
+ var previewTypes = new Set(["Panel", "Label", "Button", "NanoVG"]);
4
+ // An allowlist shared by the browser, CLI and standalone document checker.
5
+ var nanoOps = {
6
+ save: "", restore: "", beginPath: "", closePath: "", fill: "", stroke: "",
7
+ moveTo: "nn", lineTo: "nn", bezierTo: "nnnnnn", quadTo: "nnnn", arcTo: "nnnnn",
8
+ rect: "nnnn", roundedRect: "nnnnn", roundedRectVarying: "nnnnnnnn",
9
+ circle: "nnn", ellipse: "nnnn", arc: "nnnnnn",
10
+ translate: "nn", scale: "nn", rotate: "n", skewX: "n", skewY: "n", transform: "nnnnnn",
11
+ scissor: "nnnn", intersectScissor: "nnnn",
12
+ fillColor: "c", strokeColor: "c", fillPaint: "p", strokePaint: "p",
13
+ strokeWidth: "n", miterLimit: "n", lineCap: "n", lineJoin: "n", globalAlpha: "n",
14
+ fontSize: "n", fontFace: "s", textAlign: "n", textLetterSpacing: "n", text: "nns", textBox: "nnns",
15
+ };
16
+ function nanoColor(value) {
17
+ return typeof value === "string" && /^#[0-9a-f]{6}([0-9a-f]{2})?$/i.test(value) ||
18
+ Array.isArray(value) && value.length === 4 && value.every(function (n) {
19
+ return typeof n === "number" && Number.isFinite(n) && n >= 0 && n <= 255;
20
+ });
21
+ }
22
+ function checkNanoVG(node, issue, resource) {
23
+ var box = node.viewBox, commands = node.commands, depth = 0;
24
+ if (!Array.isArray(box) || box.length !== 4 || box.some(function (n) {
25
+ return typeof n !== "number" || !Number.isFinite(n);
26
+ }) || box[2] <= 0 || box[3] <= 0) issue("/viewBox", "viewBox 必须是 [x, y, 正宽度, 正高度]。");
27
+ if (!Array.isArray(commands) || commands.length > 20000) {
28
+ issue("/commands", "绘制指令必须是数组,最多 20000 条。"); return;
29
+ }
30
+ function paint(value, at) {
31
+ if (!value || typeof value !== "object" || Array.isArray(value) || typeof value.kind !== "string") return false;
32
+ var signatures = { linearGradient: "nnnncc", radialGradient: "nnnncc", imagePattern: "nnnnnsn" };
33
+ var sig = Object.prototype.hasOwnProperty.call(signatures, value.kind) && signatures[value.kind];
34
+ if (!sig || !args(value.args, sig, at + "/args")) return false;
35
+ if (value.kind === "radialGradient" && (value.args[2] < 0 || value.args[3] <= value.args[2])) return false;
36
+ if (value.kind === "imagePattern") {
37
+ if (value.args[2] <= 0 || value.args[3] <= 0 || value.args[6] < 0 || value.args[6] > 1) return false;
38
+ resource(value.args[5], at + "/args/5");
39
+ }
40
+ return true;
41
+ }
42
+ function args(values, sig, at) {
43
+ return Array.isArray(values) && values.length === sig.length && values.every(function (value, i) {
44
+ var type = sig[i];
45
+ return type === "n" ? typeof value === "number" && Number.isFinite(value) :
46
+ type === "s" ? typeof value === "string" : type === "c" ? nanoColor(value) : paint(value, at + "/" + i);
47
+ });
48
+ }
49
+ commands.forEach(function (command, i) {
50
+ var at = "/commands/" + i;
51
+ if (!Array.isArray(command) || typeof command[0] !== "string" || !Object.prototype.hasOwnProperty.call(nanoOps, command[0]) ||
52
+ !args(command.slice(1), nanoOps[command[0]], at)) {
53
+ issue(at, "不支持的 NanoVG 指令或参数。使用 ui capabilities 查询支持范围。"); return;
54
+ }
55
+ var op = command[0], a = command.slice(1);
56
+ if (op === "save" && ++depth > 32) issue(at, "NanoVG 图层状态栈超过 32 层,需为引擎保留栈空间。");
57
+ if (op === "restore" && --depth < 0) { issue(at, "restore 没有对应的 save。"); depth = 0; }
58
+ if (op === "globalAlpha" && (a[0] < 0 || a[0] > 1)) issue(at, "透明度必须在 0 到 1 之间。");
59
+ if (["strokeWidth", "miterLimit", "fontSize"].includes(op) && a[0] <= 0) issue(at, "值必须大于 0。");
60
+ if (op === "lineCap" && ![0, 1, 2].includes(a[0]) || op === "lineJoin" && ![1, 3, 4].includes(a[0]) ||
61
+ op === "arc" && ![1, 2].includes(a[5])) issue(at, "无效的 NanoVG 枚举值。");
62
+ if (op === "textBox" && a[2] <= 0) issue(at, "文本框宽度必须大于 0。");
63
+ if (op === "textAlign" && ![0, 1, 2, 4].some(function (h) {
64
+ return [0, 8, 16, 32, 64].some(function (v) { return a[0] === h + v; });
65
+ })) issue(at, "文本对齐每个方向最多指定一个 NanoVG 标志。");
66
+ if (op === "circle" && a[2] < 0 || op === "ellipse" && (a[2] < 0 || a[3] < 0) ||
67
+ op === "arc" && a[2] < 0 || op === "arcTo" && a[4] < 0 ||
68
+ op.startsWith("roundedRect") && a.slice(4).some(function (n) { return n < 0; })) issue(at, "半径不能为负数。");
69
+ });
70
+ if (depth) issue("/commands", "save/restore 必须配对。");
71
+ }
72
+ var lengths = ["width", "height", "minWidth", "minHeight", "maxWidth", "maxHeight",
73
+ "left", "right", "top", "bottom", "padding", "paddingLeft", "paddingRight",
74
+ "paddingTop", "paddingBottom", "paddingHorizontal", "paddingVertical",
75
+ "margin", "marginLeft", "marginRight", "marginTop", "marginBottom",
76
+ "marginHorizontal", "marginVertical", "gap", "flexBasis"];
77
+ var enums = {
78
+ position: ["relative", "absolute"],
79
+ backgroundFit: ["fill", "contain", "cover", "sliced"],
80
+ overflow: ["visible", "hidden", "scroll"],
81
+ flexDirection: ["row", "column", "row-reverse", "column-reverse"],
82
+ textAlign: ["left", "center", "right"],
83
+ verticalAlign: ["top", "middle", "bottom"],
84
+ };
85
+ function token(value) { return typeof value === "string" && value.charAt(0) === "$"; }
86
+ function length(value) {
87
+ return typeof value === "number" && Number.isFinite(value) ||
88
+ typeof value === "string" && /^(auto|-?\d+(?:\.\d+)?%?)$/.test(value);
89
+ }
90
+ function checkDocument(options) {
91
+ var diagnostics = [], ids = new Map(), count = 0, limited = false, parameterized = false;
92
+ function issue(code, severity, pointer, message) {
93
+ diagnostics.push({ code: code, severity: severity, file: options.file || "",
94
+ pointer: pointer, message: message });
95
+ }
96
+ function resource(value, pointer) {
97
+ if (value == null || value === "" || token(value)) return;
98
+ if (typeof value !== "string") {
99
+ issue("UI_RESOURCE_TYPE", "error", pointer, "资源引用必须是字符串。"); return;
100
+ }
101
+ if (/^uuid:\/\//.test(value)) {
102
+ issue("UI_RESOURCE_UNRESOLVED", "warning", pointer, "UUID 引用需要引擎资源索引,尚未验证。"); return;
103
+ }
104
+ if (/^(\/|\\|[a-z]+:)/i.test(value) || value.includes("\\") || value.split("/").includes("..")) {
105
+ issue("UI_RESOURCE_PATH", "error", pointer, "使用 assets 内相对资源路径,不允许绝对路径或越界引用。"); return;
106
+ }
107
+ if (value.startsWith("assets/")) {
108
+ issue("UI_RESOURCE_PREFIX", "warning", pointer, "游戏资源通常相对 assets 根,请核对是否多写了 assets/。");
109
+ }
110
+ if (options.resourceExists && !options.resourceExists(value)) {
111
+ issue("UI_RESOURCE_MISSING", "error", pointer, "找不到或无法读取资源:" + value);
112
+ }
113
+ }
114
+ function visit(node, pointer, depth) {
115
+ if (++count > 10000 || depth > 128) {
116
+ if (!limited) issue("UI_LIMIT", "error", pointer, "节点数量或深度超过检查上限。");
117
+ limited = true; return;
118
+ }
119
+ if (!node || typeof node !== "object" || Array.isArray(node)) {
120
+ issue("UI_NODE", "error", pointer, "节点必须是对象。"); return;
121
+ }
122
+ if (typeof node.type !== "string" || !node.type.trim()) {
123
+ issue("UI_NODE_TYPE", "error", pointer + "/type", "每个节点都需要非空 type。");
124
+ } else if (!previewTypes.has(node.type)) {
125
+ issue("UI_PREVIEW_TYPE", "warning", pointer + "/type",
126
+ "此类型需要核对引擎注册及编辑器预览支持:" + node.type + ";不应自动改成 Panel。");
127
+ }
128
+ if (node.id != null && !token(node.id)) {
129
+ if (typeof node.id !== "string" || !node.id.trim()) {
130
+ issue("UI_ID_TYPE", "error", pointer + "/id", "id 必须是非空字符串。");
131
+ } else if (ids.has(node.id)) {
132
+ issue("UI_DUPLICATE_ID", "error", pointer + "/id", "同一文档的 id 重复:" + node.id +
133
+ ";首次出现于 " + ids.get(node.id));
134
+ } else ids.set(node.id, pointer + "/id");
135
+ }
136
+ Object.keys(node).forEach(function (key) {
137
+ var value = node[key], at = pointer + "/" + key.replace(/~/g, "~0").replace(/\//g, "~1");
138
+ if (key.charAt(0) === "_") issue("UI_INTERNAL_FIELD", "error", at, "导出含编辑器内部字段。");
139
+ if (/^on[A-Z]/.test(key)) issue("UI_CALLBACK", "error", at, "回调保留在 Lua 中,不写入 UI JSON。");
140
+ if (token(value)) { parameterized = true; return; }
141
+ if (typeof value === "number" && !Number.isFinite(value)) {
142
+ issue("UI_NUMBER", "error", at, "数值必须有限。"); return;
143
+ }
144
+ if (lengths.includes(key) && !length(value)) {
145
+ issue("UI_LENGTH", "error", at, "尺寸/位置必须是有限数值、百分比或受支持的 auto。");
146
+ }
147
+ if (["width", "height"].includes(key) && typeof value === "number" && value <= 0) {
148
+ issue("UI_ZERO_SIZE", "warning", at, "非正尺寸可能不可见;动态尺寸需在运行时确认。");
149
+ }
150
+ if (enums[key] && !enums[key].includes(value)) {
151
+ issue("UI_ENUM", "error", at, "不支持的枚举值:" + String(value));
152
+ }
153
+ if (["visible", "disabled", "locked"].includes(key) && typeof value !== "boolean") {
154
+ issue("UI_BOOLEAN", "error", at, "此字段必须是布尔值。");
155
+ }
156
+ if (key === "opacity" && (typeof value !== "number" || value < 0 || value > 1)) {
157
+ issue("UI_OPACITY", "error", at, "透明度应为 0 到 1 的数值。");
158
+ }
159
+ if (key === "backgroundSlice" && (!Array.isArray(value) || value.length !== 4 ||
160
+ value.some(function (n) { return typeof n !== "number" || !Number.isFinite(n) || n < 0; }))) {
161
+ issue("UI_SLICE", "error", at, "九宫格切边使用四个非负数:[上, 右, 下, 左]。");
162
+ }
163
+ });
164
+ resource(node.backgroundImage, pointer + "/backgroundImage");
165
+ resource(node.pressedBackgroundImage, pointer + "/pressedBackgroundImage");
166
+ if (node.type === "NanoVG") checkNanoVG(node, function (at, message) {
167
+ issue("UI_NANOVG", "error", pointer + at, message);
168
+ }, function (ref, at) { resource(ref, pointer + at); });
169
+ if (node.component != null) {
170
+ if (token(node.component)) {
171
+ parameterized = true;
172
+ } else if (typeof node.component !== "string" || !node.component.trim()) {
173
+ issue("UI_COMPONENT_TYPE", "error", pointer + "/component", "组件引用必须是非空字符串。");
174
+ } else if (options.resourceExists && !options.resourceExists(node.component)) {
175
+ issue("UI_COMPONENT_MISSING", "error", pointer + "/component", "找不到组件文件:" + node.component);
176
+ }
177
+ }
178
+ if (node.$repeat) {
179
+ issue("UI_EDITOR_REPEAT", "warning", pointer + "/$repeat",
180
+ "$repeat 是编辑器扩展,不证明引擎会生成列表;运行时应核对模板实例化。");
181
+ resource(node.$repeat.template, pointer + "/$repeat/template");
182
+ }
183
+ if (node.children != null && !Array.isArray(node.children)) {
184
+ issue("UI_CHILDREN", "error", pointer + "/children", "children 必须是数组。");
185
+ } else (node.children || []).some(function (child, i) {
186
+ visit(child, pointer + "/children/" + i, depth + 1);
187
+ return limited;
188
+ });
189
+ }
190
+ visit(options.tree, "", 0);
191
+ if (parameterized) issue("UI_TEMPLATE_CONTEXT", "warning", "",
192
+ "含模板参数。请验证调用方 props、默认值及模板加载模式;此检查没有展开模板。");
193
+ return {
194
+ version: 1, nodes: count,
195
+ errors: diagnostics.filter(function (d) { return d.severity === "error"; }).length,
196
+ warnings: diagnostics.filter(function (d) { return d.severity === "warning"; }).length,
197
+ diagnostics: diagnostics,
198
+ skipped: ["runtime-equivalence", "layout-and-fonts", "component-expansion", "lua-bindings",
199
+ "image-decoding", "meta-and-font-resources", "source-coverage", "duplicate-json-keys"]
200
+ .concat(options.resourceExists ? [] : ["resource-existence"]),
201
+ };
202
+ }
203
+ var api = { checkDocument: checkDocument, checkNanoVG: checkNanoVG, nanoOps: nanoOps };
204
+ if (typeof module !== "undefined" && module.exports) module.exports = api;
205
+ else root.UrhoxUICheck = api;
206
+ })(typeof window !== "undefined" ? window : globalThis);