@serwist/next 9.0.0-preview.0 → 9.0.0-preview.10

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