@invarn/cibuild 2.3.7 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/cli.cjs +54 -37
  2. package/dist/src/cli.js +8 -0
  3. package/dist/src/commands/fidelity-trim.d.ts +13 -0
  4. package/dist/src/commands/fidelity-trim.d.ts.map +1 -0
  5. package/dist/src/commands/fidelity-trim.js +21 -0
  6. package/dist/src/commands/fidelity-trim.test.d.ts +8 -0
  7. package/dist/src/commands/fidelity-trim.test.d.ts.map +1 -0
  8. package/dist/src/commands/fidelity-trim.test.js +79 -0
  9. package/dist/src/yaml/steps/render-post-processor.d.ts +52 -32
  10. package/dist/src/yaml/steps/render-post-processor.d.ts.map +1 -1
  11. package/dist/src/yaml/steps/render-post-processor.js +104 -205
  12. package/dist/src/yaml/steps/render-post-processor.test.d.ts +7 -10
  13. package/dist/src/yaml/steps/render-post-processor.test.d.ts.map +1 -1
  14. package/dist/src/yaml/steps/render-post-processor.test.js +80 -183
  15. package/dist/src/yaml/steps/trim-align-corpus.test.d.ts +28 -0
  16. package/dist/src/yaml/steps/trim-align-corpus.test.d.ts.map +1 -0
  17. package/dist/src/yaml/steps/trim-align-corpus.test.js +383 -0
  18. package/dist/src/yaml/steps/trim-align.d.ts +85 -0
  19. package/dist/src/yaml/steps/trim-align.d.ts.map +1 -0
  20. package/dist/src/yaml/steps/trim-align.js +348 -0
  21. package/dist/src/yaml/steps/trim-align.test.d.ts +11 -0
  22. package/dist/src/yaml/steps/trim-align.test.d.ts.map +1 -0
  23. package/dist/src/yaml/steps/trim-align.test.js +258 -0
  24. package/dist/src/yaml/steps/ui-fidelity-preview-android.d.ts +1 -1
  25. package/dist/src/yaml/steps/ui-fidelity-preview-android.d.ts.map +1 -1
  26. package/dist/src/yaml/steps/ui-fidelity-preview-android.js +9 -0
  27. package/dist/src/yaml/steps/ui-fidelity-preview-android.test.js +4 -3
  28. package/dist/src/yaml/steps/ui-fidelity-preview.d.ts.map +1 -1
  29. package/dist/src/yaml/steps/ui-fidelity-preview.js +9 -0
  30. package/dist/src/yaml/steps/ui-fidelity-preview.test.js +13 -3
  31. package/dist/src/yaml/steps/ui-fidelity-render-android.d.ts.map +1 -1
  32. package/dist/src/yaml/steps/ui-fidelity-render-android.js +7 -16
  33. package/dist/src/yaml/steps/ui-fidelity-render-android.test.js +9 -9
  34. package/dist/src/yaml/steps/ui-fidelity-render.js +1 -1
  35. package/dist/src/yaml/steps/ui-fidelity-render.test.js +25 -20
  36. package/package.json +3 -1
