@rickcedwhat/playwright-smart-vision 0.4.0-next.b06798f → 0.4.0-next.b24e121

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