@midscene/cli 1.17.8-beta-20261106101231.0 → 1.17.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4382 @@
1
+ import * as __rspack_external_os from "os";
2
+ import * as __rspack_external_tty from "tty";
3
+ import * as __rspack_external_node_fs_5ea92f0c from "node:fs";
4
+ import { __webpack_require__ } from "./rslib-runtime.mjs";
5
+ import { ReportMergingTool, createReportCliCommands } from "@midscene/core";
6
+ import { basename, dirname, extname, join, posix, relative, resolve as external_node_path_resolve, sep, win32 } from "node:path";
7
+ import { interpolateEnvVars, midsceneYamlTargetKeys, parseYamlScript, resolveWebTarget } from "@midscene/core/yaml";
8
+ import { getDebug } from "@midscene/shared/logger";
9
+ import { fileURLToPath, pathToFileURL } from "node:url";
10
+ import node_process, { cwd } from "node:process";
11
+ import lodash_merge from "lodash.merge";
12
+ import { createHash, randomUUID } from "node:crypto";
13
+ import { getMidsceneRunSubDir } from "@midscene/shared/common";
14
+ import { buildChromeArgs, buildDownloadBehavior, defaultViewportHeight, defaultViewportWidth } from "@midscene/web/puppeteer-agent-launcher";
15
+ import puppeteer from "puppeteer";
16
+ import { createYamlPlayer } from "@midscene/test/internal/yaml-runtime";
17
+ import { inspect, stripVTControlCharacters } from "node:util";
18
+ import { createRequire } from "node:module";
19
+ import { serializeError } from "@midscene/shared/agent-tools/error-formatter";
20
+ __webpack_require__.add({
21
+ "../../node_modules/.pnpm/ansi-styles@4.3.0/node_modules/ansi-styles/index.js" (module, __unused_rspack_exports, __webpack_require__) {
22
+ module = __webpack_require__.nmd(module);
23
+ const wrapAnsi16 = (fn, offset)=>(...args)=>{
24
+ const code = fn(...args);
25
+ return `\u001B[${code + offset}m`;
26
+ };
27
+ const wrapAnsi256 = (fn, offset)=>(...args)=>{
28
+ const code = fn(...args);
29
+ return `\u001B[${38 + offset};5;${code}m`;
30
+ };
31
+ const wrapAnsi16m = (fn, offset)=>(...args)=>{
32
+ const rgb = fn(...args);
33
+ return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`;
34
+ };
35
+ const ansi2ansi = (n)=>n;
36
+ const rgb2rgb = (r, g, b)=>[
37
+ r,
38
+ g,
39
+ b
40
+ ];
41
+ const setLazyProperty = (object, property, get)=>{
42
+ Object.defineProperty(object, property, {
43
+ get: ()=>{
44
+ const value = get();
45
+ Object.defineProperty(object, property, {
46
+ value,
47
+ enumerable: true,
48
+ configurable: true
49
+ });
50
+ return value;
51
+ },
52
+ enumerable: true,
53
+ configurable: true
54
+ });
55
+ };
56
+ let colorConvert;
57
+ const makeDynamicStyles = (wrap, targetSpace, identity, isBackground)=>{
58
+ if (void 0 === colorConvert) colorConvert = __webpack_require__("../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/index.js");
59
+ const offset = isBackground ? 10 : 0;
60
+ const styles = {};
61
+ for (const [sourceSpace, suite] of Object.entries(colorConvert)){
62
+ const name = 'ansi16' === sourceSpace ? 'ansi' : sourceSpace;
63
+ if (sourceSpace === targetSpace) styles[name] = wrap(identity, offset);
64
+ else if ('object' == typeof suite) styles[name] = wrap(suite[targetSpace], offset);
65
+ }
66
+ return styles;
67
+ };
68
+ function assembleStyles() {
69
+ const codes = new Map();
70
+ const styles = {
71
+ modifier: {
72
+ reset: [
73
+ 0,
74
+ 0
75
+ ],
76
+ bold: [
77
+ 1,
78
+ 22
79
+ ],
80
+ dim: [
81
+ 2,
82
+ 22
83
+ ],
84
+ italic: [
85
+ 3,
86
+ 23
87
+ ],
88
+ underline: [
89
+ 4,
90
+ 24
91
+ ],
92
+ inverse: [
93
+ 7,
94
+ 27
95
+ ],
96
+ hidden: [
97
+ 8,
98
+ 28
99
+ ],
100
+ strikethrough: [
101
+ 9,
102
+ 29
103
+ ]
104
+ },
105
+ color: {
106
+ black: [
107
+ 30,
108
+ 39
109
+ ],
110
+ red: [
111
+ 31,
112
+ 39
113
+ ],
114
+ green: [
115
+ 32,
116
+ 39
117
+ ],
118
+ yellow: [
119
+ 33,
120
+ 39
121
+ ],
122
+ blue: [
123
+ 34,
124
+ 39
125
+ ],
126
+ magenta: [
127
+ 35,
128
+ 39
129
+ ],
130
+ cyan: [
131
+ 36,
132
+ 39
133
+ ],
134
+ white: [
135
+ 37,
136
+ 39
137
+ ],
138
+ blackBright: [
139
+ 90,
140
+ 39
141
+ ],
142
+ redBright: [
143
+ 91,
144
+ 39
145
+ ],
146
+ greenBright: [
147
+ 92,
148
+ 39
149
+ ],
150
+ yellowBright: [
151
+ 93,
152
+ 39
153
+ ],
154
+ blueBright: [
155
+ 94,
156
+ 39
157
+ ],
158
+ magentaBright: [
159
+ 95,
160
+ 39
161
+ ],
162
+ cyanBright: [
163
+ 96,
164
+ 39
165
+ ],
166
+ whiteBright: [
167
+ 97,
168
+ 39
169
+ ]
170
+ },
171
+ bgColor: {
172
+ bgBlack: [
173
+ 40,
174
+ 49
175
+ ],
176
+ bgRed: [
177
+ 41,
178
+ 49
179
+ ],
180
+ bgGreen: [
181
+ 42,
182
+ 49
183
+ ],
184
+ bgYellow: [
185
+ 43,
186
+ 49
187
+ ],
188
+ bgBlue: [
189
+ 44,
190
+ 49
191
+ ],
192
+ bgMagenta: [
193
+ 45,
194
+ 49
195
+ ],
196
+ bgCyan: [
197
+ 46,
198
+ 49
199
+ ],
200
+ bgWhite: [
201
+ 47,
202
+ 49
203
+ ],
204
+ bgBlackBright: [
205
+ 100,
206
+ 49
207
+ ],
208
+ bgRedBright: [
209
+ 101,
210
+ 49
211
+ ],
212
+ bgGreenBright: [
213
+ 102,
214
+ 49
215
+ ],
216
+ bgYellowBright: [
217
+ 103,
218
+ 49
219
+ ],
220
+ bgBlueBright: [
221
+ 104,
222
+ 49
223
+ ],
224
+ bgMagentaBright: [
225
+ 105,
226
+ 49
227
+ ],
228
+ bgCyanBright: [
229
+ 106,
230
+ 49
231
+ ],
232
+ bgWhiteBright: [
233
+ 107,
234
+ 49
235
+ ]
236
+ }
237
+ };
238
+ styles.color.gray = styles.color.blackBright;
239
+ styles.bgColor.bgGray = styles.bgColor.bgBlackBright;
240
+ styles.color.grey = styles.color.blackBright;
241
+ styles.bgColor.bgGrey = styles.bgColor.bgBlackBright;
242
+ for (const [groupName, group] of Object.entries(styles)){
243
+ for (const [styleName, style] of Object.entries(group)){
244
+ styles[styleName] = {
245
+ open: `\u001B[${style[0]}m`,
246
+ close: `\u001B[${style[1]}m`
247
+ };
248
+ group[styleName] = styles[styleName];
249
+ codes.set(style[0], style[1]);
250
+ }
251
+ Object.defineProperty(styles, groupName, {
252
+ value: group,
253
+ enumerable: false
254
+ });
255
+ }
256
+ Object.defineProperty(styles, 'codes', {
257
+ value: codes,
258
+ enumerable: false
259
+ });
260
+ styles.color.close = '\u001B[39m';
261
+ styles.bgColor.close = '\u001B[49m';
262
+ setLazyProperty(styles.color, 'ansi', ()=>makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false));
263
+ setLazyProperty(styles.color, 'ansi256', ()=>makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false));
264
+ setLazyProperty(styles.color, 'ansi16m', ()=>makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false));
265
+ setLazyProperty(styles.bgColor, 'ansi', ()=>makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true));
266
+ setLazyProperty(styles.bgColor, 'ansi256', ()=>makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true));
267
+ setLazyProperty(styles.bgColor, 'ansi16m', ()=>makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true));
268
+ return styles;
269
+ }
270
+ Object.defineProperty(module, 'exports', {
271
+ enumerable: true,
272
+ get: assembleStyles
273
+ });
274
+ },
275
+ "../../node_modules/.pnpm/chalk@4.1.2/node_modules/chalk/source/index.js" (module, __unused_rspack_exports, __webpack_require__) {
276
+ const ansiStyles = __webpack_require__("../../node_modules/.pnpm/ansi-styles@4.3.0/node_modules/ansi-styles/index.js");
277
+ const { stdout: stdoutColor, stderr: stderrColor } = __webpack_require__("../../node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js");
278
+ const { stringReplaceAll, stringEncaseCRLFWithFirstIndex } = __webpack_require__("../../node_modules/.pnpm/chalk@4.1.2/node_modules/chalk/source/util.js");
279
+ const { isArray } = Array;
280
+ const levelMapping = [
281
+ 'ansi',
282
+ 'ansi',
283
+ 'ansi256',
284
+ 'ansi16m'
285
+ ];
286
+ const styles = Object.create(null);
287
+ const applyOptions = (object, options = {})=>{
288
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) throw new Error('The `level` option should be an integer from 0 to 3');
289
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
290
+ object.level = void 0 === options.level ? colorLevel : options.level;
291
+ };
292
+ class ChalkClass {
293
+ constructor(options){
294
+ return chalkFactory(options);
295
+ }
296
+ }
297
+ const chalkFactory = (options)=>{
298
+ const chalk = {};
299
+ applyOptions(chalk, options);
300
+ chalk.template = (...arguments_)=>chalkTag(chalk.template, ...arguments_);
301
+ Object.setPrototypeOf(chalk, Chalk.prototype);
302
+ Object.setPrototypeOf(chalk.template, chalk);
303
+ chalk.template.constructor = ()=>{
304
+ throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
305
+ };
306
+ chalk.template.Instance = ChalkClass;
307
+ return chalk.template;
308
+ };
309
+ function Chalk(options) {
310
+ return chalkFactory(options);
311
+ }
312
+ for (const [styleName, style] of Object.entries(ansiStyles))styles[styleName] = {
313
+ get () {
314
+ const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
315
+ Object.defineProperty(this, styleName, {
316
+ value: builder
317
+ });
318
+ return builder;
319
+ }
320
+ };
321
+ styles.visible = {
322
+ get () {
323
+ const builder = createBuilder(this, this._styler, true);
324
+ Object.defineProperty(this, 'visible', {
325
+ value: builder
326
+ });
327
+ return builder;
328
+ }
329
+ };
330
+ const usedModels = [
331
+ 'rgb',
332
+ 'hex',
333
+ 'keyword',
334
+ 'hsl',
335
+ 'hsv',
336
+ 'hwb',
337
+ 'ansi',
338
+ 'ansi256'
339
+ ];
340
+ for (const model of usedModels)styles[model] = {
341
+ get () {
342
+ const { level } = this;
343
+ return function(...arguments_) {
344
+ const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
345
+ return createBuilder(this, styler, this._isEmpty);
346
+ };
347
+ }
348
+ };
349
+ for (const model of usedModels){
350
+ const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
351
+ styles[bgModel] = {
352
+ get () {
353
+ const { level } = this;
354
+ return function(...arguments_) {
355
+ const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
356
+ return createBuilder(this, styler, this._isEmpty);
357
+ };
358
+ }
359
+ };
360
+ }
361
+ const proto = Object.defineProperties(()=>{}, {
362
+ ...styles,
363
+ level: {
364
+ enumerable: true,
365
+ get () {
366
+ return this._generator.level;
367
+ },
368
+ set (level) {
369
+ this._generator.level = level;
370
+ }
371
+ }
372
+ });
373
+ const createStyler = (open, close, parent)=>{
374
+ let openAll;
375
+ let closeAll;
376
+ if (void 0 === parent) {
377
+ openAll = open;
378
+ closeAll = close;
379
+ } else {
380
+ openAll = parent.openAll + open;
381
+ closeAll = close + parent.closeAll;
382
+ }
383
+ return {
384
+ open,
385
+ close,
386
+ openAll,
387
+ closeAll,
388
+ parent
389
+ };
390
+ };
391
+ const createBuilder = (self, _styler, _isEmpty)=>{
392
+ const builder = (...arguments_)=>{
393
+ if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) return applyStyle(builder, chalkTag(builder, ...arguments_));
394
+ return applyStyle(builder, 1 === arguments_.length ? '' + arguments_[0] : arguments_.join(' '));
395
+ };
396
+ Object.setPrototypeOf(builder, proto);
397
+ builder._generator = self;
398
+ builder._styler = _styler;
399
+ builder._isEmpty = _isEmpty;
400
+ return builder;
401
+ };
402
+ const applyStyle = (self, string)=>{
403
+ if (self.level <= 0 || !string) return self._isEmpty ? '' : string;
404
+ let styler = self._styler;
405
+ if (void 0 === styler) return string;
406
+ const { openAll, closeAll } = styler;
407
+ if (-1 !== string.indexOf('\u001B')) while(void 0 !== styler){
408
+ string = stringReplaceAll(string, styler.close, styler.open);
409
+ styler = styler.parent;
410
+ }
411
+ const lfIndex = string.indexOf('\n');
412
+ if (-1 !== lfIndex) string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
413
+ return openAll + string + closeAll;
414
+ };
415
+ let template;
416
+ const chalkTag = (chalk, ...strings)=>{
417
+ const [firstString] = strings;
418
+ if (!isArray(firstString) || !isArray(firstString.raw)) return strings.join(' ');
419
+ const arguments_ = strings.slice(1);
420
+ const parts = [
421
+ firstString.raw[0]
422
+ ];
423
+ for(let i = 1; i < firstString.length; i++)parts.push(String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i]));
424
+ if (void 0 === template) template = __webpack_require__("../../node_modules/.pnpm/chalk@4.1.2/node_modules/chalk/source/templates.js");
425
+ return template(chalk, parts.join(''));
426
+ };
427
+ Object.defineProperties(Chalk.prototype, styles);
428
+ const chalk = Chalk();
429
+ chalk.supportsColor = stdoutColor;
430
+ chalk.stderr = Chalk({
431
+ level: stderrColor ? stderrColor.level : 0
432
+ });
433
+ chalk.stderr.supportsColor = stderrColor;
434
+ module.exports = chalk;
435
+ },
436
+ "../../node_modules/.pnpm/chalk@4.1.2/node_modules/chalk/source/templates.js" (module) {
437
+ const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
438
+ const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
439
+ const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
440
+ const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
441
+ const ESCAPES = new Map([
442
+ [
443
+ 'n',
444
+ '\n'
445
+ ],
446
+ [
447
+ 'r',
448
+ '\r'
449
+ ],
450
+ [
451
+ 't',
452
+ '\t'
453
+ ],
454
+ [
455
+ 'b',
456
+ '\b'
457
+ ],
458
+ [
459
+ 'f',
460
+ '\f'
461
+ ],
462
+ [
463
+ 'v',
464
+ '\v'
465
+ ],
466
+ [
467
+ '0',
468
+ '\0'
469
+ ],
470
+ [
471
+ '\\',
472
+ '\\'
473
+ ],
474
+ [
475
+ 'e',
476
+ '\u001B'
477
+ ],
478
+ [
479
+ 'a',
480
+ '\u0007'
481
+ ]
482
+ ]);
483
+ function unescape(c) {
484
+ const u = 'u' === c[0];
485
+ const bracket = '{' === c[1];
486
+ if (u && !bracket && 5 === c.length || 'x' === c[0] && 3 === c.length) return String.fromCharCode(parseInt(c.slice(1), 16));
487
+ if (u && bracket) return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
488
+ return ESCAPES.get(c) || c;
489
+ }
490
+ function parseArguments(name, arguments_) {
491
+ const results = [];
492
+ const chunks = arguments_.trim().split(/\s*,\s*/g);
493
+ let matches;
494
+ for (const chunk of chunks){
495
+ const number = Number(chunk);
496
+ if (Number.isNaN(number)) if (matches = chunk.match(STRING_REGEX)) results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character)=>escape ? unescape(escape) : character));
497
+ else throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
498
+ else results.push(number);
499
+ }
500
+ return results;
501
+ }
502
+ function parseStyle(style) {
503
+ STYLE_REGEX.lastIndex = 0;
504
+ const results = [];
505
+ let matches;
506
+ while(null !== (matches = STYLE_REGEX.exec(style))){
507
+ const name = matches[1];
508
+ if (matches[2]) {
509
+ const args = parseArguments(name, matches[2]);
510
+ results.push([
511
+ name
512
+ ].concat(args));
513
+ } else results.push([
514
+ name
515
+ ]);
516
+ }
517
+ return results;
518
+ }
519
+ function buildStyle(chalk, styles) {
520
+ const enabled = {};
521
+ for (const layer of styles)for (const style of layer.styles)enabled[style[0]] = layer.inverse ? null : style.slice(1);
522
+ let current = chalk;
523
+ for (const [styleName, styles] of Object.entries(enabled))if (Array.isArray(styles)) {
524
+ if (!(styleName in current)) throw new Error(`Unknown Chalk style: ${styleName}`);
525
+ current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
526
+ }
527
+ return current;
528
+ }
529
+ module.exports = (chalk, temporary)=>{
530
+ const styles = [];
531
+ const chunks = [];
532
+ let chunk = [];
533
+ temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character)=>{
534
+ if (escapeCharacter) chunk.push(unescape(escapeCharacter));
535
+ else if (style) {
536
+ const string = chunk.join('');
537
+ chunk = [];
538
+ chunks.push(0 === styles.length ? string : buildStyle(chalk, styles)(string));
539
+ styles.push({
540
+ inverse,
541
+ styles: parseStyle(style)
542
+ });
543
+ } else if (close) {
544
+ if (0 === styles.length) throw new Error('Found extraneous } in Chalk template literal');
545
+ chunks.push(buildStyle(chalk, styles)(chunk.join('')));
546
+ chunk = [];
547
+ styles.pop();
548
+ } else chunk.push(character);
549
+ });
550
+ chunks.push(chunk.join(''));
551
+ if (styles.length > 0) {
552
+ const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${1 === styles.length ? '' : 's'} (\`}\`)`;
553
+ throw new Error(errMessage);
554
+ }
555
+ return chunks.join('');
556
+ };
557
+ },
558
+ "../../node_modules/.pnpm/chalk@4.1.2/node_modules/chalk/source/util.js" (module) {
559
+ const stringReplaceAll = (string, substring, replacer)=>{
560
+ let index = string.indexOf(substring);
561
+ if (-1 === index) return string;
562
+ const substringLength = substring.length;
563
+ let endIndex = 0;
564
+ let returnValue = '';
565
+ do {
566
+ returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
567
+ endIndex = index + substringLength;
568
+ index = string.indexOf(substring, endIndex);
569
+ }while (-1 !== index);
570
+ returnValue += string.substr(endIndex);
571
+ return returnValue;
572
+ };
573
+ const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index)=>{
574
+ let endIndex = 0;
575
+ let returnValue = '';
576
+ do {
577
+ const gotCR = '\r' === string[index - 1];
578
+ returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
579
+ endIndex = index + 1;
580
+ index = string.indexOf('\n', endIndex);
581
+ }while (-1 !== index);
582
+ returnValue += string.substr(endIndex);
583
+ return returnValue;
584
+ };
585
+ module.exports = {
586
+ stringReplaceAll,
587
+ stringEncaseCRLFWithFirstIndex
588
+ };
589
+ },
590
+ "../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/conversions.js" (module, __unused_rspack_exports, __webpack_require__) {
591
+ const cssKeywords = __webpack_require__("../../node_modules/.pnpm/color-name@1.1.4/node_modules/color-name/index.js");
592
+ const reverseKeywords = {};
593
+ for (const key of Object.keys(cssKeywords))reverseKeywords[cssKeywords[key]] = key;
594
+ const convert = {
595
+ rgb: {
596
+ channels: 3,
597
+ labels: 'rgb'
598
+ },
599
+ hsl: {
600
+ channels: 3,
601
+ labels: 'hsl'
602
+ },
603
+ hsv: {
604
+ channels: 3,
605
+ labels: 'hsv'
606
+ },
607
+ hwb: {
608
+ channels: 3,
609
+ labels: 'hwb'
610
+ },
611
+ cmyk: {
612
+ channels: 4,
613
+ labels: 'cmyk'
614
+ },
615
+ xyz: {
616
+ channels: 3,
617
+ labels: 'xyz'
618
+ },
619
+ lab: {
620
+ channels: 3,
621
+ labels: 'lab'
622
+ },
623
+ lch: {
624
+ channels: 3,
625
+ labels: 'lch'
626
+ },
627
+ hex: {
628
+ channels: 1,
629
+ labels: [
630
+ 'hex'
631
+ ]
632
+ },
633
+ keyword: {
634
+ channels: 1,
635
+ labels: [
636
+ 'keyword'
637
+ ]
638
+ },
639
+ ansi16: {
640
+ channels: 1,
641
+ labels: [
642
+ 'ansi16'
643
+ ]
644
+ },
645
+ ansi256: {
646
+ channels: 1,
647
+ labels: [
648
+ 'ansi256'
649
+ ]
650
+ },
651
+ hcg: {
652
+ channels: 3,
653
+ labels: [
654
+ 'h',
655
+ 'c',
656
+ 'g'
657
+ ]
658
+ },
659
+ apple: {
660
+ channels: 3,
661
+ labels: [
662
+ 'r16',
663
+ 'g16',
664
+ 'b16'
665
+ ]
666
+ },
667
+ gray: {
668
+ channels: 1,
669
+ labels: [
670
+ 'gray'
671
+ ]
672
+ }
673
+ };
674
+ module.exports = convert;
675
+ for (const model of Object.keys(convert)){
676
+ if (!('channels' in convert[model])) throw new Error('missing channels property: ' + model);
677
+ if (!('labels' in convert[model])) throw new Error('missing channel labels property: ' + model);
678
+ if (convert[model].labels.length !== convert[model].channels) throw new Error('channel and label counts mismatch: ' + model);
679
+ const { channels, labels } = convert[model];
680
+ delete convert[model].channels;
681
+ delete convert[model].labels;
682
+ Object.defineProperty(convert[model], 'channels', {
683
+ value: channels
684
+ });
685
+ Object.defineProperty(convert[model], 'labels', {
686
+ value: labels
687
+ });
688
+ }
689
+ convert.rgb.hsl = function(rgb) {
690
+ const r = rgb[0] / 255;
691
+ const g = rgb[1] / 255;
692
+ const b = rgb[2] / 255;
693
+ const min = Math.min(r, g, b);
694
+ const max = Math.max(r, g, b);
695
+ const delta = max - min;
696
+ let h;
697
+ let s;
698
+ if (max === min) h = 0;
699
+ else if (r === max) h = (g - b) / delta;
700
+ else if (g === max) h = 2 + (b - r) / delta;
701
+ else if (b === max) h = 4 + (r - g) / delta;
702
+ h = Math.min(60 * h, 360);
703
+ if (h < 0) h += 360;
704
+ const l = (min + max) / 2;
705
+ s = max === min ? 0 : l <= 0.5 ? delta / (max + min) : delta / (2 - max - min);
706
+ return [
707
+ h,
708
+ 100 * s,
709
+ 100 * l
710
+ ];
711
+ };
712
+ convert.rgb.hsv = function(rgb) {
713
+ let rdif;
714
+ let gdif;
715
+ let bdif;
716
+ let h;
717
+ let s;
718
+ const r = rgb[0] / 255;
719
+ const g = rgb[1] / 255;
720
+ const b = rgb[2] / 255;
721
+ const v = Math.max(r, g, b);
722
+ const diff = v - Math.min(r, g, b);
723
+ const diffc = function(c) {
724
+ return (v - c) / 6 / diff + 0.5;
725
+ };
726
+ if (0 === diff) {
727
+ h = 0;
728
+ s = 0;
729
+ } else {
730
+ s = diff / v;
731
+ rdif = diffc(r);
732
+ gdif = diffc(g);
733
+ bdif = diffc(b);
734
+ if (r === v) h = bdif - gdif;
735
+ else if (g === v) h = 1 / 3 + rdif - bdif;
736
+ else if (b === v) h = 2 / 3 + gdif - rdif;
737
+ if (h < 0) h += 1;
738
+ else if (h > 1) h -= 1;
739
+ }
740
+ return [
741
+ 360 * h,
742
+ 100 * s,
743
+ 100 * v
744
+ ];
745
+ };
746
+ convert.rgb.hwb = function(rgb) {
747
+ const r = rgb[0];
748
+ const g = rgb[1];
749
+ let b = rgb[2];
750
+ const h = convert.rgb.hsl(rgb)[0];
751
+ const w = 1 / 255 * Math.min(r, Math.min(g, b));
752
+ b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
753
+ return [
754
+ h,
755
+ 100 * w,
756
+ 100 * b
757
+ ];
758
+ };
759
+ convert.rgb.cmyk = function(rgb) {
760
+ const r = rgb[0] / 255;
761
+ const g = rgb[1] / 255;
762
+ const b = rgb[2] / 255;
763
+ const k = Math.min(1 - r, 1 - g, 1 - b);
764
+ const c = (1 - r - k) / (1 - k) || 0;
765
+ const m = (1 - g - k) / (1 - k) || 0;
766
+ const y = (1 - b - k) / (1 - k) || 0;
767
+ return [
768
+ 100 * c,
769
+ 100 * m,
770
+ 100 * y,
771
+ 100 * k
772
+ ];
773
+ };
774
+ function comparativeDistance(x, y) {
775
+ return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2;
776
+ }
777
+ convert.rgb.keyword = function(rgb) {
778
+ const reversed = reverseKeywords[rgb];
779
+ if (reversed) return reversed;
780
+ let currentClosestDistance = 1 / 0;
781
+ let currentClosestKeyword;
782
+ for (const keyword of Object.keys(cssKeywords)){
783
+ const value = cssKeywords[keyword];
784
+ const distance = comparativeDistance(rgb, value);
785
+ if (distance < currentClosestDistance) {
786
+ currentClosestDistance = distance;
787
+ currentClosestKeyword = keyword;
788
+ }
789
+ }
790
+ return currentClosestKeyword;
791
+ };
792
+ convert.keyword.rgb = function(keyword) {
793
+ return cssKeywords[keyword];
794
+ };
795
+ convert.rgb.xyz = function(rgb) {
796
+ let r = rgb[0] / 255;
797
+ let g = rgb[1] / 255;
798
+ let b = rgb[2] / 255;
799
+ r = r > 0.04045 ? ((r + 0.055) / 1.055) ** 2.4 : r / 12.92;
800
+ g = g > 0.04045 ? ((g + 0.055) / 1.055) ** 2.4 : g / 12.92;
801
+ b = b > 0.04045 ? ((b + 0.055) / 1.055) ** 2.4 : b / 12.92;
802
+ const x = 0.4124 * r + 0.3576 * g + 0.1805 * b;
803
+ const y = 0.2126 * r + 0.7152 * g + 0.0722 * b;
804
+ const z = 0.0193 * r + 0.1192 * g + 0.9505 * b;
805
+ return [
806
+ 100 * x,
807
+ 100 * y,
808
+ 100 * z
809
+ ];
810
+ };
811
+ convert.rgb.lab = function(rgb) {
812
+ const xyz = convert.rgb.xyz(rgb);
813
+ let x = xyz[0];
814
+ let y = xyz[1];
815
+ let z = xyz[2];
816
+ x /= 95.047;
817
+ y /= 100;
818
+ z /= 108.883;
819
+ x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
820
+ y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
821
+ z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
822
+ const l = 116 * y - 16;
823
+ const a = 500 * (x - y);
824
+ const b = 200 * (y - z);
825
+ return [
826
+ l,
827
+ a,
828
+ b
829
+ ];
830
+ };
831
+ convert.hsl.rgb = function(hsl) {
832
+ const h = hsl[0] / 360;
833
+ const s = hsl[1] / 100;
834
+ const l = hsl[2] / 100;
835
+ let t2;
836
+ let t3;
837
+ let val;
838
+ if (0 === s) {
839
+ val = 255 * l;
840
+ return [
841
+ val,
842
+ val,
843
+ val
844
+ ];
845
+ }
846
+ t2 = l < 0.5 ? l * (1 + s) : l + s - l * s;
847
+ const t1 = 2 * l - t2;
848
+ const rgb = [
849
+ 0,
850
+ 0,
851
+ 0
852
+ ];
853
+ for(let i = 0; i < 3; i++){
854
+ t3 = h + 1 / 3 * -(i - 1);
855
+ if (t3 < 0) t3++;
856
+ if (t3 > 1) t3--;
857
+ val = 6 * t3 < 1 ? t1 + (t2 - t1) * 6 * t3 : 2 * t3 < 1 ? t2 : 3 * t3 < 2 ? t1 + (t2 - t1) * (2 / 3 - t3) * 6 : t1;
858
+ rgb[i] = 255 * val;
859
+ }
860
+ return rgb;
861
+ };
862
+ convert.hsl.hsv = function(hsl) {
863
+ const h = hsl[0];
864
+ let s = hsl[1] / 100;
865
+ let l = hsl[2] / 100;
866
+ let smin = s;
867
+ const lmin = Math.max(l, 0.01);
868
+ l *= 2;
869
+ s *= l <= 1 ? l : 2 - l;
870
+ smin *= lmin <= 1 ? lmin : 2 - lmin;
871
+ const v = (l + s) / 2;
872
+ const sv = 0 === l ? 2 * smin / (lmin + smin) : 2 * s / (l + s);
873
+ return [
874
+ h,
875
+ 100 * sv,
876
+ 100 * v
877
+ ];
878
+ };
879
+ convert.hsv.rgb = function(hsv) {
880
+ const h = hsv[0] / 60;
881
+ const s = hsv[1] / 100;
882
+ let v = hsv[2] / 100;
883
+ const hi = Math.floor(h) % 6;
884
+ const f = h - Math.floor(h);
885
+ const p = 255 * v * (1 - s);
886
+ const q = 255 * v * (1 - s * f);
887
+ const t = 255 * v * (1 - s * (1 - f));
888
+ v *= 255;
889
+ switch(hi){
890
+ case 0:
891
+ return [
892
+ v,
893
+ t,
894
+ p
895
+ ];
896
+ case 1:
897
+ return [
898
+ q,
899
+ v,
900
+ p
901
+ ];
902
+ case 2:
903
+ return [
904
+ p,
905
+ v,
906
+ t
907
+ ];
908
+ case 3:
909
+ return [
910
+ p,
911
+ q,
912
+ v
913
+ ];
914
+ case 4:
915
+ return [
916
+ t,
917
+ p,
918
+ v
919
+ ];
920
+ case 5:
921
+ return [
922
+ v,
923
+ p,
924
+ q
925
+ ];
926
+ }
927
+ };
928
+ convert.hsv.hsl = function(hsv) {
929
+ const h = hsv[0];
930
+ const s = hsv[1] / 100;
931
+ const v = hsv[2] / 100;
932
+ const vmin = Math.max(v, 0.01);
933
+ let sl;
934
+ let l;
935
+ l = (2 - s) * v;
936
+ const lmin = (2 - s) * vmin;
937
+ sl = s * vmin;
938
+ sl /= lmin <= 1 ? lmin : 2 - lmin;
939
+ sl = sl || 0;
940
+ l /= 2;
941
+ return [
942
+ h,
943
+ 100 * sl,
944
+ 100 * l
945
+ ];
946
+ };
947
+ convert.hwb.rgb = function(hwb) {
948
+ const h = hwb[0] / 360;
949
+ let wh = hwb[1] / 100;
950
+ let bl = hwb[2] / 100;
951
+ const ratio = wh + bl;
952
+ let f;
953
+ if (ratio > 1) {
954
+ wh /= ratio;
955
+ bl /= ratio;
956
+ }
957
+ const i = Math.floor(6 * h);
958
+ const v = 1 - bl;
959
+ f = 6 * h - i;
960
+ if ((0x01 & i) !== 0) f = 1 - f;
961
+ const n = wh + f * (v - wh);
962
+ let r;
963
+ let g;
964
+ let b;
965
+ switch(i){
966
+ default:
967
+ case 6:
968
+ case 0:
969
+ r = v;
970
+ g = n;
971
+ b = wh;
972
+ break;
973
+ case 1:
974
+ r = n;
975
+ g = v;
976
+ b = wh;
977
+ break;
978
+ case 2:
979
+ r = wh;
980
+ g = v;
981
+ b = n;
982
+ break;
983
+ case 3:
984
+ r = wh;
985
+ g = n;
986
+ b = v;
987
+ break;
988
+ case 4:
989
+ r = n;
990
+ g = wh;
991
+ b = v;
992
+ break;
993
+ case 5:
994
+ r = v;
995
+ g = wh;
996
+ b = n;
997
+ break;
998
+ }
999
+ return [
1000
+ 255 * r,
1001
+ 255 * g,
1002
+ 255 * b
1003
+ ];
1004
+ };
1005
+ convert.cmyk.rgb = function(cmyk) {
1006
+ const c = cmyk[0] / 100;
1007
+ const m = cmyk[1] / 100;
1008
+ const y = cmyk[2] / 100;
1009
+ const k = cmyk[3] / 100;
1010
+ const r = 1 - Math.min(1, c * (1 - k) + k);
1011
+ const g = 1 - Math.min(1, m * (1 - k) + k);
1012
+ const b = 1 - Math.min(1, y * (1 - k) + k);
1013
+ return [
1014
+ 255 * r,
1015
+ 255 * g,
1016
+ 255 * b
1017
+ ];
1018
+ };
1019
+ convert.xyz.rgb = function(xyz) {
1020
+ const x = xyz[0] / 100;
1021
+ const y = xyz[1] / 100;
1022
+ const z = xyz[2] / 100;
1023
+ let r;
1024
+ let g;
1025
+ let b;
1026
+ r = 3.2406 * x + -1.5372 * y + -0.4986 * z;
1027
+ g = -0.9689 * x + 1.8758 * y + 0.0415 * z;
1028
+ b = 0.0557 * x + -0.204 * y + 1.0570 * z;
1029
+ r = r > 0.0031308 ? 1.055 * r ** (1.0 / 2.4) - 0.055 : 12.92 * r;
1030
+ g = g > 0.0031308 ? 1.055 * g ** (1.0 / 2.4) - 0.055 : 12.92 * g;
1031
+ b = b > 0.0031308 ? 1.055 * b ** (1.0 / 2.4) - 0.055 : 12.92 * b;
1032
+ r = Math.min(Math.max(0, r), 1);
1033
+ g = Math.min(Math.max(0, g), 1);
1034
+ b = Math.min(Math.max(0, b), 1);
1035
+ return [
1036
+ 255 * r,
1037
+ 255 * g,
1038
+ 255 * b
1039
+ ];
1040
+ };
1041
+ convert.xyz.lab = function(xyz) {
1042
+ let x = xyz[0];
1043
+ let y = xyz[1];
1044
+ let z = xyz[2];
1045
+ x /= 95.047;
1046
+ y /= 100;
1047
+ z /= 108.883;
1048
+ x = x > 0.008856 ? x ** (1 / 3) : 7.787 * x + 16 / 116;
1049
+ y = y > 0.008856 ? y ** (1 / 3) : 7.787 * y + 16 / 116;
1050
+ z = z > 0.008856 ? z ** (1 / 3) : 7.787 * z + 16 / 116;
1051
+ const l = 116 * y - 16;
1052
+ const a = 500 * (x - y);
1053
+ const b = 200 * (y - z);
1054
+ return [
1055
+ l,
1056
+ a,
1057
+ b
1058
+ ];
1059
+ };
1060
+ convert.lab.xyz = function(lab) {
1061
+ const l = lab[0];
1062
+ const a = lab[1];
1063
+ const b = lab[2];
1064
+ let x;
1065
+ let y;
1066
+ let z;
1067
+ y = (l + 16) / 116;
1068
+ x = a / 500 + y;
1069
+ z = y - b / 200;
1070
+ const y2 = y ** 3;
1071
+ const x2 = x ** 3;
1072
+ const z2 = z ** 3;
1073
+ y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
1074
+ x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
1075
+ z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
1076
+ x *= 95.047;
1077
+ y *= 100;
1078
+ z *= 108.883;
1079
+ return [
1080
+ x,
1081
+ y,
1082
+ z
1083
+ ];
1084
+ };
1085
+ convert.lab.lch = function(lab) {
1086
+ const l = lab[0];
1087
+ const a = lab[1];
1088
+ const b = lab[2];
1089
+ let h;
1090
+ const hr = Math.atan2(b, a);
1091
+ h = 360 * hr / 2 / Math.PI;
1092
+ if (h < 0) h += 360;
1093
+ const c = Math.sqrt(a * a + b * b);
1094
+ return [
1095
+ l,
1096
+ c,
1097
+ h
1098
+ ];
1099
+ };
1100
+ convert.lch.lab = function(lch) {
1101
+ const l = lch[0];
1102
+ const c = lch[1];
1103
+ const h = lch[2];
1104
+ const hr = h / 360 * 2 * Math.PI;
1105
+ const a = c * Math.cos(hr);
1106
+ const b = c * Math.sin(hr);
1107
+ return [
1108
+ l,
1109
+ a,
1110
+ b
1111
+ ];
1112
+ };
1113
+ convert.rgb.ansi16 = function(args, saturation = null) {
1114
+ const [r, g, b] = args;
1115
+ let value = null === saturation ? convert.rgb.hsv(args)[2] : saturation;
1116
+ value = Math.round(value / 50);
1117
+ if (0 === value) return 30;
1118
+ let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255));
1119
+ if (2 === value) ansi += 60;
1120
+ return ansi;
1121
+ };
1122
+ convert.hsv.ansi16 = function(args) {
1123
+ return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
1124
+ };
1125
+ convert.rgb.ansi256 = function(args) {
1126
+ const r = args[0];
1127
+ const g = args[1];
1128
+ const b = args[2];
1129
+ if (r === g && g === b) {
1130
+ if (r < 8) return 16;
1131
+ if (r > 248) return 231;
1132
+ return Math.round((r - 8) / 247 * 24) + 232;
1133
+ }
1134
+ const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5);
1135
+ return ansi;
1136
+ };
1137
+ convert.ansi16.rgb = function(args) {
1138
+ let color = args % 10;
1139
+ if (0 === color || 7 === color) {
1140
+ if (args > 50) color += 3.5;
1141
+ color = color / 10.5 * 255;
1142
+ return [
1143
+ color,
1144
+ color,
1145
+ color
1146
+ ];
1147
+ }
1148
+ const mult = (~~(args > 50) + 1) * 0.5;
1149
+ const r = (1 & color) * mult * 255;
1150
+ const g = (color >> 1 & 1) * mult * 255;
1151
+ const b = (color >> 2 & 1) * mult * 255;
1152
+ return [
1153
+ r,
1154
+ g,
1155
+ b
1156
+ ];
1157
+ };
1158
+ convert.ansi256.rgb = function(args) {
1159
+ if (args >= 232) {
1160
+ const c = (args - 232) * 10 + 8;
1161
+ return [
1162
+ c,
1163
+ c,
1164
+ c
1165
+ ];
1166
+ }
1167
+ args -= 16;
1168
+ let rem;
1169
+ const r = Math.floor(args / 36) / 5 * 255;
1170
+ const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
1171
+ const b = rem % 6 / 5 * 255;
1172
+ return [
1173
+ r,
1174
+ g,
1175
+ b
1176
+ ];
1177
+ };
1178
+ convert.rgb.hex = function(args) {
1179
+ const integer = ((0xFF & Math.round(args[0])) << 16) + ((0xFF & Math.round(args[1])) << 8) + (0xFF & Math.round(args[2]));
1180
+ const string = integer.toString(16).toUpperCase();
1181
+ return '000000'.substring(string.length) + string;
1182
+ };
1183
+ convert.hex.rgb = function(args) {
1184
+ const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
1185
+ if (!match) return [
1186
+ 0,
1187
+ 0,
1188
+ 0
1189
+ ];
1190
+ let colorString = match[0];
1191
+ if (3 === match[0].length) colorString = colorString.split('').map((char)=>char + char).join('');
1192
+ const integer = parseInt(colorString, 16);
1193
+ const r = integer >> 16 & 0xFF;
1194
+ const g = integer >> 8 & 0xFF;
1195
+ const b = 0xFF & integer;
1196
+ return [
1197
+ r,
1198
+ g,
1199
+ b
1200
+ ];
1201
+ };
1202
+ convert.rgb.hcg = function(rgb) {
1203
+ const r = rgb[0] / 255;
1204
+ const g = rgb[1] / 255;
1205
+ const b = rgb[2] / 255;
1206
+ const max = Math.max(Math.max(r, g), b);
1207
+ const min = Math.min(Math.min(r, g), b);
1208
+ const chroma = max - min;
1209
+ let grayscale;
1210
+ let hue;
1211
+ grayscale = chroma < 1 ? min / (1 - chroma) : 0;
1212
+ hue = chroma <= 0 ? 0 : max === r ? (g - b) / chroma % 6 : max === g ? 2 + (b - r) / chroma : 4 + (r - g) / chroma;
1213
+ hue /= 6;
1214
+ hue %= 1;
1215
+ return [
1216
+ 360 * hue,
1217
+ 100 * chroma,
1218
+ 100 * grayscale
1219
+ ];
1220
+ };
1221
+ convert.hsl.hcg = function(hsl) {
1222
+ const s = hsl[1] / 100;
1223
+ const l = hsl[2] / 100;
1224
+ const c = l < 0.5 ? 2.0 * s * l : 2.0 * s * (1.0 - l);
1225
+ let f = 0;
1226
+ if (c < 1.0) f = (l - 0.5 * c) / (1.0 - c);
1227
+ return [
1228
+ hsl[0],
1229
+ 100 * c,
1230
+ 100 * f
1231
+ ];
1232
+ };
1233
+ convert.hsv.hcg = function(hsv) {
1234
+ const s = hsv[1] / 100;
1235
+ const v = hsv[2] / 100;
1236
+ const c = s * v;
1237
+ let f = 0;
1238
+ if (c < 1.0) f = (v - c) / (1 - c);
1239
+ return [
1240
+ hsv[0],
1241
+ 100 * c,
1242
+ 100 * f
1243
+ ];
1244
+ };
1245
+ convert.hcg.rgb = function(hcg) {
1246
+ const h = hcg[0] / 360;
1247
+ const c = hcg[1] / 100;
1248
+ const g = hcg[2] / 100;
1249
+ if (0.0 === c) return [
1250
+ 255 * g,
1251
+ 255 * g,
1252
+ 255 * g
1253
+ ];
1254
+ const pure = [
1255
+ 0,
1256
+ 0,
1257
+ 0
1258
+ ];
1259
+ const hi = h % 1 * 6;
1260
+ const v = hi % 1;
1261
+ const w = 1 - v;
1262
+ let mg = 0;
1263
+ switch(Math.floor(hi)){
1264
+ case 0:
1265
+ pure[0] = 1;
1266
+ pure[1] = v;
1267
+ pure[2] = 0;
1268
+ break;
1269
+ case 1:
1270
+ pure[0] = w;
1271
+ pure[1] = 1;
1272
+ pure[2] = 0;
1273
+ break;
1274
+ case 2:
1275
+ pure[0] = 0;
1276
+ pure[1] = 1;
1277
+ pure[2] = v;
1278
+ break;
1279
+ case 3:
1280
+ pure[0] = 0;
1281
+ pure[1] = w;
1282
+ pure[2] = 1;
1283
+ break;
1284
+ case 4:
1285
+ pure[0] = v;
1286
+ pure[1] = 0;
1287
+ pure[2] = 1;
1288
+ break;
1289
+ default:
1290
+ pure[0] = 1;
1291
+ pure[1] = 0;
1292
+ pure[2] = w;
1293
+ }
1294
+ mg = (1.0 - c) * g;
1295
+ return [
1296
+ (c * pure[0] + mg) * 255,
1297
+ (c * pure[1] + mg) * 255,
1298
+ (c * pure[2] + mg) * 255
1299
+ ];
1300
+ };
1301
+ convert.hcg.hsv = function(hcg) {
1302
+ const c = hcg[1] / 100;
1303
+ const g = hcg[2] / 100;
1304
+ const v = c + g * (1.0 - c);
1305
+ let f = 0;
1306
+ if (v > 0.0) f = c / v;
1307
+ return [
1308
+ hcg[0],
1309
+ 100 * f,
1310
+ 100 * v
1311
+ ];
1312
+ };
1313
+ convert.hcg.hsl = function(hcg) {
1314
+ const c = hcg[1] / 100;
1315
+ const g = hcg[2] / 100;
1316
+ const l = g * (1.0 - c) + 0.5 * c;
1317
+ let s = 0;
1318
+ if (l > 0.0 && l < 0.5) s = c / (2 * l);
1319
+ else if (l >= 0.5 && l < 1.0) s = c / (2 * (1 - l));
1320
+ return [
1321
+ hcg[0],
1322
+ 100 * s,
1323
+ 100 * l
1324
+ ];
1325
+ };
1326
+ convert.hcg.hwb = function(hcg) {
1327
+ const c = hcg[1] / 100;
1328
+ const g = hcg[2] / 100;
1329
+ const v = c + g * (1.0 - c);
1330
+ return [
1331
+ hcg[0],
1332
+ (v - c) * 100,
1333
+ (1 - v) * 100
1334
+ ];
1335
+ };
1336
+ convert.hwb.hcg = function(hwb) {
1337
+ const w = hwb[1] / 100;
1338
+ const b = hwb[2] / 100;
1339
+ const v = 1 - b;
1340
+ const c = v - w;
1341
+ let g = 0;
1342
+ if (c < 1) g = (v - c) / (1 - c);
1343
+ return [
1344
+ hwb[0],
1345
+ 100 * c,
1346
+ 100 * g
1347
+ ];
1348
+ };
1349
+ convert.apple.rgb = function(apple) {
1350
+ return [
1351
+ apple[0] / 65535 * 255,
1352
+ apple[1] / 65535 * 255,
1353
+ apple[2] / 65535 * 255
1354
+ ];
1355
+ };
1356
+ convert.rgb.apple = function(rgb) {
1357
+ return [
1358
+ rgb[0] / 255 * 65535,
1359
+ rgb[1] / 255 * 65535,
1360
+ rgb[2] / 255 * 65535
1361
+ ];
1362
+ };
1363
+ convert.gray.rgb = function(args) {
1364
+ return [
1365
+ args[0] / 100 * 255,
1366
+ args[0] / 100 * 255,
1367
+ args[0] / 100 * 255
1368
+ ];
1369
+ };
1370
+ convert.gray.hsl = function(args) {
1371
+ return [
1372
+ 0,
1373
+ 0,
1374
+ args[0]
1375
+ ];
1376
+ };
1377
+ convert.gray.hsv = convert.gray.hsl;
1378
+ convert.gray.hwb = function(gray) {
1379
+ return [
1380
+ 0,
1381
+ 100,
1382
+ gray[0]
1383
+ ];
1384
+ };
1385
+ convert.gray.cmyk = function(gray) {
1386
+ return [
1387
+ 0,
1388
+ 0,
1389
+ 0,
1390
+ gray[0]
1391
+ ];
1392
+ };
1393
+ convert.gray.lab = function(gray) {
1394
+ return [
1395
+ gray[0],
1396
+ 0,
1397
+ 0
1398
+ ];
1399
+ };
1400
+ convert.gray.hex = function(gray) {
1401
+ const val = 0xFF & Math.round(gray[0] / 100 * 255);
1402
+ const integer = (val << 16) + (val << 8) + val;
1403
+ const string = integer.toString(16).toUpperCase();
1404
+ return '000000'.substring(string.length) + string;
1405
+ };
1406
+ convert.rgb.gray = function(rgb) {
1407
+ const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
1408
+ return [
1409
+ val / 255 * 100
1410
+ ];
1411
+ };
1412
+ },
1413
+ "../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/index.js" (module, __unused_rspack_exports, __webpack_require__) {
1414
+ const conversions = __webpack_require__("../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/conversions.js");
1415
+ const route = __webpack_require__("../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/route.js");
1416
+ const convert = {};
1417
+ const models = Object.keys(conversions);
1418
+ function wrapRaw(fn) {
1419
+ const wrappedFn = function(...args) {
1420
+ const arg0 = args[0];
1421
+ if (null == arg0) return arg0;
1422
+ if (arg0.length > 1) args = arg0;
1423
+ return fn(args);
1424
+ };
1425
+ if ('conversion' in fn) wrappedFn.conversion = fn.conversion;
1426
+ return wrappedFn;
1427
+ }
1428
+ function wrapRounded(fn) {
1429
+ const wrappedFn = function(...args) {
1430
+ const arg0 = args[0];
1431
+ if (null == arg0) return arg0;
1432
+ if (arg0.length > 1) args = arg0;
1433
+ const result = fn(args);
1434
+ if ('object' == typeof result) for(let len = result.length, i = 0; i < len; i++)result[i] = Math.round(result[i]);
1435
+ return result;
1436
+ };
1437
+ if ('conversion' in fn) wrappedFn.conversion = fn.conversion;
1438
+ return wrappedFn;
1439
+ }
1440
+ models.forEach((fromModel)=>{
1441
+ convert[fromModel] = {};
1442
+ Object.defineProperty(convert[fromModel], 'channels', {
1443
+ value: conversions[fromModel].channels
1444
+ });
1445
+ Object.defineProperty(convert[fromModel], 'labels', {
1446
+ value: conversions[fromModel].labels
1447
+ });
1448
+ const routes = route(fromModel);
1449
+ const routeModels = Object.keys(routes);
1450
+ routeModels.forEach((toModel)=>{
1451
+ const fn = routes[toModel];
1452
+ convert[fromModel][toModel] = wrapRounded(fn);
1453
+ convert[fromModel][toModel].raw = wrapRaw(fn);
1454
+ });
1455
+ });
1456
+ module.exports = convert;
1457
+ },
1458
+ "../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/route.js" (module, __unused_rspack_exports, __webpack_require__) {
1459
+ const conversions = __webpack_require__("../../node_modules/.pnpm/color-convert@2.0.1/node_modules/color-convert/conversions.js");
1460
+ function buildGraph() {
1461
+ const graph = {};
1462
+ const models = Object.keys(conversions);
1463
+ for(let len = models.length, i = 0; i < len; i++)graph[models[i]] = {
1464
+ distance: -1,
1465
+ parent: null
1466
+ };
1467
+ return graph;
1468
+ }
1469
+ function deriveBFS(fromModel) {
1470
+ const graph = buildGraph();
1471
+ const queue = [
1472
+ fromModel
1473
+ ];
1474
+ graph[fromModel].distance = 0;
1475
+ while(queue.length){
1476
+ const current = queue.pop();
1477
+ const adjacents = Object.keys(conversions[current]);
1478
+ for(let len = adjacents.length, i = 0; i < len; i++){
1479
+ const adjacent = adjacents[i];
1480
+ const node = graph[adjacent];
1481
+ if (-1 === node.distance) {
1482
+ node.distance = graph[current].distance + 1;
1483
+ node.parent = current;
1484
+ queue.unshift(adjacent);
1485
+ }
1486
+ }
1487
+ }
1488
+ return graph;
1489
+ }
1490
+ function link(from, to) {
1491
+ return function(args) {
1492
+ return to(from(args));
1493
+ };
1494
+ }
1495
+ function wrapConversion(toModel, graph) {
1496
+ const path = [
1497
+ graph[toModel].parent,
1498
+ toModel
1499
+ ];
1500
+ let fn = conversions[graph[toModel].parent][toModel];
1501
+ let cur = graph[toModel].parent;
1502
+ while(graph[cur].parent){
1503
+ path.unshift(graph[cur].parent);
1504
+ fn = link(conversions[graph[cur].parent][cur], fn);
1505
+ cur = graph[cur].parent;
1506
+ }
1507
+ fn.conversion = path;
1508
+ return fn;
1509
+ }
1510
+ module.exports = function(fromModel) {
1511
+ const graph = deriveBFS(fromModel);
1512
+ const conversion = {};
1513
+ const models = Object.keys(graph);
1514
+ for(let len = models.length, i = 0; i < len; i++){
1515
+ const toModel = models[i];
1516
+ const node = graph[toModel];
1517
+ if (null !== node.parent) conversion[toModel] = wrapConversion(toModel, graph);
1518
+ }
1519
+ return conversion;
1520
+ };
1521
+ },
1522
+ "../../node_modules/.pnpm/color-name@1.1.4/node_modules/color-name/index.js" (module) {
1523
+ module.exports = {
1524
+ aliceblue: [
1525
+ 240,
1526
+ 248,
1527
+ 255
1528
+ ],
1529
+ antiquewhite: [
1530
+ 250,
1531
+ 235,
1532
+ 215
1533
+ ],
1534
+ aqua: [
1535
+ 0,
1536
+ 255,
1537
+ 255
1538
+ ],
1539
+ aquamarine: [
1540
+ 127,
1541
+ 255,
1542
+ 212
1543
+ ],
1544
+ azure: [
1545
+ 240,
1546
+ 255,
1547
+ 255
1548
+ ],
1549
+ beige: [
1550
+ 245,
1551
+ 245,
1552
+ 220
1553
+ ],
1554
+ bisque: [
1555
+ 255,
1556
+ 228,
1557
+ 196
1558
+ ],
1559
+ black: [
1560
+ 0,
1561
+ 0,
1562
+ 0
1563
+ ],
1564
+ blanchedalmond: [
1565
+ 255,
1566
+ 235,
1567
+ 205
1568
+ ],
1569
+ blue: [
1570
+ 0,
1571
+ 0,
1572
+ 255
1573
+ ],
1574
+ blueviolet: [
1575
+ 138,
1576
+ 43,
1577
+ 226
1578
+ ],
1579
+ brown: [
1580
+ 165,
1581
+ 42,
1582
+ 42
1583
+ ],
1584
+ burlywood: [
1585
+ 222,
1586
+ 184,
1587
+ 135
1588
+ ],
1589
+ cadetblue: [
1590
+ 95,
1591
+ 158,
1592
+ 160
1593
+ ],
1594
+ chartreuse: [
1595
+ 127,
1596
+ 255,
1597
+ 0
1598
+ ],
1599
+ chocolate: [
1600
+ 210,
1601
+ 105,
1602
+ 30
1603
+ ],
1604
+ coral: [
1605
+ 255,
1606
+ 127,
1607
+ 80
1608
+ ],
1609
+ cornflowerblue: [
1610
+ 100,
1611
+ 149,
1612
+ 237
1613
+ ],
1614
+ cornsilk: [
1615
+ 255,
1616
+ 248,
1617
+ 220
1618
+ ],
1619
+ crimson: [
1620
+ 220,
1621
+ 20,
1622
+ 60
1623
+ ],
1624
+ cyan: [
1625
+ 0,
1626
+ 255,
1627
+ 255
1628
+ ],
1629
+ darkblue: [
1630
+ 0,
1631
+ 0,
1632
+ 139
1633
+ ],
1634
+ darkcyan: [
1635
+ 0,
1636
+ 139,
1637
+ 139
1638
+ ],
1639
+ darkgoldenrod: [
1640
+ 184,
1641
+ 134,
1642
+ 11
1643
+ ],
1644
+ darkgray: [
1645
+ 169,
1646
+ 169,
1647
+ 169
1648
+ ],
1649
+ darkgreen: [
1650
+ 0,
1651
+ 100,
1652
+ 0
1653
+ ],
1654
+ darkgrey: [
1655
+ 169,
1656
+ 169,
1657
+ 169
1658
+ ],
1659
+ darkkhaki: [
1660
+ 189,
1661
+ 183,
1662
+ 107
1663
+ ],
1664
+ darkmagenta: [
1665
+ 139,
1666
+ 0,
1667
+ 139
1668
+ ],
1669
+ darkolivegreen: [
1670
+ 85,
1671
+ 107,
1672
+ 47
1673
+ ],
1674
+ darkorange: [
1675
+ 255,
1676
+ 140,
1677
+ 0
1678
+ ],
1679
+ darkorchid: [
1680
+ 153,
1681
+ 50,
1682
+ 204
1683
+ ],
1684
+ darkred: [
1685
+ 139,
1686
+ 0,
1687
+ 0
1688
+ ],
1689
+ darksalmon: [
1690
+ 233,
1691
+ 150,
1692
+ 122
1693
+ ],
1694
+ darkseagreen: [
1695
+ 143,
1696
+ 188,
1697
+ 143
1698
+ ],
1699
+ darkslateblue: [
1700
+ 72,
1701
+ 61,
1702
+ 139
1703
+ ],
1704
+ darkslategray: [
1705
+ 47,
1706
+ 79,
1707
+ 79
1708
+ ],
1709
+ darkslategrey: [
1710
+ 47,
1711
+ 79,
1712
+ 79
1713
+ ],
1714
+ darkturquoise: [
1715
+ 0,
1716
+ 206,
1717
+ 209
1718
+ ],
1719
+ darkviolet: [
1720
+ 148,
1721
+ 0,
1722
+ 211
1723
+ ],
1724
+ deeppink: [
1725
+ 255,
1726
+ 20,
1727
+ 147
1728
+ ],
1729
+ deepskyblue: [
1730
+ 0,
1731
+ 191,
1732
+ 255
1733
+ ],
1734
+ dimgray: [
1735
+ 105,
1736
+ 105,
1737
+ 105
1738
+ ],
1739
+ dimgrey: [
1740
+ 105,
1741
+ 105,
1742
+ 105
1743
+ ],
1744
+ dodgerblue: [
1745
+ 30,
1746
+ 144,
1747
+ 255
1748
+ ],
1749
+ firebrick: [
1750
+ 178,
1751
+ 34,
1752
+ 34
1753
+ ],
1754
+ floralwhite: [
1755
+ 255,
1756
+ 250,
1757
+ 240
1758
+ ],
1759
+ forestgreen: [
1760
+ 34,
1761
+ 139,
1762
+ 34
1763
+ ],
1764
+ fuchsia: [
1765
+ 255,
1766
+ 0,
1767
+ 255
1768
+ ],
1769
+ gainsboro: [
1770
+ 220,
1771
+ 220,
1772
+ 220
1773
+ ],
1774
+ ghostwhite: [
1775
+ 248,
1776
+ 248,
1777
+ 255
1778
+ ],
1779
+ gold: [
1780
+ 255,
1781
+ 215,
1782
+ 0
1783
+ ],
1784
+ goldenrod: [
1785
+ 218,
1786
+ 165,
1787
+ 32
1788
+ ],
1789
+ gray: [
1790
+ 128,
1791
+ 128,
1792
+ 128
1793
+ ],
1794
+ green: [
1795
+ 0,
1796
+ 128,
1797
+ 0
1798
+ ],
1799
+ greenyellow: [
1800
+ 173,
1801
+ 255,
1802
+ 47
1803
+ ],
1804
+ grey: [
1805
+ 128,
1806
+ 128,
1807
+ 128
1808
+ ],
1809
+ honeydew: [
1810
+ 240,
1811
+ 255,
1812
+ 240
1813
+ ],
1814
+ hotpink: [
1815
+ 255,
1816
+ 105,
1817
+ 180
1818
+ ],
1819
+ indianred: [
1820
+ 205,
1821
+ 92,
1822
+ 92
1823
+ ],
1824
+ indigo: [
1825
+ 75,
1826
+ 0,
1827
+ 130
1828
+ ],
1829
+ ivory: [
1830
+ 255,
1831
+ 255,
1832
+ 240
1833
+ ],
1834
+ khaki: [
1835
+ 240,
1836
+ 230,
1837
+ 140
1838
+ ],
1839
+ lavender: [
1840
+ 230,
1841
+ 230,
1842
+ 250
1843
+ ],
1844
+ lavenderblush: [
1845
+ 255,
1846
+ 240,
1847
+ 245
1848
+ ],
1849
+ lawngreen: [
1850
+ 124,
1851
+ 252,
1852
+ 0
1853
+ ],
1854
+ lemonchiffon: [
1855
+ 255,
1856
+ 250,
1857
+ 205
1858
+ ],
1859
+ lightblue: [
1860
+ 173,
1861
+ 216,
1862
+ 230
1863
+ ],
1864
+ lightcoral: [
1865
+ 240,
1866
+ 128,
1867
+ 128
1868
+ ],
1869
+ lightcyan: [
1870
+ 224,
1871
+ 255,
1872
+ 255
1873
+ ],
1874
+ lightgoldenrodyellow: [
1875
+ 250,
1876
+ 250,
1877
+ 210
1878
+ ],
1879
+ lightgray: [
1880
+ 211,
1881
+ 211,
1882
+ 211
1883
+ ],
1884
+ lightgreen: [
1885
+ 144,
1886
+ 238,
1887
+ 144
1888
+ ],
1889
+ lightgrey: [
1890
+ 211,
1891
+ 211,
1892
+ 211
1893
+ ],
1894
+ lightpink: [
1895
+ 255,
1896
+ 182,
1897
+ 193
1898
+ ],
1899
+ lightsalmon: [
1900
+ 255,
1901
+ 160,
1902
+ 122
1903
+ ],
1904
+ lightseagreen: [
1905
+ 32,
1906
+ 178,
1907
+ 170
1908
+ ],
1909
+ lightskyblue: [
1910
+ 135,
1911
+ 206,
1912
+ 250
1913
+ ],
1914
+ lightslategray: [
1915
+ 119,
1916
+ 136,
1917
+ 153
1918
+ ],
1919
+ lightslategrey: [
1920
+ 119,
1921
+ 136,
1922
+ 153
1923
+ ],
1924
+ lightsteelblue: [
1925
+ 176,
1926
+ 196,
1927
+ 222
1928
+ ],
1929
+ lightyellow: [
1930
+ 255,
1931
+ 255,
1932
+ 224
1933
+ ],
1934
+ lime: [
1935
+ 0,
1936
+ 255,
1937
+ 0
1938
+ ],
1939
+ limegreen: [
1940
+ 50,
1941
+ 205,
1942
+ 50
1943
+ ],
1944
+ linen: [
1945
+ 250,
1946
+ 240,
1947
+ 230
1948
+ ],
1949
+ magenta: [
1950
+ 255,
1951
+ 0,
1952
+ 255
1953
+ ],
1954
+ maroon: [
1955
+ 128,
1956
+ 0,
1957
+ 0
1958
+ ],
1959
+ mediumaquamarine: [
1960
+ 102,
1961
+ 205,
1962
+ 170
1963
+ ],
1964
+ mediumblue: [
1965
+ 0,
1966
+ 0,
1967
+ 205
1968
+ ],
1969
+ mediumorchid: [
1970
+ 186,
1971
+ 85,
1972
+ 211
1973
+ ],
1974
+ mediumpurple: [
1975
+ 147,
1976
+ 112,
1977
+ 219
1978
+ ],
1979
+ mediumseagreen: [
1980
+ 60,
1981
+ 179,
1982
+ 113
1983
+ ],
1984
+ mediumslateblue: [
1985
+ 123,
1986
+ 104,
1987
+ 238
1988
+ ],
1989
+ mediumspringgreen: [
1990
+ 0,
1991
+ 250,
1992
+ 154
1993
+ ],
1994
+ mediumturquoise: [
1995
+ 72,
1996
+ 209,
1997
+ 204
1998
+ ],
1999
+ mediumvioletred: [
2000
+ 199,
2001
+ 21,
2002
+ 133
2003
+ ],
2004
+ midnightblue: [
2005
+ 25,
2006
+ 25,
2007
+ 112
2008
+ ],
2009
+ mintcream: [
2010
+ 245,
2011
+ 255,
2012
+ 250
2013
+ ],
2014
+ mistyrose: [
2015
+ 255,
2016
+ 228,
2017
+ 225
2018
+ ],
2019
+ moccasin: [
2020
+ 255,
2021
+ 228,
2022
+ 181
2023
+ ],
2024
+ navajowhite: [
2025
+ 255,
2026
+ 222,
2027
+ 173
2028
+ ],
2029
+ navy: [
2030
+ 0,
2031
+ 0,
2032
+ 128
2033
+ ],
2034
+ oldlace: [
2035
+ 253,
2036
+ 245,
2037
+ 230
2038
+ ],
2039
+ olive: [
2040
+ 128,
2041
+ 128,
2042
+ 0
2043
+ ],
2044
+ olivedrab: [
2045
+ 107,
2046
+ 142,
2047
+ 35
2048
+ ],
2049
+ orange: [
2050
+ 255,
2051
+ 165,
2052
+ 0
2053
+ ],
2054
+ orangered: [
2055
+ 255,
2056
+ 69,
2057
+ 0
2058
+ ],
2059
+ orchid: [
2060
+ 218,
2061
+ 112,
2062
+ 214
2063
+ ],
2064
+ palegoldenrod: [
2065
+ 238,
2066
+ 232,
2067
+ 170
2068
+ ],
2069
+ palegreen: [
2070
+ 152,
2071
+ 251,
2072
+ 152
2073
+ ],
2074
+ paleturquoise: [
2075
+ 175,
2076
+ 238,
2077
+ 238
2078
+ ],
2079
+ palevioletred: [
2080
+ 219,
2081
+ 112,
2082
+ 147
2083
+ ],
2084
+ papayawhip: [
2085
+ 255,
2086
+ 239,
2087
+ 213
2088
+ ],
2089
+ peachpuff: [
2090
+ 255,
2091
+ 218,
2092
+ 185
2093
+ ],
2094
+ peru: [
2095
+ 205,
2096
+ 133,
2097
+ 63
2098
+ ],
2099
+ pink: [
2100
+ 255,
2101
+ 192,
2102
+ 203
2103
+ ],
2104
+ plum: [
2105
+ 221,
2106
+ 160,
2107
+ 221
2108
+ ],
2109
+ powderblue: [
2110
+ 176,
2111
+ 224,
2112
+ 230
2113
+ ],
2114
+ purple: [
2115
+ 128,
2116
+ 0,
2117
+ 128
2118
+ ],
2119
+ rebeccapurple: [
2120
+ 102,
2121
+ 51,
2122
+ 153
2123
+ ],
2124
+ red: [
2125
+ 255,
2126
+ 0,
2127
+ 0
2128
+ ],
2129
+ rosybrown: [
2130
+ 188,
2131
+ 143,
2132
+ 143
2133
+ ],
2134
+ royalblue: [
2135
+ 65,
2136
+ 105,
2137
+ 225
2138
+ ],
2139
+ saddlebrown: [
2140
+ 139,
2141
+ 69,
2142
+ 19
2143
+ ],
2144
+ salmon: [
2145
+ 250,
2146
+ 128,
2147
+ 114
2148
+ ],
2149
+ sandybrown: [
2150
+ 244,
2151
+ 164,
2152
+ 96
2153
+ ],
2154
+ seagreen: [
2155
+ 46,
2156
+ 139,
2157
+ 87
2158
+ ],
2159
+ seashell: [
2160
+ 255,
2161
+ 245,
2162
+ 238
2163
+ ],
2164
+ sienna: [
2165
+ 160,
2166
+ 82,
2167
+ 45
2168
+ ],
2169
+ silver: [
2170
+ 192,
2171
+ 192,
2172
+ 192
2173
+ ],
2174
+ skyblue: [
2175
+ 135,
2176
+ 206,
2177
+ 235
2178
+ ],
2179
+ slateblue: [
2180
+ 106,
2181
+ 90,
2182
+ 205
2183
+ ],
2184
+ slategray: [
2185
+ 112,
2186
+ 128,
2187
+ 144
2188
+ ],
2189
+ slategrey: [
2190
+ 112,
2191
+ 128,
2192
+ 144
2193
+ ],
2194
+ snow: [
2195
+ 255,
2196
+ 250,
2197
+ 250
2198
+ ],
2199
+ springgreen: [
2200
+ 0,
2201
+ 255,
2202
+ 127
2203
+ ],
2204
+ steelblue: [
2205
+ 70,
2206
+ 130,
2207
+ 180
2208
+ ],
2209
+ tan: [
2210
+ 210,
2211
+ 180,
2212
+ 140
2213
+ ],
2214
+ teal: [
2215
+ 0,
2216
+ 128,
2217
+ 128
2218
+ ],
2219
+ thistle: [
2220
+ 216,
2221
+ 191,
2222
+ 216
2223
+ ],
2224
+ tomato: [
2225
+ 255,
2226
+ 99,
2227
+ 71
2228
+ ],
2229
+ turquoise: [
2230
+ 64,
2231
+ 224,
2232
+ 208
2233
+ ],
2234
+ violet: [
2235
+ 238,
2236
+ 130,
2237
+ 238
2238
+ ],
2239
+ wheat: [
2240
+ 245,
2241
+ 222,
2242
+ 179
2243
+ ],
2244
+ white: [
2245
+ 255,
2246
+ 255,
2247
+ 255
2248
+ ],
2249
+ whitesmoke: [
2250
+ 245,
2251
+ 245,
2252
+ 245
2253
+ ],
2254
+ yellow: [
2255
+ 255,
2256
+ 255,
2257
+ 0
2258
+ ],
2259
+ yellowgreen: [
2260
+ 154,
2261
+ 205,
2262
+ 50
2263
+ ]
2264
+ };
2265
+ },
2266
+ "../../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js" (module) {
2267
+ module.exports = (flag, argv = process.argv)=>{
2268
+ const prefix = flag.startsWith('-') ? '' : 1 === flag.length ? '-' : '--';
2269
+ const position = argv.indexOf(prefix + flag);
2270
+ const terminatorPosition = argv.indexOf('--');
2271
+ return -1 !== position && (-1 === terminatorPosition || position < terminatorPosition);
2272
+ };
2273
+ },
2274
+ "../../node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js" (module, __unused_rspack_exports, __webpack_require__) {
2275
+ const os = __webpack_require__("os");
2276
+ const tty = __webpack_require__("tty");
2277
+ const hasFlag = __webpack_require__("../../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js");
2278
+ const { env } = process;
2279
+ let forceColor;
2280
+ if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never')) forceColor = 0;
2281
+ else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) forceColor = 1;
2282
+ if ('FORCE_COLOR' in env) forceColor = 'true' === env.FORCE_COLOR ? 1 : 'false' === env.FORCE_COLOR ? 0 : 0 === env.FORCE_COLOR.length ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
2283
+ function translateLevel(level) {
2284
+ if (0 === level) return false;
2285
+ return {
2286
+ level,
2287
+ hasBasic: true,
2288
+ has256: level >= 2,
2289
+ has16m: level >= 3
2290
+ };
2291
+ }
2292
+ function supportsColor(haveStream, streamIsTTY) {
2293
+ if (0 === forceColor) return 0;
2294
+ if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) return 3;
2295
+ if (hasFlag('color=256')) return 2;
2296
+ if (haveStream && !streamIsTTY && void 0 === forceColor) return 0;
2297
+ const min = forceColor || 0;
2298
+ if ('dumb' === env.TERM) return min;
2299
+ if ('win32' === process.platform) {
2300
+ const osRelease = os.release().split('.');
2301
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) return Number(osRelease[2]) >= 14931 ? 3 : 2;
2302
+ return 1;
2303
+ }
2304
+ if ('CI' in env) {
2305
+ if ([
2306
+ 'TRAVIS',
2307
+ 'CIRCLECI',
2308
+ 'APPVEYOR',
2309
+ 'GITLAB_CI',
2310
+ 'GITHUB_ACTIONS',
2311
+ 'BUILDKITE'
2312
+ ].some((sign)=>sign in env) || 'codeship' === env.CI_NAME) return 1;
2313
+ return min;
2314
+ }
2315
+ if ('TEAMCITY_VERSION' in env) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
2316
+ if ('truecolor' === env.COLORTERM) return 3;
2317
+ if ('TERM_PROGRAM' in env) {
2318
+ const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
2319
+ switch(env.TERM_PROGRAM){
2320
+ case 'iTerm.app':
2321
+ return version >= 3 ? 3 : 2;
2322
+ case 'Apple_Terminal':
2323
+ return 2;
2324
+ }
2325
+ }
2326
+ if (/-256(color)?$/i.test(env.TERM)) return 2;
2327
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) return 1;
2328
+ if ('COLORTERM' in env) return 1;
2329
+ return min;
2330
+ }
2331
+ function getSupportLevel(stream) {
2332
+ const level = supportsColor(stream, stream && stream.isTTY);
2333
+ return translateLevel(level);
2334
+ }
2335
+ module.exports = {
2336
+ supportsColor: getSupportLevel,
2337
+ stdout: translateLevel(supportsColor(true, tty.isatty(1))),
2338
+ stderr: translateLevel(supportsColor(true, tty.isatty(2)))
2339
+ };
2340
+ },
2341
+ os (module) {
2342
+ module.exports = __rspack_external_os;
2343
+ },
2344
+ tty (module) {
2345
+ module.exports = __rspack_external_tty;
2346
+ }
2347
+ });
2348
+ const warnRetryReport = getDebug('execution-summary', {
2349
+ console: true
2350
+ });
2351
+ const notExecutedError = 'Not executed (previous task failed)';
2352
+ function createNotExecutedYamlResult(file) {
2353
+ return {
2354
+ file,
2355
+ success: false,
2356
+ executed: false,
2357
+ output: void 0,
2358
+ report: void 0,
2359
+ duration: 0,
2360
+ resultType: 'notExecuted',
2361
+ error: notExecutedError
2362
+ };
2363
+ }
2364
+ function createUnexpectedYamlResult(options) {
2365
+ const { file, error, duration, player } = options;
2366
+ const output = player?.output;
2367
+ return {
2368
+ file,
2369
+ success: false,
2370
+ executed: true,
2371
+ output: output && (0, __rspack_external_node_fs_5ea92f0c.existsSync)(output) ? output : void 0,
2372
+ report: player?.reportFile || void 0,
2373
+ duration,
2374
+ resultType: 'failed',
2375
+ error: error.message
2376
+ };
2377
+ }
2378
+ function isYamlPlayerSuccessful(player) {
2379
+ return 'error' !== player.status && !player.taskStatusList?.some((task)=>'error' === task.status);
2380
+ }
2381
+ function createExecutedYamlResult(options) {
2382
+ const { file, player, duration } = options;
2383
+ const hasPlayerError = 'error' === player.status;
2384
+ const hasFailedTasks = !isYamlPlayerSuccessful(player) && !hasPlayerError;
2385
+ let success;
2386
+ let resultType;
2387
+ if (hasPlayerError) {
2388
+ success = false;
2389
+ resultType = 'failed';
2390
+ } else if (hasFailedTasks) {
2391
+ success = false;
2392
+ resultType = 'partialFailed';
2393
+ } else {
2394
+ success = true;
2395
+ resultType = 'success';
2396
+ }
2397
+ let outputPath = player.output || void 0;
2398
+ if (outputPath && !(0, __rspack_external_node_fs_5ea92f0c.existsSync)(outputPath)) outputPath = void 0;
2399
+ let errorMessage;
2400
+ if (player.errorInSetup?.message) errorMessage = player.errorInSetup.message;
2401
+ else if (hasPlayerError || hasFailedTasks) {
2402
+ const taskErrors = player.taskStatusList?.filter((task)=>'error' === task.status && task.error?.message).map((task)=>task.error.message);
2403
+ errorMessage = taskErrors && taskErrors.length > 0 ? taskErrors.join('; ') : hasPlayerError ? 'Execution failed' : 'Some tasks failed';
2404
+ }
2405
+ return {
2406
+ file,
2407
+ success,
2408
+ executed: true,
2409
+ output: outputPath,
2410
+ report: player.reportFile || void 0,
2411
+ duration,
2412
+ resultType,
2413
+ error: errorMessage
2414
+ };
2415
+ }
2416
+ function resolveYamlMaxAttempts(retry) {
2417
+ if (!Number.isFinite(retry) || !retry || retry < 1) return 1;
2418
+ return Math.floor(retry) + 1;
2419
+ }
2420
+ function createYamlAttempt(result, attempt) {
2421
+ return {
2422
+ attempt,
2423
+ success: result.success,
2424
+ output: result.output,
2425
+ report: result.report,
2426
+ error: result.error,
2427
+ duration: result.duration,
2428
+ resultType: result.resultType
2429
+ };
2430
+ }
2431
+ function getYamlAttemptsDuration(attempts) {
2432
+ return attempts.reduce((total, attempt)=>total + (attempt.duration ?? 0), 0);
2433
+ }
2434
+ const retryAttemptReportPath = (reportFile, attempt)=>{
2435
+ if ('index.html' === basename(reportFile)) {
2436
+ const reportDir = dirname(reportFile);
2437
+ return join(dirname(reportDir), `${basename(reportDir)}-attempt-${attempt}`, 'index.html');
2438
+ }
2439
+ const extension = extname(reportFile);
2440
+ const stem = basename(reportFile, extension);
2441
+ return join(dirname(reportFile), `${stem}-attempt-${attempt}${extension}`);
2442
+ };
2443
+ function preserveYamlAttemptReport(attempt) {
2444
+ const source = attempt.report;
2445
+ if (!source || !(0, __rspack_external_node_fs_5ea92f0c.existsSync)(source)) return attempt;
2446
+ const target = retryAttemptReportPath(source, attempt.attempt);
2447
+ if ('index.html' === basename(source)) {
2448
+ const sourceDir = dirname(source);
2449
+ const targetDir = dirname(target);
2450
+ (0, __rspack_external_node_fs_5ea92f0c.rmSync)(targetDir, {
2451
+ recursive: true,
2452
+ force: true
2453
+ });
2454
+ (0, __rspack_external_node_fs_5ea92f0c.cpSync)(sourceDir, targetDir, {
2455
+ recursive: true
2456
+ });
2457
+ (0, __rspack_external_node_fs_5ea92f0c.rmSync)(sourceDir, {
2458
+ recursive: true,
2459
+ force: true
2460
+ });
2461
+ } else {
2462
+ (0, __rspack_external_node_fs_5ea92f0c.copyFileSync)(source, target);
2463
+ (0, __rspack_external_node_fs_5ea92f0c.unlinkSync)(source);
2464
+ }
2465
+ return {
2466
+ ...attempt,
2467
+ report: target
2468
+ };
2469
+ }
2470
+ function getExecutionSummary(results) {
2471
+ return {
2472
+ total: results.length,
2473
+ successful: getResultsByType(results, 'success').length,
2474
+ failed: getResultsByType(results, 'failed').length,
2475
+ partialFailed: getResultsByType(results, 'partialFailed').length,
2476
+ notExecuted: getResultsByType(results, 'notExecuted').length,
2477
+ totalDuration: results.reduce((sum, r)=>sum + (r.duration || 0), 0)
2478
+ };
2479
+ }
2480
+ function getResultsByType(results, resultType) {
2481
+ return results.filter((result)=>result.resultType === resultType);
2482
+ }
2483
+ function getResultFilesByType(results, resultType) {
2484
+ return getResultsByType(results, resultType).map((result)=>result.file);
2485
+ }
2486
+ function getSummaryAbsolutePath(summary) {
2487
+ return external_node_path_resolve(getMidsceneRunSubDir('output'), summary);
2488
+ }
2489
+ const toOutputRelativePath = (outputDir, filePath)=>{
2490
+ const relativePath = relative(outputDir, filePath);
2491
+ return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
2492
+ };
2493
+ const toTestStatus = (attempt)=>{
2494
+ if (attempt.success) return 'passed';
2495
+ if ('notExecuted' === attempt.resultType) return 'skipped';
2496
+ return 'failed';
2497
+ };
2498
+ const safeReportNamePart = (value)=>value.replace(/[:*?"<>|# ]/g, '-');
2499
+ const createRetryReportName = (file)=>{
2500
+ const fileName = basename(file, extname(file)) || 'yaml';
2501
+ const fileHash = createHash('sha1').update(external_node_path_resolve(file)).digest('hex').slice(0, 8);
2502
+ return `${safeReportNamePart(fileName)}-${fileHash}-retry-attempts`;
2503
+ };
2504
+ const createRetryAttemptReport = (result)=>{
2505
+ const attemptsWithReports = result.attempts?.filter((attempt)=>attempt.report && (0, __rspack_external_node_fs_5ea92f0c.existsSync)(attempt.report));
2506
+ if (!attemptsWithReports || attemptsWithReports.length <= 1) return;
2507
+ const tool = new ReportMergingTool();
2508
+ for (const attempt of attemptsWithReports){
2509
+ const status = toTestStatus(attempt);
2510
+ tool.append({
2511
+ reportFilePath: attempt.report,
2512
+ reportAttributes: {
2513
+ testDuration: attempt.duration ?? 0,
2514
+ testStatus: status,
2515
+ testTitle: `Attempt ${attempt.attempt}: ${status} - ${basename(result.file)}`,
2516
+ testId: `${safeReportNamePart(basename(result.file))}-attempt-${attempt.attempt}`,
2517
+ testDescription: attempt.error ?? (attempt.success ? 'YAML attempt passed' : 'YAML attempt failed')
2518
+ }
2519
+ });
2520
+ }
2521
+ return tool.mergeReports(createRetryReportName(result.file), {
2522
+ outputDir: getMidsceneRunSubDir('report'),
2523
+ overwrite: true
2524
+ }) || void 0;
2525
+ };
2526
+ const errorMessageOf = (error)=>error instanceof Error ? error.message : String(error);
2527
+ const warnRetryReportFailure = (message)=>{
2528
+ try {
2529
+ (0, __rspack_external_node_fs_5ea92f0c.mkdirSync)(getMidsceneRunSubDir('log'), {
2530
+ recursive: true
2531
+ });
2532
+ warnRetryReport(message);
2533
+ } catch {}
2534
+ };
2535
+ const createRetryAttemptReportSafely = (result)=>{
2536
+ try {
2537
+ return {
2538
+ report: createRetryAttemptReport(result),
2539
+ failed: false
2540
+ };
2541
+ } catch (error) {
2542
+ warnRetryReportFailure(`Failed to merge retry attempt report for ${result.file}: ${errorMessageOf(error)}`);
2543
+ return {
2544
+ failed: true
2545
+ };
2546
+ }
2547
+ };
2548
+ function writeExecutionSummaryFile(summary, results) {
2549
+ const indexPath = getSummaryAbsolutePath(summary);
2550
+ const outputDir = dirname(indexPath);
2551
+ (0, __rspack_external_node_fs_5ea92f0c.mkdirSync)(outputDir, {
2552
+ recursive: true
2553
+ });
2554
+ const executionSummary = getExecutionSummary(results);
2555
+ const indexData = {
2556
+ summary: {
2557
+ ...executionSummary,
2558
+ generatedAt: new Date().toLocaleString()
2559
+ },
2560
+ results: results.map((result)=>{
2561
+ const retryReport = createRetryAttemptReportSafely(result);
2562
+ return {
2563
+ script: relative(outputDir, result.file),
2564
+ success: result.success,
2565
+ resultType: result.resultType,
2566
+ output: result.output ? toOutputRelativePath(outputDir, result.output) : void 0,
2567
+ report: result.report ? relative(outputDir, result.report) : void 0,
2568
+ retryReport: retryReport.report ? relative(outputDir, retryReport.report) : !retryReport.failed && result.retryReport ? relative(outputDir, result.retryReport) : void 0,
2569
+ attempts: result.attempts?.map((attempt)=>({
2570
+ attempt: attempt.attempt,
2571
+ success: attempt.success,
2572
+ resultType: attempt.resultType,
2573
+ output: attempt.output ? toOutputRelativePath(outputDir, attempt.output) : void 0,
2574
+ report: attempt.report ? relative(outputDir, attempt.report) : void 0,
2575
+ error: attempt.error,
2576
+ duration: attempt.duration
2577
+ })),
2578
+ error: result.error,
2579
+ duration: result.duration
2580
+ };
2581
+ })
2582
+ };
2583
+ (0, __rspack_external_node_fs_5ea92f0c.writeFileSync)(indexPath, JSON.stringify(indexData, null, 2));
2584
+ return indexPath;
2585
+ }
2586
+ function printExecutionPlan(config) {
2587
+ if (config.setup) {
2588
+ console.log(" Setup script:");
2589
+ console.log(` - ${config.setup}`);
2590
+ }
2591
+ console.log(' Scripts:');
2592
+ for (const file of config.files)console.log(` - ${file}`);
2593
+ console.log('📋 Execution plan');
2594
+ console.log(` Concurrency: ${config.concurrent}`);
2595
+ console.log(` Keep window: ${config.keepWindow}`);
2596
+ console.log(` Headed: ${config.headed}`);
2597
+ console.log(` Continue on error: ${config.continueOnError}`);
2598
+ console.log(` Retry: ${config.retry ?? 0}`);
2599
+ console.log(` Share browser context: ${config.shareBrowserContext ?? false}`);
2600
+ console.log(` Reuse browser page: ${config.reusePage ?? false}`);
2601
+ console.log(` Summary output: ${config.summary}`);
2602
+ }
2603
+ function printExecutionFinished() {
2604
+ console.log('Execution finished:');
2605
+ }
2606
+ const printResultArtifacts = (result)=>{
2607
+ if (result.report) console.log(` Report: ${result.report}`);
2608
+ if (result.output) console.log(` Output: ${result.output}`);
2609
+ };
2610
+ function printExecutionSummary(results, summaryPath) {
2611
+ const summary = getExecutionSummary(results);
2612
+ const successfulFiles = getResultsByType(results, 'success');
2613
+ const failedFiles = getResultsByType(results, 'failed');
2614
+ const partialFailedFiles = getResultsByType(results, 'partialFailed');
2615
+ const notExecutedFiles = getResultsByType(results, 'notExecuted');
2616
+ const success = 0 === summary.failed && 0 === summary.partialFailed && 0 === summary.notExecuted;
2617
+ console.log('\n📊 Execution Summary:');
2618
+ console.log(` Total files: ${summary.total}`);
2619
+ console.log(` Successful: ${summary.successful}`);
2620
+ console.log(` Failed: ${summary.failed}`);
2621
+ console.log(` Partial failed: ${summary.partialFailed}`);
2622
+ console.log(` Not executed: ${summary.notExecuted}`);
2623
+ console.log(` Duration: ${(summary.totalDuration / 1000).toFixed(2)}s`);
2624
+ console.log(` Summary: ${summaryPath}`);
2625
+ if (successfulFiles.length > 0) {
2626
+ console.log('\n✅ Successful files:');
2627
+ successfulFiles.forEach((result)=>{
2628
+ console.log(` ${result.file}`);
2629
+ printResultArtifacts(result);
2630
+ });
2631
+ }
2632
+ if (failedFiles.length > 0) {
2633
+ console.log('\n❌ Failed files');
2634
+ failedFiles.forEach((result)=>{
2635
+ console.log(` ${result.file}`);
2636
+ if (result.error) console.log(` Error: ${result.error}`);
2637
+ });
2638
+ }
2639
+ if (partialFailedFiles.length > 0) {
2640
+ console.log('\n⚠️ Partial failed files (some tasks failed with continueOnError)');
2641
+ partialFailedFiles.forEach((result)=>{
2642
+ console.log(` ${result.file}`);
2643
+ if (result.error) console.log(` Error: ${result.error}`);
2644
+ });
2645
+ }
2646
+ if (notExecutedFiles.length > 0) {
2647
+ console.log('\n⏸️ Not executed files');
2648
+ notExecutedFiles.forEach((result)=>{
2649
+ console.log(` ${result.file}`);
2650
+ });
2651
+ }
2652
+ if (success) console.log('\n🎉 All files executed successfully!');
2653
+ else console.log('\n⚠️ Some files failed or were not executed.');
2654
+ return success;
2655
+ }
2656
+ function _define_property(obj, key, value) {
2657
+ if (key in obj) Object.defineProperty(obj, key, {
2658
+ value: value,
2659
+ enumerable: true,
2660
+ configurable: true,
2661
+ writable: true
2662
+ });
2663
+ else obj[key] = value;
2664
+ return obj;
2665
+ }
2666
+ const normalizeBatchError = (error)=>error instanceof Error ? error : new Error('Unexpected YAML execution failure', {
2667
+ cause: error
2668
+ });
2669
+ class YamlBatchExecutionError extends Error {
2670
+ constructor(error, occurrences){
2671
+ const cause = normalizeBatchError(error);
2672
+ super(cause.message, {
2673
+ cause
2674
+ }), _define_property(this, "results", void 0), _define_property(this, "occurrences", void 0);
2675
+ this.name = 'YamlBatchExecutionError';
2676
+ this.occurrences = occurrences.map(({ caseId, result })=>({
2677
+ caseId,
2678
+ result
2679
+ }));
2680
+ this.results = this.occurrences.map(({ result })=>result);
2681
+ }
2682
+ }
2683
+ function isYamlBatchExecutionError(error) {
2684
+ return error instanceof YamlBatchExecutionError;
2685
+ }
2686
+ class Node {
2687
+ value;
2688
+ next;
2689
+ constructor(value){
2690
+ this.value = value;
2691
+ }
2692
+ }
2693
+ class Queue {
2694
+ #head;
2695
+ #tail;
2696
+ #size;
2697
+ constructor(){
2698
+ this.clear();
2699
+ }
2700
+ enqueue(value) {
2701
+ const node = new Node(value);
2702
+ if (this.#head) {
2703
+ this.#tail.next = node;
2704
+ this.#tail = node;
2705
+ } else {
2706
+ this.#head = node;
2707
+ this.#tail = node;
2708
+ }
2709
+ this.#size++;
2710
+ }
2711
+ dequeue() {
2712
+ const current = this.#head;
2713
+ if (!current) return;
2714
+ this.#head = this.#head.next;
2715
+ this.#size--;
2716
+ if (!this.#head) this.#tail = void 0;
2717
+ return current.value;
2718
+ }
2719
+ peek() {
2720
+ if (!this.#head) return;
2721
+ return this.#head.value;
2722
+ }
2723
+ clear() {
2724
+ this.#head = void 0;
2725
+ this.#tail = void 0;
2726
+ this.#size = 0;
2727
+ }
2728
+ get size() {
2729
+ return this.#size;
2730
+ }
2731
+ *[Symbol.iterator]() {
2732
+ let current = this.#head;
2733
+ while(current){
2734
+ yield current.value;
2735
+ current = current.next;
2736
+ }
2737
+ }
2738
+ *drain() {
2739
+ while(this.#head)yield this.dequeue();
2740
+ }
2741
+ }
2742
+ function pLimit(concurrency) {
2743
+ validateConcurrency(concurrency);
2744
+ const queue = new Queue();
2745
+ let activeCount = 0;
2746
+ const resumeNext = ()=>{
2747
+ if (activeCount < concurrency && queue.size > 0) {
2748
+ queue.dequeue()();
2749
+ activeCount++;
2750
+ }
2751
+ };
2752
+ const next = ()=>{
2753
+ activeCount--;
2754
+ resumeNext();
2755
+ };
2756
+ const run = async (function_, resolve, arguments_)=>{
2757
+ const result = (async ()=>function_(...arguments_))();
2758
+ resolve(result);
2759
+ try {
2760
+ await result;
2761
+ } catch {}
2762
+ next();
2763
+ };
2764
+ const enqueue = (function_, resolve, arguments_)=>{
2765
+ new Promise((internalResolve)=>{
2766
+ queue.enqueue(internalResolve);
2767
+ }).then(run.bind(void 0, function_, resolve, arguments_));
2768
+ (async ()=>{
2769
+ await Promise.resolve();
2770
+ if (activeCount < concurrency) resumeNext();
2771
+ })();
2772
+ };
2773
+ const generator = (function_, ...arguments_)=>new Promise((resolve)=>{
2774
+ enqueue(function_, resolve, arguments_);
2775
+ });
2776
+ Object.defineProperties(generator, {
2777
+ activeCount: {
2778
+ get: ()=>activeCount
2779
+ },
2780
+ pendingCount: {
2781
+ get: ()=>queue.size
2782
+ },
2783
+ clearQueue: {
2784
+ value () {
2785
+ queue.clear();
2786
+ }
2787
+ },
2788
+ concurrency: {
2789
+ get: ()=>concurrency,
2790
+ set (newConcurrency) {
2791
+ validateConcurrency(newConcurrency);
2792
+ concurrency = newConcurrency;
2793
+ queueMicrotask(()=>{
2794
+ while(activeCount < concurrency && queue.size > 0)resumeNext();
2795
+ });
2796
+ }
2797
+ }
2798
+ });
2799
+ return generator;
2800
+ }
2801
+ function validateConcurrency(concurrency) {
2802
+ if (!((Number.isInteger(concurrency) || concurrency === 1 / 0) && concurrency > 0)) throw new TypeError('Expected `concurrency` to be a number from 1 and up');
2803
+ }
2804
+ const source_0 = __webpack_require__("../../node_modules/.pnpm/chalk@4.1.2/node_modules/chalk/source/index.js");
2805
+ var source_0_default = /*#__PURE__*/ __webpack_require__.n(source_0);
2806
+ function resolveIsTTY(env = process.env, stdoutIsTTY = process.stdout.isTTY) {
2807
+ if (env.MIDSCENE_CLI_LOG_ON_NON_TTY || env.NO_COLOR || 'dumb' === env.TERM || env.CI) return false;
2808
+ return Boolean(stdoutIsTTY);
2809
+ }
2810
+ const isTTY = resolveIsTTY();
2811
+ const indent = ' ';
2812
+ const spinnerInterval = 80;
2813
+ const spinnerFrames = [
2814
+ '◰',
2815
+ '◳',
2816
+ '◲',
2817
+ '◱'
2818
+ ];
2819
+ const currentSpinningFrame = ()=>spinnerFrames[Math.floor(Date.now() / spinnerInterval) % spinnerFrames.length];
2820
+ function indicatorForStatus(status) {
2821
+ if ('init' === status) return source_0_default().gray('◌');
2822
+ if ('running' === status) return source_0_default().yellowBright(currentSpinningFrame());
2823
+ if ('done' === status) return source_0_default().green('✔︎');
2824
+ if ('error' === status) return source_0_default().red('✘');
2825
+ }
2826
+ const contextInfo = (context)=>{
2827
+ const filePath = context.file;
2828
+ const filePathToShow = relative(process.cwd(), filePath);
2829
+ const fileNameToPrint = `${source_0_default().gray(`${filePathToShow}`)}`;
2830
+ const fileStatusText = indicatorForStatus(context.player.status);
2831
+ const contextActionText = void 0 === context.player.currentTaskIndex && 'running' === context.player.status ? source_0_default().gray('(navigating)') : '';
2832
+ const errorText = context.player.errorInSetup ? `\n${indent}${source_0_default().red('error:')} ${context.player.errorInSetup?.message}\n${indent}${indent}${context.player.errorInSetup?.stack}` : '';
2833
+ const outputFile = context.player.output;
2834
+ const outputText = outputFile && Object.keys(context.player.result || {}).length > 0 ? `\n${indent}${source_0_default().gray(`output: ${outputFile}`)}` : '';
2835
+ const reportFile = context.player.reportFile;
2836
+ const reportText = reportFile ? `\n${indent}${source_0_default().gray(`report: ${reportFile}`)}` : '';
2837
+ const agentStatusTip = context.player.agentStatusTip;
2838
+ const agentStatusText = agentStatusTip ? `\n${indent}${source_0_default().gray(`agent status: ${agentStatusTip}`)}` : '';
2839
+ const mergedText = `${fileStatusText} ${fileNameToPrint} ${contextActionText}${outputText}${reportText}${errorText}${agentStatusText}`.trim();
2840
+ return {
2841
+ fileNameToPrint,
2842
+ fileStatusText,
2843
+ contextActionText,
2844
+ outputText,
2845
+ reportText,
2846
+ mergedText
2847
+ };
2848
+ };
2849
+ const singleTaskInfo = (task)=>{
2850
+ let stepText = '';
2851
+ if ('init' === task.status) stepText = '';
2852
+ else if ('running' === task.status || 'error' === task.status) if (void 0 === task.currentStep) stepText = source_0_default().gray('(navigating)');
2853
+ else if ('number' == typeof task.currentStep) {
2854
+ const actionText = '';
2855
+ stepText = source_0_default().gray(`(task ${task.currentStep + 1}/${task.totalSteps}${actionText})`.trim());
2856
+ } else stepText = source_0_default().gray('(unknown task)');
2857
+ const errorText = 'error' === task.status ? `\n${indent}${source_0_default().gray('error:')}\n${indent}${indent}${task.error?.message}` : '';
2858
+ const statusText = indicatorForStatus(task.status);
2859
+ const mergedLine = `${statusText} ${task.name} ${stepText}${errorText}`;
2860
+ return {
2861
+ nameText: task.name,
2862
+ stepText,
2863
+ errorText,
2864
+ itemStatusText: statusText,
2865
+ mergedLine
2866
+ };
2867
+ };
2868
+ function paddingLines(lines) {
2869
+ return lines.map((line)=>`${indent}${line}`);
2870
+ }
2871
+ const contextTaskListSummary = (taskStatusArray, context)=>{
2872
+ const prefixLines = [];
2873
+ const currentLine = [];
2874
+ const suffixText = [];
2875
+ const { mergedText: fileInfo } = contextInfo(context);
2876
+ if (!context.player.errorInSetup) for (const task of taskStatusArray){
2877
+ const { mergedLine } = singleTaskInfo(task);
2878
+ if ('init' === context.player.status) suffixText.push(mergedLine);
2879
+ else if ('running' === context.player.status) currentLine.push(mergedLine);
2880
+ else if ('done' === context.player.status) prefixLines.push(mergedLine);
2881
+ else if ('error' === context.player.status) prefixLines.push(mergedLine);
2882
+ }
2883
+ const lines = [
2884
+ fileInfo
2885
+ ];
2886
+ if (prefixLines.length > 0) lines.push(...paddingLines(prefixLines));
2887
+ if (currentLine.length > 0) lines.push(...paddingLines(currentLine));
2888
+ if (suffixText.length > 0) lines.push(...paddingLines(suffixText));
2889
+ return lines.join('\n');
2890
+ };
2891
+ const formatYamlProgressSnapshot = (message, attempt, totalAttempts)=>totalAttempts > 1 ? `Attempt ${attempt}/${totalAttempts}\n${message}` : message;
2892
+ const copyProperty = (to, from, property, ignoreNonConfigurable)=>{
2893
+ if ('length' === property || 'prototype' === property) return;
2894
+ if ('arguments' === property || 'caller' === property) return;
2895
+ const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
2896
+ const fromDescriptor = Object.getOwnPropertyDescriptor(from, property);
2897
+ if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) return;
2898
+ Object.defineProperty(to, property, fromDescriptor);
2899
+ };
2900
+ const canCopyProperty = function(toDescriptor, fromDescriptor) {
2901
+ return void 0 === toDescriptor || toDescriptor.configurable || toDescriptor.writable === fromDescriptor.writable && toDescriptor.enumerable === fromDescriptor.enumerable && toDescriptor.configurable === fromDescriptor.configurable && (toDescriptor.writable || toDescriptor.value === fromDescriptor.value);
2902
+ };
2903
+ const changePrototype = (to, from)=>{
2904
+ const fromPrototype = Object.getPrototypeOf(from);
2905
+ if (fromPrototype === Object.getPrototypeOf(to)) return;
2906
+ Object.setPrototypeOf(to, fromPrototype);
2907
+ };
2908
+ const wrappedToString = (withName, fromBody)=>`/* Wrapped ${withName}*/\n${fromBody}`;
2909
+ const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString');
2910
+ const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name');
2911
+ const changeToString = (to, from, name)=>{
2912
+ const withName = '' === name ? '' : `with ${name.trim()}() `;
2913
+ const newToString = wrappedToString.bind(null, withName, from.toString());
2914
+ Object.defineProperty(newToString, 'name', toStringName);
2915
+ const { writable, enumerable, configurable } = toStringDescriptor;
2916
+ Object.defineProperty(to, 'toString', {
2917
+ value: newToString,
2918
+ writable,
2919
+ enumerable,
2920
+ configurable
2921
+ });
2922
+ };
2923
+ function mimicFunction(to, from, { ignoreNonConfigurable = false } = {}) {
2924
+ const { name } = to;
2925
+ for (const property of Reflect.ownKeys(from))copyProperty(to, from, property, ignoreNonConfigurable);
2926
+ changePrototype(to, from);
2927
+ changeToString(to, from, name);
2928
+ return to;
2929
+ }
2930
+ const calledFunctions = new WeakMap();
2931
+ const onetime_onetime = (function_, options = {})=>{
2932
+ if ('function' != typeof function_) throw new TypeError('Expected a function');
2933
+ let returnValue;
2934
+ let callCount = 0;
2935
+ const functionName = function_.displayName || function_.name || '<anonymous>';
2936
+ const onetime = function(...arguments_) {
2937
+ calledFunctions.set(onetime, ++callCount);
2938
+ if (1 === callCount) {
2939
+ returnValue = function_.apply(this, arguments_);
2940
+ function_ = void 0;
2941
+ } else if (true === options.throw) throw new Error(`Function \`${functionName}\` can only be called once`);
2942
+ return returnValue;
2943
+ };
2944
+ mimicFunction(onetime, function_);
2945
+ calledFunctions.set(onetime, callCount);
2946
+ return onetime;
2947
+ };
2948
+ onetime_onetime.callCount = (function_)=>{
2949
+ if (!calledFunctions.has(function_)) throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
2950
+ return calledFunctions.get(function_);
2951
+ };
2952
+ const node_modules_onetime = onetime_onetime;
2953
+ const signals = [];
2954
+ signals.push('SIGHUP', 'SIGINT', 'SIGTERM');
2955
+ if ('win32' !== process.platform) signals.push('SIGALRM', 'SIGABRT', 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT');
2956
+ if ('linux' === process.platform) signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT');
2957
+ const processOk = (process1)=>!!process1 && 'object' == typeof process1 && 'function' == typeof process1.removeListener && 'function' == typeof process1.emit && 'function' == typeof process1.reallyExit && 'function' == typeof process1.listeners && 'function' == typeof process1.kill && 'number' == typeof process1.pid && 'function' == typeof process1.on;
2958
+ const kExitEmitter = Symbol.for('signal-exit emitter');
2959
+ const global = globalThis;
2960
+ const ObjectDefineProperty = Object.defineProperty.bind(Object);
2961
+ class Emitter {
2962
+ emitted = {
2963
+ afterExit: false,
2964
+ exit: false
2965
+ };
2966
+ listeners = {
2967
+ afterExit: [],
2968
+ exit: []
2969
+ };
2970
+ count = 0;
2971
+ id = Math.random();
2972
+ constructor(){
2973
+ if (global[kExitEmitter]) return global[kExitEmitter];
2974
+ ObjectDefineProperty(global, kExitEmitter, {
2975
+ value: this,
2976
+ writable: false,
2977
+ enumerable: false,
2978
+ configurable: false
2979
+ });
2980
+ }
2981
+ on(ev, fn) {
2982
+ this.listeners[ev].push(fn);
2983
+ }
2984
+ removeListener(ev, fn) {
2985
+ const list = this.listeners[ev];
2986
+ const i = list.indexOf(fn);
2987
+ if (-1 === i) return;
2988
+ if (0 === i && 1 === list.length) list.length = 0;
2989
+ else list.splice(i, 1);
2990
+ }
2991
+ emit(ev, code, signal) {
2992
+ if (this.emitted[ev]) return false;
2993
+ this.emitted[ev] = true;
2994
+ let ret = false;
2995
+ for (const fn of this.listeners[ev])ret = true === fn(code, signal) || ret;
2996
+ if ('exit' === ev) ret = this.emit('afterExit', code, signal) || ret;
2997
+ return ret;
2998
+ }
2999
+ }
3000
+ class SignalExitBase {
3001
+ }
3002
+ const signalExitWrap = (handler)=>({
3003
+ onExit (cb, opts) {
3004
+ return handler.onExit(cb, opts);
3005
+ },
3006
+ load () {
3007
+ return handler.load();
3008
+ },
3009
+ unload () {
3010
+ return handler.unload();
3011
+ }
3012
+ });
3013
+ class SignalExitFallback extends SignalExitBase {
3014
+ onExit() {
3015
+ return ()=>{};
3016
+ }
3017
+ load() {}
3018
+ unload() {}
3019
+ }
3020
+ class SignalExit extends SignalExitBase {
3021
+ #hupSig = 'win32' === mjs_process.platform ? 'SIGINT' : 'SIGHUP';
3022
+ #emitter = new Emitter();
3023
+ #process;
3024
+ #originalProcessEmit;
3025
+ #originalProcessReallyExit;
3026
+ #sigListeners = {};
3027
+ #loaded = false;
3028
+ constructor(process1){
3029
+ super();
3030
+ this.#process = process1;
3031
+ this.#sigListeners = {};
3032
+ for (const sig of signals)this.#sigListeners[sig] = ()=>{
3033
+ const listeners = this.#process.listeners(sig);
3034
+ let { count } = this.#emitter;
3035
+ const p = process1;
3036
+ if ('object' == typeof p.__signal_exit_emitter__ && 'number' == typeof p.__signal_exit_emitter__.count) count += p.__signal_exit_emitter__.count;
3037
+ if (listeners.length === count) {
3038
+ this.unload();
3039
+ const ret = this.#emitter.emit('exit', null, sig);
3040
+ const s = 'SIGHUP' === sig ? this.#hupSig : sig;
3041
+ if (!ret) process1.kill(process1.pid, s);
3042
+ }
3043
+ };
3044
+ this.#originalProcessReallyExit = process1.reallyExit;
3045
+ this.#originalProcessEmit = process1.emit;
3046
+ }
3047
+ onExit(cb, opts) {
3048
+ if (!processOk(this.#process)) return ()=>{};
3049
+ if (false === this.#loaded) this.load();
3050
+ const ev = opts?.alwaysLast ? 'afterExit' : 'exit';
3051
+ this.#emitter.on(ev, cb);
3052
+ return ()=>{
3053
+ this.#emitter.removeListener(ev, cb);
3054
+ if (0 === this.#emitter.listeners['exit'].length && 0 === this.#emitter.listeners['afterExit'].length) this.unload();
3055
+ };
3056
+ }
3057
+ load() {
3058
+ if (this.#loaded) return;
3059
+ this.#loaded = true;
3060
+ this.#emitter.count += 1;
3061
+ for (const sig of signals)try {
3062
+ const fn = this.#sigListeners[sig];
3063
+ if (fn) this.#process.on(sig, fn);
3064
+ } catch (_) {}
3065
+ this.#process.emit = (ev, ...a)=>this.#processEmit(ev, ...a);
3066
+ this.#process.reallyExit = (code)=>this.#processReallyExit(code);
3067
+ }
3068
+ unload() {
3069
+ if (!this.#loaded) return;
3070
+ this.#loaded = false;
3071
+ signals.forEach((sig)=>{
3072
+ const listener = this.#sigListeners[sig];
3073
+ if (!listener) throw new Error('Listener not defined for signal: ' + sig);
3074
+ try {
3075
+ this.#process.removeListener(sig, listener);
3076
+ } catch (_) {}
3077
+ });
3078
+ this.#process.emit = this.#originalProcessEmit;
3079
+ this.#process.reallyExit = this.#originalProcessReallyExit;
3080
+ this.#emitter.count -= 1;
3081
+ }
3082
+ #processReallyExit(code) {
3083
+ if (!processOk(this.#process)) return 0;
3084
+ this.#process.exitCode = code || 0;
3085
+ this.#emitter.emit('exit', this.#process.exitCode, null);
3086
+ return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode);
3087
+ }
3088
+ #processEmit(ev, ...args) {
3089
+ const og = this.#originalProcessEmit;
3090
+ if (!('exit' === ev && processOk(this.#process))) return og.call(this.#process, ev, ...args);
3091
+ {
3092
+ if ('number' == typeof args[0]) this.#process.exitCode = args[0];
3093
+ const ret = og.call(this.#process, ev, ...args);
3094
+ this.#emitter.emit('exit', this.#process.exitCode, null);
3095
+ return ret;
3096
+ }
3097
+ }
3098
+ }
3099
+ const mjs_process = globalThis.process;
3100
+ const { onExit: onExit, load: load, unload: unload } = signalExitWrap(processOk(mjs_process) ? new SignalExit(mjs_process) : new SignalExitFallback());
3101
+ const terminal = node_process.stderr.isTTY ? node_process.stderr : node_process.stdout.isTTY ? node_process.stdout : void 0;
3102
+ const restoreCursor = terminal ? node_modules_onetime(()=>{
3103
+ onExit(()=>{
3104
+ terminal.write('\u001B[?25h');
3105
+ }, {
3106
+ alwaysLast: true
3107
+ });
3108
+ }) : ()=>{};
3109
+ const restore_cursor = restoreCursor;
3110
+ function tty_renderer_define_property(obj, key, value) {
3111
+ if (key in obj) Object.defineProperty(obj, key, {
3112
+ value: value,
3113
+ enumerable: true,
3114
+ configurable: true,
3115
+ writable: true
3116
+ });
3117
+ else obj[key] = value;
3118
+ return obj;
3119
+ }
3120
+ const DEFAULT_RENDER_INTERVAL = 160;
3121
+ const ESC = '\x1B[';
3122
+ const CLEAR_LINE = `${ESC}K`;
3123
+ const MOVE_CURSOR_ONE_ROW_UP = `${ESC}1A`;
3124
+ const HIDE_CURSOR = `${ESC}?25l`;
3125
+ const SHOW_CURSOR = `${ESC}?25h`;
3126
+ const SYNC_START = `${ESC}?2026h`;
3127
+ const SYNC_END = `${ESC}?2026l`;
3128
+ class TTYWindowRenderer {
3129
+ start() {
3130
+ this.finished = false;
3131
+ this.renderInterval = setInterval(()=>this.flushBuffer(), this.options.interval);
3132
+ }
3133
+ stop() {
3134
+ this.flushBuffer();
3135
+ this.write(SHOW_CURSOR, 'output');
3136
+ this.cleanups.splice(0).map((fn)=>fn());
3137
+ clearInterval(this.renderInterval);
3138
+ }
3139
+ finish() {
3140
+ this.finished = true;
3141
+ this.flushBuffer();
3142
+ clearInterval(this.renderInterval);
3143
+ }
3144
+ flushBuffer() {
3145
+ if (0 === this.buffer.length) return this.render();
3146
+ let current;
3147
+ for (const next of this.buffer.splice(0)){
3148
+ if (!current) {
3149
+ current = next;
3150
+ continue;
3151
+ }
3152
+ if (current.type !== next.type) {
3153
+ this.render(current.message, current.type);
3154
+ current = next;
3155
+ continue;
3156
+ }
3157
+ current.message += next.message;
3158
+ }
3159
+ if (current) this.render(current?.message, current?.type);
3160
+ }
3161
+ render(message, type = 'output') {
3162
+ if (this.finished) {
3163
+ this.clearWindow();
3164
+ return this.write(message || '', type);
3165
+ }
3166
+ const windowContent = this.options.getWindow();
3167
+ const rowCount = getRenderedRowCount(windowContent, this.options.outputStream);
3168
+ let padding = this.windowHeight - rowCount;
3169
+ if (padding > 0 && message) padding -= getRenderedRowCount([
3170
+ message
3171
+ ], this.options.outputStream);
3172
+ this.write(SYNC_START);
3173
+ this.clearWindow();
3174
+ if (message) this.write(message, type);
3175
+ if (padding > 0) this.write('\n'.repeat(padding));
3176
+ this.write(windowContent.join('\n'));
3177
+ this.write(SYNC_END);
3178
+ this.windowHeight = rowCount + Math.max(0, padding);
3179
+ }
3180
+ clearWindow() {
3181
+ if (0 === this.windowHeight) return;
3182
+ this.write(CLEAR_LINE);
3183
+ for(let i = 1; i < this.windowHeight; i++)this.write(`${MOVE_CURSOR_ONE_ROW_UP}${CLEAR_LINE}`);
3184
+ this.windowHeight = 0;
3185
+ }
3186
+ interceptStream(stream, type) {
3187
+ const original = stream.write;
3188
+ stream.write = (chunk, _, callback)=>{
3189
+ if (chunk) if (this.finished) this.write(chunk.toString(), type);
3190
+ else this.buffer.push({
3191
+ type,
3192
+ message: chunk.toString()
3193
+ });
3194
+ callback?.();
3195
+ };
3196
+ return function() {
3197
+ stream.write = original;
3198
+ };
3199
+ }
3200
+ write(message, type = 'output') {
3201
+ this.streams[type](message);
3202
+ }
3203
+ constructor(options){
3204
+ tty_renderer_define_property(this, "options", void 0);
3205
+ tty_renderer_define_property(this, "streams", void 0);
3206
+ tty_renderer_define_property(this, "buffer", []);
3207
+ tty_renderer_define_property(this, "renderInterval", void 0);
3208
+ tty_renderer_define_property(this, "windowHeight", 0);
3209
+ tty_renderer_define_property(this, "finished", false);
3210
+ tty_renderer_define_property(this, "cleanups", []);
3211
+ this.options = {
3212
+ interval: DEFAULT_RENDER_INTERVAL,
3213
+ ...options
3214
+ };
3215
+ this.streams = {
3216
+ output: options.outputStream.write.bind(options.outputStream),
3217
+ error: options.errorStream.write.bind(options.errorStream)
3218
+ };
3219
+ this.cleanups.push(this.interceptStream(process.stdout, 'output'), this.interceptStream(process.stderr, 'error'));
3220
+ restore_cursor();
3221
+ this.write(HIDE_CURSOR, 'output');
3222
+ this.start();
3223
+ }
3224
+ }
3225
+ function getRenderedRowCount(contents, stream) {
3226
+ let count = 0;
3227
+ const columns = 'columns' in stream ? stream.columns : 80;
3228
+ for (const content of contents){
3229
+ const rows = content.split('\n');
3230
+ for (const row of rows){
3231
+ const text = stripVTControlCharacters(row);
3232
+ count += Math.max(1, Math.ceil(text.length / columns));
3233
+ }
3234
+ }
3235
+ return count;
3236
+ }
3237
+ function yaml_batch_executor_define_property(obj, key, value) {
3238
+ if (key in obj) Object.defineProperty(obj, key, {
3239
+ value: value,
3240
+ enumerable: true,
3241
+ configurable: true,
3242
+ writable: true
3243
+ });
3244
+ else obj[key] = value;
3245
+ return obj;
3246
+ }
3247
+ const batchWarning = getDebug('yaml-batch-executor', {
3248
+ console: true
3249
+ });
3250
+ const normalizeExecutionError = (error)=>error instanceof Error ? error : new Error('Unexpected YAML execution failure', {
3251
+ cause: error
3252
+ });
3253
+ const batchRuntimeTargetLabel = {
3254
+ 'puppeteer-web': 'Puppeteer Web',
3255
+ 'bridge-web': 'Web bridge mode',
3256
+ android: 'Android',
3257
+ ios: 'iOS',
3258
+ harmony: 'HarmonyOS',
3259
+ computer: 'Computer',
3260
+ interface: 'Interface'
3261
+ };
3262
+ const resolveBatchRuntimeTarget = (config)=>{
3263
+ const webTarget = resolveWebTarget(config);
3264
+ const targets = [];
3265
+ if (webTarget) targets.push(webTarget.target.bridgeMode ? 'bridge-web' : 'puppeteer-web');
3266
+ if (void 0 !== config.android) targets.push('android');
3267
+ if (void 0 !== config.ios) targets.push('ios');
3268
+ if (void 0 !== config.harmony) targets.push('harmony');
3269
+ if (void 0 !== config.computer) targets.push('computer');
3270
+ if (void 0 !== config.interface) targets.push('interface');
3271
+ return 1 === targets.length ? targets[0] : void 0;
3272
+ };
3273
+ const assertBrowserContextUsage = (setupContext, allContexts, shareBrowserContext)=>{
3274
+ const resolvedTargets = allContexts.map((context)=>({
3275
+ context,
3276
+ target: resolveBatchRuntimeTarget(context.executionConfig)
3277
+ }));
3278
+ if (shareBrowserContext) {
3279
+ const unsupported = resolvedTargets.find(({ target })=>target && 'puppeteer-web' !== target);
3280
+ if (unsupported?.target) throw new Error(`shareBrowserContext only supports Puppeteer Web targets, but "${unsupported.context.file}" uses ${batchRuntimeTargetLabel[unsupported.target]}. Remove shareBrowserContext or use a Puppeteer Web target.`);
3281
+ const browserCreationOptions = [
3282
+ 'cdpEndpoint',
3283
+ 'chromeArgs',
3284
+ 'acceptInsecureCerts',
3285
+ 'downloadPath'
3286
+ ];
3287
+ for (const { context, target } of resolvedTargets){
3288
+ if ('puppeteer-web' !== target) continue;
3289
+ const fileWebConfig = resolveWebTarget(context.sourceConfig)?.target;
3290
+ const misplacedOptions = browserCreationOptions.filter((option)=>void 0 !== fileWebConfig?.[option]);
3291
+ if (misplacedOptions.length > 0) throw new Error(`shareBrowserContext creates one browser from the batch global config, so browser-level option(s) ${misplacedOptions.map((option)=>`"${option}"`).join(', ')} in "${context.file}" would be ignored. Move them to the batch config's global Web target.`);
3292
+ }
3293
+ }
3294
+ if (setupContext && !shareBrowserContext && 'puppeteer-web' === resolveBatchRuntimeTarget(setupContext.executionConfig)) throw new Error(`Puppeteer Web setup "${setupContext.file}" requires shareBrowserContext: true so its browser state can be shared with the main files.`);
3295
+ };
3296
+ const createSharedBrowserRuntime = async (browser, browserContextOptions, reusePage = false)=>{
3297
+ const browserContext = await browser.createBrowserContext(browserContextOptions);
3298
+ try {
3299
+ const page = reusePage ? await browserContext.newPage() : void 0;
3300
+ return {
3301
+ browserContext,
3302
+ page
3303
+ };
3304
+ } catch (error) {
3305
+ try {
3306
+ await browserContext.close();
3307
+ } catch (cleanupError) {
3308
+ batchWarning('failed to close the shared browser context after page creation failed; preserving the original error', cleanupError);
3309
+ }
3310
+ throw error;
3311
+ }
3312
+ };
3313
+ class YamlBatchExecutor {
3314
+ async run(options = {}) {
3315
+ const generateSummary = options.generateSummary ?? true;
3316
+ const shouldPrintExecutionPlan = options.printExecutionPlan ?? true;
3317
+ const { keepWindow, headed } = this.config;
3318
+ const setup = this.config.setup;
3319
+ if (shouldPrintExecutionPlan) printExecutionPlan(this.config);
3320
+ let setupContext;
3321
+ const fileContextList = [];
3322
+ let browser = null;
3323
+ const sharedRuntime = {
3324
+ current: null
3325
+ };
3326
+ let caseIndex = 0;
3327
+ let executionError;
3328
+ try {
3329
+ if (setup) {
3330
+ const fileConfig = await this.loadFileConfig(setup);
3331
+ setupContext = await this.createFileContext(setup, fileConfig, {
3332
+ headed,
3333
+ keepWindow
3334
+ }, this.caseIds[caseIndex++]);
3335
+ }
3336
+ for (const file of this.config.files){
3337
+ const fileConfig = await this.loadFileConfig(file);
3338
+ const context = await this.createFileContext(file, fileConfig, {
3339
+ headed,
3340
+ keepWindow
3341
+ }, this.caseIds[caseIndex++]);
3342
+ fileContextList.push(context);
3343
+ }
3344
+ if (setupContext) {
3345
+ const setupPath = external_node_path_resolve(setupContext.file);
3346
+ const conflict = fileContextList.find((ctx)=>external_node_path_resolve(ctx.file) === setupPath);
3347
+ if (conflict) throw new Error(`"${conflict.file}" is used as both the setup file and a main file; a yaml file cannot be both`);
3348
+ }
3349
+ const allContexts = setupContext ? [
3350
+ setupContext,
3351
+ ...fileContextList
3352
+ ] : fileContextList;
3353
+ assertBrowserContextUsage(setupContext, allContexts, this.config.shareBrowserContext);
3354
+ const needsBrowser = allContexts.some((ctx)=>void 0 !== resolveWebTarget(ctx.executionConfig));
3355
+ let resetSetupRuntime;
3356
+ if (needsBrowser && this.config.shareBrowserContext) {
3357
+ const globalWebConfig = resolveWebTarget(this.config.globalConfig ?? {})?.target;
3358
+ const downloadBehavior = buildDownloadBehavior(globalWebConfig?.downloadPath);
3359
+ const browserContextOptions = downloadBehavior ? {
3360
+ downloadBehavior
3361
+ } : void 0;
3362
+ if (globalWebConfig?.cdpEndpoint) browser = await puppeteer.connect({
3363
+ browserWSEndpoint: globalWebConfig.cdpEndpoint,
3364
+ defaultViewport: null,
3365
+ downloadBehavior
3366
+ });
3367
+ else {
3368
+ const width = globalWebConfig?.viewportWidth ?? defaultViewportWidth;
3369
+ const height = globalWebConfig?.viewportHeight ?? defaultViewportHeight;
3370
+ const args = buildChromeArgs({
3371
+ userAgent: globalWebConfig?.userAgent,
3372
+ windowSize: headed ? {
3373
+ width,
3374
+ height
3375
+ } : void 0,
3376
+ chromeArgs: globalWebConfig?.chromeArgs
3377
+ });
3378
+ browser = await puppeteer.launch({
3379
+ headless: !headed,
3380
+ defaultViewport: headed ? null : {
3381
+ width,
3382
+ height
3383
+ },
3384
+ downloadBehavior,
3385
+ args,
3386
+ acceptInsecureCerts: globalWebConfig?.acceptInsecureCerts
3387
+ });
3388
+ }
3389
+ resetSetupRuntime = async ()=>{
3390
+ if (!browser) throw new Error('Cannot create a shared runtime without a browser');
3391
+ if (sharedRuntime.current) {
3392
+ const staleRuntime = sharedRuntime.current;
3393
+ sharedRuntime.current = null;
3394
+ await staleRuntime.browserContext.close();
3395
+ }
3396
+ sharedRuntime.current = await createSharedBrowserRuntime(browser, browserContextOptions, this.config.reusePage);
3397
+ for (const context of allContexts){
3398
+ context.options.browser = browser;
3399
+ context.options.browserContext = sharedRuntime.current.browserContext;
3400
+ if (sharedRuntime.current.page) context.options.page = sharedRuntime.current.page;
3401
+ }
3402
+ };
3403
+ await resetSetupRuntime();
3404
+ }
3405
+ const { executedResults, unexpectedResults, notExecutedContexts, unexpectedError } = await this.executeFiles(setupContext, fileContextList, {
3406
+ onProgress: options.onProgress,
3407
+ resetSetupRuntime
3408
+ });
3409
+ this.results = await this.processResults(executedResults, unexpectedResults, notExecutedContexts);
3410
+ executionError = unexpectedError;
3411
+ } catch (error) {
3412
+ executionError = error;
3413
+ } finally{
3414
+ if (browser && !this.config.keepWindow) {
3415
+ try {
3416
+ if (sharedRuntime.current) {
3417
+ await sharedRuntime.current.browserContext.close();
3418
+ sharedRuntime.current = null;
3419
+ }
3420
+ } catch (error) {
3421
+ if (executionError) batchWarning('failed to close the shared browser context after execution had already failed; preserving the original error', error);
3422
+ else executionError = error;
3423
+ }
3424
+ try {
3425
+ const isCdp = !!resolveWebTarget(this.config.globalConfig ?? {})?.target.cdpEndpoint;
3426
+ if (isCdp) browser.disconnect();
3427
+ else await browser.close();
3428
+ } catch (error) {
3429
+ if (executionError) batchWarning('failed to clean up the shared browser after execution had already failed; preserving the original error', error);
3430
+ else executionError = error;
3431
+ }
3432
+ }
3433
+ if (generateSummary) await this.generateOutputIndex();
3434
+ }
3435
+ if (executionError) throw new YamlBatchExecutionError(executionError, this.results);
3436
+ return this.results;
3437
+ }
3438
+ async createFileContext(file, fileConfig, options, caseId) {
3439
+ const { globalConfig } = this.config;
3440
+ const clonedFileConfig = JSON.parse(JSON.stringify(fileConfig));
3441
+ const executionConfig = lodash_merge(clonedFileConfig, globalConfig);
3442
+ return {
3443
+ caseId,
3444
+ file,
3445
+ sourceConfig: fileConfig,
3446
+ executionConfig,
3447
+ options
3448
+ };
3449
+ }
3450
+ async executeFiles(setupContext, fileContextList, options) {
3451
+ const { onProgress, resetSetupRuntime } = options;
3452
+ const executedResults = [];
3453
+ const unexpectedResults = [];
3454
+ const notExecutedContexts = [];
3455
+ const allFileContexts = [];
3456
+ const fileContextsByCaseId = new Map();
3457
+ const createFilePlayerContext = async (context)=>{
3458
+ const fileContext = {
3459
+ file: context.file,
3460
+ player: await createYamlPlayer(context.file, context.executionConfig, context.options)
3461
+ };
3462
+ fileContextsByCaseId.set(context.caseId, fileContext);
3463
+ return fileContext;
3464
+ };
3465
+ const initialContexts = setupContext ? [
3466
+ setupContext
3467
+ ] : fileContextList;
3468
+ for (const context of initialContexts)allFileContexts.push(await createFilePlayerContext(context));
3469
+ let ttyRenderer;
3470
+ if (isTTY && !onProgress) {
3471
+ const summaryContents = ()=>{
3472
+ const summary = [
3473
+ ''
3474
+ ];
3475
+ for (const context of allFileContexts)summary.push(contextTaskListSummary(context.player.taskStatusList, context));
3476
+ summary.push('');
3477
+ return summary;
3478
+ };
3479
+ ttyRenderer = new TTYWindowRenderer({
3480
+ outputStream: process.stdout,
3481
+ errorStream: process.stderr,
3482
+ getWindow: summaryContents,
3483
+ interval: spinnerInterval
3484
+ });
3485
+ ttyRenderer.start();
3486
+ }
3487
+ const reportProgressSnapshot = (context, attempt, totalAttempts)=>{
3488
+ const summary = contextTaskListSummary(context.player.taskStatusList, context);
3489
+ onProgress?.(formatYamlProgressSnapshot(summary, attempt, totalAttempts));
3490
+ };
3491
+ let unexpectedError;
3492
+ try {
3493
+ const executeFile = async (context, beforeRetry)=>{
3494
+ const allFileContext = fileContextsByCaseId.get(context.caseId);
3495
+ let lastAttemptStartTime;
3496
+ try {
3497
+ if (!allFileContext) throw new Error(`Player not found for file: ${context.file}`);
3498
+ const totalAttempts = resolveYamlMaxAttempts(this.config.retry);
3499
+ const attempts = [];
3500
+ let executedContext;
3501
+ for(let attempt = 1; attempt <= totalAttempts; attempt++){
3502
+ if (attempt > 1) {
3503
+ if (context.executionConfig.agent?.reportFileName) attempts[attempts.length - 1] = preserveYamlAttemptReport(attempts[attempts.length - 1]);
3504
+ await beforeRetry?.();
3505
+ allFileContext.player = await createYamlPlayer(context.file, context.executionConfig, context.options);
3506
+ }
3507
+ if (onProgress) reportProgressSnapshot(allFileContext, attempt, totalAttempts);
3508
+ else if (!isTTY) {
3509
+ const { mergedText } = contextInfo(allFileContext);
3510
+ console.log(mergedText);
3511
+ }
3512
+ if (context.outputPath) allFileContext.player.output = context.outputPath;
3513
+ const startTime = Date.now();
3514
+ lastAttemptStartTime = startTime;
3515
+ await allFileContext.player.run();
3516
+ const duration = Date.now() - startTime;
3517
+ const attemptResult = createExecutedYamlResult({
3518
+ file: context.file,
3519
+ player: allFileContext.player,
3520
+ duration
3521
+ });
3522
+ attempts.push(createYamlAttempt(attemptResult, attempt));
3523
+ const totalDuration = getYamlAttemptsDuration(attempts);
3524
+ const yamlResult = {
3525
+ ...attemptResult,
3526
+ duration: totalDuration,
3527
+ attempts: [
3528
+ ...attempts
3529
+ ]
3530
+ };
3531
+ executedContext = {
3532
+ caseId: context.caseId,
3533
+ file: context.file,
3534
+ player: allFileContext.player,
3535
+ duration: totalDuration,
3536
+ yamlResult
3537
+ };
3538
+ if (onProgress) reportProgressSnapshot(executedContext, attempt, totalAttempts);
3539
+ else if (!isTTY) console.log(contextTaskListSummary(allFileContext.player.taskStatusList, executedContext));
3540
+ if (yamlResult.success) break;
3541
+ }
3542
+ if (!executedContext) throw new Error(`No attempts executed for file: ${context.file}`);
3543
+ return {
3544
+ kind: 'executed',
3545
+ context: executedContext
3546
+ };
3547
+ } catch (error) {
3548
+ const normalizedError = normalizeExecutionError(error);
3549
+ return {
3550
+ kind: 'unexpected',
3551
+ context: {
3552
+ caseId: context.caseId,
3553
+ file: context.file,
3554
+ error: normalizedError,
3555
+ yamlResult: createUnexpectedYamlResult({
3556
+ file: context.file,
3557
+ error: normalizedError,
3558
+ duration: void 0 === lastAttemptStartTime ? 0 : Date.now() - lastAttemptStartTime,
3559
+ player: allFileContext?.player
3560
+ })
3561
+ }
3562
+ };
3563
+ }
3564
+ };
3565
+ let setupFailed = false;
3566
+ if (setupContext) {
3567
+ const outcome = await executeFile(setupContext, resetSetupRuntime);
3568
+ if ('unexpected' === outcome.kind) {
3569
+ unexpectedResults.push(outcome.context);
3570
+ unexpectedError = outcome.context.error;
3571
+ setupFailed = true;
3572
+ } else {
3573
+ executedResults.push(outcome.context);
3574
+ setupFailed = !outcome.context.yamlResult.success;
3575
+ }
3576
+ }
3577
+ if (setupFailed) for (const context of fileContextList)notExecutedContexts.push({
3578
+ caseId: context.caseId,
3579
+ file: context.file,
3580
+ player: null
3581
+ });
3582
+ else {
3583
+ if (setupContext) for (const context of fileContextList)allFileContexts.push(await createFilePlayerContext(context));
3584
+ unexpectedError = await this.executeConcurrently(fileContextList, executeFile, executedResults, unexpectedResults, notExecutedContexts);
3585
+ }
3586
+ if (!isTTY && !onProgress) {
3587
+ console.log('\n📋 Execution Results:');
3588
+ for (const context of executedResults)console.log(contextTaskListSummary(context.player.taskStatusList, context));
3589
+ }
3590
+ } finally{
3591
+ if (ttyRenderer) ttyRenderer.stop();
3592
+ }
3593
+ return {
3594
+ executedResults,
3595
+ unexpectedResults,
3596
+ notExecutedContexts,
3597
+ unexpectedError
3598
+ };
3599
+ }
3600
+ async executeConcurrently(fileContextList, executeFile, executedResults, unexpectedResults, notExecutedContexts) {
3601
+ const limit = pLimit(this.config.concurrent);
3602
+ let unexpectedError;
3603
+ const recordOutcome = (outcome)=>{
3604
+ if ('unexpected' === outcome.kind) {
3605
+ unexpectedResults.push(outcome.context);
3606
+ unexpectedError ??= outcome.context.error;
3607
+ } else executedResults.push(outcome.context);
3608
+ };
3609
+ if (this.config.continueOnError) {
3610
+ const tasks = fileContextList.map((context)=>limit(async ()=>{
3611
+ recordOutcome(await executeFile(context));
3612
+ }));
3613
+ await Promise.all(tasks);
3614
+ } else {
3615
+ let shouldStop = false;
3616
+ const stopLock = {
3617
+ value: false
3618
+ };
3619
+ const tasks = fileContextList.map((context)=>limit(async ()=>{
3620
+ if (stopLock.value) return void notExecutedContexts.push({
3621
+ caseId: context.caseId,
3622
+ file: context.file,
3623
+ player: null
3624
+ });
3625
+ const outcome = await executeFile(context);
3626
+ recordOutcome(outcome);
3627
+ if (('unexpected' === outcome.kind || !outcome.context.yamlResult.success) && !stopLock.value) {
3628
+ stopLock.value = true;
3629
+ shouldStop = true;
3630
+ }
3631
+ }));
3632
+ await Promise.all(tasks);
3633
+ if (shouldStop) {
3634
+ for (const context of fileContextList)if (!executedResults.some((r)=>r.caseId === context.caseId) && !unexpectedResults.some((r)=>r.caseId === context.caseId) && !notExecutedContexts.some((ctx)=>ctx.caseId === context.caseId)) notExecutedContexts.push({
3635
+ caseId: context.caseId,
3636
+ file: context.file,
3637
+ player: null
3638
+ });
3639
+ }
3640
+ }
3641
+ return unexpectedError;
3642
+ }
3643
+ async processResults(executedContexts, unexpectedContexts, notExecutedContexts) {
3644
+ const resultsByCaseId = new Map();
3645
+ for (const context of executedContexts)resultsByCaseId.set(context.caseId, context.yamlResult);
3646
+ for (const context of unexpectedContexts)resultsByCaseId.set(context.caseId, context.yamlResult);
3647
+ for (const context of notExecutedContexts)resultsByCaseId.set(context.caseId, createNotExecutedYamlResult(context.file));
3648
+ return this.caseIds.map((caseId)=>{
3649
+ const result = resultsByCaseId.get(caseId);
3650
+ if (!result) throw new Error(`Batch result missing for case ID: ${caseId}`);
3651
+ return {
3652
+ caseId,
3653
+ result
3654
+ };
3655
+ });
3656
+ }
3657
+ async loadFileConfig(file) {
3658
+ const content = (0, __rspack_external_node_fs_5ea92f0c.readFileSync)(file, 'utf8');
3659
+ return parseYamlScript(content, file);
3660
+ }
3661
+ async generateOutputIndex() {
3662
+ try {
3663
+ writeExecutionSummaryFile(this.config.summary, this.results.map(({ result })=>result));
3664
+ printExecutionFinished();
3665
+ } catch (error) {
3666
+ console.error('Failed to generate output index:', error);
3667
+ }
3668
+ }
3669
+ constructor(config, caseIds){
3670
+ yaml_batch_executor_define_property(this, "config", void 0);
3671
+ yaml_batch_executor_define_property(this, "caseIds", void 0);
3672
+ yaml_batch_executor_define_property(this, "results", []);
3673
+ this.config = config;
3674
+ const occurrenceCount = config.files.length + (config.setup ? 1 : 0);
3675
+ this.caseIds = caseIds ?? Array.from({
3676
+ length: occurrenceCount
3677
+ }, (_, index)=>`batch-occurrence-${index + 1}`);
3678
+ if (this.caseIds.length !== occurrenceCount) throw new Error(`Batch occurrence identity mismatch: expected ${occurrenceCount} case ID(s), received ${this.caseIds.length}`);
3679
+ if (new Set(this.caseIds).size !== this.caseIds.length) throw new Error('Batch occurrence case IDs must be unique');
3680
+ if (config.reusePage && !config.shareBrowserContext) throw new Error('reusePage requires shareBrowserContext: true');
3681
+ if (config.reusePage && 1 !== config.concurrent) throw new Error('reusePage requires concurrent: 1');
3682
+ }
3683
+ }
3684
+ async function runYamlBatch(config, options = {}) {
3685
+ const results = await new YamlBatchExecutor(config).run(options);
3686
+ return results.map(({ result })=>result);
3687
+ }
3688
+ async function runYamlBatchWithCaseIds(config, caseIds, options = {}) {
3689
+ return new YamlBatchExecutor(config, caseIds).run(options);
3690
+ }
3691
+ function batch_runner_define_property(obj, key, value) {
3692
+ if (key in obj) Object.defineProperty(obj, key, {
3693
+ value: value,
3694
+ enumerable: true,
3695
+ configurable: true,
3696
+ writable: true
3697
+ });
3698
+ else obj[key] = value;
3699
+ return obj;
3700
+ }
3701
+ class BatchRunner {
3702
+ async run(options = {}) {
3703
+ this.results = [];
3704
+ try {
3705
+ this.results = await runYamlBatch(this.config, options);
3706
+ return this.results;
3707
+ } catch (error) {
3708
+ if (isYamlBatchExecutionError(error)) this.results = [
3709
+ ...error.results
3710
+ ];
3711
+ throw error;
3712
+ }
3713
+ }
3714
+ getExecutionSummary() {
3715
+ return getExecutionSummary(this.results);
3716
+ }
3717
+ getFailedFiles() {
3718
+ return getResultFilesByType(this.results, 'failed');
3719
+ }
3720
+ getPartialFailedFiles() {
3721
+ return getResultFilesByType(this.results, 'partialFailed');
3722
+ }
3723
+ getNotExecutedFiles() {
3724
+ return getResultFilesByType(this.results, 'notExecuted');
3725
+ }
3726
+ getSuccessfulFiles() {
3727
+ return getResultFilesByType(this.results, 'success');
3728
+ }
3729
+ getResults() {
3730
+ return [
3731
+ ...this.results
3732
+ ];
3733
+ }
3734
+ printExecutionSummary() {
3735
+ return printExecutionSummary(this.results, getSummaryAbsolutePath(this.config.summary));
3736
+ }
3737
+ constructor(config){
3738
+ batch_runner_define_property(this, "config", void 0);
3739
+ batch_runner_define_property(this, "results", void 0);
3740
+ this.config = config;
3741
+ this.results = [];
3742
+ }
3743
+ }
3744
+ const requireFromCliPackage = ()=>{
3745
+ if ("u" > typeof __dirname) return createRequire(join(__dirname, 'index.js'));
3746
+ const entry = process.argv[1] ? external_node_path_resolve(process.argv[1]) : join(process.cwd(), 'midscene-cli.js');
3747
+ return createRequire(entry);
3748
+ };
3749
+ const resolvePackageFromRstestCore = (packageName)=>{
3750
+ const require = requireFromCliPackage();
3751
+ const rstestPackageJsonPath = require.resolve('@rstest/core/package.json');
3752
+ return createRequire(rstestPackageJsonPath).resolve(packageName);
3753
+ };
3754
+ function resolveRstestCoreImportPath() {
3755
+ const require = requireFromCliPackage();
3756
+ return require.resolve('@rstest/core');
3757
+ }
3758
+ const DEFAULT_YAML_TEST_TIMEOUT = 0;
3759
+ const RSTEST_YAML_BATCH_TEST_MODULE = 'virtual:midscene-yaml/batch.test.ts';
3760
+ const RSTEST_YAML_BATCH_TEST_NAME = 'midscene yaml batch';
3761
+ const RSTEST_YAML_SEQUENTIAL_TEST_MODULE = 'virtual:midscene-yaml/sequential.test.ts';
3762
+ const toPosixPath = (value)=>value.split(sep).join('/');
3763
+ const toImportLiteral = (value)=>JSON.stringify(toPosixPath(value));
3764
+ const toVirtualModuleId = (fileStem)=>`virtual:midscene-yaml/${fileStem}.test.ts`;
3765
+ const safeFileStem = (file, index)=>{
3766
+ const base = basename(file, extname(file)).replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
3767
+ return `${String(index + 1).padStart(3, '0')}-${base || 'case'}`;
3768
+ };
3769
+ const resolveTestName = (projectDir, yamlFile)=>{
3770
+ const relativePath = relative(projectDir, yamlFile);
3771
+ return toPosixPath(relativePath.startsWith('..') ? yamlFile : relativePath);
3772
+ };
3773
+ const createGeneratedCaseTestContent = (options)=>`import { test } from ${toImportLiteral(options.rstestCoreImport)};
3774
+ import { defineYamlCaseTest } from ${toImportLiteral(options.frameworkImport)};
3775
+
3776
+ const testOptionsList = ${JSON.stringify(options.testOptions, null, 2)};
3777
+
3778
+ for (const testOptions of testOptionsList) {
3779
+ defineYamlCaseTest(${options.sequential ? 'test.sequential' : 'test'}, testOptions);
3780
+ }
3781
+ `;
3782
+ const createGeneratedBatchTestContent = (options)=>`import { test } from ${toImportLiteral(options.rstestCoreImport)};
3783
+ import { defineYamlBatchTest } from ${toImportLiteral(options.frameworkImport)};
3784
+
3785
+ const testOptions = ${JSON.stringify(options.testOptions, null, 2)};
3786
+
3787
+ defineYamlBatchTest(test, testOptions);
3788
+ `;
3789
+ const resolveDefaultFrameworkImport = (moduleDir)=>{
3790
+ const anchorDir = moduleDir ?? ("u" > typeof __dirname ? __dirname : void 0);
3791
+ const candidates = [
3792
+ anchorDir ? join(anchorDir, 'framework', 'index.js') : ''
3793
+ ];
3794
+ const entry = process.argv[1] ? external_node_path_resolve(process.argv[1]) : '';
3795
+ if (entry) {
3796
+ candidates.push(join(dirname(entry), 'framework', 'index.js'));
3797
+ candidates.push(join(dirname(entry), '..', 'dist', 'lib', 'framework', 'index.js'));
3798
+ }
3799
+ const matched = candidates.filter(Boolean).find((candidate)=>(0, __rspack_external_node_fs_5ea92f0c.existsSync)(candidate));
3800
+ return matched || '@midscene/cli/dist/lib/framework/index.js';
3801
+ };
3802
+ function createRstestYamlProject(options) {
3803
+ const projectDir = external_node_path_resolve(options.projectDir || process.cwd());
3804
+ const outputDir = options.outputDir || join(getMidsceneRunSubDir('tmp'), `rstest-yaml-${Date.now()}`);
3805
+ const resultDir = options.resultDir || join(outputDir, 'results');
3806
+ const frameworkImport = options.frameworkImport || resolveDefaultFrameworkImport();
3807
+ const rstestCoreImport = options.rstestCoreImport || resolveRstestCoreImportPath();
3808
+ const testTimeout = options.testTimeout ?? DEFAULT_YAML_TEST_TIMEOUT;
3809
+ (0, __rspack_external_node_fs_5ea92f0c.rmSync)(outputDir, {
3810
+ recursive: true,
3811
+ force: true
3812
+ });
3813
+ (0, __rspack_external_node_fs_5ea92f0c.mkdirSync)(resultDir, {
3814
+ recursive: true
3815
+ });
3816
+ const resultYamlFiles = options.batchConfig ? [
3817
+ ...options.batchConfig.setup ? [
3818
+ options.batchConfig.setup
3819
+ ] : [],
3820
+ ...options.batchConfig.files
3821
+ ] : options.files;
3822
+ const cases = resultYamlFiles.map((file, index)=>{
3823
+ const yamlFile = external_node_path_resolve(file);
3824
+ const testName = resolveTestName(projectDir, yamlFile);
3825
+ const caseId = safeFileStem(yamlFile, index);
3826
+ const resultFile = join(resultDir, `${caseId}.json`);
3827
+ return {
3828
+ caseId,
3829
+ yamlFile,
3830
+ resultFile,
3831
+ testName,
3832
+ retry: options.retry,
3833
+ ...options.caseOptions?.[yamlFile] ? {
3834
+ caseOptions: options.caseOptions[yamlFile]
3835
+ } : {},
3836
+ ...options.webRuntimeOptions?.[yamlFile] ? {
3837
+ webRuntimeOptions: options.webRuntimeOptions[yamlFile]
3838
+ } : {}
3839
+ };
3840
+ });
3841
+ const baseProject = {
3842
+ projectDir,
3843
+ outputDir,
3844
+ resultDir,
3845
+ cases,
3846
+ testTimeout,
3847
+ bail: options.bail
3848
+ };
3849
+ if (options.batchConfig) {
3850
+ const testOptions = {
3851
+ caseIds: cases.map((item)=>item.caseId),
3852
+ testName: RSTEST_YAML_BATCH_TEST_NAME,
3853
+ config: options.batchConfig,
3854
+ resultTargets: cases.map(({ caseId, yamlFile, resultFile })=>({
3855
+ caseId,
3856
+ yamlFile,
3857
+ resultFile
3858
+ }))
3859
+ };
3860
+ return {
3861
+ ...baseProject,
3862
+ modules: [
3863
+ {
3864
+ id: RSTEST_YAML_BATCH_TEST_MODULE,
3865
+ caseIds: testOptions.caseIds,
3866
+ source: createGeneratedBatchTestContent({
3867
+ rstestCoreImport,
3868
+ frameworkImport,
3869
+ testOptions
3870
+ })
3871
+ }
3872
+ ],
3873
+ maxConcurrency: 1
3874
+ };
3875
+ }
3876
+ if (1 === options.maxConcurrency) {
3877
+ const caseIds = cases.map((item)=>item.caseId);
3878
+ return {
3879
+ ...baseProject,
3880
+ modules: [
3881
+ {
3882
+ id: RSTEST_YAML_SEQUENTIAL_TEST_MODULE,
3883
+ caseIds,
3884
+ source: createGeneratedCaseTestContent({
3885
+ rstestCoreImport,
3886
+ frameworkImport,
3887
+ testOptions: cases,
3888
+ sequential: true
3889
+ })
3890
+ }
3891
+ ],
3892
+ maxConcurrency: 1,
3893
+ retry: options.retry
3894
+ };
3895
+ }
3896
+ return {
3897
+ ...baseProject,
3898
+ modules: cases.map((item)=>{
3899
+ const id = toVirtualModuleId(item.caseId);
3900
+ return {
3901
+ id,
3902
+ caseIds: [
3903
+ item.caseId
3904
+ ],
3905
+ source: createGeneratedCaseTestContent({
3906
+ rstestCoreImport,
3907
+ frameworkImport,
3908
+ testOptions: [
3909
+ item
3910
+ ],
3911
+ sequential: false
3912
+ })
3913
+ };
3914
+ }),
3915
+ maxConcurrency: options.maxConcurrency,
3916
+ retry: options.retry
3917
+ };
3918
+ }
3919
+ const yamlProgressLogPrefix = '__MIDSCENE_YAML_PROGRESS__:';
3920
+ const emitYamlProgress = (message)=>{
3921
+ console.log(`${yamlProgressLogPrefix}${message}`);
3922
+ };
3923
+ const createYamlProgressReporter = ()=>({
3924
+ onUserConsoleLog (log) {
3925
+ if (!log.content.startsWith(yamlProgressLogPrefix)) return;
3926
+ const message = log.content.slice(yamlProgressLogPrefix.length);
3927
+ console.log(message.replace(/\r?\n$/, ''));
3928
+ }
3929
+ });
3930
+ const RSTEST_YAML_CASE_IDS_META_KEY = 'midsceneYamlCaseIds';
3931
+ const formatRunError = (error)=>error.stack || `${error.name || 'Error'}: ${error.message}`;
3932
+ const collectRunErrors = (result)=>{
3933
+ const messages = [];
3934
+ const push = (error, label)=>{
3935
+ const formatted = formatRunError(error);
3936
+ messages.push(label ? `${label}: ${formatted}` : formatted);
3937
+ };
3938
+ for (const file of result.results){
3939
+ for (const error of file.errors ?? [])push(error, file.name || file.testPath);
3940
+ for (const testResult of file.results ?? [])for (const error of testResult.errors ?? [])push(error, testResult.name);
3941
+ }
3942
+ for (const error of result.unhandledErrors)push(error);
3943
+ return Array.from(new Set(messages));
3944
+ };
3945
+ const rstest_runner_errorMessage = (error)=>error.message || error.name || 'YAML case failed';
3946
+ const mapRunErrorsToCases = (project, result)=>{
3947
+ const knownCaseIds = new Set(project.cases.map((item)=>item.caseId));
3948
+ const errors = new Map();
3949
+ const add = (caseId, message)=>{
3950
+ if (knownCaseIds.has(caseId) && message && !errors.has(caseId)) errors.set(caseId, message);
3951
+ };
3952
+ const addCases = (caseIds, message)=>{
3953
+ for (const caseId of caseIds)add(caseId, message);
3954
+ };
3955
+ const findModuleCaseIds = (file)=>{
3956
+ for (const key of [
3957
+ file.name,
3958
+ file.testPath
3959
+ ]){
3960
+ if (!key) continue;
3961
+ const matched = project.modules.find((item)=>key === item.id || key.includes(item.id));
3962
+ if (matched) return matched.caseIds;
3963
+ }
3964
+ return [];
3965
+ };
3966
+ const metadataCaseIds = (testResult)=>{
3967
+ const value = testResult.meta?.[RSTEST_YAML_CASE_IDS_META_KEY];
3968
+ return Array.isArray(value) ? value.filter((item)=>'string' == typeof item) : [];
3969
+ };
3970
+ for (const file of result.results){
3971
+ const moduleCaseIds = findModuleCaseIds(file);
3972
+ for (const error of file.errors ?? [])addCases(moduleCaseIds, rstest_runner_errorMessage(error));
3973
+ for (const testResult of file.results ?? []){
3974
+ const caseIds = metadataCaseIds(testResult);
3975
+ for (const error of testResult.errors ?? [])addCases(caseIds.length ? caseIds : moduleCaseIds, rstest_runner_errorMessage(error));
3976
+ }
3977
+ }
3978
+ if (result.unhandledErrors.length) {
3979
+ const message = rstest_runner_errorMessage(result.unhandledErrors[0]);
3980
+ for (const item of project.cases)if (!errors.has(item.caseId) && !(0, __rspack_external_node_fs_5ea92f0c.existsSync)(item.resultFile)) errors.set(item.caseId, message);
3981
+ }
3982
+ return errors;
3983
+ };
3984
+ const writePendingCaseFailures = (project, caseErrors)=>{
3985
+ for (const item of project.cases){
3986
+ if ((0, __rspack_external_node_fs_5ea92f0c.existsSync)(item.resultFile)) continue;
3987
+ const error = caseErrors.get(item.caseId);
3988
+ if (!error) continue;
3989
+ const failure = {
3990
+ file: item.yamlFile,
3991
+ success: false,
3992
+ executed: true,
3993
+ output: void 0,
3994
+ report: void 0,
3995
+ duration: 0,
3996
+ resultType: 'failed',
3997
+ error
3998
+ };
3999
+ (0, __rspack_external_node_fs_5ea92f0c.mkdirSync)(dirname(item.resultFile), {
4000
+ recursive: true
4001
+ });
4002
+ (0, __rspack_external_node_fs_5ea92f0c.writeFileSync)(item.resultFile, JSON.stringify(failure, null, 2));
4003
+ }
4004
+ };
4005
+ async function runRstestYamlProject(options) {
4006
+ const [{ createRstest }, { rspack }] = await Promise.all([
4007
+ import("@rstest/core/api"),
4008
+ import(pathToFileURL(resolvePackageFromRstestCore('@rsbuild/core')).href)
4009
+ ]);
4010
+ const { project } = options;
4011
+ const maxConcurrency = void 0 !== project.maxConcurrency ? Math.max(1, project.maxConcurrency) : void 0;
4012
+ const config = {
4013
+ root: project.projectDir,
4014
+ include: project.modules.map((item)=>item.id),
4015
+ testEnvironment: 'node',
4016
+ testTimeout: project.testTimeout,
4017
+ ...void 0 !== maxConcurrency ? {
4018
+ maxConcurrency
4019
+ } : {},
4020
+ ...void 0 !== maxConcurrency ? {
4021
+ pool: {
4022
+ maxWorkers: maxConcurrency
4023
+ }
4024
+ } : {},
4025
+ ...void 0 !== project.bail ? {
4026
+ bail: project.bail
4027
+ } : {},
4028
+ ...void 0 !== project.retry && project.retry > 0 ? {
4029
+ retry: project.retry
4030
+ } : {},
4031
+ reporters: 'pipe' === options.stdio ? [] : [
4032
+ createYamlProgressReporter()
4033
+ ],
4034
+ tools: {
4035
+ rspack: (_config, { appendPlugins })=>{
4036
+ appendPlugins(new rspack.experiments.VirtualModulesPlugin(Object.fromEntries(project.modules.map((item)=>[
4037
+ item.id,
4038
+ item.source
4039
+ ]))));
4040
+ }
4041
+ }
4042
+ };
4043
+ let result;
4044
+ try {
4045
+ const rstest = await createRstest({
4046
+ cwd: options.cwd || project.projectDir,
4047
+ config
4048
+ });
4049
+ result = await rstest.run();
4050
+ } catch (error) {
4051
+ const serialized = serializeError(error);
4052
+ writePendingCaseFailures(project, new Map(project.cases.map((item)=>[
4053
+ item.caseId,
4054
+ serialized.message
4055
+ ])));
4056
+ if ('pipe' !== options.stdio) console.error(`\nYAML execution failed:\n${formatRunError(serialized)}`);
4057
+ return 1;
4058
+ }
4059
+ const ok = 'pass' === result.status;
4060
+ if (!ok) {
4061
+ writePendingCaseFailures(project, mapRunErrorsToCases(project, result));
4062
+ if ('pipe' !== options.stdio) {
4063
+ const runErrors = collectRunErrors(result);
4064
+ if (runErrors.length) console.error(`\nYAML execution failed:\n${runErrors.join('\n\n')}`);
4065
+ }
4066
+ }
4067
+ return ok ? 0 : 1;
4068
+ }
4069
+ const defaultInProcessRunner = (config)=>new BatchRunner(config).run();
4070
+ async function runConfigInMainProcess(config, commandOptions) {
4071
+ const runner = commandOptions.inProcessRunner ?? defaultInProcessRunner;
4072
+ const results = await runner(config);
4073
+ const success = printExecutionSummary(results, getSummaryAbsolutePath(config.summary));
4074
+ return success ? 0 : 1;
4075
+ }
4076
+ const createCaseOptions = (config)=>{
4077
+ const caseOptions = {};
4078
+ for (const file of config.files)caseOptions[external_node_path_resolve(file)] = {
4079
+ globalConfig: config.globalConfig
4080
+ };
4081
+ return caseOptions;
4082
+ };
4083
+ const createWebRuntimeOptions = (config, runtimeOptions)=>{
4084
+ const caseOptions = {};
4085
+ for (const file of config.files)caseOptions[external_node_path_resolve(file)] = {
4086
+ headed: runtimeOptions.headed ?? config.headed,
4087
+ keepWindow: runtimeOptions.keepWindow ?? config.keepWindow
4088
+ };
4089
+ return caseOptions;
4090
+ };
4091
+ const readProjectResults = (project)=>project.cases.map((item)=>{
4092
+ if ((0, __rspack_external_node_fs_5ea92f0c.existsSync)(item.resultFile)) return JSON.parse((0, __rspack_external_node_fs_5ea92f0c.readFileSync)(item.resultFile, 'utf8'));
4093
+ return createNotExecutedYamlResult(item.yamlFile);
4094
+ });
4095
+ async function runFrameworkTestConfig(config, commandOptions = {}) {
4096
+ if (config.keepWindow) return runConfigInMainProcess(config, commandOptions);
4097
+ printExecutionPlan(config);
4098
+ const projectDir = external_node_path_resolve(commandOptions.projectDir || process.cwd());
4099
+ const project = createRstestYamlProject({
4100
+ files: config.files,
4101
+ projectDir,
4102
+ outputDir: commandOptions.outputDir,
4103
+ frameworkImport: commandOptions.frameworkImport,
4104
+ caseOptions: createCaseOptions(config),
4105
+ webRuntimeOptions: createWebRuntimeOptions(config, commandOptions),
4106
+ maxConcurrency: commandOptions.concurrent ?? config.concurrent,
4107
+ bail: config.continueOnError ? 0 : 1,
4108
+ retry: config.retry,
4109
+ batchConfig: config.shareBrowserContext || config.setup ? config : void 0
4110
+ });
4111
+ const runner = commandOptions.rstestRunner || runRstestYamlProject;
4112
+ const exitCode = await runner({
4113
+ project,
4114
+ cwd: projectDir,
4115
+ stdio: commandOptions.stdio
4116
+ });
4117
+ const results = readProjectResults(project);
4118
+ const summaryPath = writeExecutionSummaryFile(config.summary, results);
4119
+ printExecutionFinished();
4120
+ const success = printExecutionSummary(results, summaryPath);
4121
+ return success ? exitCode : 1;
4122
+ }
4123
+ const writeResultFile = (resultFile, data)=>{
4124
+ (0, __rspack_external_node_fs_5ea92f0c.mkdirSync)(dirname(resultFile), {
4125
+ recursive: true
4126
+ });
4127
+ (0, __rspack_external_node_fs_5ea92f0c.writeFileSync)(resultFile, JSON.stringify(data, null, 2));
4128
+ };
4129
+ const batchFailureMessage = (results)=>{
4130
+ const failed = results.filter((result)=>!result.success);
4131
+ return failed.map((result)=>`${result.file}: ${result.error || result.resultType}`).join('\n');
4132
+ };
4133
+ async function runYamlBatchInRstest(options) {
4134
+ const resultTargetsByCaseId = new Map();
4135
+ for (const target of options.resultTargets){
4136
+ if (resultTargetsByCaseId.has(target.caseId)) throw new Error(`Duplicate batch result target case ID: ${target.caseId}`);
4137
+ resultTargetsByCaseId.set(target.caseId, target);
4138
+ }
4139
+ let executionError;
4140
+ let occurrenceResults;
4141
+ try {
4142
+ occurrenceResults = await runYamlBatchWithCaseIds(options.config, options.resultTargets.map(({ caseId })=>caseId), {
4143
+ generateSummary: false,
4144
+ printExecutionPlan: false,
4145
+ onProgress: emitYamlProgress
4146
+ });
4147
+ } catch (error) {
4148
+ if (!isYamlBatchExecutionError(error)) throw error;
4149
+ executionError = error;
4150
+ occurrenceResults = error.occurrences;
4151
+ }
4152
+ const unmappedResults = [];
4153
+ for (const { caseId, result } of occurrenceResults){
4154
+ const target = resultTargetsByCaseId.get(caseId);
4155
+ if (!target || external_node_path_resolve(target.yamlFile) !== external_node_path_resolve(result.file)) {
4156
+ unmappedResults.push(caseId);
4157
+ continue;
4158
+ }
4159
+ writeResultFile(target.resultFile, result);
4160
+ resultTargetsByCaseId.delete(caseId);
4161
+ }
4162
+ if (executionError) throw executionError;
4163
+ const unwrittenTargets = Array.from(resultTargetsByCaseId.keys());
4164
+ if (unmappedResults.length || unwrittenTargets.length) throw new Error(`Batch result mapping mismatch: ${unmappedResults.length} result(s) had no target and ${unwrittenTargets.length} target(s) had no result`);
4165
+ const results = occurrenceResults.map(({ result })=>result);
4166
+ if (results.some((result)=>!result.success)) throw new Error(batchFailureMessage(results));
4167
+ return results;
4168
+ }
4169
+ const taskErrorMessage = (task)=>{
4170
+ if (task.error?.message) return task.error.message;
4171
+ if ('error' === task.status) return `Task "${task.name}" failed`;
4172
+ };
4173
+ const cloneJson = (value)=>JSON.parse(JSON.stringify(value));
4174
+ const yaml_case_errorMessageOf = (error)=>error instanceof Error ? error.message : String(error);
4175
+ const normalizeTargetConfig = (config)=>{
4176
+ if (config.target) {
4177
+ config.web = {
4178
+ ...config.target,
4179
+ ...config.web
4180
+ };
4181
+ config.target = void 0;
4182
+ }
4183
+ };
4184
+ const createExecutionConfig = (file, globalConfig)=>{
4185
+ const content = (0, __rspack_external_node_fs_5ea92f0c.readFileSync)(file, 'utf8');
4186
+ const fileConfig = cloneJson(parseYamlScript(content, file));
4187
+ normalizeTargetConfig(fileConfig);
4188
+ const clonedGlobalConfig = cloneJson(globalConfig);
4189
+ normalizeTargetConfig(clonedGlobalConfig);
4190
+ return lodash_merge(fileConfig, clonedGlobalConfig);
4191
+ };
4192
+ const getYamlPlayerFailure = (player)=>{
4193
+ if (player.errorInSetup) return player.errorInSetup;
4194
+ const failedMessages = player.taskStatusList?.map(taskErrorMessage).filter(Boolean) || [];
4195
+ if ('error' === player.status || failedMessages.length > 0) {
4196
+ const details = failedMessages.length ? failedMessages.join('; ') : 'YAML case failed';
4197
+ const reportLine = player.reportFile ? `\nReport: ${player.reportFile}` : '';
4198
+ const outputLine = player.output ? `\nOutput: ${player.output}` : '';
4199
+ return new Error(`${details}${reportLine}${outputLine}`);
4200
+ }
4201
+ };
4202
+ const createYamlCaseResult = (file, player, duration)=>{
4203
+ const hasFailedTasks = player.taskStatusList?.some((task)=>'error' === task.status) ?? false;
4204
+ const hasPlayerError = 'error' === player.status;
4205
+ const outputPath = player.output && (0, __rspack_external_node_fs_5ea92f0c.existsSync)(player.output) ? player.output : void 0;
4206
+ const reportFile = player.reportFile || void 0;
4207
+ let errorMessage;
4208
+ if (player.errorInSetup?.message) errorMessage = player.errorInSetup.message;
4209
+ else if (hasPlayerError || hasFailedTasks) {
4210
+ const taskErrors = player.taskStatusList?.filter((task)=>'error' === task.status && task.error?.message).map((task)=>task.error.message);
4211
+ errorMessage = taskErrors && taskErrors.length > 0 ? taskErrors.join('; ') : hasPlayerError ? 'Execution failed' : 'Some tasks failed';
4212
+ }
4213
+ const resultType = hasPlayerError ? 'failed' : hasFailedTasks ? 'partialFailed' : 'success';
4214
+ return {
4215
+ file,
4216
+ success: 'success' === resultType,
4217
+ executed: true,
4218
+ output: outputPath,
4219
+ report: reportFile,
4220
+ duration,
4221
+ resultType,
4222
+ error: errorMessage
4223
+ };
4224
+ };
4225
+ const createYamlCaseFailure = (result)=>{
4226
+ const reportLine = result.report ? `\nReport: ${result.report}` : '';
4227
+ const outputLine = result.output ? `\nOutput: ${result.output}` : '';
4228
+ return new Error(`${result.error || 'YAML case failed'}${reportLine}${outputLine}`);
4229
+ };
4230
+ const executeYamlCaseResult = async (options, onPlayerSnapshot)=>{
4231
+ const file = external_node_path_resolve(options.file);
4232
+ const startTime = Date.now();
4233
+ const executionConfig = options.executionConfig || (options.globalConfig ? createExecutionConfig(file, options.globalConfig) : void 0);
4234
+ const player = await createYamlPlayer(file, executionConfig, {
4235
+ headed: options.headed,
4236
+ keepWindow: options.keepWindow
4237
+ });
4238
+ const reportSnapshot = ()=>{
4239
+ onPlayerSnapshot?.({
4240
+ file,
4241
+ player
4242
+ });
4243
+ };
4244
+ reportSnapshot();
4245
+ let runError;
4246
+ try {
4247
+ await player.run();
4248
+ } catch (error) {
4249
+ runError = error;
4250
+ } finally{
4251
+ reportSnapshot();
4252
+ }
4253
+ const result = createYamlCaseResult(file, player, Date.now() - startTime);
4254
+ if (void 0 === runError) return result;
4255
+ return {
4256
+ ...result,
4257
+ success: false,
4258
+ resultType: 'failed',
4259
+ error: result.error ?? yaml_case_errorMessageOf(runError)
4260
+ };
4261
+ };
4262
+ function runYamlCaseResultWithSnapshots(options, onPlayerSnapshot) {
4263
+ return executeYamlCaseResult(options, onPlayerSnapshot);
4264
+ }
4265
+ function runYamlCaseResult(options) {
4266
+ return executeYamlCaseResult(options);
4267
+ }
4268
+ async function runYamlCase(options) {
4269
+ const result = await runYamlCaseResult(options);
4270
+ if (!result.success) throw createYamlCaseFailure(result);
4271
+ return {
4272
+ file: result.file,
4273
+ output: result.output || void 0,
4274
+ report: result.report,
4275
+ duration: result.duration || 0
4276
+ };
4277
+ }
4278
+ const rstest_entry_errorMessageOf = (error)=>error instanceof Error ? error.message : String(error);
4279
+ const rstest_entry_writeResultFile = (resultFile, data)=>{
4280
+ (0, __rspack_external_node_fs_5ea92f0c.mkdirSync)(dirname(resultFile), {
4281
+ recursive: true
4282
+ });
4283
+ (0, __rspack_external_node_fs_5ea92f0c.writeFileSync)(resultFile, JSON.stringify(data, null, 2));
4284
+ };
4285
+ const attemptHistoryFileFor = (resultFile)=>`${resultFile}.attempts.json`;
4286
+ const readAttemptHistory = (resultFile)=>{
4287
+ const attemptHistoryFile = attemptHistoryFileFor(resultFile);
4288
+ if (!(0, __rspack_external_node_fs_5ea92f0c.existsSync)(attemptHistoryFile)) return [];
4289
+ return JSON.parse((0, __rspack_external_node_fs_5ea92f0c.readFileSync)(attemptHistoryFile, 'utf8'));
4290
+ };
4291
+ const appendAttemptHistory = (resultFile, result, attempts)=>{
4292
+ const nextAttempts = [
4293
+ ...attempts,
4294
+ createYamlAttempt(result, attempts.length + 1)
4295
+ ];
4296
+ (0, __rspack_external_node_fs_5ea92f0c.mkdirSync)(dirname(resultFile), {
4297
+ recursive: true
4298
+ });
4299
+ (0, __rspack_external_node_fs_5ea92f0c.writeFileSync)(attemptHistoryFileFor(resultFile), JSON.stringify(nextAttempts, null, 2));
4300
+ return {
4301
+ ...result,
4302
+ duration: getYamlAttemptsDuration(nextAttempts),
4303
+ attempts: nextAttempts
4304
+ };
4305
+ };
4306
+ const hasExplicitReportFileName = (file, caseOptions)=>{
4307
+ if (caseOptions?.executionConfig) return Boolean(caseOptions.executionConfig.agent?.reportFileName);
4308
+ const script = parseYamlScript((0, __rspack_external_node_fs_5ea92f0c.readFileSync)(file, 'utf8'), file);
4309
+ return Boolean(script.agent?.reportFileName);
4310
+ };
4311
+ const prepareAttemptHistory = (resultFile, attempts, preserveReport)=>{
4312
+ if (!preserveReport || 0 === attempts.length) return attempts;
4313
+ const nextAttempts = [
4314
+ ...attempts
4315
+ ];
4316
+ nextAttempts[nextAttempts.length - 1] = preserveYamlAttemptReport(nextAttempts[nextAttempts.length - 1]);
4317
+ (0, __rspack_external_node_fs_5ea92f0c.writeFileSync)(attemptHistoryFileFor(resultFile), JSON.stringify(nextAttempts, null, 2));
4318
+ return nextAttempts;
4319
+ };
4320
+ const createRuntimeFailureResult = (file, startTime, error)=>({
4321
+ file,
4322
+ success: false,
4323
+ executed: true,
4324
+ duration: Date.now() - startTime,
4325
+ resultType: 'failed',
4326
+ error: rstest_entry_errorMessageOf(error)
4327
+ });
4328
+ const createYamlPlayerProgressReporter = (attempt, totalAttempts)=>({ file, player })=>{
4329
+ const summary = contextTaskListSummary(player.taskStatusList, {
4330
+ file,
4331
+ player
4332
+ });
4333
+ emitYamlProgress(formatYamlProgressSnapshot(summary, attempt, totalAttempts));
4334
+ };
4335
+ const defineYamlCaseTest = (test, options)=>{
4336
+ test(options.testName, {
4337
+ meta: {
4338
+ [RSTEST_YAML_CASE_IDS_META_KEY]: [
4339
+ options.caseId
4340
+ ]
4341
+ }
4342
+ }, async ()=>{
4343
+ const file = external_node_path_resolve(options.yamlFile);
4344
+ const startTime = Date.now();
4345
+ let attempts = readAttemptHistory(options.resultFile);
4346
+ const attempt = attempts.length + 1;
4347
+ const totalAttempts = resolveYamlMaxAttempts(options.retry);
4348
+ let result;
4349
+ try {
4350
+ if (attempt > 1) attempts = prepareAttemptHistory(options.resultFile, attempts, hasExplicitReportFileName(file, options.caseOptions));
4351
+ result = await runYamlCaseResultWithSnapshots({
4352
+ ...options.caseOptions,
4353
+ ...options.webRuntimeOptions,
4354
+ file
4355
+ }, createYamlPlayerProgressReporter(attempt, totalAttempts));
4356
+ result = appendAttemptHistory(options.resultFile, result, attempts);
4357
+ rstest_entry_writeResultFile(options.resultFile, result);
4358
+ if (!result.success) throw createYamlCaseFailure(result);
4359
+ } catch (error) {
4360
+ if (!result) {
4361
+ const failureResult = appendAttemptHistory(options.resultFile, createRuntimeFailureResult(file, startTime, error), attempts);
4362
+ rstest_entry_writeResultFile(options.resultFile, failureResult);
4363
+ }
4364
+ throw error;
4365
+ }
4366
+ });
4367
+ };
4368
+ const defineYamlBatchTest = (test, options)=>{
4369
+ test(options.testName, {
4370
+ meta: {
4371
+ [RSTEST_YAML_CASE_IDS_META_KEY]: options.caseIds
4372
+ }
4373
+ }, async ()=>{
4374
+ await runYamlBatchInRstest({
4375
+ config: options.config,
4376
+ resultTargets: options.resultTargets
4377
+ });
4378
+ });
4379
+ };
4380
+ export { __rspack_external_node_fs_5ea92f0c, basename, createReportCliCommands, createRstestYamlProject, createYamlCaseFailure, createYamlCaseResult, cwd, defineYamlBatchTest, defineYamlCaseTest, dirname, external_node_path_resolve, extname, fileURLToPath, getDebug, getYamlPlayerFailure, inspect, interpolateEnvVars, join, lodash_merge, midsceneYamlTargetKeys, posix, randomUUID, resolveRstestCoreImportPath, resolveTestName, resolveWebTarget, runFrameworkTestConfig, runRstestYamlProject, runYamlBatchInRstest, runYamlCase, runYamlCaseResult, win32 };
4381
+
4382
+ //# sourceMappingURL=998.mjs.map