@get-snappy/cli 0.0.0-stage → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +1338 -0
  2. package/package.json +29 -4
  3. package/README.md +0 -3
package/dist/index.js ADDED
@@ -0,0 +1,1338 @@
1
+ #!/usr/bin/env node
2
+ import { execSync, spawn } from "node:child_process";
3
+ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { z } from "zod";
8
+ import { createRequire } from "node:module";
9
+ import playwright from "playwright";
10
+ import { createHash } from "node:crypto";
11
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
12
+ import { Hono } from "hono";
13
+ import { cors } from "hono/cors";
14
+ import * as __rspack_external_node_path_806ed179 from "node:path";
15
+ import * as __rspack_external_node_fs_1b05aee1 from "node:fs";
16
+ import * as __rspack_external_yaml from "yaml";
17
+ import * as __rspack_external__sentry_node_573b6ee6 from "@sentry/node";
18
+ const DEFAULT_REQUEST_TIMEOUT_MS = 60000;
19
+ const PRESIGNED_URL_TIMEOUT_MS = 10000;
20
+ class SubscriptionError extends Error {
21
+ subscriptionRequired = true;
22
+ constructor(message){
23
+ super(message);
24
+ this.name = "SubscriptionError";
25
+ }
26
+ }
27
+ async function defaultDelay(ms) {
28
+ return new Promise((resolve)=>setTimeout(resolve, ms));
29
+ }
30
+ function shouldRetry(response, error) {
31
+ if (error) return true;
32
+ if (!response) return false;
33
+ const status = response.status;
34
+ if (status >= 400 && status < 500) return true;
35
+ if (0 === status || status >= 500 && 501 !== status) return true;
36
+ return false;
37
+ }
38
+ async function retryFetch(input, init, options) {
39
+ const baseDelay = options?.baseDelay ?? 100;
40
+ const maxAttempts = options?.maxAttempts ?? 4;
41
+ const delayFn = options?.delayFn ?? defaultDelay;
42
+ const timeoutMs = options?.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
43
+ for(let attempt = 0; attempt < maxAttempts; attempt++){
44
+ const isLastAttempt = attempt === maxAttempts - 1;
45
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
46
+ const signal = init?.signal ? AbortSignal.any([
47
+ init.signal,
48
+ timeoutSignal
49
+ ]) : timeoutSignal;
50
+ let response;
51
+ try {
52
+ response = await fetch(input, {
53
+ ...init,
54
+ signal
55
+ });
56
+ } catch (error) {
57
+ if (isLastAttempt || !shouldRetry(null, error)) throw error;
58
+ await delayFn(baseDelay * 2 ** attempt);
59
+ continue;
60
+ }
61
+ if (isLastAttempt || !shouldRetry(response, null)) return response;
62
+ await delayFn(baseDelay * 2 ** attempt);
63
+ }
64
+ throw new Error('retryFetch: unexpected state');
65
+ }
66
+ async function createBuild(payload, retryOptions) {
67
+ const url = new URL(payload.serverLocation);
68
+ url.pathname = '/api/builds';
69
+ const body = {
70
+ build: {
71
+ branch: payload.branch,
72
+ commit: payload.commit,
73
+ pull_request: payload.pullRequest,
74
+ unique_identifier: payload.uniqueIdentifier
75
+ }
76
+ };
77
+ const response = await retryFetch(url.toString(), {
78
+ method: 'POST',
79
+ headers: {
80
+ Authorization: `Bearer ${payload.apiKey}`,
81
+ 'Content-Type': 'application/json'
82
+ },
83
+ body: JSON.stringify(body)
84
+ }, retryOptions);
85
+ const rawBody = await response.text();
86
+ let parsedBody;
87
+ try {
88
+ parsedBody = JSON.parse(rawBody);
89
+ } catch {
90
+ parsedBody = void 0;
91
+ }
92
+ if (201 === response.status) {
93
+ if (!parsedBody?.build_id) throw new Error(`Build creation returned 201 with no build_id: ${rawBody}`);
94
+ return parsedBody.build_id;
95
+ }
96
+ if (401 === response.status) throw new Error('Invalid API Key');
97
+ if (402 === response.status) {
98
+ const error = new SubscriptionError(parsedBody?.error || "Subscription required");
99
+ throw error;
100
+ }
101
+ throw new Error(`Build creation failed: ${response.status} ${rawBody}`);
102
+ }
103
+ async function getPresignedUrl(params, retryOptions) {
104
+ const url = new URL(params.serverLocation);
105
+ url.pathname = `/api/builds/${params.buildId}/get_presigned_url/${params.filename}`;
106
+ const response = await retryFetch(url.toString(), {
107
+ method: 'POST',
108
+ headers: {
109
+ Authorization: `Bearer ${params.apiKey}`,
110
+ 'Content-Type': 'application/json'
111
+ }
112
+ }, {
113
+ ...retryOptions,
114
+ timeoutMs: retryOptions?.timeoutMs ?? PRESIGNED_URL_TIMEOUT_MS
115
+ });
116
+ const rawBody = await response.text();
117
+ let parsedBody;
118
+ try {
119
+ parsedBody = JSON.parse(rawBody);
120
+ } catch {
121
+ parsedBody = void 0;
122
+ }
123
+ if (!parsedBody?.url) throw new Error(`Empty or invalid presigned URL response (status ${response.status}): ${rawBody}`);
124
+ return parsedBody.url;
125
+ }
126
+ async function uploadFile(params, retryOptions) {
127
+ let contentType = 'application/json';
128
+ if (params.filename.endsWith('.png')) contentType = 'image/png';
129
+ const response = await retryFetch(params.presignedUrl, {
130
+ method: 'PUT',
131
+ headers: {
132
+ 'Content-Type': contentType
133
+ },
134
+ body: params.fileData
135
+ }, retryOptions);
136
+ if (!response.ok) throw new Error(`Upload failed: status ${response.status}`);
137
+ }
138
+ async function sendComplete(params, retryOptions) {
139
+ const url = new URL(params.serverLocation);
140
+ url.pathname = `/api/builds/${params.buildId}/complete`;
141
+ const response = await retryFetch(url.toString(), {
142
+ method: 'POST',
143
+ headers: {
144
+ Authorization: `Bearer ${params.apiKey}`
145
+ }
146
+ }, retryOptions);
147
+ if (!response.ok) throw new Error(`Send complete failed: status ${response.status}`);
148
+ }
149
+ async function sendFailed(params, retryOptions) {
150
+ const url = new URL(params.serverLocation);
151
+ url.pathname = `/api/builds/${params.buildId}/failed`;
152
+ const response = await retryFetch(url.toString(), {
153
+ method: 'POST',
154
+ headers: {
155
+ Authorization: `Bearer ${params.apiKey}`
156
+ }
157
+ }, retryOptions);
158
+ if (!response.ok) throw new Error(`Send failed failed: status ${response.status}`);
159
+ }
160
+ const DimensionsSchema = z.object({
161
+ width: z.number().int().positive(),
162
+ height: z.number().int().positive()
163
+ });
164
+ const PlaywrightOptionsSchema = z.object({
165
+ full_page: z.boolean().optional(),
166
+ locator: z.string().optional(),
167
+ dark_mode: z.boolean().optional(),
168
+ animations: z.union([
169
+ z.string(),
170
+ z.boolean()
171
+ ]).optional().nullable().transform((val)=>'boolean' == typeof val ? val ? 'allow' : 'disabled' : val ?? void 0),
172
+ mask: z.array(z.string()).optional(),
173
+ mask_color: z.string().optional(),
174
+ omit_background: z.boolean().optional(),
175
+ clip: DimensionsSchema.optional().nullable().transform((val)=>null === val ? void 0 : val),
176
+ scale: z.string().optional(),
177
+ caret: z.string().optional(),
178
+ wait_until: z["enum"]([
179
+ 'load',
180
+ 'domcontentloaded',
181
+ 'networkidle',
182
+ 'commit'
183
+ ]).optional()
184
+ });
185
+ const SnapshotOptionsSchema = z.object({
186
+ scope: z.string().default(''),
187
+ dimensions: z.array(DimensionsSchema).default([]),
188
+ name: z.string().default(''),
189
+ browsers: z.array(z.string()).default([]),
190
+ precision_threshold: z.number().min(0).max(100).optional()
191
+ });
192
+ const GlobalConfigSchema = z.object({
193
+ api_key: z.string().default(''),
194
+ branch: z.string().default(''),
195
+ commit: z.string().default(''),
196
+ test_command: z.string().default(''),
197
+ pull_request: z.string().default(''),
198
+ server_location: z.string().default('https://get-snappy.com'),
199
+ browsers: z.array(z.string()).default([
200
+ 'chrome'
201
+ ]),
202
+ parallel: z.union([
203
+ z.boolean(),
204
+ z["enum"]([
205
+ 'true',
206
+ 'false'
207
+ ]).transform((value)=>'true' === value)
208
+ ]).default(false),
209
+ unique_identifier: z.string().default(''),
210
+ upload_workers: z.number().int().positive().default(32),
211
+ snappy_workers: z.number().int().positive().default(4),
212
+ debug: z.boolean().default(false),
213
+ local_dist_dir: z.string().default(''),
214
+ wait_until: z["enum"]([
215
+ 'load',
216
+ 'domcontentloaded',
217
+ 'networkidle',
218
+ 'commit'
219
+ ]).optional()
220
+ });
221
+ const CONFIG_FILE_NAMES = [
222
+ '.get-snappy.json',
223
+ '.get-snappy.yaml',
224
+ '.get-snappy.yml',
225
+ '.get-snappy'
226
+ ];
227
+ const BUILD_ENV_KEYS = [
228
+ 'api_key',
229
+ 'branch',
230
+ 'commit',
231
+ 'pull_request',
232
+ 'server_location',
233
+ 'parallel',
234
+ 'unique_identifier'
235
+ ];
236
+ function loadConfig(configPath, options = {}) {
237
+ const env = options.env ?? process.env;
238
+ const cwd = options.cwd ?? process.cwd();
239
+ const file = configPath ?? CONFIG_FILE_NAMES.map((name)=>__rspack_external_node_path_806ed179.join(cwd, name)).find(__rspack_external_node_fs_1b05aee1.existsSync);
240
+ const fileValues = file ? z.record(z.unknown()).parse(__rspack_external_yaml.parse(__rspack_external_node_fs_1b05aee1.readFileSync(file, 'utf-8')) ?? {}) : {};
241
+ if (file) console.log(`Using config file: ${file}`);
242
+ const envValues = Object.fromEntries(BUILD_ENV_KEYS.flatMap((key)=>{
243
+ const value = env[`GET_SNAPPY_${key.toUpperCase()}`];
244
+ return value ? [
245
+ [
246
+ key,
247
+ value
248
+ ]
249
+ ] : [];
250
+ }));
251
+ const result = GlobalConfigSchema.safeParse({
252
+ ...fileValues,
253
+ ...envValues
254
+ });
255
+ if (!result.success) {
256
+ const problems = result.error.issues.map((issue)=>` ${issue.path.join('.') || '(root)'}: ${issue.message}`);
257
+ throw new Error(`Invalid config${file ? ` in ${file}` : ''}:\n${problems.join('\n')}`);
258
+ }
259
+ return result.data;
260
+ }
261
+ function fatal(message) {
262
+ process.stderr.write(`${message}\n`);
263
+ process.exit(1);
264
+ }
265
+ async function captureErrorAndExit(err) {
266
+ __rspack_external__sentry_node_573b6ee6.captureException(err);
267
+ await __rspack_external__sentry_node_573b6ee6.flush(2000);
268
+ fatal(err.message);
269
+ }
270
+ function setSentryTags(tags) {
271
+ if (void 0 !== tags.branch) __rspack_external__sentry_node_573b6ee6.setTag('branch', tags.branch);
272
+ if (void 0 !== tags.commit) __rspack_external__sentry_node_573b6ee6.setTag('commit', tags.commit);
273
+ if (void 0 !== tags.pull_request) __rspack_external__sentry_node_573b6ee6.setTag('pull_request', tags.pull_request);
274
+ if (void 0 !== tags.unique_identifier) __rspack_external__sentry_node_573b6ee6.setTag('unique_identifier', tags.unique_identifier);
275
+ if (void 0 !== tags.parallel) __rspack_external__sentry_node_573b6ee6.setTag('parallel', String(tags.parallel));
276
+ if (void 0 !== tags.browsers) __rspack_external__sentry_node_573b6ee6.setTag('browsers', JSON.stringify(tags.browsers));
277
+ if (void 0 !== tags.build_id) __rspack_external__sentry_node_573b6ee6.setTag('build_id', tags.build_id);
278
+ }
279
+ function initSentry(dsn, release) {
280
+ __rspack_external__sentry_node_573b6ee6.init({
281
+ dsn,
282
+ release,
283
+ environment: 'production',
284
+ tracesSampleRate: 1.0
285
+ });
286
+ }
287
+ const SENTRY_TAG_MAX_LENGTH = 200;
288
+ function snapshotErrorCaptureContext(context) {
289
+ const fields = [
290
+ [
291
+ 'snapshot_name',
292
+ 'name',
293
+ context.snapshotName
294
+ ],
295
+ [
296
+ 'snapshot_id',
297
+ 'id',
298
+ context.snapshotId
299
+ ],
300
+ [
301
+ 'snapshot_md5',
302
+ 'md5',
303
+ context.snapshotMd5
304
+ ],
305
+ [
306
+ 'browser',
307
+ 'browser',
308
+ context.browser
309
+ ],
310
+ [
311
+ 'wait_until',
312
+ 'wait_until',
313
+ context.waitUntil
314
+ ],
315
+ [
316
+ 'locator',
317
+ 'locator',
318
+ context.locator
319
+ ],
320
+ [
321
+ 'dimension',
322
+ 'dimension',
323
+ context.dimension
324
+ ]
325
+ ];
326
+ const tags = {};
327
+ const snapshot = {};
328
+ for (const [tag, contextKey, value] of fields)if (value) {
329
+ tags[tag] = value.slice(0, SENTRY_TAG_MAX_LENGTH);
330
+ snapshot[contextKey] = value;
331
+ }
332
+ return {
333
+ tags,
334
+ contexts: {
335
+ snapshot
336
+ }
337
+ };
338
+ }
339
+ function captureSnapshotError(err, context) {
340
+ __rspack_external__sentry_node_573b6ee6.captureException(err, snapshotErrorCaptureContext(context));
341
+ }
342
+ function getBrowserType(browserName) {
343
+ switch(browserName.toLowerCase()){
344
+ case 'chrome':
345
+ case 'chromium':
346
+ return playwright.chromium;
347
+ case 'firefox':
348
+ return playwright.firefox;
349
+ case 'webkit':
350
+ case 'safari':
351
+ return playwright.webkit;
352
+ default:
353
+ throw new Error(`Unsupported browser: ${browserName}`);
354
+ }
355
+ }
356
+ class PlaywrightBrowserAdapter {
357
+ realBrowser;
358
+ constructor(realBrowser){
359
+ this.realBrowser = realBrowser;
360
+ }
361
+ async newContext(options) {
362
+ const context = await this.realBrowser.newContext(options);
363
+ return new PlaywrightContextAdapter(context);
364
+ }
365
+ async close() {
366
+ return this.realBrowser.close();
367
+ }
368
+ }
369
+ class PlaywrightContextAdapter {
370
+ realContext;
371
+ constructor(realContext){
372
+ this.realContext = realContext;
373
+ }
374
+ async newPage() {
375
+ const page = await this.realContext.newPage();
376
+ return new PlaywrightPageAdapter(page);
377
+ }
378
+ async close() {
379
+ return this.realContext.close();
380
+ }
381
+ setDefaultTimeout(timeout) {
382
+ this.realContext.setDefaultTimeout(timeout);
383
+ }
384
+ }
385
+ class PlaywrightPageAdapter {
386
+ realPage;
387
+ constructor(realPage){
388
+ this.realPage = realPage;
389
+ }
390
+ async goto(url, options) {
391
+ return this.realPage.goto(url, options);
392
+ }
393
+ async emulateMedia(options) {
394
+ return this.realPage.emulateMedia(options);
395
+ }
396
+ async setViewportSize(width, height) {
397
+ return this.realPage.setViewportSize({
398
+ width,
399
+ height
400
+ });
401
+ }
402
+ async screenshot(options) {
403
+ return this.realPage.screenshot(options);
404
+ }
405
+ locator(selector) {
406
+ const realLocator = this.realPage.locator(selector);
407
+ return new PlaywrightLocatorAdapter(realLocator);
408
+ }
409
+ context() {
410
+ throw new Error('context() adapter not implemented');
411
+ }
412
+ }
413
+ class PlaywrightLocatorAdapter {
414
+ realLocator;
415
+ constructor(realLocator){
416
+ this.realLocator = realLocator;
417
+ }
418
+ async boundingBox() {
419
+ return this.realLocator.boundingBox();
420
+ }
421
+ async screenshot(options) {
422
+ return this.realLocator.screenshot(options);
423
+ }
424
+ }
425
+ const DEFAULT_LAUNCH_TIMEOUT_MS = 60000;
426
+ async function launchBrowser(browserName, { timeoutMs = DEFAULT_LAUNCH_TIMEOUT_MS } = {}) {
427
+ const browserType = getBrowserType(browserName);
428
+ console.log(`Launching ${browserName}...`);
429
+ try {
430
+ const realBrowser = await browserType.launch({
431
+ headless: true,
432
+ timeout: timeoutMs
433
+ });
434
+ return new PlaywrightBrowserAdapter(realBrowser);
435
+ } catch (error) {
436
+ const reason = error instanceof Error ? error.message.split('\n')[0] : String(error);
437
+ throw new Error(`Failed to launch ${browserName}: ${reason}`, {
438
+ cause: error
439
+ });
440
+ }
441
+ }
442
+ function bundledPlaywrightCli() {
443
+ const require = createRequire(import.meta.url);
444
+ return __rspack_external_node_path_806ed179["default"].join(__rspack_external_node_path_806ed179["default"].dirname(require.resolve('playwright/package.json')), 'cli.js');
445
+ }
446
+ class WorkerPool {
447
+ size;
448
+ handler;
449
+ onError;
450
+ queue = [];
451
+ workerCounts;
452
+ activeTasks = new Set();
453
+ drainWakeup = new Set();
454
+ constructor(options){
455
+ this.size = options.size;
456
+ this.handler = options.handler;
457
+ this.onError = options.onError;
458
+ this.workerCounts = Array(this.size).fill(0);
459
+ for(let i = 0; i < this.size; i++)this.startWorker(i);
460
+ }
461
+ enqueue(job) {
462
+ this.queue.push(job);
463
+ this.wakeupWorkers();
464
+ }
465
+ async drain() {
466
+ while(this.queue.length > 0 || this.activeTasks.size > 0)await new Promise((resolve)=>{
467
+ if (0 === this.queue.length && 0 === this.activeTasks.size) resolve();
468
+ else this.drainWakeup.add(resolve);
469
+ });
470
+ }
471
+ getWorkerCounts() {
472
+ return [
473
+ ...this.workerCounts
474
+ ];
475
+ }
476
+ notifyDrainListeners() {
477
+ const listeners = Array.from(this.drainWakeup);
478
+ this.drainWakeup.clear();
479
+ for (const listener of listeners)listener();
480
+ }
481
+ wakeupWorkers() {
482
+ this.notifyDrainListeners();
483
+ }
484
+ async startWorker(workerId) {
485
+ while(true){
486
+ const job = this.queue.length > 0 ? this.queue.shift() : void 0;
487
+ if (void 0 !== job) {
488
+ const taskPromise = this.processJob(workerId, job);
489
+ this.activeTasks.add(taskPromise);
490
+ await taskPromise;
491
+ this.activeTasks.delete(taskPromise);
492
+ this.notifyDrainListeners();
493
+ } else await new Promise((resolve)=>{
494
+ if (this.queue.length > 0) resolve();
495
+ else this.drainWakeup.add(resolve);
496
+ });
497
+ }
498
+ }
499
+ async processJob(workerId, job) {
500
+ try {
501
+ await this.handler(job);
502
+ this.workerCounts[workerId]++;
503
+ } catch (error) {
504
+ if (this.onError) this.onError(error);
505
+ this.workerCounts[workerId]++;
506
+ }
507
+ }
508
+ }
509
+ class PlaywrightScreenshotPool {
510
+ browser;
511
+ browserName;
512
+ outputDir;
513
+ onScreenshotCaptured;
514
+ onError;
515
+ defaultWaitUntil;
516
+ reportSnapshotError;
517
+ workerStates = [];
518
+ pools = [];
519
+ currentWorkerIndex = 0;
520
+ initializationPromises = new Map();
521
+ JOBS_PER_CONTEXT = 100;
522
+ SCREENSHOT_MAX_ATTEMPTS = 3;
523
+ SCREENSHOT_RETRY_BACKOFF_MS = 250;
524
+ GOTO_MAX_ATTEMPTS = 3;
525
+ GOTO_TIMEOUT_MS = 15000;
526
+ GOTO_RETRY_BACKOFF_MS = 250;
527
+ DEFAULT_ACTION_TIMEOUT_MS = 30000;
528
+ constructor(options){
529
+ this.browser = options.browser;
530
+ this.browserName = options.browserName;
531
+ this.outputDir = options.outputDir;
532
+ this.onScreenshotCaptured = options.onScreenshotCaptured;
533
+ this.onError = options.onError;
534
+ this.defaultWaitUntil = options.defaultWaitUntil;
535
+ this.reportSnapshotError = options.reportSnapshotError ?? captureSnapshotError;
536
+ const workerCount = options.workerCount;
537
+ for(let i = 0; i < workerCount; i++)this.workerStates[i] = null;
538
+ for(let workerId = 0; workerId < workerCount; workerId++)this.pools[workerId] = new WorkerPool({
539
+ size: 1,
540
+ handler: (job)=>this.processScreenshotJobForWorker(job, workerId),
541
+ onError: (error)=>this.onError?.(workerId, error)
542
+ });
543
+ this.initializeAllWorkers();
544
+ }
545
+ initializeAllWorkers() {
546
+ for(let i = 0; i < this.workerStates.length; i++)this.startInitializeWorker(i);
547
+ }
548
+ startInitializeWorker(workerId) {
549
+ if (this.initializationPromises.has(workerId)) return this.initializationPromises.get(workerId);
550
+ const promise = this.initializeWorker(workerId).catch((error)=>{
551
+ console.error(`Failed to initialize worker ${workerId}:`, error);
552
+ this.onError?.(workerId, error);
553
+ this.initializationPromises.delete(workerId);
554
+ });
555
+ this.initializationPromises.set(workerId, promise);
556
+ return promise;
557
+ }
558
+ async ensureInitialized() {
559
+ const initPromises = [];
560
+ for(let i = 0; i < this.workerStates.length; i++)initPromises.push(this.startInitializeWorker(i));
561
+ await Promise.all(initPromises);
562
+ }
563
+ async initializeWorker(workerId) {
564
+ const context = await this.browser.newContext({
565
+ reducedMotion: 'reduce'
566
+ });
567
+ context.setDefaultTimeout(this.DEFAULT_ACTION_TIMEOUT_MS);
568
+ const page = await context.newPage();
569
+ this.workerStates[workerId] = {
570
+ page,
571
+ context,
572
+ jobsProcessed: 0
573
+ };
574
+ }
575
+ async recycleWorker(workerId) {
576
+ const state = this.workerStates[workerId];
577
+ if (!state) return;
578
+ await state.context.close();
579
+ this.workerStates[workerId] = null;
580
+ try {
581
+ await this.initializeWorker(workerId);
582
+ } catch (error) {
583
+ this.initializationPromises.delete(workerId);
584
+ throw error;
585
+ }
586
+ }
587
+ enqueueSnapshot(url, snapshotName, snapshotOptions, playwrightOptions) {
588
+ const workerId = this.currentWorkerIndex % this.workerStates.length;
589
+ this.currentWorkerIndex++;
590
+ this.pools[workerId].enqueue({
591
+ url,
592
+ snapshotName,
593
+ snapshotOptions,
594
+ playwrightOptions
595
+ });
596
+ }
597
+ async captureSnapshot(url, snapshotName, snapshotOptions, playwrightOptions) {
598
+ this.enqueueSnapshot(url, snapshotName, snapshotOptions, playwrightOptions);
599
+ }
600
+ async drain() {
601
+ await Promise.all(this.pools.map((pool)=>pool.drain()));
602
+ }
603
+ async closeBrowser() {
604
+ await this.browser.close();
605
+ }
606
+ async processScreenshotJobForWorker(job, workerId) {
607
+ let state = this.workerStates[workerId];
608
+ if (!state) {
609
+ await this.startInitializeWorker(workerId);
610
+ state = this.workerStates[workerId];
611
+ }
612
+ if (!state) throw new Error(`Worker ${workerId} has no initialized browser context/page - skipping job`);
613
+ if (state.jobsProcessed >= this.JOBS_PER_CONTEXT) {
614
+ await this.recycleWorker(workerId);
615
+ state = this.workerStates[workerId];
616
+ if (!state) throw new Error(`Worker ${workerId} failed to recycle its browser context - skipping job`);
617
+ }
618
+ await this.captureSnapshots(state.page, job.url, job.snapshotName, job.snapshotOptions, job.playwrightOptions);
619
+ state.jobsProcessed++;
620
+ }
621
+ async captureSnapshots(page, url, snapshotName, snapshotOptions, playwrightOptions) {
622
+ const nameForHash = snapshotOptions.name || snapshotName;
623
+ const md5 = createHash('md5').update(nameForHash).digest('hex');
624
+ const waitUntil = playwrightOptions.wait_until || this.defaultWaitUntil || 'networkidle';
625
+ const errorContext = {
626
+ snapshotName: nameForHash,
627
+ snapshotId: url.slice(url.lastIndexOf('/') + 1),
628
+ snapshotMd5: md5,
629
+ browser: this.browserName,
630
+ waitUntil,
631
+ locator: playwrightOptions.locator
632
+ };
633
+ try {
634
+ await this.navigateToSnapshot(page, url, waitUntil);
635
+ } catch (error) {
636
+ const navigationError = error instanceof Error ? error : new Error(String(error));
637
+ this.reportSnapshotError(navigationError, errorContext);
638
+ console.error(`Skipping snapshot ${nameForHash} (${this.browserName}): failed to navigate after ${this.GOTO_MAX_ATTEMPTS} attempts: ${navigationError.message}`);
639
+ return;
640
+ }
641
+ for (const dimension of snapshotOptions.dimensions)await this.takeSnapshot(page, dimension, md5, playwrightOptions, errorContext);
642
+ }
643
+ async navigateToSnapshot(page, url, waitUntil) {
644
+ let lastError = null;
645
+ for(let attempt = 1; attempt <= this.GOTO_MAX_ATTEMPTS; attempt++)try {
646
+ await page.goto(url, {
647
+ waitUntil,
648
+ timeout: this.GOTO_TIMEOUT_MS
649
+ });
650
+ return;
651
+ } catch (error) {
652
+ lastError = error instanceof Error ? error : new Error(String(error));
653
+ if (attempt < this.GOTO_MAX_ATTEMPTS) {
654
+ console.error(`Navigation to ${url} failed on attempt ${attempt}/${this.GOTO_MAX_ATTEMPTS}, retrying: ${lastError.message}`);
655
+ await this.sleep(this.GOTO_RETRY_BACKOFF_MS);
656
+ }
657
+ }
658
+ throw lastError;
659
+ }
660
+ async takeSnapshot(page, dimension, md5, playwrightOptions, errorContext) {
661
+ if (playwrightOptions.dark_mode) await page.emulateMedia({
662
+ colorScheme: 'dark'
663
+ });
664
+ let lastError = null;
665
+ let capturedFilePath = null;
666
+ for(let attempt = 1; attempt <= this.SCREENSHOT_MAX_ATTEMPTS; attempt++){
667
+ let result;
668
+ try {
669
+ result = playwrightOptions.locator ? await this.captureLocatorScreenshot(page, dimension, md5, playwrightOptions) : await this.captureNormalScreenshot(page, dimension, md5, playwrightOptions);
670
+ if ((0, __rspack_external_node_fs_1b05aee1.existsSync)(result)) {
671
+ lastError = null;
672
+ capturedFilePath = result;
673
+ break;
674
+ } else {
675
+ lastError = new Error(`File not written: ${result}`);
676
+ if (attempt < this.SCREENSHOT_MAX_ATTEMPTS) await this.sleep(this.SCREENSHOT_RETRY_BACKOFF_MS);
677
+ }
678
+ } catch (error) {
679
+ lastError = error instanceof Error ? error : new Error(String(error));
680
+ if (attempt < this.SCREENSHOT_MAX_ATTEMPTS) await this.sleep(this.SCREENSHOT_RETRY_BACKOFF_MS);
681
+ }
682
+ }
683
+ await page.emulateMedia({
684
+ colorScheme: 'no-preference'
685
+ });
686
+ if (lastError) {
687
+ const dimensionLabel = `${dimension.width}x${dimension.height}`;
688
+ this.reportSnapshotError(lastError, {
689
+ ...errorContext,
690
+ dimension: dimensionLabel
691
+ });
692
+ console.error(`Skipping snapshot ${errorContext.snapshotName} (${this.browserName}, ${dimensionLabel}): ${lastError.message}`);
693
+ } else if (capturedFilePath) this.onScreenshotCaptured?.(capturedFilePath);
694
+ }
695
+ async captureNormalScreenshot(page, dimension, md5, playwrightOptions) {
696
+ await page.setViewportSize(dimension.width, dimension.height);
697
+ const filename = (0, __rspack_external_node_path_806ed179.join)(this.outputDir, `${md5}-${this.browserName}-${dimension.width}x${dimension.height}.png`);
698
+ const options = this.buildScreenshotOptions(filename, playwrightOptions);
699
+ await page.screenshot(options);
700
+ return filename;
701
+ }
702
+ async captureLocatorScreenshot(page, dimension, md5, playwrightOptions) {
703
+ const locator = page.locator(playwrightOptions.locator);
704
+ const boundingBox = await locator.boundingBox();
705
+ if (!boundingBox) throw new Error(`Locator bounding box is null: ${playwrightOptions.locator}`);
706
+ await page.setViewportSize(Math.ceil(boundingBox.width), Math.ceil(boundingBox.height));
707
+ const filename = (0, __rspack_external_node_path_806ed179.join)(this.outputDir, `${md5}-${this.browserName}-${dimension.width}x${dimension.height}.png`);
708
+ const options = this.buildLocatorScreenshotOptions(filename, playwrightOptions);
709
+ await locator.screenshot(options);
710
+ return filename;
711
+ }
712
+ buildScreenshotOptions(filepath, opts) {
713
+ const options = {
714
+ path: filepath,
715
+ fullPage: opts.full_page ?? false,
716
+ timeout: this.DEFAULT_ACTION_TIMEOUT_MS
717
+ };
718
+ if (opts.animations) options.animations = 'disabled' === opts.animations ? 'disabled' : 'allow';
719
+ else options.animations = 'disabled';
720
+ if (opts.caret) options.caret = 'hide' === opts.caret ? 'hide' : 'initial' === opts.caret ? 'initial' : 'hide';
721
+ if (opts.clip) options.clip = {
722
+ x: 0,
723
+ y: 0,
724
+ width: opts.clip.width,
725
+ height: opts.clip.height
726
+ };
727
+ opts.mask && opts.mask.length;
728
+ if (opts.mask_color) options.maskColor = opts.mask_color;
729
+ if (opts.omit_background) options.omitBackground = opts.omit_background;
730
+ if (opts.scale) options.scale = 'device' === opts.scale ? 'device' : 'css' === opts.scale ? 'css' : 'css';
731
+ const defaultStyle = `.percy\\:hidden {
732
+ visibility: hidden !important;
733
+ }
734
+ .snappy\\:invisible {
735
+ visibility: hidden !important;
736
+ }`;
737
+ options.style = defaultStyle;
738
+ return options;
739
+ }
740
+ buildLocatorScreenshotOptions(filepath, opts) {
741
+ const options = {
742
+ path: filepath,
743
+ timeout: this.DEFAULT_ACTION_TIMEOUT_MS
744
+ };
745
+ if (opts.animations) options.animations = 'disabled' === opts.animations ? 'disabled' : 'allow';
746
+ else options.animations = 'disabled';
747
+ if (opts.caret) options.caret = 'hide' === opts.caret ? 'hide' : 'initial' === opts.caret ? 'initial' : 'hide';
748
+ opts.mask && opts.mask.length;
749
+ if (opts.mask_color) options.maskColor = opts.mask_color;
750
+ if (opts.omit_background) options.omitBackground = opts.omit_background;
751
+ if (opts.scale) options.scale = 'device' === opts.scale ? 'device' : 'css' === opts.scale ? 'css' : 'css';
752
+ const defaultStyle = `.percy\\:hidden {
753
+ visibility: hidden !important;
754
+ }
755
+ .snappy\\:invisible {
756
+ visibility: hidden !important;
757
+ }`;
758
+ options.style = defaultStyle;
759
+ return options;
760
+ }
761
+ sleep(ms) {
762
+ return new Promise((resolve)=>setTimeout(resolve, ms));
763
+ }
764
+ }
765
+ class DrainTimeoutError extends Error {
766
+ constructor(timeoutMs){
767
+ super(`Timed out after ${timeoutMs}ms waiting for browser/upload pools to drain`);
768
+ this.name = 'DrainTimeoutError';
769
+ }
770
+ }
771
+ function withTimeout(promise, timeoutMs) {
772
+ return new Promise((resolve, reject)=>{
773
+ const timer = setTimeout(()=>reject(new DrainTimeoutError(timeoutMs)), timeoutMs);
774
+ promise.then((value)=>{
775
+ clearTimeout(timer);
776
+ resolve(value);
777
+ }, (error)=>{
778
+ clearTimeout(timer);
779
+ reject(error);
780
+ });
781
+ });
782
+ }
783
+ const DEFAULT_DRAIN_TIMEOUT_MS = 600000;
784
+ async function defaultPtyRunner(command, onStdout) {
785
+ return new Promise((resolve, reject)=>{
786
+ const proc = spawn('sh', [
787
+ '-c',
788
+ command
789
+ ], {
790
+ stdio: [
791
+ 'inherit',
792
+ 'pipe',
793
+ 'pipe'
794
+ ],
795
+ shell: false
796
+ });
797
+ proc.stdout?.on('data', (data)=>{
798
+ onStdout(data.toString());
799
+ });
800
+ proc.stderr?.on('data', (data)=>{
801
+ onStdout(data.toString());
802
+ });
803
+ proc.on('error', (error)=>{
804
+ reject(error);
805
+ });
806
+ proc.on('exit', (code)=>{
807
+ resolve({
808
+ exitCode: code ?? 1
809
+ });
810
+ });
811
+ });
812
+ }
813
+ async function runSnapshotRun(config, deps) {
814
+ const createBuildFn = deps.createBuildFn ?? createBuild;
815
+ const browserPoolFactory = deps.browserPoolFactory ?? (async (_browserName, _buildId)=>({}));
816
+ const uploadPool = deps.uploadPool;
817
+ const serveFn = deps.serveFn ?? (async ()=>{});
818
+ const ptyRunnerFn = deps.ptyRunnerFn ?? defaultPtyRunner;
819
+ const sendCompleteFn = deps.sendCompleteFn ?? sendComplete;
820
+ const sendFailedFn = deps.sendFailedFn ?? sendFailed;
821
+ const drainTimeoutMs = deps.drainTimeoutMs ?? DEFAULT_DRAIN_TIMEOUT_MS;
822
+ let buildId;
823
+ let serverHandle;
824
+ const browserPools = new Map();
825
+ try {
826
+ const buildPayload = {
827
+ serverLocation: config.server_location,
828
+ apiKey: config.api_key,
829
+ branch: config.branch,
830
+ commit: config.commit,
831
+ pullRequest: config.pull_request,
832
+ uniqueIdentifier: config.unique_identifier
833
+ };
834
+ buildId = await createBuildFn(buildPayload);
835
+ console.log(`Created build: ${buildId}`);
836
+ const uniqueBrowsers = Array.from(new Set(config.browsers));
837
+ for (const browserName of uniqueBrowsers){
838
+ const pool = await browserPoolFactory(browserName, buildId);
839
+ browserPools.set(browserName, pool);
840
+ }
841
+ const app = deps.buildApp(buildId, browserPools);
842
+ serverHandle = await serveFn(app, 4050);
843
+ let testExitCode = 0;
844
+ if (config.test_command) {
845
+ console.log(`Running: ${config.test_command}`);
846
+ const result = await ptyRunnerFn(config.test_command, (data)=>{
847
+ process.stdout.write(data);
848
+ });
849
+ testExitCode = result.exitCode;
850
+ }
851
+ if (0 !== testExitCode) {
852
+ console.log(`Test command exited with code ${testExitCode}`);
853
+ throw new Error(`Test command failed with exit code ${testExitCode}`);
854
+ }
855
+ console.log('Draining browser and upload pools...');
856
+ await withTimeout((async ()=>{
857
+ await Promise.all(Array.from(browserPools.values()).map((pool)=>pool.drain()));
858
+ await uploadPool.drain();
859
+ })(), drainTimeoutMs);
860
+ console.log('All pools drained successfully');
861
+ if (config.parallel) console.log('Parallel mode: skipping sendComplete (finalizeBuild will handle it)');
862
+ else {
863
+ console.log('Sending build completion...');
864
+ await sendCompleteFn({
865
+ serverLocation: config.server_location,
866
+ apiKey: config.api_key,
867
+ buildId
868
+ });
869
+ }
870
+ console.log('Build completed successfully');
871
+ } catch (error) {
872
+ if (error instanceof DrainTimeoutError) console.error(error.message);
873
+ if (buildId) try {
874
+ await sendFailedFn({
875
+ serverLocation: config.server_location,
876
+ apiKey: config.api_key,
877
+ buildId
878
+ });
879
+ } catch (sendFailedError) {
880
+ console.error('Failed to report build failure to server:', sendFailedError);
881
+ }
882
+ if (error instanceof Error) throw error;
883
+ throw new Error(`Unknown error: ${error}`);
884
+ } finally{
885
+ for (const pool of browserPools.values())try {
886
+ await pool.closeBrowser();
887
+ } catch (closeError) {
888
+ console.error('Error closing browser:', closeError);
889
+ }
890
+ try {
891
+ await serverHandle?.close?.();
892
+ } catch (closeError) {
893
+ console.error('Error closing server:', closeError);
894
+ }
895
+ }
896
+ }
897
+ async function finalizeBuild(config, deps) {
898
+ const createBuildFn = deps.createBuildFn ?? createBuild;
899
+ const sendCompleteFn = deps.sendCompleteFn ?? sendComplete;
900
+ try {
901
+ const buildPayload = {
902
+ serverLocation: config.server_location,
903
+ apiKey: config.api_key,
904
+ branch: config.branch,
905
+ commit: config.commit,
906
+ pullRequest: config.pull_request,
907
+ uniqueIdentifier: config.unique_identifier
908
+ };
909
+ const buildId = await createBuildFn(buildPayload);
910
+ console.log(`Finalizing build: ${buildId}`);
911
+ await sendCompleteFn({
912
+ serverLocation: config.server_location,
913
+ apiKey: config.api_key,
914
+ buildId
915
+ });
916
+ console.log('Build finalized successfully');
917
+ } catch (error) {
918
+ if (error instanceof Error) throw error;
919
+ throw new Error(`Unknown error: ${error}`);
920
+ }
921
+ }
922
+ function isUnsafePathSegment(segment) {
923
+ return segment.includes('..') || segment.includes('/') || segment.includes('\\');
924
+ }
925
+ function createApp(options) {
926
+ const app = new Hono();
927
+ app.use('*', cors());
928
+ app.get('/up', (c)=>c.json({
929
+ ok: true
930
+ }));
931
+ app.post('/snappy-api/snapshot/:id', async (c)=>{
932
+ const snapshotId = c.req.param('id');
933
+ if (isUnsafePathSegment(snapshotId)) return c.json({
934
+ error: 'Invalid snapshot id'
935
+ }, 400);
936
+ let requestBody;
937
+ try {
938
+ requestBody = await c.req.json();
939
+ } catch (_err) {
940
+ return c.json({
941
+ error: 'Invalid JSON'
942
+ }, 400);
943
+ }
944
+ if (!requestBody.html) return c.json({
945
+ error: 'Missing required field: html'
946
+ }, 400);
947
+ let snapshotOptions;
948
+ let playwrightOptions;
949
+ try {
950
+ snapshotOptions = SnapshotOptionsSchema.parse(requestBody.options || {});
951
+ playwrightOptions = PlaywrightOptionsSchema.parse(requestBody.playwright_options || {});
952
+ } catch (err) {
953
+ return c.json({
954
+ error: 'Invalid options schema',
955
+ details: err.message
956
+ }, 400);
957
+ }
958
+ const htmlContent = requestBody.html;
959
+ let snapshotName = requestBody.name || '';
960
+ if (snapshotOptions.name) snapshotName = snapshotOptions.name;
961
+ const md5 = createHash('md5').update(snapshotName).digest('hex');
962
+ const configuredBrowsers = options.browsers || [];
963
+ for (const browser of configuredBrowsers)if (!options.playwrightPoolsByBrowser.has(browser)) {
964
+ console.error(`No PlaywrightScreenshotPool configured for browser: ${browser}`);
965
+ return c.json({
966
+ error: `No pool configured for browser: ${browser}`
967
+ }, 500);
968
+ }
969
+ try {
970
+ await mkdir(options.htmlDir, {
971
+ recursive: true
972
+ });
973
+ const htmlPath = (0, __rspack_external_node_path_806ed179.join)(options.htmlDir, `${snapshotId}.html`);
974
+ await writeFile(htmlPath, htmlContent, 'utf-8');
975
+ } catch (err) {
976
+ console.error(`Failed to write HTML file: ${err}`);
977
+ return c.json({
978
+ error: 'Failed to write HTML'
979
+ }, 500);
980
+ }
981
+ if (!snapshotOptions.dimensions || 0 === snapshotOptions.dimensions.length) snapshotOptions.dimensions = [
982
+ {
983
+ width: 1920,
984
+ height: 1080
985
+ }
986
+ ];
987
+ const metadata = {
988
+ id: snapshotId,
989
+ name: snapshotName,
990
+ html: htmlContent,
991
+ options: snapshotOptions,
992
+ md5
993
+ };
994
+ let jsonWritten = false;
995
+ let jsonFilePath = '';
996
+ try {
997
+ await mkdir(options.snapshotDir, {
998
+ recursive: true
999
+ });
1000
+ jsonFilePath = (0, __rspack_external_node_path_806ed179.join)(options.snapshotDir, `${md5}.json`);
1001
+ await writeFile(jsonFilePath, JSON.stringify(metadata), 'utf-8');
1002
+ jsonWritten = true;
1003
+ } catch (err) {
1004
+ console.error(`Failed to write snapshot JSON: ${err}`);
1005
+ }
1006
+ for (const browser of configuredBrowsers){
1007
+ const pool = options.playwrightPoolsByBrowser.get(browser);
1008
+ const url = `http://localhost:${options.port}/snappy-api/snapshot/${snapshotId}`;
1009
+ pool.enqueueSnapshot(url, snapshotName, snapshotOptions, playwrightOptions);
1010
+ }
1011
+ if (jsonWritten && jsonFilePath) options.uploadPool.enqueue({
1012
+ filePath: jsonFilePath,
1013
+ buildId: options.buildId
1014
+ });
1015
+ return c.text('OK', 200);
1016
+ });
1017
+ app.get('/snappy-api/snapshot/:id', async (c)=>{
1018
+ const snapshotId = c.req.param('id');
1019
+ if (isUnsafePathSegment(snapshotId)) return c.json({
1020
+ error: 'Not Found'
1021
+ }, 404);
1022
+ const htmlPath = (0, __rspack_external_node_path_806ed179.join)(options.htmlDir, `${snapshotId}.html`);
1023
+ try {
1024
+ const htmlContent = await readFile(htmlPath, 'utf-8');
1025
+ return c.html(htmlContent);
1026
+ } catch (err) {
1027
+ if ('ENOENT' === err.code) return c.json({
1028
+ error: 'Not Found'
1029
+ }, 404);
1030
+ console.error(`Failed to read snapshot file: ${err}`);
1031
+ return c.json({
1032
+ error: 'Failed to read snapshot'
1033
+ }, 500);
1034
+ }
1035
+ });
1036
+ app.get('/snappy-api/are-we-done', (c)=>c.json({
1037
+ done: true
1038
+ }));
1039
+ app.notFound(async (c)=>{
1040
+ const path = c.req.path;
1041
+ if (path.includes('..')) return c.json({
1042
+ error: 'Not Found'
1043
+ }, 404);
1044
+ const safePath = path.startsWith('/') ? path.slice(1) : path;
1045
+ const filePath = (0, __rspack_external_node_path_806ed179.join)(options.localDistDir, safePath);
1046
+ try {
1047
+ const fileContent = await readFile(filePath);
1048
+ const ext = (0, __rspack_external_node_path_806ed179.extname)(filePath).toLowerCase();
1049
+ let contentType = 'application/octet-stream';
1050
+ if ('.html' === ext) contentType = 'text/html';
1051
+ else if ('.css' === ext) contentType = 'text/css';
1052
+ else if ('.js' === ext) contentType = "application/javascript";
1053
+ else if ('.json' === ext) contentType = 'application/json';
1054
+ else if ('.png' === ext) contentType = 'image/png';
1055
+ else if ('.jpg' === ext || '.jpeg' === ext) contentType = 'image/jpeg';
1056
+ else if ('.gif' === ext) contentType = 'image/gif';
1057
+ else if ('.svg' === ext) contentType = 'image/svg+xml';
1058
+ else if ('.woff' === ext) contentType = 'font/woff';
1059
+ else if ('.woff2' === ext) contentType = 'font/woff2';
1060
+ return c.body(fileContent, 200, {
1061
+ 'Content-Type': contentType
1062
+ });
1063
+ } catch (err) {
1064
+ if ('ENOENT' === err.code) return c.json({
1065
+ error: 'Not Found'
1066
+ }, 404);
1067
+ console.error(`Failed to serve static file: ${err}`);
1068
+ return c.json({
1069
+ error: 'Failed to serve static file'
1070
+ }, 500);
1071
+ }
1072
+ });
1073
+ return app;
1074
+ }
1075
+ async function serve(app, port) {
1076
+ const { serve: nodeServe } = await import("@hono/node-server");
1077
+ console.log(`Starting server on http://localhost:${port}`);
1078
+ const server = nodeServe({
1079
+ fetch: app.fetch,
1080
+ port
1081
+ });
1082
+ return {
1083
+ close: ()=>new Promise((resolve, reject)=>{
1084
+ server.close((err)=>err ? reject(err) : resolve());
1085
+ })
1086
+ };
1087
+ }
1088
+ class UploadPool {
1089
+ pool;
1090
+ serverLocation;
1091
+ apiKey;
1092
+ uploadCount = 0;
1093
+ onUnrecoverableFailure;
1094
+ retryOptions;
1095
+ getPresignedUrlFn;
1096
+ uploadFileFn;
1097
+ constructor(options){
1098
+ this.serverLocation = options.serverLocation;
1099
+ this.apiKey = options.apiKey;
1100
+ this.onUnrecoverableFailure = options.onUnrecoverableFailure;
1101
+ this.retryOptions = options.retryOptions;
1102
+ this.getPresignedUrlFn = options.getPresignedUrlFn ?? getPresignedUrl;
1103
+ this.uploadFileFn = options.uploadFileFn ?? uploadFile;
1104
+ const poolSize = options.poolSize ?? 32;
1105
+ this.pool = new WorkerPool({
1106
+ size: poolSize,
1107
+ handler: (job)=>this.processUploadJob(job),
1108
+ onError: (error)=>{
1109
+ if (this.onUnrecoverableFailure) this.onUnrecoverableFailure(error);
1110
+ }
1111
+ });
1112
+ }
1113
+ enqueue(job) {
1114
+ this.pool.enqueue(job);
1115
+ }
1116
+ async drain() {
1117
+ await this.pool.drain();
1118
+ }
1119
+ getUploadCount() {
1120
+ return this.uploadCount;
1121
+ }
1122
+ async processUploadJob(job) {
1123
+ const filename = (0, __rspack_external_node_path_806ed179.basename)(job.filePath);
1124
+ try {
1125
+ const fileData = new Uint8Array(await readFile(job.filePath));
1126
+ const presignedUrl = await this.getPresignedUrlFn({
1127
+ serverLocation: this.serverLocation,
1128
+ apiKey: this.apiKey,
1129
+ buildId: job.buildId,
1130
+ filename
1131
+ }, this.retryOptions);
1132
+ await this.uploadFileFn({
1133
+ presignedUrl,
1134
+ filename,
1135
+ fileData
1136
+ }, this.retryOptions);
1137
+ this.uploadCount++;
1138
+ } catch (error) {
1139
+ if (this.onUnrecoverableFailure) this.onUnrecoverableFailure(error);
1140
+ }
1141
+ }
1142
+ }
1143
+ const SENTRY_DSN = 'https://d061161d801a3657e347c6b1290c2cfe@o4507366754549760.ingest.us.sentry.io/4507366844006400';
1144
+ function getVersion() {
1145
+ try {
1146
+ const __filename = fileURLToPath(import.meta.url);
1147
+ const __dirname = dirname(__filename);
1148
+ const packageJsonPath = join(__dirname, '../package.json');
1149
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
1150
+ return packageJson.version;
1151
+ } catch (_error) {
1152
+ return '0.0.0';
1153
+ }
1154
+ }
1155
+ async function parseArgs(argv, deps = {}) {
1156
+ const command = argv[2] || '';
1157
+ const args = argv.slice(3);
1158
+ let configPath;
1159
+ const configIndex = args.indexOf('--config');
1160
+ if (-1 !== configIndex) {
1161
+ if (configIndex + 1 >= args.length) {
1162
+ console.error('Error: --config requires a path argument');
1163
+ process.exit(1);
1164
+ }
1165
+ configPath = args[configIndex + 1];
1166
+ }
1167
+ const loadConfigFn = deps.loadConfigFn ?? loadConfig;
1168
+ const runSnapshotRunFn = deps.runSnapshotRunFn ?? runSnapshotRun;
1169
+ const finalizeBuildFn = deps.finalizeBuildFn ?? finalizeBuild;
1170
+ const initSentryFn = deps.initSentryFn ?? initSentry;
1171
+ const setSentryTagsFn = deps.setSentryTagsFn ?? setSentryTags;
1172
+ const execSyncFn = deps.execSyncFn ?? execSync;
1173
+ const captureErrorAndExitFn = deps.captureErrorAndExitFn ?? captureErrorAndExit;
1174
+ if (args.includes('--help') || args.includes('-h')) return handleHelp();
1175
+ if ('--version' === command || '-v' === command) return handleVersion();
1176
+ try {
1177
+ switch(command){
1178
+ case 'version':
1179
+ return handleVersion();
1180
+ case 'snapshot-run':
1181
+ return await handleSnapshotRun(configPath, loadConfigFn, runSnapshotRunFn, initSentryFn, setSentryTagsFn);
1182
+ case 'finalize-build':
1183
+ return await handleFinalizeBuild(configPath, loadConfigFn, finalizeBuildFn, initSentryFn, setSentryTagsFn);
1184
+ case 'install-browsers':
1185
+ return handleInstallBrowsers(execSyncFn);
1186
+ case '--help':
1187
+ case '-h':
1188
+ case '':
1189
+ return handleHelp();
1190
+ default:
1191
+ console.error(`Unknown command: ${command}`);
1192
+ process.exit(1);
1193
+ }
1194
+ } catch (error) {
1195
+ const err = error instanceof Error ? error : new Error(String(error));
1196
+ await captureErrorAndExitFn(err);
1197
+ }
1198
+ }
1199
+ function handleVersion() {
1200
+ const version = getVersion();
1201
+ console.log(`get-snappy version ${version}`);
1202
+ }
1203
+ function handleHelp() {
1204
+ console.log(`get-snappy - CLI tool for https://get-snappy.com
1205
+
1206
+ Usage:
1207
+ get-snappy [command] [options]
1208
+
1209
+ Commands:
1210
+ snapshot-run Execute your test suite and send snapshots to GetSnappy
1211
+ finalize-build Finalize the build and send results to GetSnappy
1212
+ install-browsers Install Playwright browsers
1213
+ version Print the CLI version
1214
+
1215
+ Options:
1216
+ --config <path> Config file (default: .get-snappy.json, .yaml, .yml or
1217
+ .get-snappy in the current directory)
1218
+ --help, -h Show this help message
1219
+ --version, -v Print the CLI version
1220
+
1221
+ Config file settings:
1222
+ test_command Command that runs your test suite (required for snapshot-run)
1223
+ browsers Browsers to render in (default: [chrome])
1224
+ snappy_workers Page workers per browser (default: 4)
1225
+ upload_workers Upload workers (default: 32)
1226
+ local_dist_dir Directory of static assets to serve
1227
+ wait_until load, domcontentloaded, networkidle or commit
1228
+
1229
+ Environment Variables (GET_SNAPPY_* prefix, override the config file):
1230
+ API_KEY API key for GetSnappy
1231
+ BRANCH Git branch name
1232
+ COMMIT Git commit hash
1233
+ PULL_REQUEST Pull request number
1234
+ SERVER_LOCATION GetSnappy server URL (default: https://get-snappy.com)
1235
+ PARALLEL Enable parallel mode (true/false)
1236
+ UNIQUE_IDENTIFIER Unique run identifier`);
1237
+ }
1238
+ async function handleSnapshotRun(configPath, loadConfigFn, runSnapshotRunFn, initSentryFn, setSentryTagsFn) {
1239
+ const config = loadConfigFn(configPath);
1240
+ const version = getVersion();
1241
+ initSentryFn(SENTRY_DSN, `get-snappy@${version}`);
1242
+ setSentryTagsFn({
1243
+ branch: config.branch,
1244
+ commit: config.commit,
1245
+ pull_request: config.pull_request,
1246
+ unique_identifier: config.unique_identifier,
1247
+ parallel: config.parallel,
1248
+ browsers: config.browsers
1249
+ });
1250
+ if (!config.test_command) throw new Error('No test command provided');
1251
+ const uploadPool = new UploadPool({
1252
+ serverLocation: config.server_location,
1253
+ apiKey: config.api_key,
1254
+ poolSize: config.upload_workers
1255
+ });
1256
+ const htmlDir = mkdtempSync(join(tmpdir(), 'get-snappy-html-'));
1257
+ const snapshotDir = mkdtempSync(join(tmpdir(), 'get-snappy-snapshot-'));
1258
+ const screenshotDir = mkdtempSync(join(tmpdir(), 'get-snappy-screenshots-'));
1259
+ try {
1260
+ await runSnapshotRunFn(config, {
1261
+ uploadPool,
1262
+ serveFn: serve,
1263
+ buildApp: (buildId, browserPools)=>{
1264
+ const appOptions = {
1265
+ playwrightPoolsByBrowser: browserPools,
1266
+ uploadPool,
1267
+ htmlDir,
1268
+ snapshotDir,
1269
+ localDistDir: config.local_dist_dir,
1270
+ buildId,
1271
+ browsers: config.browsers,
1272
+ port: 4050
1273
+ };
1274
+ return createApp(appOptions);
1275
+ },
1276
+ browserPoolFactory: async (browserName, buildId)=>{
1277
+ const browser = await launchBrowser(browserName);
1278
+ return new PlaywrightScreenshotPool({
1279
+ browser,
1280
+ browserName,
1281
+ workerCount: config.snappy_workers,
1282
+ outputDir: screenshotDir,
1283
+ defaultWaitUntil: config.wait_until,
1284
+ onScreenshotCaptured: (filePath)=>{
1285
+ uploadPool.enqueue({
1286
+ filePath,
1287
+ buildId
1288
+ });
1289
+ }
1290
+ });
1291
+ }
1292
+ });
1293
+ } finally{
1294
+ for (const dir of [
1295
+ htmlDir,
1296
+ snapshotDir,
1297
+ screenshotDir
1298
+ ])try {
1299
+ rmSync(dir, {
1300
+ recursive: true,
1301
+ force: true
1302
+ });
1303
+ } catch (cleanupError) {
1304
+ console.error(`Failed to remove temp directory ${dir}:`, cleanupError);
1305
+ }
1306
+ }
1307
+ }
1308
+ async function handleFinalizeBuild(configPath, loadConfigFn, finalizeBuildFn, initSentryFn, setSentryTagsFn) {
1309
+ const config = loadConfigFn(configPath);
1310
+ const version = getVersion();
1311
+ initSentryFn(SENTRY_DSN, `get-snappy@${version}`);
1312
+ setSentryTagsFn({
1313
+ branch: config.branch,
1314
+ commit: config.commit,
1315
+ pull_request: config.pull_request,
1316
+ unique_identifier: config.unique_identifier,
1317
+ parallel: config.parallel
1318
+ });
1319
+ await finalizeBuildFn(config, {});
1320
+ }
1321
+ function handleInstallBrowsers(execSyncFn) {
1322
+ try {
1323
+ execSyncFn(`"${process.execPath}" "${bundledPlaywrightCli()}" install`, {
1324
+ stdio: 'inherit'
1325
+ });
1326
+ } catch (error) {
1327
+ if (error instanceof Error) throw error;
1328
+ throw new Error(`Failed to install browsers: ${String(error)}`);
1329
+ }
1330
+ }
1331
+ async function main() {
1332
+ await parseArgs(process.argv);
1333
+ process.exit(0);
1334
+ }
1335
+ main().catch((error)=>{
1336
+ console.error('Error:', error);
1337
+ process.exit(1);
1338
+ });
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@get-snappy/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.6.1",
4
+ "description": "CLI for get-snappy visual regression testing",
5
+ "type": "module",
6
+ "bin": {
7
+ "get-snappy": "dist/index.js"
8
+ },
9
+ "main": "./dist/index.js",
10
+ "files": [
11
+ "dist"
12
+ ],
13
+ "publishConfig": {
14
+ "access": "public"
15
+ },
16
+ "scripts": {
17
+ "build": "rslib build"
18
+ },
19
+ "dependencies": {
20
+ "@hono/node-server": "^1.14.0",
21
+ "@sentry/node": "^10.64.0",
22
+ "hono": "^4.6.0",
23
+ "playwright": "1.61.1",
24
+ "yaml": "^2.3.0",
25
+ "zod": "^3.22.0"
26
+ },
27
+ "devDependencies": {
28
+ "@get-snappy/core": "workspace:*",
29
+ "@rslib/core": "1.0.3"
30
+ }
31
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.