@serwist/next 8.4.4 → 9.0.0-preview.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/index.d.ts +5 -4
  2. package/dist/index.d.ts.map +1 -0
  3. package/dist/index.js +43 -716
  4. package/dist/index.worker.d.ts +5 -0
  5. package/dist/index.worker.d.ts.map +1 -0
  6. package/dist/{index.browser.cjs → index.worker.js} +53 -26
  7. package/dist/internal-types.d.ts +7 -1
  8. package/dist/internal-types.d.ts.map +1 -0
  9. package/dist/sw-entry-worker.d.ts +1 -0
  10. package/dist/sw-entry-worker.d.ts.map +1 -0
  11. package/dist/sw-entry.d.ts +1 -0
  12. package/dist/sw-entry.d.ts.map +1 -0
  13. package/dist/sw-entry.js +5 -5
  14. package/dist/utils/find-first-truthy.d.ts +1 -0
  15. package/dist/utils/find-first-truthy.d.ts.map +1 -0
  16. package/dist/utils/get-content-hash.d.ts +1 -0
  17. package/dist/utils/get-content-hash.d.ts.map +1 -0
  18. package/dist/utils/get-file-hash.d.ts +1 -0
  19. package/dist/utils/get-file-hash.d.ts.map +1 -0
  20. package/dist/utils/get-package-version.d.ts +1 -0
  21. package/dist/utils/get-package-version.d.ts.map +1 -0
  22. package/dist/utils/index.d.ts +1 -0
  23. package/dist/utils/index.d.ts.map +1 -0
  24. package/dist/utils/load-tsconfig.d.ts +1 -0
  25. package/dist/utils/load-tsconfig.d.ts.map +1 -0
  26. package/dist/utils/logger.d.ts +1 -0
  27. package/dist/utils/logger.d.ts.map +1 -0
  28. package/dist/utils.d.ts +1 -0
  29. package/dist/utils.d.ts.map +1 -0
  30. package/dist/worker/defaultCache.d.ts +3 -0
  31. package/dist/worker/defaultCache.d.ts.map +1 -0
  32. package/dist/worker/definePageRuntimeCaching.d.ts +16 -0
  33. package/dist/worker/definePageRuntimeCaching.d.ts.map +1 -0
  34. package/package.json +48 -50
  35. package/src/index.ts +241 -0
  36. package/src/index.worker.ts +5 -0
  37. package/src/internal-types.ts +17 -0
  38. package/src/sw-entry-worker.ts +46 -0
  39. package/src/sw-entry.ts +64 -0
  40. package/src/utils/find-first-truthy.ts +15 -0
  41. package/src/utils/get-content-hash.ts +10 -0
  42. package/src/utils/get-file-hash.ts +4 -0
  43. package/src/utils/get-package-version.ts +16 -0
  44. package/src/utils/load-tsconfig.ts +27 -0
  45. package/src/utils/logger.ts +57 -0
  46. package/src/utils.ts +11 -0
  47. package/src/worker/defaultCache.ts +223 -0
  48. package/src/worker/definePageRuntimeCaching.ts +36 -0
  49. package/dist/index.browser.d.cts +0 -2
  50. package/dist/index.browser.d.ts +0 -2
  51. package/dist/index.browser.js +0 -208
  52. package/dist/index.cjs +0 -928
  53. package/dist/index.d.cts +0 -5
  54. package/dist/internal-types.d.cts +0 -9
  55. package/dist/sw-entry-worker.cjs +0 -35
  56. package/dist/sw-entry-worker.d.cts +0 -7
  57. package/dist/sw-entry.cjs +0 -43
  58. package/dist/sw-entry.d.cts +0 -6
  59. package/dist/types.d.cts +0 -81
  60. package/dist/types.d.ts +0 -81
  61. package/dist/utils/find-first-truthy.d.cts +0 -7
  62. package/dist/utils/get-content-hash.d.cts +0 -3
  63. package/dist/utils/get-file-hash.d.cts +0 -3
  64. package/dist/utils/get-package-version.d.cts +0 -6
  65. package/dist/utils/load-tsconfig.d.cts +0 -2
  66. package/dist/utils/logger.d.cts +0 -5
  67. package/dist/utils.d.cts +0 -4
  68. /package/{dist/utils/index.d.cts → src/utils/index.ts} +0 -0
