@rickcedwhat/playwright-smart-vision 0.4.0-next.b06798f → 0.4.0-next.c249538
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/author/apply.d.ts +56 -8
- package/dist/author/apply.d.ts.map +1 -1
- package/dist/author/apply.js +442 -144
- package/dist/author/apply.js.map +1 -1
- package/dist/author/author.test.js.map +1 -1
- package/dist/author/catalog.d.ts +1 -0
- package/dist/author/catalog.d.ts.map +1 -1
- package/dist/author/catalog.js +2 -2
- package/dist/author/catalog.js.map +1 -1
- package/dist/author/index.d.ts +3 -3
- package/dist/author/index.d.ts.map +1 -1
- package/dist/author/index.js +2 -2
- package/dist/author/index.js.map +1 -1
- package/dist/author/options.d.ts +2 -1
- package/dist/author/options.d.ts.map +1 -1
- package/dist/author/options.js.map +1 -1
- package/dist/author/roundtrip.test.d.ts +2 -0
- package/dist/author/roundtrip.test.d.ts.map +1 -0
- package/dist/author/roundtrip.test.js +223 -0
- package/dist/author/roundtrip.test.js.map +1 -0
- package/dist/devtools.d.ts.map +1 -1
- package/dist/devtools.js +196 -1
- package/dist/devtools.js.map +1 -1
- package/dist/element.d.ts +8 -1
- package/dist/element.d.ts.map +1 -1
- package/dist/element.js +12 -1
- package/dist/element.js.map +1 -1
- package/package.json +1 -1
package/dist/author/apply.js
CHANGED
|
@@ -3,7 +3,7 @@ import path from 'node:path';
|
|
|
3
3
|
import { PNG } from 'pngjs';
|
|
4
4
|
import { cellRunsToRects, evenHorizontalSlices, expandLeftForLabel, findAlignedCells, insetRect, kebab, ocrRectFromBoxes, valueBoxesForOcr, relativeToCrop, sliceRectHorizontal, unionRects, } from './geometry.js';
|
|
5
5
|
import { screenDir } from './storage.js';
|
|
6
|
-
import { writeScreenCatalog } from './catalog.js';
|
|
6
|
+
import { writeScreenCatalog, screenCatalogPath } from './catalog.js';
|
|
7
7
|
function cropPng(pngBuffer, x, y, width, height) {
|
|
8
8
|
const png = PNG.sync.read(pngBuffer);
|
|
9
9
|
const sx = Math.max(0, Math.round(x));
|
|
@@ -40,9 +40,10 @@ function cropForElement(el, boxes, fieldBoxes, labelRects, png, extraBoxes = [])
|
|
|
40
40
|
return padRect(unionRects(joined), 2);
|
|
41
41
|
return unionRects(fieldBoxes);
|
|
42
42
|
}
|
|
43
|
-
function toIndex(name, elements, sections) {
|
|
43
|
+
function toIndex(name, elements, sections, ready) {
|
|
44
44
|
return {
|
|
45
45
|
name,
|
|
46
|
+
...(ready !== undefined ? { ready } : {}),
|
|
46
47
|
sections,
|
|
47
48
|
elements,
|
|
48
49
|
};
|
|
@@ -103,6 +104,9 @@ function resolveParts(specs, fieldBoxes, crop, byId, png, prevParts) {
|
|
|
103
104
|
else if (even[i]) {
|
|
104
105
|
rect = even[i];
|
|
105
106
|
}
|
|
107
|
+
else if (part.rect) {
|
|
108
|
+
rect = { ...part.rect, x: crop.x + part.rect.x, y: crop.y + part.rect.y };
|
|
109
|
+
}
|
|
106
110
|
else {
|
|
107
111
|
continue;
|
|
108
112
|
}
|
|
@@ -134,173 +138,467 @@ function readPreviousIndex(dir) {
|
|
|
134
138
|
const indexPath = path.join(dir, 'index.json');
|
|
135
139
|
if (!fs.existsSync(indexPath))
|
|
136
140
|
return new Map();
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
catch {
|
|
142
|
-
return new Map();
|
|
143
|
-
}
|
|
141
|
+
const raw = JSON.parse(fs.readFileSync(indexPath, 'utf8'));
|
|
142
|
+
if (!Array.isArray(raw.elements))
|
|
143
|
+
throw new Error('Existing index.json has no elements array; repair it before Apply.');
|
|
144
|
+
return new Map(raw.elements.map((el) => [el.name, el]));
|
|
144
145
|
}
|
|
145
146
|
function pickOption(next, prev) {
|
|
146
147
|
return next !== undefined ? next : prev;
|
|
147
148
|
}
|
|
149
|
+
function rectOnly(rect) {
|
|
150
|
+
return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
|
|
151
|
+
}
|
|
152
|
+
function sameRect(a, b) {
|
|
153
|
+
return Boolean(a && b && a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height);
|
|
154
|
+
}
|
|
155
|
+
function clampRect(rect, width, height) {
|
|
156
|
+
return { x: rect.x, y: rect.y, width: Math.min(rect.width, width - rect.x), height: Math.min(rect.height, height - rect.y) };
|
|
157
|
+
}
|
|
158
|
+
function validateRect(rect, label) {
|
|
159
|
+
if (!rect || !['x', 'y', 'width', 'height'].every(key => Number.isFinite(rect[key])) || rect.width <= 0 || rect.height <= 0) {
|
|
160
|
+
throw new Error(`${label}: expected a finite rectangle with positive width/height.`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
function validateRelativeRect(rect, anchor, width, height, label) {
|
|
164
|
+
validateRect(rect, label);
|
|
165
|
+
if (anchor.x + rect.x < 0 || anchor.y + rect.y < 0 || anchor.x + rect.x + rect.width > width || anchor.y + rect.y + rect.height > height) {
|
|
166
|
+
throw new Error(`${label}: value region extends outside the reference screenshot.`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
function safeTemplatePath(base, filename) {
|
|
170
|
+
if (typeof filename !== 'string' || !filename || path.isAbsolute(filename) || filename.includes('\\') || filename.split('/').some(part => !part || part === '.' || part === '..') || !filename.toLowerCase().endsWith('.png')) {
|
|
171
|
+
throw new Error(`Invalid template filename: ${JSON.stringify(filename)}. Use a relative PNG path within templates/.`);
|
|
172
|
+
}
|
|
173
|
+
const root = path.resolve(base);
|
|
174
|
+
const file = path.resolve(root, filename);
|
|
175
|
+
for (let current = file; current.startsWith(root); current = path.dirname(current)) {
|
|
176
|
+
if (fs.existsSync(current) && fs.lstatSync(current).isSymbolicLink())
|
|
177
|
+
throw new Error(`Template path must not contain symlinks: ${filename}`);
|
|
178
|
+
if (current === root)
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
return file;
|
|
182
|
+
}
|
|
183
|
+
function validateVariantMap(variants, label) {
|
|
184
|
+
if (!variants || typeof variants !== 'object' || Array.isArray(variants))
|
|
185
|
+
throw new Error(`${label}.variants must be a map of names to { filename }.`);
|
|
186
|
+
for (const [name, value] of Object.entries(variants)) {
|
|
187
|
+
if (!name || !value || typeof value !== 'object' || typeof value.filename !== 'string')
|
|
188
|
+
throw new Error(`${label}: invalid variant ${JSON.stringify(name)}.`);
|
|
189
|
+
safeTemplatePath('/templates', value.filename);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
function validateReady(ready, names) {
|
|
193
|
+
if (ready === undefined)
|
|
194
|
+
return;
|
|
195
|
+
const required = typeof ready === 'string' ? [ready] : Array.isArray(ready) ? ready : ready && Array.isArray(ready.any) ? ready.any : [];
|
|
196
|
+
if (!required.length || required.some(name => typeof name !== 'string' || !names.includes(name)))
|
|
197
|
+
throw new Error('ready must reference existing element names (string, array, or { any: [...] }).');
|
|
198
|
+
}
|
|
199
|
+
function validateReadOptions(record, label) {
|
|
200
|
+
if (record.type !== undefined && (typeof record.type !== 'string' || !record.type))
|
|
201
|
+
throw new Error(`${label}.type must be a nonempty string.`);
|
|
202
|
+
if (record.read !== undefined && !['ocr', 'clipboard'].includes(record.read))
|
|
203
|
+
throw new Error(`${label}.read must be ocr or clipboard.`);
|
|
204
|
+
if (record.overflow !== undefined && !['none', 'left', 'right', 'start', 'end', 'both'].includes(record.overflow))
|
|
205
|
+
throw new Error(`${label}.overflow is invalid.`);
|
|
206
|
+
if (record.options !== undefined && (!Array.isArray(record.options) || record.options.some(value => typeof value !== 'string')))
|
|
207
|
+
throw new Error(`${label}.options must be an array of strings.`);
|
|
208
|
+
if (record.charset !== undefined && typeof record.charset !== 'string') {
|
|
209
|
+
const charset = record.charset;
|
|
210
|
+
if (!charset || !Array.isArray(charset.only) || !charset.only.length || charset.only.some(value => typeof value !== 'string') || (charset.exclude !== undefined && (!Array.isArray(charset.exclude) || charset.exclude.some(value => typeof value !== 'string'))))
|
|
211
|
+
throw new Error(`${label}.charset must be a name or { only: string[], exclude?: string[] }.`);
|
|
212
|
+
}
|
|
213
|
+
if (record.swaps !== undefined && (!record.swaps || typeof record.swaps !== 'object' || Array.isArray(record.swaps) || Object.values(record.swaps).some(value => typeof value !== 'string' && (!Array.isArray(value) || value.some(item => typeof item !== 'string')))))
|
|
214
|
+
throw new Error(`${label}.swaps must map strings to strings or string arrays.`);
|
|
215
|
+
}
|
|
216
|
+
function validateInputs(pass, file, width, height) {
|
|
217
|
+
if (!pass || !Array.isArray(pass.elements) || !pass.elements.length)
|
|
218
|
+
throw new Error('first-pass.json needs a nonempty elements array with boxIds; runtime rectangles alone are not authoring input.');
|
|
219
|
+
if (!file || !Array.isArray(file.boxes))
|
|
220
|
+
throw new Error('boxes.json needs a boxes array from detectScreen() or writeBoxes().');
|
|
221
|
+
const validateBoxes = (boxes, label) => {
|
|
222
|
+
const ids = new Set();
|
|
223
|
+
for (const box of boxes) {
|
|
224
|
+
validateRect(box, `${label} ${box?.id}`);
|
|
225
|
+
if (!Number.isInteger(box.id) || ids.has(box.id))
|
|
226
|
+
throw new Error(`${label}: duplicate or invalid ID ${box.id}.`);
|
|
227
|
+
if (box.x < 0 || box.y < 0 || box.x + box.width > width || box.y + box.height > height)
|
|
228
|
+
throw new Error(`${label} ${box.id}: outside reference screenshot.`);
|
|
229
|
+
ids.add(box.id);
|
|
230
|
+
}
|
|
231
|
+
return ids;
|
|
232
|
+
};
|
|
233
|
+
const ids = validateBoxes(file.boxes, 'box');
|
|
234
|
+
if (file.labels !== undefined && !Array.isArray(file.labels))
|
|
235
|
+
throw new Error('boxes.json labels must be an array.');
|
|
236
|
+
const labels = validateBoxes(file.labels || [], 'label');
|
|
237
|
+
const references = (values, available, label, required = false) => {
|
|
238
|
+
if (!Array.isArray(values) || (required && !values.length) || values.some(id => !available.has(id)))
|
|
239
|
+
throw new Error(`${label}: use existing ${label.includes('label') ? 'label' : 'box'} IDs from boxes.json.`);
|
|
240
|
+
};
|
|
241
|
+
const safeName = (name, label) => {
|
|
242
|
+
if (typeof name !== 'string' || !name.trim() || !kebab(name))
|
|
243
|
+
throw new Error(`${label}: a nonempty name is required.`);
|
|
244
|
+
};
|
|
245
|
+
if (pass.sections !== undefined && !Array.isArray(pass.sections))
|
|
246
|
+
throw new Error('first-pass sections must be an array.');
|
|
247
|
+
const sectionNames = new Set();
|
|
248
|
+
for (const section of pass.sections || []) {
|
|
249
|
+
safeName(section.name, 'section');
|
|
250
|
+
if (sectionNames.has(section.name))
|
|
251
|
+
throw new Error(`Duplicate section ${section.name}.`);
|
|
252
|
+
sectionNames.add(section.name);
|
|
253
|
+
references(section.boxIds, ids, `${section.name}.boxIds`, true);
|
|
254
|
+
if (!pass.elements.some(el => el?.section === section.name) && (section.variants != null || section.ocrRect != null))
|
|
255
|
+
throw new Error(`${section.name}: refinements require section member elements.`);
|
|
256
|
+
if (section.variants != null)
|
|
257
|
+
validateVariantMap(section.variants, section.name);
|
|
258
|
+
if (section.ocrRect != null)
|
|
259
|
+
validateRect(section.ocrRect, section.name + '.ocrRect');
|
|
260
|
+
}
|
|
261
|
+
const names = new Set();
|
|
262
|
+
for (const el of pass.elements) {
|
|
263
|
+
if (!el || typeof el !== 'object')
|
|
264
|
+
throw new Error('Each first-pass element must be an object.');
|
|
265
|
+
safeName(el.name, 'element');
|
|
266
|
+
validateReadOptions(el, el.name);
|
|
267
|
+
const key = `${el.section || ''}:${el.name}`;
|
|
268
|
+
if (names.has(key))
|
|
269
|
+
throw new Error(`Duplicate element ${el.name}.`);
|
|
270
|
+
names.add(key);
|
|
271
|
+
if (el.section && !sectionNames.has(el.section))
|
|
272
|
+
throw new Error(`${el.name}: unknown section ${el.section}.`);
|
|
273
|
+
references(el.boxIds, ids, `${el.name}.boxIds`, true);
|
|
274
|
+
if (el.labelIds !== undefined)
|
|
275
|
+
references(el.labelIds, labels, `${el.name}.labelIds`);
|
|
276
|
+
if (el.ocrRect != null)
|
|
277
|
+
validateRect(el.ocrRect, el.name + '.ocrRect');
|
|
278
|
+
if (el.variants != null)
|
|
279
|
+
validateVariantMap(el.variants, el.name);
|
|
280
|
+
if (el.parts !== undefined && !Array.isArray(el.parts))
|
|
281
|
+
throw new Error(`${el.name}.parts must be an array.`);
|
|
282
|
+
const parts = new Set();
|
|
283
|
+
for (const part of el.parts || []) {
|
|
284
|
+
if (!part || typeof part !== 'object')
|
|
285
|
+
throw new Error(`${el.name}: each part must be an object.`);
|
|
286
|
+
safeName(part.name, `${el.name} part`);
|
|
287
|
+
validateReadOptions(part, `${el.name}.${part.name}`);
|
|
288
|
+
if (parts.has(part.name))
|
|
289
|
+
throw new Error(`${el.name}: duplicate part ${part.name}.`);
|
|
290
|
+
parts.add(part.name);
|
|
291
|
+
if (part.boxId != null && !ids.has(part.boxId))
|
|
292
|
+
throw new Error(`${el.name}.${part.name}: unknown boxId ${part.boxId}.`);
|
|
293
|
+
if ((part.start != null || part.end != null) && !(Number.isFinite(part.start) && Number.isFinite(part.end) && part.start >= 0 && part.end <= 1 && part.start < part.end))
|
|
294
|
+
throw new Error(`${el.name}.${part.name}: invalid part span.`);
|
|
295
|
+
if (part.rect != null)
|
|
296
|
+
validateRect(part.rect, `${el.name}.${part.name}.rect`);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
/** Stage fully, then replace; roll back ordinary I/O/catalog failures as a unit. */
|
|
301
|
+
function commitScreen(dir, stage, index, firstPass, catalogDefaults) {
|
|
302
|
+
const templates = path.join(dir, 'templates');
|
|
303
|
+
const backup = path.join(stage, 'previous-templates');
|
|
304
|
+
const files = [path.join(dir, 'index.json'), path.join(dir, 'first-pass.json'), screenCatalogPath()];
|
|
305
|
+
const previous = files.map(file => fs.existsSync(file) ? fs.readFileSync(file) : undefined);
|
|
306
|
+
fs.writeFileSync(path.join(stage, 'index.json'), JSON.stringify(index, null, 2) + '\n');
|
|
307
|
+
if (firstPass)
|
|
308
|
+
fs.writeFileSync(path.join(stage, 'first-pass.json'), JSON.stringify(firstPass, null, 2) + '\n');
|
|
309
|
+
let movedOld = false, installed = false;
|
|
310
|
+
try {
|
|
311
|
+
if (fs.existsSync(templates)) {
|
|
312
|
+
fs.renameSync(templates, backup);
|
|
313
|
+
movedOld = true;
|
|
314
|
+
}
|
|
315
|
+
fs.renameSync(path.join(stage, 'templates'), templates);
|
|
316
|
+
installed = true;
|
|
317
|
+
fs.renameSync(path.join(stage, 'index.json'), files[0]);
|
|
318
|
+
if (firstPass)
|
|
319
|
+
fs.renameSync(path.join(stage, 'first-pass.json'), files[1]);
|
|
320
|
+
writeScreenCatalog(undefined, undefined, catalogDefaults);
|
|
321
|
+
}
|
|
322
|
+
catch (error) {
|
|
323
|
+
if (installed)
|
|
324
|
+
fs.rmSync(templates, { recursive: true, force: true });
|
|
325
|
+
if (movedOld)
|
|
326
|
+
fs.renameSync(backup, templates);
|
|
327
|
+
files.forEach((file, i) => { const bytes = previous[i]; if (bytes)
|
|
328
|
+
fs.writeFileSync(file, bytes);
|
|
329
|
+
else
|
|
330
|
+
fs.rmSync(file, { force: true }); });
|
|
331
|
+
throw error;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
148
334
|
/**
|
|
149
335
|
* Turn first-pass.json (boxIds) into templates/ + index.json.
|
|
150
336
|
* Pass `firstPass` to write that file first if you're generating it programmatically.
|
|
151
337
|
*/
|
|
152
|
-
export function applyScreen(name, firstPass) {
|
|
338
|
+
export function applyScreen(name, firstPass, options = {}) {
|
|
153
339
|
const dir = screenDir(name);
|
|
154
340
|
const firstPassPath = path.join(dir, 'first-pass.json');
|
|
155
|
-
if (firstPass) {
|
|
156
|
-
fs.writeFileSync(firstPassPath, `${JSON.stringify(firstPass, null, 2)}\n`);
|
|
157
|
-
}
|
|
158
341
|
const blankPath = path.join(dir, 'blank.png');
|
|
159
342
|
const boxesPath = path.join(dir, 'boxes.json');
|
|
160
|
-
if (!fs.existsSync(blankPath))
|
|
343
|
+
if (!fs.existsSync(blankPath))
|
|
161
344
|
throw new Error(`applyScreen('${name}'): no blank.png at ${blankPath}`);
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
if (!fs.existsSync(firstPassPath)) {
|
|
167
|
-
throw new Error(`applyScreen('${name}'): no first-pass.json — pass the AI naming result as the second argument`);
|
|
168
|
-
}
|
|
345
|
+
if (!fs.existsSync(boxesPath))
|
|
346
|
+
throw new Error(`applyScreen('${name}'): no boxes.json — use detectScreen() or writeBoxes() first`);
|
|
347
|
+
if (!firstPass && !fs.existsSync(firstPassPath))
|
|
348
|
+
throw new Error(`applyScreen('${name}'): no first-pass.json — supply box-ID authoring data`);
|
|
169
349
|
const blank = fs.readFileSync(blankPath);
|
|
170
350
|
const png = PNG.sync.read(blank);
|
|
171
351
|
const boxesFile = JSON.parse(fs.readFileSync(boxesPath, 'utf8'));
|
|
352
|
+
const pass = firstPass ?? JSON.parse(fs.readFileSync(firstPassPath, 'utf8'));
|
|
353
|
+
validateInputs(pass, boxesFile, png.width, png.height);
|
|
172
354
|
const { boxes } = boxesFile;
|
|
173
355
|
const labels = boxesFile.labels || [];
|
|
174
|
-
const pass = JSON.parse(fs.readFileSync(firstPassPath, 'utf8'));
|
|
175
356
|
const previous = readPreviousIndex(dir);
|
|
357
|
+
const oldIndex = fs.existsSync(path.join(dir, 'index.json')) ? JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')) : {};
|
|
176
358
|
const byId = new Map(boxes.map((box) => [box.id, box]));
|
|
177
359
|
const byLabel = new Map(labels.map((label) => [label.id, label]));
|
|
178
|
-
const
|
|
179
|
-
fs.
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
360
|
+
const originalTemplates = path.join(dir, 'templates');
|
|
361
|
+
const stage = fs.mkdtempSync(path.join(dir, '.apply-'));
|
|
362
|
+
const tmplDir = path.join(stage, 'templates');
|
|
363
|
+
const warnings = [];
|
|
364
|
+
fs.mkdirSync(tmplDir);
|
|
365
|
+
try {
|
|
366
|
+
// Sections whose members should be merged into a single parent element with named parts.
|
|
367
|
+
// A section is absorbed when it has at least one member element; the parent name is the
|
|
368
|
+
// section name with the trailing "Section" suffix stripped.
|
|
369
|
+
const membersBySection = new Map();
|
|
370
|
+
for (const el of pass.elements || []) {
|
|
371
|
+
if (el.section) {
|
|
372
|
+
const group = membersBySection.get(el.section) ?? [];
|
|
373
|
+
group.push(el);
|
|
374
|
+
membersBySection.set(el.section, group);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
const absorbedSections = new Set();
|
|
378
|
+
const syntheticElements = [];
|
|
379
|
+
const usedParentNames = new Set();
|
|
380
|
+
for (const sec of pass.sections || []) {
|
|
381
|
+
const members = membersBySection.get(sec.name);
|
|
382
|
+
if (!members?.length)
|
|
383
|
+
continue;
|
|
384
|
+
const parentName = sec.name.replace(/Section$/, '') || sec.name;
|
|
385
|
+
if (usedParentNames.has(parentName))
|
|
386
|
+
throw new Error(`Sections generate the same parent name: ${parentName}. Rename one section.`);
|
|
387
|
+
usedParentNames.add(parentName);
|
|
388
|
+
absorbedSections.add(sec.name);
|
|
389
|
+
const allLabelIds = [...new Set(members.flatMap((m) => m.labelIds ?? []))];
|
|
390
|
+
const synthetic = {
|
|
391
|
+
name: parentName,
|
|
392
|
+
type: 'other',
|
|
393
|
+
...(sec.ocrRect !== undefined ? { ocrRect: sec.ocrRect } : {}),
|
|
394
|
+
...(sec.variants !== undefined ? { variants: sec.variants } : {}),
|
|
395
|
+
boxIds: sec.boxIds,
|
|
396
|
+
labelIds: allLabelIds,
|
|
397
|
+
parts: members.map((m) => ({
|
|
398
|
+
name: m.name,
|
|
399
|
+
...(m.type ? { type: m.type } : {}),
|
|
400
|
+
...(m.read ? { read: m.read } : {}),
|
|
401
|
+
...(m.charset ? { charset: m.charset } : {}),
|
|
402
|
+
...(m.swaps ? { swaps: m.swaps } : {}),
|
|
403
|
+
...(m.overflow ? { overflow: m.overflow } : {}),
|
|
404
|
+
...((m.boxIds ?? [])[0] != null ? { boxId: (m.boxIds ?? [])[0] } : {}),
|
|
405
|
+
})),
|
|
406
|
+
};
|
|
407
|
+
const parentCropRaw = cropForElement(synthetic, boxes, sec.boxIds.map(id => byId.get(id)), allLabelIds.map(id => byLabel.get(id)), png);
|
|
408
|
+
const parentCrop = parentCropRaw && clampRect(parentCropRaw, png.width, png.height);
|
|
409
|
+
for (const member of members) {
|
|
410
|
+
if (member.variants !== undefined)
|
|
411
|
+
throw new Error(`${sec.name}.${member.name}: variants belong on the section parent, not an absorbed member.`);
|
|
412
|
+
if (member.parts?.length)
|
|
413
|
+
throw new Error(`${sec.name}.${member.name}: nested parts are not supported for absorbed members.`);
|
|
414
|
+
if (member.ocrRect !== undefined) {
|
|
415
|
+
const part = synthetic.parts.find(part => part.name === member.name);
|
|
416
|
+
if (member.ocrRect === null)
|
|
417
|
+
part.rect = null;
|
|
418
|
+
else {
|
|
419
|
+
const memberCropRaw = cropForElement(member, boxes, member.boxIds.map(id => byId.get(id)), (member.labelIds || []).map(id => byLabel.get(id)), png);
|
|
420
|
+
if (!parentCrop || !memberCropRaw)
|
|
421
|
+
throw new Error(`No crop for section member ${member.name}.`);
|
|
422
|
+
const memberCrop = clampRect(memberCropRaw, png.width, png.height);
|
|
423
|
+
part.rect = { ...member.ocrRect, x: memberCrop.x + member.ocrRect.x - parentCrop.x, y: memberCrop.y + member.ocrRect.y - parentCrop.y };
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
syntheticElements.push(synthetic);
|
|
428
|
+
}
|
|
429
|
+
const indexSections = [];
|
|
430
|
+
const sectionFile = new Map();
|
|
431
|
+
const sectionBoxesByName = new Map();
|
|
432
|
+
for (const sec of pass.sections || []) {
|
|
433
|
+
if (absorbedSections.has(sec.name))
|
|
434
|
+
continue;
|
|
435
|
+
const secBoxes = (sec.boxIds || []).map((id) => byId.get(id)).filter((b) => Boolean(b));
|
|
436
|
+
if (!sec.name || !secBoxes.length)
|
|
437
|
+
continue;
|
|
438
|
+
const memberLabels = (pass.elements || [])
|
|
439
|
+
.filter((el) => el.section === sec.name)
|
|
440
|
+
.flatMap((el) => (el.labelIds || []).map((id) => byLabel.get(id)).filter((l) => Boolean(l)));
|
|
441
|
+
const union = unionRects([...secBoxes, ...memberLabels]);
|
|
442
|
+
const crop = clampRect(padRect(union, memberLabels.length ? 4 : 2), png.width, png.height);
|
|
443
|
+
const filename = `section-${kebab(sec.name)}.png`;
|
|
444
|
+
fs.writeFileSync(path.join(tmplDir, filename), cropPng(blank, crop.x, crop.y, crop.width, crop.height));
|
|
445
|
+
indexSections.push({ name: sec.name, filename, ...crop });
|
|
446
|
+
sectionFile.set(sec.name, filename);
|
|
447
|
+
sectionBoxesByName.set(sec.name, secBoxes);
|
|
448
|
+
}
|
|
449
|
+
const allElements = [
|
|
450
|
+
...syntheticElements,
|
|
451
|
+
...(pass.elements || []).filter((el) => !el.section || !absorbedSections.has(el.section)),
|
|
452
|
+
];
|
|
453
|
+
const owners = new Map();
|
|
454
|
+
for (const [filename, owner] of [
|
|
455
|
+
...indexSections.map(section => [section.filename, `section ${section.name}`]),
|
|
456
|
+
...allElements.map(el => [`${kebab(el.name)}.png`, el.name]),
|
|
457
|
+
]) {
|
|
458
|
+
if (owners.has(filename))
|
|
459
|
+
throw new Error(`Generated filename collision: ${filename}. Rename the conflicting elements/sections.`);
|
|
460
|
+
owners.set(filename, owner);
|
|
190
461
|
}
|
|
462
|
+
const elements = [];
|
|
463
|
+
for (const el of allElements) {
|
|
464
|
+
const fieldBoxes = (el.boxIds || []).map((id) => byId.get(id)).filter((b) => Boolean(b));
|
|
465
|
+
const labelRects = (el.labelIds || []).map((id) => byLabel.get(id)).filter((l) => Boolean(l));
|
|
466
|
+
const extraBoxes = el.section ? (sectionBoxesByName.get(el.section) || []) : [];
|
|
467
|
+
const overlayRaw = cropForElement(el, boxes, fieldBoxes, labelRects, png);
|
|
468
|
+
const matchRaw = cropForElement(el, boxes, fieldBoxes, labelRects, png, extraBoxes);
|
|
469
|
+
const overlay = overlayRaw && clampRect(overlayRaw, png.width, png.height);
|
|
470
|
+
const match = matchRaw && clampRect(matchRaw, png.width, png.height);
|
|
471
|
+
if (!match)
|
|
472
|
+
throw new Error(`No crop can be generated for "${el.name}".`);
|
|
473
|
+
const filename = `${kebab(el.name)}.png`;
|
|
474
|
+
fs.writeFileSync(path.join(tmplDir, filename), cropPng(blank, match.x, match.y, match.width, match.height));
|
|
475
|
+
const prev = previous.get(el.name);
|
|
476
|
+
const parts = resolveParts(el.parts || [], fieldBoxes, match, byId, png, prev?.parts);
|
|
477
|
+
const shown = overlay || match;
|
|
478
|
+
const applied = {
|
|
479
|
+
name: el.name,
|
|
480
|
+
filename,
|
|
481
|
+
type: el.type || 'field',
|
|
482
|
+
x: shown.x,
|
|
483
|
+
y: shown.y,
|
|
484
|
+
width: shown.width,
|
|
485
|
+
height: shown.height,
|
|
486
|
+
};
|
|
487
|
+
if (el.boxIds?.length)
|
|
488
|
+
applied.boxIds = el.boxIds;
|
|
489
|
+
if (el.labelIds?.length)
|
|
490
|
+
applied.labelIds = el.labelIds;
|
|
491
|
+
const charset = pickOption(el.charset, prev?.charset);
|
|
492
|
+
const swaps = pickOption(el.swaps, prev?.swaps);
|
|
493
|
+
const overflow = pickOption(el.overflow, prev?.overflow);
|
|
494
|
+
const read = pickOption(el.read, prev?.read);
|
|
495
|
+
if (charset)
|
|
496
|
+
applied.charset = charset;
|
|
497
|
+
if (swaps)
|
|
498
|
+
applied.swaps = swaps;
|
|
499
|
+
if (overflow)
|
|
500
|
+
applied.overflow = overflow;
|
|
501
|
+
if (read)
|
|
502
|
+
applied.read = read;
|
|
503
|
+
const choices = pickOption(el.options, prev?.options);
|
|
504
|
+
if (choices?.length)
|
|
505
|
+
applied.options = choices;
|
|
506
|
+
if (el.section)
|
|
507
|
+
applied.section = sectionFile.get(el.section) || el.section;
|
|
508
|
+
if (el.type !== 'other') {
|
|
509
|
+
const ocrBoxes = parts.length
|
|
510
|
+
? parts.map((part) => ({
|
|
511
|
+
x: match.x + part.x,
|
|
512
|
+
y: match.y + part.y,
|
|
513
|
+
width: part.width,
|
|
514
|
+
height: part.height,
|
|
515
|
+
}))
|
|
516
|
+
: valueBoxesForOcr(fieldBoxes, el.type || 'field');
|
|
517
|
+
if (ocrBoxes.length)
|
|
518
|
+
applied.ocrRect = ocrRectFromBoxes(match, ocrBoxes, el.type || 'field');
|
|
519
|
+
}
|
|
520
|
+
if (parts.length)
|
|
521
|
+
applied.parts = parts;
|
|
522
|
+
const orderedRects = (rects) => rects.map(rect => relativeToCrop(rect, match)).sort((a, b) => a.x - b.x || a.y - b.y || a.width - b.width || a.height - b.height);
|
|
523
|
+
const layout = JSON.stringify({
|
|
524
|
+
width: match.width, height: match.height,
|
|
525
|
+
fields: orderedRects(fieldBoxes),
|
|
526
|
+
labels: orderedRects(labelRects),
|
|
527
|
+
extra: orderedRects(extraBoxes),
|
|
528
|
+
parts: parts.map(part => ({ name: part.name, rect: rectOnly(part) })).sort((a, b) => a.name.localeCompare(b.name)),
|
|
529
|
+
});
|
|
530
|
+
const generatedParts = parts.map(part => ({ name: part.name, rect: rectOnly(part) }));
|
|
531
|
+
const generatedOcrRect = applied.ocrRect;
|
|
532
|
+
const inheritedOcr = prev?.ocrRect && !sameRect(prev.ocrRect, prev.authoring ? prev.authoring.generatedOcrRect : generatedOcrRect) ? prev.ocrRect : undefined;
|
|
533
|
+
const refinedParts = parts.flatMap(part => {
|
|
534
|
+
const spec = (el.parts || []).find(p => p.name === part.name);
|
|
535
|
+
const old = prev?.parts?.find(p => p.name === part.name);
|
|
536
|
+
const baseline = prev?.authoring?.generatedParts.find(p => p.name === part.name)?.rect ?? rectOnly(part);
|
|
537
|
+
const inherited = old && !sameRect(old, baseline) ? rectOnly(old) : undefined;
|
|
538
|
+
return spec?.rect || (spec?.rect !== null && inherited) ? [{ part, rect: spec?.rect || inherited }] : [];
|
|
539
|
+
});
|
|
540
|
+
const variants = el.variants !== undefined ? el.variants : prev?.variants;
|
|
541
|
+
const explicitOcr = el.ocrRect !== undefined ? el.ocrRect : inheritedOcr;
|
|
542
|
+
const hasRefinements = Boolean(explicitOcr || refinedParts.length || (variants && Object.keys(variants).length));
|
|
543
|
+
const sameLayout = prev?.authoring ? prev.authoring.layout === layout : prev?.width === shown.width && prev?.height === shown.height;
|
|
544
|
+
if (prev && hasRefinements && !sameLayout && !options.confirmLayoutChange) {
|
|
545
|
+
throw new Error(`Layout changed for "${el.name}". Review its variants/value regions, then apply with { confirmLayoutChange: true }, or explicitly clear obsolete refinements.`);
|
|
546
|
+
}
|
|
547
|
+
if (explicitOcr) {
|
|
548
|
+
validateRelativeRect(explicitOcr, match, png.width, png.height, `${el.name}.ocrRect`);
|
|
549
|
+
applied.ocrRect = explicitOcr;
|
|
550
|
+
}
|
|
551
|
+
for (const { part, rect } of refinedParts) {
|
|
552
|
+
validateRelativeRect(rect, match, png.width, png.height, `${el.name}.${part.name}.rect`);
|
|
553
|
+
Object.assign(part, rect);
|
|
554
|
+
}
|
|
555
|
+
applied.authoring = { layout, generatedParts, ...(generatedOcrRect ? { generatedOcrRect } : {}) };
|
|
556
|
+
if (variants && Object.keys(variants).length) {
|
|
557
|
+
validateVariantMap(variants, el.name);
|
|
558
|
+
for (const variant of Object.values(variants)) {
|
|
559
|
+
const filename = variant.filename;
|
|
560
|
+
if (owners.has(filename.toLowerCase()) && owners.get(filename.toLowerCase()) !== el.name)
|
|
561
|
+
throw new Error(`Variant "${filename}" collides with a generated template.`);
|
|
562
|
+
const source = safeTemplatePath(originalTemplates, filename);
|
|
563
|
+
const destination = safeTemplatePath(tmplDir, filename);
|
|
564
|
+
if (filename !== applied.filename && fs.existsSync(destination))
|
|
565
|
+
throw new Error(`Variant "${filename}" collides with a generated template.`);
|
|
566
|
+
if (fs.existsSync(source)) {
|
|
567
|
+
PNG.sync.read(fs.readFileSync(source));
|
|
568
|
+
fs.mkdirSync(path.dirname(destination), { recursive: true });
|
|
569
|
+
fs.copyFileSync(source, destination);
|
|
570
|
+
}
|
|
571
|
+
else if (filename !== applied.filename)
|
|
572
|
+
throw new Error(`Missing variant image "${filename}" for "${el.name}".`);
|
|
573
|
+
}
|
|
574
|
+
if (prev?.filename && prev.variants)
|
|
575
|
+
warnings.push(`${el.name}: normalized combined filename/variants to a variant-only definition.`);
|
|
576
|
+
applied.variants = variants;
|
|
577
|
+
delete applied.filename;
|
|
578
|
+
}
|
|
579
|
+
elements.push(applied);
|
|
580
|
+
}
|
|
581
|
+
const folder = pass.screen?.name || name;
|
|
582
|
+
const indexPath = path.join(dir, 'index.json');
|
|
583
|
+
const ready = pass.ready !== undefined ? pass.ready ?? undefined : oldIndex.ready;
|
|
584
|
+
validateReady(ready, elements.map(el => el.name));
|
|
585
|
+
const index = toIndex(folder, elements, indexSections, ready);
|
|
586
|
+
if (!options.dryRun)
|
|
587
|
+
commitScreen(dir, stage, index, firstPass, options.catalogDefaults);
|
|
588
|
+
return { dir, indexPath, firstPassPath, elements, warnings };
|
|
191
589
|
}
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
const usedParentNames = new Set();
|
|
195
|
-
for (const sec of pass.sections || []) {
|
|
196
|
-
const members = membersBySection.get(sec.name);
|
|
197
|
-
if (!members?.length)
|
|
198
|
-
continue;
|
|
199
|
-
absorbedSections.add(sec.name);
|
|
200
|
-
const parentName = sec.name.replace(/Section$/, '') || sec.name;
|
|
201
|
-
if (usedParentNames.has(parentName))
|
|
202
|
-
continue; // skip duplicates silently
|
|
203
|
-
usedParentNames.add(parentName);
|
|
204
|
-
const allLabelIds = [...new Set(members.flatMap((m) => m.labelIds ?? []))];
|
|
205
|
-
syntheticElements.push({
|
|
206
|
-
name: parentName,
|
|
207
|
-
type: 'other',
|
|
208
|
-
boxIds: sec.boxIds,
|
|
209
|
-
labelIds: allLabelIds,
|
|
210
|
-
parts: members.map((m) => ({
|
|
211
|
-
name: m.name,
|
|
212
|
-
...(m.type ? { type: m.type } : {}),
|
|
213
|
-
...((m.boxIds ?? [])[0] != null ? { boxId: (m.boxIds ?? [])[0] } : {}),
|
|
214
|
-
})),
|
|
215
|
-
});
|
|
590
|
+
finally {
|
|
591
|
+
fs.rmSync(stage, { recursive: true, force: true });
|
|
216
592
|
}
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
const secBoxes = (sec.boxIds || []).map((id) => byId.get(id)).filter((b) => Boolean(b));
|
|
224
|
-
if (!sec.name || !secBoxes.length)
|
|
225
|
-
continue;
|
|
226
|
-
const memberLabels = (pass.elements || [])
|
|
227
|
-
.filter((el) => el.section === sec.name)
|
|
228
|
-
.flatMap((el) => (el.labelIds || []).map((id) => byLabel.get(id)).filter((l) => Boolean(l)));
|
|
229
|
-
const union = unionRects([...secBoxes, ...memberLabels]);
|
|
230
|
-
const crop = padRect(union, memberLabels.length ? 4 : 2);
|
|
231
|
-
const filename = `section-${kebab(sec.name)}.png`;
|
|
232
|
-
fs.writeFileSync(path.join(tmplDir, filename), cropPng(blank, crop.x, crop.y, crop.width, crop.height));
|
|
233
|
-
indexSections.push({ name: sec.name, filename, ...crop });
|
|
234
|
-
sectionFile.set(sec.name, filename);
|
|
235
|
-
sectionBoxesByName.set(sec.name, secBoxes);
|
|
593
|
+
}
|
|
594
|
+
/** Full read-only authoring preflight, including generated crops and referenced state images. */
|
|
595
|
+
export function validateScreenAuthoring(name, firstPass, options = {}) {
|
|
596
|
+
try {
|
|
597
|
+
const result = applyScreen(name, firstPass, { ...options, dryRun: true });
|
|
598
|
+
return { valid: true, errors: [], warnings: result.warnings, elements: result.elements.map(el => el.name) };
|
|
236
599
|
}
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
...(pass.elements || []).filter((el) => !el.section || !absorbedSections.has(el.section)),
|
|
240
|
-
];
|
|
241
|
-
const elements = [];
|
|
242
|
-
for (const el of allElements) {
|
|
243
|
-
const fieldBoxes = (el.boxIds || []).map((id) => byId.get(id)).filter((b) => Boolean(b));
|
|
244
|
-
const labelRects = (el.labelIds || []).map((id) => byLabel.get(id)).filter((l) => Boolean(l));
|
|
245
|
-
const extraBoxes = el.section ? (sectionBoxesByName.get(el.section) || []) : [];
|
|
246
|
-
const overlay = cropForElement(el, boxes, fieldBoxes, labelRects, png);
|
|
247
|
-
const match = cropForElement(el, boxes, fieldBoxes, labelRects, png, extraBoxes);
|
|
248
|
-
if (!match)
|
|
249
|
-
continue;
|
|
250
|
-
const filename = `${kebab(el.name)}.png`;
|
|
251
|
-
fs.writeFileSync(path.join(tmplDir, filename), cropPng(blank, match.x, match.y, match.width, match.height));
|
|
252
|
-
const prev = previous.get(el.name);
|
|
253
|
-
const parts = resolveParts(el.parts || [], fieldBoxes, match, byId, png, prev?.parts);
|
|
254
|
-
const shown = overlay || match;
|
|
255
|
-
const applied = {
|
|
256
|
-
name: el.name,
|
|
257
|
-
filename,
|
|
258
|
-
type: el.type || 'field',
|
|
259
|
-
x: shown.x,
|
|
260
|
-
y: shown.y,
|
|
261
|
-
width: shown.width,
|
|
262
|
-
height: shown.height,
|
|
263
|
-
};
|
|
264
|
-
if (el.boxIds?.length)
|
|
265
|
-
applied.boxIds = el.boxIds;
|
|
266
|
-
if (el.labelIds?.length)
|
|
267
|
-
applied.labelIds = el.labelIds;
|
|
268
|
-
const charset = pickOption(el.charset, prev?.charset);
|
|
269
|
-
const swaps = pickOption(el.swaps, prev?.swaps);
|
|
270
|
-
const overflow = pickOption(el.overflow, prev?.overflow);
|
|
271
|
-
const read = pickOption(el.read, prev?.read);
|
|
272
|
-
if (charset)
|
|
273
|
-
applied.charset = charset;
|
|
274
|
-
if (swaps)
|
|
275
|
-
applied.swaps = swaps;
|
|
276
|
-
if (overflow)
|
|
277
|
-
applied.overflow = overflow;
|
|
278
|
-
if (read)
|
|
279
|
-
applied.read = read;
|
|
280
|
-
if (el.options?.length)
|
|
281
|
-
applied.options = el.options;
|
|
282
|
-
if (el.section)
|
|
283
|
-
applied.section = sectionFile.get(el.section) || el.section;
|
|
284
|
-
if (el.type !== 'other') {
|
|
285
|
-
const ocrBoxes = parts.length
|
|
286
|
-
? parts.map((part) => ({
|
|
287
|
-
x: match.x + part.x,
|
|
288
|
-
y: match.y + part.y,
|
|
289
|
-
width: part.width,
|
|
290
|
-
height: part.height,
|
|
291
|
-
}))
|
|
292
|
-
: valueBoxesForOcr(fieldBoxes, el.type || 'field');
|
|
293
|
-
if (ocrBoxes.length)
|
|
294
|
-
applied.ocrRect = ocrRectFromBoxes(match, ocrBoxes, el.type || 'field');
|
|
295
|
-
}
|
|
296
|
-
if (parts.length)
|
|
297
|
-
applied.parts = parts;
|
|
298
|
-
elements.push(applied);
|
|
600
|
+
catch (error) {
|
|
601
|
+
return { valid: false, errors: [error instanceof Error ? error.message : String(error)], warnings: [], elements: [] };
|
|
299
602
|
}
|
|
300
|
-
const folder = pass.screen?.name || name;
|
|
301
|
-
const indexPath = path.join(dir, 'index.json');
|
|
302
|
-
fs.writeFileSync(indexPath, `${JSON.stringify(toIndex(folder, elements, indexSections), null, 2)}\n`);
|
|
303
|
-
writeScreenCatalog();
|
|
304
|
-
return { dir, indexPath, firstPassPath, elements };
|
|
305
603
|
}
|
|
306
604
|
//# sourceMappingURL=apply.js.map
|