@serwist/next 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,926 @@
1
+ import path from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { InjectManifest } from '@serwist/webpack-plugin';
4
+ import { ChildCompilationPlugin } from '@serwist/webpack-plugin/internal';
5
+ import { CleanWebpackPlugin } from 'clean-webpack-plugin';
6
+ import fg from 'fast-glob';
7
+ import crypto from 'node:crypto';
8
+ import fs from 'node:fs';
9
+ import { createRequire } from 'node:module';
10
+ import process from 'node:process';
11
+ import os from 'node:os';
12
+ import tty from 'node:tty';
13
+
14
+ /**
15
+ * Find the first truthy value in an array.
16
+ * @param arr
17
+ * @param fn
18
+ * @returns
19
+ */ const findFirstTruthy = (arr, fn)=>{
20
+ for (const i of arr){
21
+ const resolved = fn(i);
22
+ if (resolved) {
23
+ return resolved;
24
+ }
25
+ }
26
+ return undefined;
27
+ };
28
+
29
+ const getFileHash = (file)=>crypto.createHash("md5").update(fs.readFileSync(file)).digest("hex");
30
+
31
+ const getContentHash = (file, isDev)=>{
32
+ if (isDev) {
33
+ return "development";
34
+ }
35
+ return getFileHash(file).slice(0, 16);
36
+ };
37
+
38
+ createRequire(import.meta.url);
39
+
40
+ const loadTSConfig = (baseDir, relativeTSConfigPath)=>{
41
+ try {
42
+ // Find tsconfig.json file
43
+ const tsConfigPath = findFirstTruthy([
44
+ relativeTSConfigPath ?? "tsconfig.json",
45
+ "jsconfig.json"
46
+ ], (filePath)=>{
47
+ const resolvedPath = path.join(baseDir, filePath);
48
+ return fs.existsSync(resolvedPath) ? resolvedPath : undefined;
49
+ });
50
+ if (!tsConfigPath) {
51
+ return undefined;
52
+ }
53
+ // Read tsconfig.json file
54
+ const tsConfigFile = JSON.parse(fs.readFileSync(tsConfigPath, "utf-8"));
55
+ return tsConfigFile;
56
+ } catch {
57
+ return undefined;
58
+ }
59
+ };
60
+
61
+ const ANSI_BACKGROUND_OFFSET = 10;
62
+ const wrapAnsi16 = (offset = 0)=>(code)=>`\u001B[${code + offset}m`;
63
+ const wrapAnsi256 = (offset = 0)=>(code)=>`\u001B[${38 + offset};5;${code}m`;
64
+ const wrapAnsi16m = (offset = 0)=>(red, green, blue)=>`\u001B[${38 + offset};2;${red};${green};${blue}m`;
65
+ const styles$1 = {
66
+ modifier: {
67
+ reset: [
68
+ 0,
69
+ 0
70
+ ],
71
+ // 21 isn't widely supported and 22 does the same thing
72
+ bold: [
73
+ 1,
74
+ 22
75
+ ],
76
+ dim: [
77
+ 2,
78
+ 22
79
+ ],
80
+ italic: [
81
+ 3,
82
+ 23
83
+ ],
84
+ underline: [
85
+ 4,
86
+ 24
87
+ ],
88
+ overline: [
89
+ 53,
90
+ 55
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
+ // Bright color
139
+ blackBright: [
140
+ 90,
141
+ 39
142
+ ],
143
+ gray: [
144
+ 90,
145
+ 39
146
+ ],
147
+ grey: [
148
+ 90,
149
+ 39
150
+ ],
151
+ redBright: [
152
+ 91,
153
+ 39
154
+ ],
155
+ greenBright: [
156
+ 92,
157
+ 39
158
+ ],
159
+ yellowBright: [
160
+ 93,
161
+ 39
162
+ ],
163
+ blueBright: [
164
+ 94,
165
+ 39
166
+ ],
167
+ magentaBright: [
168
+ 95,
169
+ 39
170
+ ],
171
+ cyanBright: [
172
+ 96,
173
+ 39
174
+ ],
175
+ whiteBright: [
176
+ 97,
177
+ 39
178
+ ]
179
+ },
180
+ bgColor: {
181
+ bgBlack: [
182
+ 40,
183
+ 49
184
+ ],
185
+ bgRed: [
186
+ 41,
187
+ 49
188
+ ],
189
+ bgGreen: [
190
+ 42,
191
+ 49
192
+ ],
193
+ bgYellow: [
194
+ 43,
195
+ 49
196
+ ],
197
+ bgBlue: [
198
+ 44,
199
+ 49
200
+ ],
201
+ bgMagenta: [
202
+ 45,
203
+ 49
204
+ ],
205
+ bgCyan: [
206
+ 46,
207
+ 49
208
+ ],
209
+ bgWhite: [
210
+ 47,
211
+ 49
212
+ ],
213
+ // Bright color
214
+ bgBlackBright: [
215
+ 100,
216
+ 49
217
+ ],
218
+ bgGray: [
219
+ 100,
220
+ 49
221
+ ],
222
+ bgGrey: [
223
+ 100,
224
+ 49
225
+ ],
226
+ bgRedBright: [
227
+ 101,
228
+ 49
229
+ ],
230
+ bgGreenBright: [
231
+ 102,
232
+ 49
233
+ ],
234
+ bgYellowBright: [
235
+ 103,
236
+ 49
237
+ ],
238
+ bgBlueBright: [
239
+ 104,
240
+ 49
241
+ ],
242
+ bgMagentaBright: [
243
+ 105,
244
+ 49
245
+ ],
246
+ bgCyanBright: [
247
+ 106,
248
+ 49
249
+ ],
250
+ bgWhiteBright: [
251
+ 107,
252
+ 49
253
+ ]
254
+ }
255
+ };
256
+ Object.keys(styles$1.modifier);
257
+ const foregroundColorNames = Object.keys(styles$1.color);
258
+ const backgroundColorNames = Object.keys(styles$1.bgColor);
259
+ [
260
+ ...foregroundColorNames,
261
+ ...backgroundColorNames
262
+ ];
263
+ function assembleStyles() {
264
+ const codes = new Map();
265
+ for (const [groupName, group] of Object.entries(styles$1)){
266
+ for (const [styleName, style] of Object.entries(group)){
267
+ styles$1[styleName] = {
268
+ open: `\u001B[${style[0]}m`,
269
+ close: `\u001B[${style[1]}m`
270
+ };
271
+ group[styleName] = styles$1[styleName];
272
+ codes.set(style[0], style[1]);
273
+ }
274
+ Object.defineProperty(styles$1, groupName, {
275
+ value: group,
276
+ enumerable: false
277
+ });
278
+ }
279
+ Object.defineProperty(styles$1, 'codes', {
280
+ value: codes,
281
+ enumerable: false
282
+ });
283
+ styles$1.color.close = '\u001B[39m';
284
+ styles$1.bgColor.close = '\u001B[49m';
285
+ styles$1.color.ansi = wrapAnsi16();
286
+ styles$1.color.ansi256 = wrapAnsi256();
287
+ styles$1.color.ansi16m = wrapAnsi16m();
288
+ styles$1.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
289
+ styles$1.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
290
+ styles$1.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
291
+ // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js
292
+ Object.defineProperties(styles$1, {
293
+ rgbToAnsi256: {
294
+ value (red, green, blue) {
295
+ // We use the extended greyscale palette here, with the exception of
296
+ // black and white. normal palette only has 4 greyscale shades.
297
+ if (red === green && green === blue) {
298
+ if (red < 8) {
299
+ return 16;
300
+ }
301
+ if (red > 248) {
302
+ return 231;
303
+ }
304
+ return Math.round((red - 8) / 247 * 24) + 232;
305
+ }
306
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
307
+ },
308
+ enumerable: false
309
+ },
310
+ hexToRgb: {
311
+ value (hex) {
312
+ const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16));
313
+ if (!matches) {
314
+ return [
315
+ 0,
316
+ 0,
317
+ 0
318
+ ];
319
+ }
320
+ let [colorString] = matches;
321
+ if (colorString.length === 3) {
322
+ colorString = [
323
+ ...colorString
324
+ ].map((character)=>character + character).join('');
325
+ }
326
+ const integer = Number.parseInt(colorString, 16);
327
+ return [
328
+ /* eslint-disable no-bitwise */ integer >> 16 & 0xFF,
329
+ integer >> 8 & 0xFF,
330
+ integer & 0xFF
331
+ ];
332
+ },
333
+ enumerable: false
334
+ },
335
+ hexToAnsi256: {
336
+ value: (hex)=>styles$1.rgbToAnsi256(...styles$1.hexToRgb(hex)),
337
+ enumerable: false
338
+ },
339
+ ansi256ToAnsi: {
340
+ value (code) {
341
+ if (code < 8) {
342
+ return 30 + code;
343
+ }
344
+ if (code < 16) {
345
+ return 90 + (code - 8);
346
+ }
347
+ let red;
348
+ let green;
349
+ let blue;
350
+ if (code >= 232) {
351
+ red = ((code - 232) * 10 + 8) / 255;
352
+ green = red;
353
+ blue = red;
354
+ } else {
355
+ code -= 16;
356
+ const remainder = code % 36;
357
+ red = Math.floor(code / 36) / 5;
358
+ green = Math.floor(remainder / 6) / 5;
359
+ blue = remainder % 6 / 5;
360
+ }
361
+ const value = Math.max(red, green, blue) * 2;
362
+ if (value === 0) {
363
+ return 30;
364
+ }
365
+ // eslint-disable-next-line no-bitwise
366
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
367
+ if (value === 2) {
368
+ result += 60;
369
+ }
370
+ return result;
371
+ },
372
+ enumerable: false
373
+ },
374
+ rgbToAnsi: {
375
+ value: (red, green, blue)=>styles$1.ansi256ToAnsi(styles$1.rgbToAnsi256(red, green, blue)),
376
+ enumerable: false
377
+ },
378
+ hexToAnsi: {
379
+ value: (hex)=>styles$1.ansi256ToAnsi(styles$1.hexToAnsi256(hex)),
380
+ enumerable: false
381
+ }
382
+ });
383
+ return styles$1;
384
+ }
385
+ const ansiStyles = assembleStyles();
386
+
387
+ // From: https://github.com/sindresorhus/has-flag/blob/main/index.js
388
+ /// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) {
389
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) {
390
+ const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--';
391
+ const position = argv.indexOf(prefix + flag);
392
+ const terminatorPosition = argv.indexOf('--');
393
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
394
+ }
395
+ const { env } = process;
396
+ let flagForceColor;
397
+ if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never')) {
398
+ flagForceColor = 0;
399
+ } else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) {
400
+ flagForceColor = 1;
401
+ }
402
+ function envForceColor() {
403
+ if ('FORCE_COLOR' in env) {
404
+ if (env.FORCE_COLOR === 'true') {
405
+ return 1;
406
+ }
407
+ if (env.FORCE_COLOR === 'false') {
408
+ return 0;
409
+ }
410
+ return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
411
+ }
412
+ }
413
+ function translateLevel(level) {
414
+ if (level === 0) {
415
+ return false;
416
+ }
417
+ return {
418
+ level,
419
+ hasBasic: true,
420
+ has256: level >= 2,
421
+ has16m: level >= 3
422
+ };
423
+ }
424
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
425
+ const noFlagForceColor = envForceColor();
426
+ if (noFlagForceColor !== undefined) {
427
+ flagForceColor = noFlagForceColor;
428
+ }
429
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
430
+ if (forceColor === 0) {
431
+ return 0;
432
+ }
433
+ if (sniffFlags) {
434
+ if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) {
435
+ return 3;
436
+ }
437
+ if (hasFlag('color=256')) {
438
+ return 2;
439
+ }
440
+ }
441
+ // Check for Azure DevOps pipelines.
442
+ // Has to be above the `!streamIsTTY` check.
443
+ if ('TF_BUILD' in env && 'AGENT_NAME' in env) {
444
+ return 1;
445
+ }
446
+ if (haveStream && !streamIsTTY && forceColor === undefined) {
447
+ return 0;
448
+ }
449
+ const min = forceColor || 0;
450
+ if (env.TERM === 'dumb') {
451
+ return min;
452
+ }
453
+ if (process.platform === 'win32') {
454
+ // Windows 10 build 10586 is the first Windows release that supports 256 colors.
455
+ // Windows 10 build 14931 is the first release that supports 16m/TrueColor.
456
+ const osRelease = os.release().split('.');
457
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10_586) {
458
+ return Number(osRelease[2]) >= 14_931 ? 3 : 2;
459
+ }
460
+ return 1;
461
+ }
462
+ if ('CI' in env) {
463
+ if ('GITHUB_ACTIONS' in env || 'GITEA_ACTIONS' in env) {
464
+ return 3;
465
+ }
466
+ if ([
467
+ 'TRAVIS',
468
+ 'CIRCLECI',
469
+ 'APPVEYOR',
470
+ 'GITLAB_CI',
471
+ 'BUILDKITE',
472
+ 'DRONE'
473
+ ].some((sign)=>sign in env) || env.CI_NAME === 'codeship') {
474
+ return 1;
475
+ }
476
+ return min;
477
+ }
478
+ if ('TEAMCITY_VERSION' in env) {
479
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
480
+ }
481
+ if (env.COLORTERM === 'truecolor') {
482
+ return 3;
483
+ }
484
+ if (env.TERM === 'xterm-kitty') {
485
+ return 3;
486
+ }
487
+ if ('TERM_PROGRAM' in env) {
488
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
489
+ switch(env.TERM_PROGRAM){
490
+ case 'iTerm.app':
491
+ {
492
+ return version >= 3 ? 3 : 2;
493
+ }
494
+ case 'Apple_Terminal':
495
+ {
496
+ return 2;
497
+ }
498
+ }
499
+ }
500
+ if (/-256(color)?$/i.test(env.TERM)) {
501
+ return 2;
502
+ }
503
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
504
+ return 1;
505
+ }
506
+ if ('COLORTERM' in env) {
507
+ return 1;
508
+ }
509
+ return min;
510
+ }
511
+ function createSupportsColor(stream, options = {}) {
512
+ const level = _supportsColor(stream, {
513
+ streamIsTTY: stream && stream.isTTY,
514
+ ...options
515
+ });
516
+ return translateLevel(level);
517
+ }
518
+ const supportsColor = {
519
+ stdout: createSupportsColor({
520
+ isTTY: tty.isatty(1)
521
+ }),
522
+ stderr: createSupportsColor({
523
+ isTTY: tty.isatty(2)
524
+ })
525
+ };
526
+
527
+ // TODO: When targeting Node.js 16, use `String.prototype.replaceAll`.
528
+ function stringReplaceAll(string, substring, replacer) {
529
+ let index = string.indexOf(substring);
530
+ if (index === -1) {
531
+ return string;
532
+ }
533
+ const substringLength = substring.length;
534
+ let endIndex = 0;
535
+ let returnValue = '';
536
+ do {
537
+ returnValue += string.slice(endIndex, index) + substring + replacer;
538
+ endIndex = index + substringLength;
539
+ index = string.indexOf(substring, endIndex);
540
+ }while (index !== -1)
541
+ returnValue += string.slice(endIndex);
542
+ return returnValue;
543
+ }
544
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
545
+ let endIndex = 0;
546
+ let returnValue = '';
547
+ do {
548
+ const gotCR = string[index - 1] === '\r';
549
+ returnValue += string.slice(endIndex, gotCR ? index - 1 : index) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
550
+ endIndex = index + 1;
551
+ index = string.indexOf('\n', endIndex);
552
+ }while (index !== -1)
553
+ returnValue += string.slice(endIndex);
554
+ return returnValue;
555
+ }
556
+
557
+ const { stdout: stdoutColor, stderr: stderrColor } = supportsColor;
558
+ const GENERATOR = Symbol('GENERATOR');
559
+ const STYLER = Symbol('STYLER');
560
+ const IS_EMPTY = Symbol('IS_EMPTY');
561
+ // `supportsColor.level` → `ansiStyles.color[name]` mapping
562
+ const levelMapping = [
563
+ 'ansi',
564
+ 'ansi',
565
+ 'ansi256',
566
+ 'ansi16m'
567
+ ];
568
+ const styles = Object.create(null);
569
+ const applyOptions = (object, options = {})=>{
570
+ if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
571
+ throw new Error('The `level` option should be an integer from 0 to 3');
572
+ }
573
+ // Detect level if not set manually
574
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
575
+ object.level = options.level === undefined ? colorLevel : options.level;
576
+ };
577
+ const chalkFactory = (options)=>{
578
+ const chalk = (...strings)=>strings.join(' ');
579
+ applyOptions(chalk, options);
580
+ Object.setPrototypeOf(chalk, createChalk.prototype);
581
+ return chalk;
582
+ };
583
+ function createChalk(options) {
584
+ return chalkFactory(options);
585
+ }
586
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
587
+ for (const [styleName, style] of Object.entries(ansiStyles)){
588
+ styles[styleName] = {
589
+ get () {
590
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
591
+ Object.defineProperty(this, styleName, {
592
+ value: builder
593
+ });
594
+ return builder;
595
+ }
596
+ };
597
+ }
598
+ styles.visible = {
599
+ get () {
600
+ const builder = createBuilder(this, this[STYLER], true);
601
+ Object.defineProperty(this, 'visible', {
602
+ value: builder
603
+ });
604
+ return builder;
605
+ }
606
+ };
607
+ const getModelAnsi = (model, level, type, ...arguments_)=>{
608
+ if (model === 'rgb') {
609
+ if (level === 'ansi16m') {
610
+ return ansiStyles[type].ansi16m(...arguments_);
611
+ }
612
+ if (level === 'ansi256') {
613
+ return ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_));
614
+ }
615
+ return ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_));
616
+ }
617
+ if (model === 'hex') {
618
+ return getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_));
619
+ }
620
+ return ansiStyles[type][model](...arguments_);
621
+ };
622
+ const usedModels = [
623
+ 'rgb',
624
+ 'hex',
625
+ 'ansi256'
626
+ ];
627
+ for (const model of usedModels){
628
+ styles[model] = {
629
+ get () {
630
+ const { level } = this;
631
+ return function(...arguments_) {
632
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]);
633
+ return createBuilder(this, styler, this[IS_EMPTY]);
634
+ };
635
+ }
636
+ };
637
+ const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
638
+ styles[bgModel] = {
639
+ get () {
640
+ const { level } = this;
641
+ return function(...arguments_) {
642
+ const styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]);
643
+ return createBuilder(this, styler, this[IS_EMPTY]);
644
+ };
645
+ }
646
+ };
647
+ }
648
+ const proto = Object.defineProperties(()=>{}, {
649
+ ...styles,
650
+ level: {
651
+ enumerable: true,
652
+ get () {
653
+ return this[GENERATOR].level;
654
+ },
655
+ set (level) {
656
+ this[GENERATOR].level = level;
657
+ }
658
+ }
659
+ });
660
+ const createStyler = (open, close, parent)=>{
661
+ let openAll;
662
+ let closeAll;
663
+ if (parent === undefined) {
664
+ openAll = open;
665
+ closeAll = close;
666
+ } else {
667
+ openAll = parent.openAll + open;
668
+ closeAll = close + parent.closeAll;
669
+ }
670
+ return {
671
+ open,
672
+ close,
673
+ openAll,
674
+ closeAll,
675
+ parent
676
+ };
677
+ };
678
+ const createBuilder = (self, _styler, _isEmpty)=>{
679
+ // Single argument is hot path, implicit coercion is faster than anything
680
+ // eslint-disable-next-line no-implicit-coercion
681
+ const builder = (...arguments_)=>applyStyle(builder, arguments_.length === 1 ? '' + arguments_[0] : arguments_.join(' '));
682
+ // We alter the prototype because we must return a function, but there is
683
+ // no way to create a function with a different prototype
684
+ Object.setPrototypeOf(builder, proto);
685
+ builder[GENERATOR] = self;
686
+ builder[STYLER] = _styler;
687
+ builder[IS_EMPTY] = _isEmpty;
688
+ return builder;
689
+ };
690
+ const applyStyle = (self, string)=>{
691
+ if (self.level <= 0 || !string) {
692
+ return self[IS_EMPTY] ? '' : string;
693
+ }
694
+ let styler = self[STYLER];
695
+ if (styler === undefined) {
696
+ return string;
697
+ }
698
+ const { openAll, closeAll } = styler;
699
+ if (string.includes('\u001B')) {
700
+ while(styler !== undefined){
701
+ // Replace any instances already present with a re-opening code
702
+ // otherwise only the part of the string until said closing code
703
+ // will be colored, and the rest will simply be 'plain'.
704
+ string = stringReplaceAll(string, styler.close, styler.open);
705
+ styler = styler.parent;
706
+ }
707
+ }
708
+ // We can move both next actions out of loop, because remaining actions in loop won't have
709
+ // any/visible effect on parts we add here. Close the styling before a linebreak and reopen
710
+ // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
711
+ const lfIndex = string.indexOf('\n');
712
+ if (lfIndex !== -1) {
713
+ string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
714
+ }
715
+ return openAll + string + closeAll;
716
+ };
717
+ Object.defineProperties(createChalk.prototype, styles);
718
+ const chalk = createChalk();
719
+ createChalk({
720
+ level: stderrColor ? stderrColor.level : 0
721
+ });
722
+ var chalk$1 = chalk;
723
+
724
+ const mapLoggingMethodToConsole = {
725
+ wait: "log",
726
+ error: "error",
727
+ warn: "warn",
728
+ info: "log",
729
+ event: "log"
730
+ };
731
+ const prefixes = {
732
+ wait: `${chalk$1.white(chalk$1.bold("○"))} (serwist)`,
733
+ error: `${chalk$1.red(chalk$1.bold("X"))} (serwist)`,
734
+ warn: `${chalk$1.yellow(chalk$1.bold("⚠"))} (serwist)`,
735
+ info: `${chalk$1.white(chalk$1.bold("○"))} (serwist)`,
736
+ event: `${chalk$1.green(chalk$1.bold("✓"))} (serwist)`
737
+ };
738
+ const prefixedLog = (prefixType, ...message)=>{
739
+ const consoleMethod = mapLoggingMethodToConsole[prefixType];
740
+ const prefix = prefixes[prefixType];
741
+ if ((message[0] === "" || message[0] === undefined) && message.length === 1) {
742
+ message.shift();
743
+ }
744
+ // If there's no message, don't print the prefix but a new line
745
+ if (message.length === 0) {
746
+ console[consoleMethod]("");
747
+ } else {
748
+ console[consoleMethod](" " + prefix, ...message);
749
+ }
750
+ };
751
+ const info = (...message)=>{
752
+ prefixedLog("info", ...message);
753
+ };
754
+ const event = (...message)=>{
755
+ prefixedLog("event", ...message);
756
+ };
757
+
758
+ const __dirname = fileURLToPath(new URL(".", import.meta.url));
759
+ const withPWAInit = (pluginOptions)=>{
760
+ return (nextConfig = {})=>({
761
+ ...nextConfig,
762
+ webpack (config, options) {
763
+ const webpack = options.webpack;
764
+ const { buildId, dev } = options;
765
+ const basePath = options.config.basePath || "/";
766
+ const tsConfigJson = loadTSConfig(options.dir, nextConfig?.typescript?.tsconfigPath);
767
+ const { cacheOnFrontEndNav = false, disable = false, scope = basePath, swUrl = "sw.js", register = true, reloadOnOnline = true, ...buildOptions } = pluginOptions;
768
+ if (typeof nextConfig.webpack === "function") {
769
+ config = nextConfig.webpack(config, options);
770
+ }
771
+ if (disable) {
772
+ options.isServer && info("PWA support is disabled.");
773
+ return config;
774
+ }
775
+ if (!config.plugins) {
776
+ config.plugins = [];
777
+ }
778
+ event(`Compiling for ${options.isServer ? "server" : "client (static)"}...`);
779
+ const _sw = path.posix.join(basePath, swUrl);
780
+ const _scope = path.posix.join(scope, "/");
781
+ config.plugins.push(new webpack.DefinePlugin({
782
+ "self.__SERWIST_SW_ENTRY.sw": `'${_sw}'`,
783
+ "self.__SERWIST_SW_ENTRY.scope": `'${_scope}'`,
784
+ "self.__SERWIST_SW_ENTRY.cacheOnFrontEndNav": `${Boolean(cacheOnFrontEndNav)}`,
785
+ "self.__SERWIST_SW_ENTRY.register": `${Boolean(register)}`,
786
+ "self.__SERWIST_SW_ENTRY.reloadOnOnline": `${Boolean(reloadOnOnline)}`
787
+ }));
788
+ const swEntryJs = path.join(__dirname, "sw-entry.js");
789
+ const entry = config.entry;
790
+ config.entry = ()=>entry().then((entries)=>{
791
+ if (entries["main.js"] && !entries["main.js"].includes(swEntryJs)) {
792
+ if (Array.isArray(entries["main.js"])) {
793
+ entries["main.js"].unshift(swEntryJs);
794
+ } else if (typeof entries["main.js"] === "string") {
795
+ entries["main.js"] = [
796
+ swEntryJs,
797
+ entries["main.js"]
798
+ ];
799
+ }
800
+ }
801
+ if (entries["main-app"] && !entries["main-app"].includes(swEntryJs)) {
802
+ if (Array.isArray(entries["main-app"])) {
803
+ entries["main-app"].unshift(swEntryJs);
804
+ } else if (typeof entries["main-app"] === "string") {
805
+ entries["main-app"] = [
806
+ swEntryJs,
807
+ entries["main-app"]
808
+ ];
809
+ }
810
+ }
811
+ return entries;
812
+ });
813
+ if (!options.isServer) {
814
+ if (!register) {
815
+ info("Service worker won't be automatically registered as per the config, please call the following code in componentDidMount or useEffect:");
816
+ info(` window.serwist.register()`);
817
+ if (!tsConfigJson?.compilerOptions?.types?.includes("@serwist/next/typings")) {
818
+ info("You may also want to add @serwist/next/typings to compilerOptions.types in your tsconfig.json/jsconfig.json.");
819
+ }
820
+ }
821
+ const { swSrc: providedSwSrc, swDest: providedSwDest, additionalPrecacheEntries, exclude = [], modifyURLPrefix = {}, manifestTransforms = [], ...otherBuildOptions } = buildOptions;
822
+ let swSrc = providedSwSrc, swDest = providedSwDest;
823
+ if (!path.isAbsolute(swSrc)) {
824
+ swSrc = path.join(options.dir, swSrc);
825
+ }
826
+ if (!path.isAbsolute(swDest)) {
827
+ swDest = path.join(options.dir, swDest);
828
+ }
829
+ const destDir = path.dirname(swDest);
830
+ const shouldBuildSWEntryWorker = cacheOnFrontEndNav;
831
+ let swEntryPublicPath = undefined;
832
+ if (shouldBuildSWEntryWorker) {
833
+ const swEntryWorkerSrc = path.join(__dirname, `sw-entry-worker.js`);
834
+ const swEntryName = `swe-worker-${getContentHash(swEntryWorkerSrc, dev)}.js`;
835
+ swEntryPublicPath = path.posix.join(basePath, swEntryName);
836
+ const swEntryWorkerDest = path.join(destDir, swEntryName);
837
+ config.plugins.push(new ChildCompilationPlugin({
838
+ src: swEntryWorkerSrc,
839
+ dest: swEntryWorkerDest
840
+ }));
841
+ }
842
+ config.plugins.push(new webpack.DefinePlugin({
843
+ "self.__SERWIST_SW_ENTRY.swEntryWorker": swEntryPublicPath && `'${swEntryPublicPath}'`
844
+ }));
845
+ info(`Service worker: ${swDest}`);
846
+ info(` URL: ${_sw}`);
847
+ info(` Scope: ${_scope}`);
848
+ config.plugins.push(new CleanWebpackPlugin({
849
+ cleanOnceBeforeBuildPatterns: [
850
+ path.join(destDir, "swe-worker-*.js"),
851
+ path.join(destDir, "swe-worker-*.js.map"),
852
+ swDest
853
+ ]
854
+ }));
855
+ // Precache files in public folder
856
+ let resolvedManifestEntries = additionalPrecacheEntries ?? [];
857
+ if (!resolvedManifestEntries) {
858
+ const swDestFileName = path.basename(swDest);
859
+ resolvedManifestEntries = fg.sync([
860
+ "**/*",
861
+ // Include these in case the user outputs these files to `public`.
862
+ "!swe-worker-*.js",
863
+ "!swe-worker-*.js.map",
864
+ `!${swDestFileName.replace(/^\/+/, "")}`,
865
+ `!${swDestFileName.replace(/^\/+/, "")}.map`
866
+ ], {
867
+ cwd: "public"
868
+ }).map((f)=>({
869
+ url: path.posix.join(basePath, f),
870
+ revision: getFileHash(`public/${f}`)
871
+ }));
872
+ }
873
+ const publicPath = config.output?.publicPath;
874
+ config.plugins.push(new InjectManifest({
875
+ swSrc,
876
+ swDest,
877
+ disablePrecacheManifest: dev,
878
+ additionalPrecacheEntries: dev ? [] : resolvedManifestEntries,
879
+ exclude: [
880
+ ...exclude,
881
+ ({ asset })=>{
882
+ if (asset.name.startsWith("server/") || asset.name.match(/^((app-|^)build-manifest\.json|react-loadable-manifest\.json)$/)) {
883
+ return true;
884
+ }
885
+ if (dev && !asset.name.startsWith("static/runtime/")) {
886
+ return true;
887
+ }
888
+ return false;
889
+ }
890
+ ],
891
+ modifyURLPrefix: {
892
+ ...modifyURLPrefix,
893
+ "/_next/../public/": "/"
894
+ },
895
+ manifestTransforms: [
896
+ ...manifestTransforms,
897
+ async (manifestEntries, compilation)=>{
898
+ const manifest = manifestEntries.map((m)=>{
899
+ m.url = m.url.replace("/_next//static/image", "/_next/static/image");
900
+ m.url = m.url.replace("/_next//static/media", "/_next/static/media");
901
+ if (m.revision === null) {
902
+ let key = m.url;
903
+ if (typeof publicPath === "string" && key.startsWith(publicPath)) {
904
+ key = m.url.substring(publicPath.length);
905
+ }
906
+ const asset = compilation.assetsInfo.get(key);
907
+ m.revision = asset ? asset.contenthash || buildId : buildId;
908
+ }
909
+ m.url = m.url.replace(/\[/g, "%5B").replace(/\]/g, "%5D");
910
+ return m;
911
+ });
912
+ return {
913
+ manifest,
914
+ warnings: []
915
+ };
916
+ }
917
+ ],
918
+ ...otherBuildOptions
919
+ }));
920
+ }
921
+ return config;
922
+ }
923
+ });
924
+ };
925
+
926
+ export { withPWAInit as default };