package/dist/index.js CHANGED
@@ -1,22 +1,16 @@
1
1
  import path from 'node:path';
2
2
  import { fileURLToPath } from 'node:url';
3
+ import { validateNextInjectManifestOptions } from '@serwist/build/next';
3
4
  import { InjectManifest } from '@serwist/webpack-plugin';
4
- import { ChildCompilationPlugin } from '@serwist/webpack-plugin/internal';
5
+ import { ChildCompilationPlugin, relativeToOutputPath } from '@serwist/webpack-plugin/internal';
5
6
  import { CleanWebpackPlugin } from 'clean-webpack-plugin';
6
7
  import fg from 'fast-glob';
7
8
  import crypto from 'node:crypto';
8
9
  import fs from 'node:fs';
9
10
  import { createRequire } from 'node:module';
10
- import process from 'node:process';
11
- import os from 'node:os';
12
- import tty from 'node:tty';
11
+ import chalk from 'chalk';
13
12
 
14
- /**
15
- * Find the first truthy value in an array.
16
- * @param arr
17
- * @param fn
18
- * @returns
19
- */ const findFirstTruthy = (arr, fn)=>{
13
+ const findFirstTruthy = (arr, fn)=>{
20
14
  for (const i of arr){
21
15
  const resolved = fn(i);
22
16
  if (resolved) {
@@ -39,7 +33,6 @@ createRequire(import.meta.url);
39
33
 
40
34
  const loadTSConfig = (baseDir, relativeTSConfigPath)=>{
41
35
  try {
42
- // Find tsconfig.json file
43
36
  const tsConfigPath = findFirstTruthy([
44
37
  relativeTSConfigPath ?? "tsconfig.json",
45
38
  "jsconfig.json"
@@ -50,7 +43,6 @@ const loadTSConfig = (baseDir, relativeTSConfigPath)=>{
50
43
  if (!tsConfigPath) {
51
44
  return undefined;
52
45
  }
53
- // Read tsconfig.json file
54
46
  const tsConfigFile = JSON.parse(fs.readFileSync(tsConfigPath, "utf-8"));
55
47
  return tsConfigFile;
56
48
  } catch {
@@ -58,669 +50,6 @@ const loadTSConfig = (baseDir, relativeTSConfigPath)=>{
58
50
  }
59
51
  };
60
52
 
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
53
  const mapLoggingMethodToConsole = {
725
54
  wait: "log",
726
55
  error: "error",
@@ -729,11 +58,11 @@ const mapLoggingMethodToConsole = {
729
58
  event: "log"
730
59
  };
731
60
  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)`
61
+ wait: `${chalk.white(chalk.bold("○"))} (serwist)`,
62
+ error: `${chalk.red(chalk.bold("X"))} (serwist)`,
63
+ warn: `${chalk.yellow(chalk.bold("⚠"))} (serwist)`,
64
+ info: `${chalk.white(chalk.bold("○"))} (serwist)`,
65
+ event: `${chalk.green(chalk.bold("✓"))} (serwist)`
737
66
  };
738
67
  const prefixedLog = (prefixType, ...message)=>{
739
68
  const consoleMethod = mapLoggingMethodToConsole[prefixType];
@@ -741,7 +70,6 @@ const prefixedLog = (prefixType, ...message)=>{
741
70
  if ((message[0] === "" || message[0] === undefined) && message.length === 1) {
742
71
  message.shift();
743
72
  }
744
- // If there's no message, don't print the prefix but a new line
745
73
  if (message.length === 0) {
746
74
  console[consoleMethod]("");
747
75
  } else {
@@ -756,15 +84,15 @@ const event = (...message)=>{
756
84
  };
757
85
 
758
86
  const __dirname = fileURLToPath(new URL(".", import.meta.url));
759
- const withPWAInit = (pluginOptions)=>{
87
+ const withSerwistInit = (pluginOptions)=>{
760
88
  return (nextConfig = {})=>({
761
89
  ...nextConfig,
762
90
  webpack (config, options) {
763
91
  const webpack = options.webpack;
764
- const { buildId, dev } = options;
92
+ const { dev } = options;
765
93
  const basePath = options.config.basePath || "/";
766
94
  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;
95
+ const { cacheOnNavigation, disable, scope = basePath, swUrl, register, reloadOnOnline, globPublicPatterns, ...buildOptions } = validateNextInjectManifestOptions(pluginOptions);
768
96
  if (typeof nextConfig.webpack === "function") {
769
97
  config = nextConfig.webpack(config, options);
770
98
  }
@@ -781,9 +109,9 @@ const withPWAInit = (pluginOptions)=>{
781
109
  config.plugins.push(new webpack.DefinePlugin({
782
110
  "self.__SERWIST_SW_ENTRY.sw": `'${_sw}'`,
783
111
  "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)}`
112
+ "self.__SERWIST_SW_ENTRY.cacheOnNavigation": `${cacheOnNavigation}`,
113
+ "self.__SERWIST_SW_ENTRY.register": `${register}`,
114
+ "self.__SERWIST_SW_ENTRY.reloadOnOnline": `${reloadOnOnline}`
787
115
  }));
788
116
  const swEntryJs = path.join(__dirname, "sw-entry.js");
789
117
  const entry = config.entry;
@@ -819,23 +147,25 @@ const withPWAInit = (pluginOptions)=>{
819
147
  info("You may also want to add @serwist/next/typings to compilerOptions.types in your tsconfig.json/jsconfig.json.");
820
148
  }
821
149
  }
822
- const { swSrc: providedSwSrc, swDest: providedSwDest, additionalPrecacheEntries, exclude = [], manifestTransforms = [], ...otherBuildOptions } = buildOptions;
823
- let swSrc = providedSwSrc;
824
- let swDest = providedSwDest;
150
+ const { swSrc: userSwSrc, swDest: userSwDest, additionalPrecacheEntries, exclude, manifestTransforms = [], ...otherBuildOptions } = buildOptions;
151
+ let swSrc = userSwSrc;
152
+ let swDest = userSwDest;
825
153
  if (!path.isAbsolute(swSrc)) {
826
154
  swSrc = path.join(options.dir, swSrc);
827
155
  }
828
156
  if (!path.isAbsolute(swDest)) {
829
157
  swDest = path.join(options.dir, swDest);
830
158
  }
159
+ const publicDir = path.resolve(options.dir, "public");
831
160
  const destDir = path.dirname(swDest);
832
- const shouldBuildSWEntryWorker = cacheOnFrontEndNav;
161
+ const shouldBuildSWEntryWorker = cacheOnNavigation;
833
162
  let swEntryPublicPath = undefined;
163
+ let swEntryWorkerDest = undefined;
834
164
  if (shouldBuildSWEntryWorker) {
835
165
  const swEntryWorkerSrc = path.join(__dirname, "sw-entry-worker.js");
836
166
  const swEntryName = `swe-worker-${getContentHash(swEntryWorkerSrc, dev)}.js`;
837
167
  swEntryPublicPath = path.posix.join(basePath, swEntryName);
838
- const swEntryWorkerDest = path.join(destDir, swEntryName);
168
+ swEntryWorkerDest = path.join(destDir, swEntryName);
839
169
  config.plugins.push(new ChildCompilationPlugin({
840
170
  src: swEntryWorkerSrc,
841
171
  dest: swEntryWorkerDest
@@ -854,22 +184,26 @@ const withPWAInit = (pluginOptions)=>{
854
184
  swDest
855
185
  ]
856
186
  }));
857
- // Precache files in public folder
858
187
  let resolvedManifestEntries = additionalPrecacheEntries;
859
188
  if (!resolvedManifestEntries) {
860
189
  const swDestFileName = path.basename(swDest);
861
- resolvedManifestEntries = fg.sync([
862
- "**/*",
863
- // Include these in case the user outputs these files to `public`.
190
+ const userPublicGlob = typeof globPublicPatterns === "string" ? [
191
+ globPublicPatterns
192
+ ] : globPublicPatterns ?? [
193
+ "**/*"
194
+ ];
195
+ const publicScan = fg.sync([
196
+ ...userPublicGlob,
864
197
  "!swe-worker-*.js",
865
198
  "!swe-worker-*.js.map",
866
199
  `!${swDestFileName.replace(/^\/+/, "")}`,
867
200
  `!${swDestFileName.replace(/^\/+/, "")}.map`
868
201
  ], {
869
- cwd: "public"
870
- }).map((f)=>({
202
+ cwd: publicDir
203
+ });
204
+ resolvedManifestEntries = publicScan.map((f)=>({
871
205
  url: path.posix.join(basePath, f),
872
- revision: getFileHash(`public/${f}`)
206
+ revision: getFileHash(path.join(publicDir, f))
873
207
  }));
874
208
  }
875
209
  const publicPath = config.output?.publicPath;
@@ -880,28 +214,21 @@ const withPWAInit = (pluginOptions)=>{
880
214
  additionalPrecacheEntries: dev ? [] : resolvedManifestEntries,
881
215
  exclude: [
882
216
  ...exclude,
883
- ({ asset })=>{
884
- if (asset.name.startsWith("server/") || asset.name.match(/^((app-|^)build-manifest\.json|react-loadable-manifest\.json)$/)) {
885
- return true;
886
- }
887
- if (dev && !asset.name.startsWith("static/runtime/")) {
888
- return true;
889
- }
890
- return false;
217
+ ({ asset, compilation })=>{
218
+ const swDestRelativeOutput = relativeToOutputPath(compilation, swDest);
219
+ const swAsset = compilation.getAsset(swDestRelativeOutput);
220
+ 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/");
891
221
  }
892
222
  ],
893
223
  manifestTransforms: [
894
224
  ...manifestTransforms,
895
225
  async (manifestEntries, compilation)=>{
226
+ const publicDirRelativeOutput = relativeToOutputPath(compilation, publicDir);
227
+ const publicFilesPrefix = `${publicPath}${publicDirRelativeOutput}`;
896
228
  const manifest = manifestEntries.map((m)=>{
897
- m.url = m.url.replace("/_next//static/image", "/_next/static/image").replace("/_next//static/media", "/_next/static/media").replace("/_next/../public", "");
898
- if (m.revision === null) {
899
- let key = m.url;
900
- if (typeof publicPath === "string" && key.startsWith(publicPath)) {
901
- key = m.url.substring(publicPath.length);
902
- }
903
- const asset = compilation.assetsInfo.get(key);
904
- m.revision = asset ? asset.contenthash || buildId : buildId;
229
+ m.url = m.url.replace("/_next//static/image", "/_next/static/image").replace("/_next//static/media", "/_next/static/media");
230
+ if (m.url.startsWith(publicFilesPrefix)) {
231
+ m.url = path.posix.join(basePath, m.url.replace(publicFilesPrefix, ""));
905
232
  }
906
233
  m.url = m.url.replace(/\[/g, "%5B").replace(/\]/g, "%5D");
907
234
  return m;
@@ -920,4 +247,4 @@ const withPWAInit = (pluginOptions)=>{
920
247
  });
921
248
  };
922
249
 
923
- export { withPWAInit as default };
250
+ export { withSerwistInit as default };