@@ -0,0 +1,383 @@
1
+ /**
2
+ * Corpus gate for the pure-JS trim/align port (fidelity-linux 06).
3
+ *
4
+ * Runs the RETIRED CoreGraphics/Swift helper (kept verbatim below as the
5
+ * equivalence oracle — it no longer ships) and the JS port over the same
6
+ * inputs and requires:
7
+ *
8
+ * - pixel-identical TRIMMED outputs (decoded RGBA compare) — HARD. The
9
+ * trimmed image is what feeds render digests and the fidelity history.
10
+ * - identical TRIMDIMS lines — HARD.
11
+ * - identical exit codes on failure inputs — HARD.
12
+ * - pixel-identical ALIGNED outputs whenever the Swift path did not resample
13
+ * (trimmed size == reference size, integer placement) — HARD. Where
14
+ * CoreGraphics resampled, its proprietary `.high` interpolation is not
15
+ * bit-reproducible outside CoreGraphics; those cases assert canvas
16
+ * geometry and report the pixel deltas in the run summary instead.
17
+ *
18
+ * Inputs: crafted scenes covering every bounding-box branch (including
19
+ * anti-aliased/semi-transparent edges, where the premultiplied-analysis
20
+ * subtlety lives), plus every real PNG pair found under
21
+ * CIBUILD_TRIM_CORPUS_DIR (rendered screens, Figma-extracted references,
22
+ * alpha-heavy assets), each run as no-reference, self-reference, and
23
+ * cross-reference cases.
24
+ *
25
+ * Gated behind CIBUILD_UI_FIDELITY_REAL_SWIFT=1 (needs a real `swift`).
26
+ */
27
+ import { spawnSync } from 'node:child_process';
28
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync, } from 'node:fs';
29
+ import { tmpdir } from 'node:os';
30
+ import { join } from 'node:path';
31
+ import { PNG } from 'pngjs';
32
+ import { describe, test, expect, afterAll } from '@jest/globals';
33
+ import { runTrimAlign } from './trim-align.js';
34
+ const realSwiftTest = process.env.CIBUILD_UI_FIDELITY_REAL_SWIFT === '1' ? test : test.skip;
35
+ // The retired helper, verbatim (was TRIM_HELPER_SWIFT_SOURCE in
36
+ // render-post-processor.ts). Do not edit: it is the oracle the port is
37
+ // measured against.
38
+ const RETIRED_TRIM_HELPER_SWIFT = [
39
+ 'import Foundation',
40
+ 'import ImageIO',
41
+ 'import CoreGraphics',
42
+ 'import UniformTypeIdentifiers',
43
+ '',
44
+ 'func loadCGImage(_ path: String) -> CGImage? {',
45
+ ' guard let src = CGImageSourceCreateWithURL(URL(fileURLWithPath: path) as CFURL, nil),',
46
+ ' let img = CGImageSourceCreateImageAtIndex(src, 0, nil) else { return nil }',
47
+ ' return img',
48
+ '}',
49
+ '',
50
+ 'func writePNG(_ image: CGImage, to path: String) -> Bool {',
51
+ ' guard let dest = CGImageDestinationCreateWithURL(URL(fileURLWithPath: path) as CFURL, UTType.png.identifier as CFString, 1, nil) else { return false }',
52
+ ' CGImageDestinationAddImage(dest, image, nil)',
53
+ ' return CGImageDestinationFinalize(dest)',
54
+ '}',
55
+ '',
56
+ 'func fitPad(_ image: CGImage, toWidth w: Int, height h: Int) -> CGImage? {',
57
+ ' if w <= 0 || h <= 0 { return nil }',
58
+ ' let bytesPerRow = w * 4',
59
+ ' let space = CGColorSpaceCreateDeviceRGB()',
60
+ ' guard let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: space, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }',
61
+ ' ctx.clear(CGRect(x: 0, y: 0, width: w, height: h))',
62
+ ' ctx.interpolationQuality = .high',
63
+ ' let scale = min(Double(w) / Double(image.width), Double(h) / Double(image.height))',
64
+ ' let drawW = Double(image.width) * scale',
65
+ ' let drawH = Double(image.height) * scale',
66
+ ' let originX = (Double(w) - drawW) / 2.0',
67
+ ' let originY = (Double(h) - drawH) / 2.0',
68
+ ' ctx.draw(image, in: CGRect(x: originX, y: originY, width: drawW, height: drawH))',
69
+ ' return ctx.makeImage()',
70
+ '}',
71
+ '',
72
+ 'func contentBoundingBox(_ image: CGImage) -> CGRect? {',
73
+ ' let w = image.width, h = image.height',
74
+ ' if w == 0 || h == 0 { return nil }',
75
+ ' let bytesPerRow = w * 4',
76
+ ' var data = [UInt8](repeating: 0, count: bytesPerRow * h)',
77
+ ' let space = CGColorSpaceCreateDeviceRGB()',
78
+ ' guard let ctx = CGContext(data: &data, width: w, height: h, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: space, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil }',
79
+ ' ctx.draw(image, in: CGRect(x: 0, y: 0, width: w, height: h))',
80
+ ' let tolerance = 4',
81
+ ' func sample(_ x: Int, _ y: Int) -> (Int, Int, Int, Int) {',
82
+ ' let i = y * bytesPerRow + x * 4',
83
+ ' return (Int(data[i]), Int(data[i + 1]), Int(data[i + 2]), Int(data[i + 3]))',
84
+ ' }',
85
+ ' var aMinX = w, aMinY = h, aMaxX = -1, aMaxY = -1',
86
+ ' for y in 0..<h {',
87
+ ' let rowBase = y * bytesPerRow',
88
+ ' for x in 0..<w {',
89
+ ' if data[rowBase + x * 4 + 3] > 0 {',
90
+ ' if x < aMinX { aMinX = x }',
91
+ ' if x > aMaxX { aMaxX = x }',
92
+ ' if y < aMinY { aMinY = y }',
93
+ ' if y > aMaxY { aMaxY = y }',
94
+ ' }',
95
+ ' }',
96
+ ' }',
97
+ ' if aMaxX < 0 { return nil }',
98
+ ' let opaqueBox = CGRect(x: aMinX, y: aMinY, width: aMaxX - aMinX + 1, height: aMaxY - aMinY + 1)',
99
+ ' let corners = [sample(aMinX, aMinY), sample(aMaxX, aMinY), sample(aMinX, aMaxY), sample(aMaxX, aMaxY)]',
100
+ ' var background: (Int, Int, Int, Int)? = corners[0]',
101
+ ' for c in corners {',
102
+ ' if let bg = background {',
103
+ ' if c.3 == 0 || abs(c.0 - bg.0) > tolerance || abs(c.1 - bg.1) > tolerance || abs(c.2 - bg.2) > tolerance || abs(c.3 - bg.3) > tolerance {',
104
+ ' background = nil',
105
+ ' }',
106
+ ' }',
107
+ ' }',
108
+ ' guard let bg = background else { return opaqueBox }',
109
+ ' var minX = aMaxX + 1, minY = aMaxY + 1, maxX = aMinX - 1, maxY = aMinY - 1',
110
+ ' for y in aMinY...aMaxY {',
111
+ ' let rowBase = y * bytesPerRow',
112
+ ' for x in aMinX...aMaxX {',
113
+ ' let idx = rowBase + x * 4',
114
+ ' let a = Int(data[idx + 3])',
115
+ ' if a == 0 { continue }',
116
+ ' let r = Int(data[idx]), g = Int(data[idx + 1]), b = Int(data[idx + 2])',
117
+ ' if abs(r - bg.0) <= tolerance && abs(g - bg.1) <= tolerance && abs(b - bg.2) <= tolerance && abs(a - bg.3) <= tolerance { continue }',
118
+ ' if x < minX { minX = x }',
119
+ ' if x > maxX { maxX = x }',
120
+ ' if y < minY { minY = y }',
121
+ ' if y > maxY { maxY = y }',
122
+ ' }',
123
+ ' }',
124
+ ' if maxX < minX { return opaqueBox }',
125
+ ' return CGRect(x: minX, y: minY, width: maxX - minX + 1, height: maxY - minY + 1)',
126
+ '}',
127
+ '',
128
+ 'let arguments = CommandLine.arguments',
129
+ 'guard arguments.count >= 3 else {',
130
+ ' FileHandle.standardError.write(Data("usage: Trim <in.png> <out.png>".utf8))',
131
+ ' exit(64)',
132
+ '}',
133
+ 'let inputPath = arguments[1]',
134
+ 'let outputPath = arguments[2]',
135
+ 'guard let image = loadCGImage(inputPath) else {',
136
+ ' FileHandle.standardError.write(Data(("could not read image at " + inputPath).utf8))',
137
+ ' exit(65)',
138
+ '}',
139
+ 'guard let box = contentBoundingBox(image) else {',
140
+ ' FileHandle.standardError.write(Data("no content to trim (image is uniform)".utf8))',
141
+ ' exit(66)',
142
+ '}',
143
+ 'guard let cropped = image.cropping(to: box) else {',
144
+ ' FileHandle.standardError.write(Data("could not crop image".utf8))',
145
+ ' exit(67)',
146
+ '}',
147
+ 'let croppedWidth = cropped.width',
148
+ 'let croppedHeight = cropped.height',
149
+ 'guard writePNG(cropped, to: outputPath) else {',
150
+ ' FileHandle.standardError.write(Data(("could not write trimmed PNG to " + outputPath).utf8))',
151
+ ' exit(68)',
152
+ '}',
153
+ 'var referenceWidth = 0',
154
+ 'var referenceHeight = 0',
155
+ 'if arguments.count >= 5 {',
156
+ ' let alignedPath = arguments[3]',
157
+ ' let referencePath = arguments[4]',
158
+ ' if let reference = loadCGImage(referencePath) {',
159
+ ' referenceWidth = reference.width',
160
+ ' referenceHeight = reference.height',
161
+ ' if let aligned = fitPad(cropped, toWidth: referenceWidth, height: referenceHeight) {',
162
+ ' _ = writePNG(aligned, to: alignedPath)',
163
+ ' }',
164
+ ' }',
165
+ '}',
166
+ 'print("TRIMDIMS " + String(croppedWidth) + " " + String(croppedHeight) + " " + String(referenceWidth) + " " + String(referenceHeight) + " " + String(image.width) + " " + String(image.height))',
167
+ ].join('\n') + '\n';
168
+ function craftPng(w, h, rects) {
169
+ const png = new PNG({ width: w, height: h });
170
+ for (const rect of rects) {
171
+ for (let y = rect.y; y < rect.y + rect.h; y++) {
172
+ for (let x = rect.x; x < rect.x + rect.w; x++) {
173
+ const i = (y * w + x) * 4;
174
+ png.data[i] = rect.r;
175
+ png.data[i + 1] = rect.g;
176
+ png.data[i + 2] = rect.b;
177
+ png.data[i + 3] = rect.a;
178
+ }
179
+ }
180
+ }
181
+ return PNG.sync.write(png);
182
+ }
183
+ /** A gradient-alpha disc over a white card — anti-aliased-edge analog. */
184
+ function craftAntiAliasedScene() {
185
+ const w = 160;
186
+ const h = 120;
187
+ const png = new PNG({ width: w, height: h });
188
+ // White card with a transparent margin.
189
+ for (let y = 10; y < 110; y++) {
190
+ for (let x = 10; x < 150; x++) {
191
+ const i = (y * w + x) * 4;
192
+ png.data[i] = 255;
193
+ png.data[i + 1] = 255;
194
+ png.data[i + 2] = 255;
195
+ png.data[i + 3] = 255;
196
+ }
197
+ }
198
+ // Soft-edged blue disc: alpha falls off with distance (many partial alphas,
199
+ // including the 251..254 band where premultiplied analysis is sensitive).
200
+ const cx = 80;
201
+ const cy = 60;
202
+ for (let y = 20; y < 100; y++) {
203
+ for (let x = 30; x < 130; x++) {
204
+ const d = Math.sqrt((x - cx) ** 2 + (y - cy) ** 2);
205
+ if (d < 36) {
206
+ const alpha = d < 28 ? 255 : Math.max(0, Math.round(255 * (36 - d) / 8));
207
+ if (alpha === 0)
208
+ continue;
209
+ const i = (y * w + x) * 4;
210
+ png.data[i] = 30;
211
+ png.data[i + 1] = 90;
212
+ png.data[i + 2] = 220;
213
+ png.data[i + 3] = Math.max(png.data[i + 3], alpha);
214
+ }
215
+ }
216
+ }
217
+ return PNG.sync.write(png);
218
+ }
219
+ function decode(filePath) {
220
+ const png = PNG.sync.read(readFileSync(filePath));
221
+ return { width: png.width, height: png.height, data: png.data };
222
+ }
223
+ function diffPixels(a, b) {
224
+ const totalPixels = a.width * a.height;
225
+ let differingPixels = 0;
226
+ let maxChannelDelta = 0;
227
+ for (let i = 0; i < a.data.length; i += 4) {
228
+ let pixelDiffers = false;
229
+ for (let c = 0; c < 4; c++) {
230
+ const delta = Math.abs(a.data[i + c] - b.data[i + c]);
231
+ if (delta > 0)
232
+ pixelDiffers = true;
233
+ if (delta > maxChannelDelta)
234
+ maxChannelDelta = delta;
235
+ }
236
+ if (pixelDiffers)
237
+ differingPixels++;
238
+ }
239
+ return { totalPixels, differingPixels, maxChannelDelta };
240
+ }
241
+ // ---- the gate -----------------------------------------------------------------------
242
+ describe('trim/align corpus gate — retired Swift helper vs JS port', () => {
243
+ const dirs = [];
244
+ const resampledSummaries = [];
245
+ afterAll(() => {
246
+ if (resampledSummaries.length > 0) {
247
+ // eslint-disable-next-line no-console
248
+ console.log('[corpus] CG-resampled aligned outputs (geometry asserted, pixels reported):\n' +
249
+ resampledSummaries.join('\n'));
250
+ }
251
+ for (const dir of dirs) {
252
+ try {
253
+ rmSync(dir, { recursive: true, force: true });
254
+ }
255
+ catch {
256
+ // best effort
257
+ }
258
+ }
259
+ });
260
+ function scene() {
261
+ const dir = mkdtempSync(join(tmpdir(), 'trim-corpus-'));
262
+ dirs.push(dir);
263
+ return dir;
264
+ }
265
+ function runSwiftHelper(dir, input, output, aligned, reference) {
266
+ const helper = join(dir, 'Trim.swift');
267
+ if (!existsSync(helper))
268
+ writeFileSync(helper, RETIRED_TRIM_HELPER_SWIFT);
269
+ const args = [helper, input, output];
270
+ if (aligned && reference)
271
+ args.push(aligned, reference);
272
+ return spawnSync('swift', args, { encoding: 'utf-8', maxBuffer: 16 * 1024 * 1024 });
273
+ }
274
+ function lastTrimDims(stdout) {
275
+ const lines = String(stdout || '')
276
+ .split('\n')
277
+ .filter((l) => l.trim().startsWith('TRIMDIMS'));
278
+ return lines.length > 0 ? lines[lines.length - 1].trim() : null;
279
+ }
280
+ /**
281
+ * Runs both helpers over one (input, reference?) case and enforces the gate.
282
+ * Returns a human line describing the case outcome.
283
+ */
284
+ function compareCase(label, inputBytes, referenceBytes) {
285
+ const dir = scene();
286
+ const input = join(dir, 'in.png');
287
+ writeFileSync(input, inputBytes);
288
+ let reference;
289
+ if (referenceBytes !== null) {
290
+ reference = join(dir, 'ref.png');
291
+ writeFileSync(reference, referenceBytes);
292
+ }
293
+ const outSwift = join(dir, 'out-swift.png');
294
+ const alignedSwift = join(dir, 'aligned-swift.png');
295
+ const outJs = join(dir, 'out-js.png');
296
+ const alignedJs = join(dir, 'aligned-js.png');
297
+ const swiftRun = runSwiftHelper(dir, input, outSwift, reference ? alignedSwift : undefined, reference);
298
+ const jsArgs = reference ? [input, outJs, alignedJs, reference] : [input, outJs];
299
+ const jsRun = runTrimAlign(jsArgs);
300
+ // Same verdict on every input, success or failure.
301
+ expect(`${label}: js status ${jsRun.status}`).toBe(`${label}: js status ${swiftRun.status}`);
302
+ if (swiftRun.status !== 0)
303
+ return;
304
+ // TRIMDIMS identical.
305
+ const swiftDims = lastTrimDims(swiftRun.stdout);
306
+ const jsDims = lastTrimDims(jsRun.stdout);
307
+ expect(`${label}: ${jsDims}`).toBe(`${label}: ${swiftDims}`);
308
+ // Trimmed output pixel-identical (the fidelity-history surface).
309
+ const trimmedSwift = decode(outSwift);
310
+ const trimmedJs = decode(outJs);
311
+ expect(`${label}: trimmed ${trimmedJs.width}x${trimmedJs.height}`).toBe(`${label}: trimmed ${trimmedSwift.width}x${trimmedSwift.height}`);
312
+ const trimmedDiff = diffPixels(trimmedSwift, trimmedJs);
313
+ expect(`${label}: trimmed differing=${trimmedDiff.differingPixels} maxDelta=${trimmedDiff.maxChannelDelta}`).toBe(`${label}: trimmed differing=0 maxDelta=0`);
314
+ // Aligned output: identical when CG did not resample; geometry + report otherwise.
315
+ if (existsSync(alignedSwift) || existsSync(alignedJs)) {
316
+ expect(existsSync(alignedJs)).toBe(existsSync(alignedSwift));
317
+ if (existsSync(alignedSwift)) {
318
+ const aSwift = decode(alignedSwift);
319
+ const aJs = decode(alignedJs);
320
+ expect(`${label}: aligned ${aJs.width}x${aJs.height}`).toBe(`${label}: aligned ${aSwift.width}x${aSwift.height}`);
321
+ const identity = trimmedSwift.width === aSwift.width && trimmedSwift.height === aSwift.height;
322
+ const alignedDiff = diffPixels(aSwift, aJs);
323
+ if (identity) {
324
+ expect(`${label}: aligned(identity) differing=${alignedDiff.differingPixels} maxDelta=${alignedDiff.maxChannelDelta}`).toBe(`${label}: aligned(identity) differing=0 maxDelta=0`);
325
+ }
326
+ else if (alignedDiff.differingPixels > 0) {
327
+ resampledSummaries.push(` ${label}: ${alignedDiff.differingPixels}/${alignedDiff.totalPixels} px differ, ` +
328
+ `max channel delta ${alignedDiff.maxChannelDelta}`);
329
+ }
330
+ }
331
+ }
332
+ }
333
+ const RED = { r: 255, g: 0, b: 0, a: 255 };
334
+ const BLUE = { r: 0, g: 0, b: 255, a: 255 };
335
+ const WHITE = { r: 255, g: 255, b: 255, a: 255 };
336
+ const PINK = { r: 255, g: 240, b: 238, a: 255 };
337
+ realSwiftTest('crafted scenes: every bounding-box branch is pixel-identical', () => {
338
+ compareCase('transparent-frame', craftPng(200, 200, [{ x: 30, y: 50, w: 60, h: 40, ...RED }]), null);
339
+ compareCase('uniform-background-wrapper', craftPng(420, 320, [
340
+ { x: 20, y: 40, w: 375, h: 200, ...WHITE },
341
+ { x: 36, y: 56, w: 343, h: 168, ...PINK },
342
+ ]), null);
343
+ compareCase('corners-disagree', craftPng(120, 120, [
344
+ { x: 20, y: 20, w: 40, h: 80, ...RED },
345
+ { x: 60, y: 20, w: 40, h: 80, ...BLUE },
346
+ ]), null);
347
+ compareCase('fully-opaque-uniform', craftPng(64, 48, [{ x: 0, y: 0, w: 64, h: 48, ...WHITE }]), null);
348
+ compareCase('fully-transparent', craftPng(40, 40, []), null);
349
+ compareCase('anti-aliased-edges', craftAntiAliasedScene(), null);
350
+ compareCase('aligned-identity', craftPng(80, 40, [
351
+ { x: 0, y: 0, w: 40, h: 40, ...RED },
352
+ { x: 40, y: 0, w: 40, h: 40, ...BLUE },
353
+ ]), craftPng(80, 40, [{ x: 0, y: 0, w: 80, h: 40, ...WHITE }]));
354
+ compareCase('aligned-letterbox', craftPng(80, 40, [{ x: 0, y: 0, w: 80, h: 40, ...RED }]), craftPng(50, 50, [{ x: 0, y: 0, w: 50, h: 50, ...BLUE }]));
355
+ compareCase('aligned-aa-content', craftAntiAliasedScene(), craftPng(140, 100, [{ x: 0, y: 0, w: 140, h: 100, ...WHITE }]));
356
+ }, 900_000);
357
+ realSwiftTest('real corpus: every PNG pair under CIBUILD_TRIM_CORPUS_DIR is pixel-identical', () => {
358
+ const corpusDir = process.env.CIBUILD_TRIM_CORPUS_DIR;
359
+ if (!corpusDir) {
360
+ // eslint-disable-next-line no-console
361
+ console.log('[corpus] CIBUILD_TRIM_CORPUS_DIR not set — real-corpus pass skipped');
362
+ return;
363
+ }
364
+ const entries = readdirSync(corpusDir)
365
+ .filter((name) => name.toLowerCase().endsWith('.png'))
366
+ .sort();
367
+ expect(entries.length).toBeGreaterThan(0);
368
+ // eslint-disable-next-line no-console
369
+ console.log(`[corpus] ${entries.length} real PNGs from ${corpusDir}`);
370
+ for (let i = 0; i < entries.length; i++) {
371
+ const name = entries[i];
372
+ const bytes = readFileSync(join(corpusDir, name));
373
+ // No-reference case: trim only.
374
+ compareCase(`${name} (no-ref)`, bytes, null);
375
+ // Self-reference: reference dims = source dims (identity-leaning).
376
+ compareCase(`${name} (self-ref)`, bytes, bytes);
377
+ // Cross-reference: the next PNG as reference (arbitrary scale factors).
378
+ const next = entries[(i + 1) % entries.length];
379
+ compareCase(`${name} (ref=${next})`, bytes, readFileSync(join(corpusDir, next)));
380
+ }
381
+ }, 1_800_000);
382
+ });
383
+ //# sourceMappingURL=trim-align-corpus.test.js.map
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Pure-JS trim/align helper — the CoreGraphics port (fidelity-linux 06).
3
+ *
4
+ * This is a PORT of the embedded Swift helper that used to live in
5
+ * render-post-processor.ts (`TRIM_HELPER_SWIFT_SOURCE`), not a redesign: the
6
+ * bounding-box semantics (alpha pass, corner-derived uniform background,
7
+ * tolerance 4, never-crop-to-nothing fallback), the fit-pad geometry
8
+ * (aspect-preserving scale, centered, transparent letterbox) and the TRIMDIMS
9
+ * contract are byte-for-byte the Swift behavior. CoreGraphics/ImageIO do not
10
+ * exist on Linux, so the pixel work moved into the ci binary itself (pngjs is
11
+ * pure JS and bundles via bundle.mjs) — iOS and Android now run the SAME bytes,
12
+ * and output pixels can only change with our lockfile, never with a runner OS
13
+ * upgrade.
14
+ *
15
+ * Port-fidelity notes, load-bearing for the corpus gate:
16
+ * - The Swift helper ANALYZED pixels through a premultiplied-alpha CGContext
17
+ * but CROPPED the original (straight-alpha) image. We mirror both: the
18
+ * bounding box is computed over premultiplied values, the trimmed output is
19
+ * a raw copy of the source pixels.
20
+ * - The Swift aligned output was drawn through a premultiplied context and
21
+ * unpremultiplied on PNG encode, which is lossy on semi-transparent pixels;
22
+ * we reproduce that roundtrip. Where CoreGraphics RESAMPLED (trimmed size ≠
23
+ * reference size), its proprietary `.high` interpolation is not bit-exactly
24
+ * reproducible — we use bilinear filtering in premultiplied space. The
25
+ * trimmed image and TRIMDIMS never depend on resampling and are the
26
+ * pixel-identical surface the corpus gate enforces.
27
+ */
28
+ import { PNG } from 'pngjs';
29
+ /** Content bounding box in top-left image coordinates. */
30
+ export interface ContentBox {
31
+ x: number;
32
+ y: number;
33
+ width: number;
34
+ height: number;
35
+ }
36
+ /** Mirror of the Swift helper's exit codes. */
37
+ export declare const TRIM_EXIT_USAGE = 64;
38
+ export declare const TRIM_EXIT_UNREADABLE = 65;
39
+ export declare const TRIM_EXIT_NO_CONTENT = 66;
40
+ export declare const TRIM_EXIT_WRITE_FAILED = 68;
41
+ /**
42
+ * Bounding box of content: pixels that are neither transparent nor part of a
43
+ * uniform solid background. Two passes, because the renderer forces the view
44
+ * into a fixed device frame whose margins are transparent: (1) bound the
45
+ * non-transparent pixels, then (2) detect a uniform opaque background from the
46
+ * CORNERS OF THAT OPAQUE BOX — not the raw frame, whose corners are the
47
+ * transparent device margin — and bound everything that is not that
48
+ * background. A wrapper that fills the canvas with .background(.white) is thus
49
+ * trimmed to its real content. When the opaque corners disagree, only
50
+ * transparency is trimmed. Top-left image coordinates.
51
+ *
52
+ * `data` is straight-alpha RGBA8 (as pngjs decodes); the color comparisons run
53
+ * on premultiplied values to mirror the Swift helper's analysis context.
54
+ */
55
+ export declare function contentBoundingBox(data: Buffer | Uint8Array, width: number, height: number): ContentBox | null;
56
+ /** Raw pixel copy of a region — the Swift `image.cropping(to:)` equivalent. */
57
+ export declare function cropImage(src: PNG, box: ContentBox): PNG;
58
+ /**
59
+ * Draw `src` centered on a transparent reference-sized canvas, scaled to fit
60
+ * while PRESERVING its aspect ratio. Unlike a stretch-to-fit (which distorts
61
+ * proportions when the aspect ratios differ), this keeps the rendered shape
62
+ * honest: an aspect mismatch shows as transparent letterbox/pillarbox padding
63
+ * rather than a squished image, while the canvas stays exactly reference-sized
64
+ * so the pair still overlays 1:1.
65
+ *
66
+ * Compositing happens in premultiplied space with an unpremultiply on the way
67
+ * out, mirroring the Swift context roundtrip. Resampling is bilinear (see the
68
+ * module docblock for why CG's `.high` filter is not reproducible).
69
+ */
70
+ export declare function fitPad(src: PNG, width: number, height: number): PNG | null;
71
+ /** Result of one helper invocation — the process-free CLI contract. */
72
+ export interface TrimAlignResult {
73
+ status: number;
74
+ stdout: string;
75
+ stderr: string;
76
+ }
77
+ /**
78
+ * The helper entry point, argv-compatible with the retired Swift helper:
79
+ * `[in.png, out.png]` or `[in.png, out.png, aligned.png, reference.png]`.
80
+ * Crops the input to its content bounding box, optionally writes a
81
+ * reference-sized aligned copy (best-effort), and reports a TRIMDIMS line.
82
+ * Same exit codes, same stdout/stderr shape as the Swift helper.
83
+ */
84
+ export declare function runTrimAlign(argv: string[]): TrimAlignResult;
85
+ //# sourceMappingURL=trim-align.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trim-align.d.ts","sourceRoot":"","sources":["../../../../src/yaml/steps/trim-align.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAGH,OAAO,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC;AAE5B,0DAA0D;AAC1D,MAAM,WAAW,UAAU;IACzB,CAAC,EAAE,MAAM,CAAC;IACV,CAAC,EAAE,MAAM,CAAC;IACV,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,+CAA+C;AAC/C,eAAO,MAAM,eAAe,KAAK,CAAC;AAClC,eAAO,MAAM,oBAAoB,KAAK,CAAC;AACvC,eAAO,MAAM,oBAAoB,KAAK,CAAC;AACvC,eAAO,MAAM,sBAAsB,KAAK,CAAC;AA0BzC;;;;;;;;;;;;;GAaG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,MAAM,GAAG,UAAU,EACzB,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,GACb,UAAU,GAAG,IAAI,CAkGnB;AAED,+EAA+E;AAC/E,wBAAgB,SAAS,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,UAAU,GAAG,GAAG,CAOxD;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,GAAG,GAAG,IAAI,CAyE1E;AAED,uEAAuE;AACvE,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,eAAe,CA6E5D"}