@serwist/build 9.5.6 → 9.5.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.
Files changed (98) hide show
  1. package/dist/chunks/constants-BLOVm9H2.js +6 -0
  2. package/dist/chunks/constants-BLOVm9H2.js.map +1 -0
  3. package/dist/chunks/error-Cl4d1Wf-.js +31 -0
  4. package/dist/chunks/error-Cl4d1Wf-.js.map +1 -0
  5. package/dist/chunks/get-manifest-De0D0LAJ.js +14 -0
  6. package/dist/chunks/get-manifest-De0D0LAJ.js.map +1 -0
  7. package/dist/chunks/glob-B4_meZ_o.js +67 -0
  8. package/dist/chunks/glob-B4_meZ_o.js.map +1 -0
  9. package/dist/chunks/inject-manifest-DNqDY-04.js +27 -0
  10. package/dist/chunks/inject-manifest-DNqDY-04.js.map +1 -0
  11. package/dist/chunks/manifest-transform-BCUeQ0-V.d.ts +75 -0
  12. package/dist/chunks/manifest-transform-BCUeQ0-V.d.ts.map +1 -0
  13. package/dist/chunks/rolldown-runtime-CzwdidQP.js +13 -0
  14. package/dist/index.d.mts +475 -0
  15. package/dist/index.d.mts.map +1 -0
  16. package/dist/index.mjs +594 -0
  17. package/dist/index.mjs.map +1 -0
  18. package/dist/index.schema.d.mts +278 -0
  19. package/dist/index.schema.d.mts.map +1 -0
  20. package/dist/index.schema.mjs +5 -0
  21. package/package.json +15 -16
  22. package/src/lib/replace-and-update-source-map.ts +0 -1
  23. package/dist/chunks/constants.js +0 -59
  24. package/dist/chunks/get-manifest.js +0 -11
  25. package/dist/chunks/glob.js +0 -75
  26. package/dist/chunks/inject-manifest.js +0 -29
  27. package/dist/get-manifest.d.ts +0 -19
  28. package/dist/get-manifest.d.ts.map +0 -1
  29. package/dist/index.d.ts +0 -24
  30. package/dist/index.d.ts.map +0 -1
  31. package/dist/index.js +0 -614
  32. package/dist/index.schema.d.ts +0 -13
  33. package/dist/index.schema.d.ts.map +0 -1
  34. package/dist/index.schema.js +0 -9
  35. package/dist/inject-manifest.d.ts +0 -29
  36. package/dist/inject-manifest.d.ts.map +0 -1
  37. package/dist/lib/additional-precache-entries-transform.d.ts +0 -12
  38. package/dist/lib/additional-precache-entries-transform.d.ts.map +0 -1
  39. package/dist/lib/constants.d.ts +0 -2
  40. package/dist/lib/constants.d.ts.map +0 -1
  41. package/dist/lib/errors.d.ts +0 -46
  42. package/dist/lib/errors.d.ts.map +0 -1
  43. package/dist/lib/escape-regexp.d.ts +0 -2
  44. package/dist/lib/escape-regexp.d.ts.map +0 -1
  45. package/dist/lib/get-composite-details.d.ts +0 -3
  46. package/dist/lib/get-composite-details.d.ts.map +0 -1
  47. package/dist/lib/get-file-details.d.ts +0 -9
  48. package/dist/lib/get-file-details.d.ts.map +0 -1
  49. package/dist/lib/get-file-hash.d.ts +0 -2
  50. package/dist/lib/get-file-hash.d.ts.map +0 -1
  51. package/dist/lib/get-file-manifest-entries.d.ts +0 -3
  52. package/dist/lib/get-file-manifest-entries.d.ts.map +0 -1
  53. package/dist/lib/get-file-size.d.ts +0 -2
  54. package/dist/lib/get-file-size.d.ts.map +0 -1
  55. package/dist/lib/get-source-map-url.d.ts +0 -2
  56. package/dist/lib/get-source-map-url.d.ts.map +0 -1
  57. package/dist/lib/get-string-details.d.ts +0 -3
  58. package/dist/lib/get-string-details.d.ts.map +0 -1
  59. package/dist/lib/get-string-hash.d.ts +0 -3
  60. package/dist/lib/get-string-hash.d.ts.map +0 -1
  61. package/dist/lib/maximum-size-transform.d.ts +0 -3
  62. package/dist/lib/maximum-size-transform.d.ts.map +0 -1
  63. package/dist/lib/modify-url-prefix-transform.d.ts +0 -5
  64. package/dist/lib/modify-url-prefix-transform.d.ts.map +0 -1
  65. package/dist/lib/no-revision-for-urls-matching-transform.d.ts +0 -3
  66. package/dist/lib/no-revision-for-urls-matching-transform.d.ts.map +0 -1
  67. package/dist/lib/rebase-path.d.ts +0 -5
  68. package/dist/lib/rebase-path.d.ts.map +0 -1
  69. package/dist/lib/replace-and-update-source-map.d.ts +0 -42
  70. package/dist/lib/replace-and-update-source-map.d.ts.map +0 -1
  71. package/dist/lib/transform-manifest.d.ts +0 -61
  72. package/dist/lib/transform-manifest.d.ts.map +0 -1
  73. package/dist/lib/translate-url-to-sourcemap-paths.d.ts +0 -6
  74. package/dist/lib/translate-url-to-sourcemap-paths.d.ts.map +0 -1
  75. package/dist/lib/validate-options.d.ts +0 -4
  76. package/dist/lib/validate-options.d.ts.map +0 -1
  77. package/dist/schema/assert-type.d.ts +0 -4
  78. package/dist/schema/assert-type.d.ts.map +0 -1
  79. package/dist/schema/base.d.ts +0 -66
  80. package/dist/schema/base.d.ts.map +0 -1
  81. package/dist/schema/error.d.ts +0 -9
  82. package/dist/schema/error.d.ts.map +0 -1
  83. package/dist/schema/get-manifest.d.ts +0 -72
  84. package/dist/schema/get-manifest.d.ts.map +0 -1
  85. package/dist/schema/glob.d.ts +0 -15
  86. package/dist/schema/glob.d.ts.map +0 -1
  87. package/dist/schema/inject-manifest.d.ts +0 -79
  88. package/dist/schema/inject-manifest.d.ts.map +0 -1
  89. package/dist/schema/manifest-entry.d.ts +0 -7
  90. package/dist/schema/manifest-entry.d.ts.map +0 -1
  91. package/dist/schema/manifest-transform.d.ts +0 -64
  92. package/dist/schema/manifest-transform.d.ts.map +0 -1
  93. package/dist/schema/sw-dest.d.ts +0 -8
  94. package/dist/schema/sw-dest.d.ts.map +0 -1
  95. package/dist/schema/utils.d.ts +0 -10
  96. package/dist/schema/utils.d.ts.map +0 -1
  97. package/dist/types.d.ts +0 -204
  98. package/dist/types.d.ts.map +0 -1
package/dist/index.js DELETED
@@ -1,614 +0,0 @@
1
- import assert from 'node:assert';
2
- import { oneLine } from 'common-tags';
3
- import crypto from 'node:crypto';
4
- import path from 'node:path';
5
- import { globSync } from 'glob';
6
- import fs, { readFileSync } from 'node:fs';
7
- import prettyBytes from 'pretty-bytes';
8
- import { z } from 'zod';
9
- import { v as validationErrorMap, S as SerwistConfigError } from './chunks/constants.js';
10
- export { D as DEFAULT_GLOB_PATTERNS } from './chunks/constants.js';
11
- import fsp from 'node:fs/promises';
12
- import { toUnix } from '@serwist/utils';
13
- import { SourceMapGenerator, SourceMapConsumer } from 'source-map';
14
-
15
- const errors = {
16
- "unable-to-get-rootdir": "Unable to get the root directory of your web app.",
17
- "no-extension": oneLine`Unable to detect a usable extension for a file in your web
18
- app directory.`,
19
- "invalid-file-manifest-name": oneLine`The File Manifest Name must have at least one
20
- character.`,
21
- "unable-to-get-file-manifest-name": "Unable to get a file manifest name.",
22
- "invalid-sw-dest": `The 'swDest' value must be a valid path.`,
23
- "unable-to-get-sw-name": "Unable to get a service worker file name.",
24
- "unable-to-get-save-config": oneLine`An error occurred when asking to save details
25
- in a config file.`,
26
- "unable-to-get-file-hash": oneLine`An error occurred when attempting to create a
27
- file hash.`,
28
- "unable-to-get-file-size": oneLine`An error occurred when attempting to get a file
29
- size.`,
30
- "unable-to-glob-files": "An error occurred when globbing for files.",
31
- "unable-to-make-manifest-directory": oneLine`Unable to make output directory for
32
- file manifest.`,
33
- "read-manifest-template-failure": "Unable to read template for file manifest",
34
- "populating-manifest-tmpl-failed": oneLine`An error occurred when populating the
35
- file manifest template.`,
36
- "manifest-file-write-failure": "Unable to write the file manifest.",
37
- "unable-to-make-sw-directory": oneLine`Unable to make the directories to output
38
- the service worker path.`,
39
- "sw-write-failure": "Unable to write the service worker file.",
40
- "sw-write-failure-directory": oneLine`Unable to write the service worker file;
41
- 'swDest' should be a full path to the file, not a path to a directory.`,
42
- "unable-to-copy-serwist-libraries": oneLine`One or more of the Serwist libraries
43
- could not be copied over to the destination directory: `,
44
- "invalid-glob-directory": oneLine`The supplied globDirectory must be a path as a
45
- string.`,
46
- "invalid-dont-cache-bust": oneLine`The supplied 'dontCacheBustURLsMatching'
47
- parameter must be a RegExp.`,
48
- "invalid-exclude-files": "The excluded files should be an array of strings.",
49
- "invalid-get-manifest-entries-input": oneLine`The input to
50
- 'getFileManifestEntries()' must be an object.`,
51
- "invalid-manifest-path": oneLine`The supplied manifest path is not a string with
52
- at least one character.`,
53
- "invalid-manifest-entries": oneLine`The manifest entries must be an array of
54
- strings or JavaScript objects containing a url parameter.`,
55
- "invalid-manifest-format": oneLine`The value of the 'format' option passed to
56
- generateFileManifest() must be either 'iife' (the default) or 'es'.`,
57
- "invalid-static-file-globs": oneLine`The 'globPatterns' value must be an array
58
- of strings.`,
59
- "invalid-templated-urls": oneLine`The 'templatedURLs' value should be an object
60
- that maps URLs to either a string, or to an array of glob patterns.`,
61
- "templated-url-matches-glob": oneLine`One of the 'templatedURLs' URLs is already
62
- being tracked via 'globPatterns': `,
63
- "invalid-glob-ignores": oneLine`The 'globIgnores' parameter must be an array of
64
- glob pattern strings.`,
65
- "manifest-entry-bad-url": oneLine`The generated manifest contains an entry without
66
- a URL string. This is likely an error with @serwist/build.`,
67
- "modify-url-prefix-bad-prefixes": oneLine`The 'modifyURLPrefix' parameter must be
68
- an object with string key value pairs.`,
69
- "invalid-inject-manifest-arg": oneLine`The input to 'injectManifest()' must be an
70
- object.`,
71
- "injection-point-not-found": oneLine`Unable to find a place to inject the manifest.
72
- Please ensure that your service worker file contains the following: `,
73
- "multiple-injection-points": oneLine`Please ensure that your 'swSrc' file contains
74
- only one match for the following: `,
75
- "bad-template-urls-asset": oneLine`There was an issue using one of the provided
76
- 'templatedURLs'.`,
77
- "invalid-generate-file-manifest-arg": oneLine`The input to generateFileManifest()
78
- must be an Object.`,
79
- "invalid-sw-src": `The 'swSrc' file can't be read.`,
80
- "same-src-and-dest": oneLine`Unable to find a place to inject the manifest. This is
81
- likely because swSrc and swDest are configured to the same file.
82
- Please ensure that your swSrc file contains the following:`,
83
- "no-module-name": oneLine`You must provide a moduleName parameter when calling
84
- getModuleURL().`,
85
- "bad-manifest-transforms-return-value": oneLine`The return value from a
86
- manifestTransform should be an object with 'manifest' and optionally
87
- 'warnings' properties.`,
88
- "string-entry-warning": oneLine`Some items were passed to additionalPrecacheEntries
89
- without revisioning info. This is generally NOT safe. Learn more at
90
- https://bit.ly/wb-precache.`,
91
- "cant-find-sourcemap": oneLine`The swSrc file refers to a sourcemap that can't be
92
- opened:`,
93
- "manifest-transforms": oneLine`When using manifestTransforms, you must provide
94
- an array of functions.`
95
- };
96
-
97
- const getCompositeDetails = (compositeURL, dependencyDetails)=>{
98
- let totalSize = 0;
99
- let compositeHash = "";
100
- for (const fileDetails of dependencyDetails){
101
- totalSize += fileDetails.size;
102
- compositeHash += fileDetails.hash === null ? "" : fileDetails.hash;
103
- }
104
- const md5 = crypto.createHash("md5");
105
- md5.update(compositeHash);
106
- const hashOfHashes = md5.digest("hex");
107
- return {
108
- file: compositeURL,
109
- hash: hashOfHashes,
110
- size: totalSize
111
- };
112
- };
113
-
114
- function getStringHash(input) {
115
- const md5 = crypto.createHash("md5");
116
- md5.update(input);
117
- return md5.digest("hex");
118
- }
119
-
120
- const getFileHash = (file)=>{
121
- try {
122
- const buffer = readFileSync(file);
123
- return getStringHash(buffer);
124
- } catch (err) {
125
- throw new Error(`${errors["unable-to-get-file-hash"]} '${err instanceof Error && err.message ? err.message : ""}'`);
126
- }
127
- };
128
-
129
- const getFileSize = (file)=>{
130
- try {
131
- const stat = fs.statSync(file);
132
- if (!stat.isFile()) {
133
- return null;
134
- }
135
- return stat.size;
136
- } catch (err) {
137
- throw new Error(`${errors["unable-to-get-file-size"]} '${err instanceof Error && err.message ? err.message : ""}'`);
138
- }
139
- };
140
-
141
- const getFileDetails = ({ globDirectory, globFollow, globIgnores, globPattern })=>{
142
- let globbedFiles;
143
- let warning = "";
144
- try {
145
- globbedFiles = globSync(globPattern, {
146
- cwd: globDirectory,
147
- follow: globFollow,
148
- ignore: globIgnores
149
- });
150
- } catch (err) {
151
- throw new Error(`${errors["unable-to-glob-files"]} '${err instanceof Error && err.message ? err.message : ""}'`);
152
- }
153
- const globbedFileDetails = [];
154
- for (const file of globbedFiles){
155
- const fullPath = path.join(globDirectory, file);
156
- const fileSize = getFileSize(fullPath);
157
- if (fileSize !== null) {
158
- const fileHash = getFileHash(fullPath);
159
- globbedFileDetails.push({
160
- file: path.relative(globDirectory, fullPath),
161
- hash: fileHash,
162
- size: fileSize
163
- });
164
- }
165
- }
166
- return {
167
- globbedFileDetails,
168
- warning
169
- };
170
- };
171
-
172
- const getStringDetails = (url, str)=>({
173
- file: url,
174
- hash: getStringHash(str),
175
- size: str.length
176
- });
177
-
178
- const additionalPrecacheEntriesTransform = (additionalPrecacheEntries)=>{
179
- return (manifest)=>{
180
- const warnings = [];
181
- const stringEntries = new Set();
182
- for (const additionalEntry of additionalPrecacheEntries){
183
- if (typeof additionalEntry === "string") {
184
- stringEntries.add(additionalEntry);
185
- manifest.push({
186
- revision: null,
187
- size: 0,
188
- url: additionalEntry
189
- });
190
- } else {
191
- if (additionalEntry && !additionalEntry.integrity && additionalEntry.revision === undefined) {
192
- stringEntries.add(additionalEntry.url);
193
- }
194
- manifest.push(Object.assign({
195
- size: 0
196
- }, additionalEntry));
197
- }
198
- }
199
- if (stringEntries.size > 0) {
200
- let urls = "\n";
201
- for (const stringEntry of stringEntries){
202
- urls += ` - ${stringEntry}\n`;
203
- }
204
- warnings.push(errors["string-entry-warning"] + urls);
205
- }
206
- return {
207
- manifest,
208
- warnings
209
- };
210
- };
211
- };
212
-
213
- function maximumSizeTransform(maximumFileSizeToCacheInBytes) {
214
- return (originalManifest)=>{
215
- const warnings = [];
216
- const manifest = originalManifest.filter((entry)=>{
217
- if (entry.size <= maximumFileSizeToCacheInBytes) {
218
- return true;
219
- }
220
- warnings.push(`${entry.url} is ${prettyBytes(entry.size)}, and won't be precached. Configure maximumFileSizeToCacheInBytes to change this limit.`);
221
- return false;
222
- });
223
- return {
224
- manifest,
225
- warnings
226
- };
227
- };
228
- }
229
-
230
- const escapeRegExp = (str)=>{
231
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
232
- };
233
-
234
- function modifyURLPrefixTransform(modifyURLPrefix) {
235
- if (!modifyURLPrefix || typeof modifyURLPrefix !== "object" || Array.isArray(modifyURLPrefix)) {
236
- throw new Error(errors["modify-url-prefix-bad-prefixes"]);
237
- }
238
- if (Object.keys(modifyURLPrefix).length === 0) {
239
- return (manifest)=>{
240
- return {
241
- manifest
242
- };
243
- };
244
- }
245
- for (const key of Object.keys(modifyURLPrefix)){
246
- if (typeof modifyURLPrefix[key] !== "string") {
247
- throw new Error(errors["modify-url-prefix-bad-prefixes"]);
248
- }
249
- }
250
- const safeModifyURLPrefixes = Object.keys(modifyURLPrefix).map(escapeRegExp);
251
- const prefixMatchesStrings = safeModifyURLPrefixes.join("|");
252
- const modifyRegex = new RegExp(`^(${prefixMatchesStrings})`);
253
- return (originalManifest)=>{
254
- const manifest = originalManifest.map((entry)=>{
255
- if (typeof entry.url !== "string") {
256
- throw new Error(errors["manifest-entry-bad-url"]);
257
- }
258
- entry.url = entry.url.replace(modifyRegex, (match)=>{
259
- return modifyURLPrefix[match];
260
- });
261
- return entry;
262
- });
263
- return {
264
- manifest
265
- };
266
- };
267
- }
268
-
269
- function noRevisionForURLsMatchingTransform(regexp) {
270
- if (!(regexp instanceof RegExp)) {
271
- throw new Error(errors["invalid-dont-cache-bust"]);
272
- }
273
- return (originalManifest)=>{
274
- const manifest = originalManifest.map((entry)=>{
275
- if (typeof entry.url !== "string") {
276
- throw new Error(errors["manifest-entry-bad-url"]);
277
- }
278
- if (entry.url.match(regexp)) {
279
- entry.revision = null;
280
- }
281
- return entry;
282
- });
283
- return {
284
- manifest
285
- };
286
- };
287
- }
288
-
289
- async function transformManifest({ additionalPrecacheEntries, dontCacheBustURLsMatching, fileDetails, manifestTransforms, maximumFileSizeToCacheInBytes, modifyURLPrefix, transformParam, disablePrecacheManifest }) {
290
- if (disablePrecacheManifest) {
291
- return {
292
- count: 0,
293
- size: 0,
294
- manifestEntries: undefined,
295
- warnings: []
296
- };
297
- }
298
- const allWarnings = [];
299
- const normalizedManifest = fileDetails.map((fileDetails)=>({
300
- url: fileDetails.file.replace(/\\/g, "/"),
301
- revision: fileDetails.hash,
302
- size: fileDetails.size
303
- }));
304
- const transformsToApply = [];
305
- if (maximumFileSizeToCacheInBytes) {
306
- transformsToApply.push(maximumSizeTransform(maximumFileSizeToCacheInBytes));
307
- }
308
- if (modifyURLPrefix) {
309
- transformsToApply.push(modifyURLPrefixTransform(modifyURLPrefix));
310
- }
311
- if (dontCacheBustURLsMatching) {
312
- transformsToApply.push(noRevisionForURLsMatchingTransform(dontCacheBustURLsMatching));
313
- }
314
- if (manifestTransforms) {
315
- transformsToApply.push(...manifestTransforms);
316
- }
317
- if (additionalPrecacheEntries) {
318
- transformsToApply.push(additionalPrecacheEntriesTransform(additionalPrecacheEntries));
319
- }
320
- let transformedManifest = normalizedManifest;
321
- for (const transform of transformsToApply){
322
- const result = await transform(transformedManifest, transformParam);
323
- if (!("manifest" in result)) {
324
- throw new Error(errors["bad-manifest-transforms-return-value"]);
325
- }
326
- transformedManifest = result.manifest;
327
- allWarnings.push(...result.warnings || []);
328
- }
329
- const count = transformedManifest.length;
330
- let size = 0;
331
- for (const manifestEntry of transformedManifest){
332
- size += manifestEntry.size || 0;
333
- delete manifestEntry.size;
334
- }
335
- return {
336
- count,
337
- size,
338
- manifestEntries: transformedManifest,
339
- warnings: allWarnings
340
- };
341
- }
342
-
343
- const getFileManifestEntries = async ({ additionalPrecacheEntries, dontCacheBustURLsMatching, globDirectory, globFollow, globIgnores, globPatterns = [], globStrict, manifestTransforms, maximumFileSizeToCacheInBytes, modifyURLPrefix, templatedURLs, disablePrecacheManifest })=>{
344
- if (disablePrecacheManifest) {
345
- return {
346
- count: 0,
347
- size: 0,
348
- manifestEntries: undefined,
349
- warnings: []
350
- };
351
- }
352
- const warnings = [];
353
- const allFileDetails = new Map();
354
- try {
355
- for (const globPattern of globPatterns){
356
- const { globbedFileDetails, warning } = getFileDetails({
357
- globDirectory,
358
- globFollow,
359
- globIgnores,
360
- globPattern,
361
- globStrict
362
- });
363
- if (warning) ;
364
- for (const details of globbedFileDetails){
365
- if (details && !allFileDetails.has(details.file)) {
366
- allFileDetails.set(details.file, details);
367
- }
368
- }
369
- }
370
- } catch (error) {
371
- if (error instanceof Error && error.message) {
372
- warnings.push(error.message);
373
- }
374
- }
375
- if (templatedURLs) {
376
- for (const url of Object.keys(templatedURLs)){
377
- assert(!allFileDetails.has(url), errors["templated-url-matches-glob"]);
378
- const dependencies = templatedURLs[url];
379
- if (Array.isArray(dependencies)) {
380
- const details = dependencies.reduce((previous, globPattern)=>{
381
- try {
382
- const { globbedFileDetails, warning } = getFileDetails({
383
- globDirectory,
384
- globFollow,
385
- globIgnores,
386
- globPattern,
387
- globStrict
388
- });
389
- if (warning) ;
390
- return previous.concat(globbedFileDetails);
391
- } catch (error) {
392
- const debugObj = {};
393
- debugObj[url] = dependencies;
394
- throw new Error(`${errors["bad-template-urls-asset"]} '${globPattern}' from '${JSON.stringify(debugObj)}':\n${error instanceof Error ? error.toString() : ""}`);
395
- }
396
- }, []);
397
- if (details.length === 0) {
398
- throw new Error(`${errors["bad-template-urls-asset"]} The glob pattern '${dependencies.toString()}' did not match anything.`);
399
- }
400
- allFileDetails.set(url, getCompositeDetails(url, details));
401
- } else if (typeof dependencies === "string") {
402
- allFileDetails.set(url, getStringDetails(url, dependencies));
403
- }
404
- }
405
- }
406
- const transformedManifest = await transformManifest({
407
- additionalPrecacheEntries,
408
- dontCacheBustURLsMatching,
409
- manifestTransforms,
410
- maximumFileSizeToCacheInBytes,
411
- modifyURLPrefix,
412
- fileDetails: Array.from(allFileDetails.values()),
413
- disablePrecacheManifest
414
- });
415
- transformedManifest.warnings.push(...warnings);
416
- return transformedManifest;
417
- };
418
-
419
- const validateGetManifestOptions = async (input)=>{
420
- const result = await (await import('./chunks/get-manifest.js')).getManifestOptions.spa(input, {
421
- error: validationErrorMap
422
- });
423
- if (!result.success) {
424
- throw new SerwistConfigError({
425
- moduleName: "@serwist/build",
426
- message: z.prettifyError(result.error)
427
- });
428
- }
429
- return result.data;
430
- };
431
- const validateInjectManifestOptions = async (input)=>{
432
- const result = await (await import('./chunks/inject-manifest.js').then(function (n) { return n.a; })).injectManifestOptions.spa(input, {
433
- error: validationErrorMap
434
- });
435
- if (!result.success) {
436
- throw new SerwistConfigError({
437
- moduleName: "@serwist/build",
438
- message: z.prettifyError(result.error)
439
- });
440
- }
441
- return result.data;
442
- };
443
-
444
- const getManifest = async (config)=>{
445
- const options = await validateGetManifestOptions(config);
446
- return await getFileManifestEntries(options);
447
- };
448
-
449
- const innerRegex = /[#@] sourceMappingURL=([^\s'"]*)/;
450
- const regex = RegExp(`(?:/\\*(?:\\s*\r?\n(?://)?)?(?:${innerRegex.source})\\s*\\*/|//(?:${innerRegex.source}))\\s*`);
451
- function getSourceMapURL(srcContents) {
452
- const match = srcContents.match(regex);
453
- return match ? match[1] || match[2] || "" : null;
454
- }
455
-
456
- function rebasePath({ baseDirectory, file }) {
457
- const absolutePath = path.resolve(file);
458
- const relativePath = path.relative(baseDirectory, absolutePath);
459
- const normalizedPath = path.normalize(relativePath);
460
- return toUnix(normalizedPath);
461
- }
462
-
463
- async function replaceAndUpdateSourceMap({ jsFilename, originalMap, originalSource, replaceString, searchString }) {
464
- const generator = new SourceMapGenerator({
465
- file: jsFilename
466
- });
467
- const consumer = await new SourceMapConsumer(originalMap);
468
- let pos;
469
- let src = originalSource;
470
- const replacements = [];
471
- let lineNum = 0;
472
- let filePos = 0;
473
- const lines = src.split("\n");
474
- for (let line of lines){
475
- lineNum++;
476
- let searchPos = 0;
477
- while((pos = line.indexOf(searchString, searchPos)) !== -1){
478
- src = src.substring(0, filePos + pos) + replaceString + src.substring(filePos + pos + searchString.length);
479
- line = line.substring(0, pos) + replaceString + line.substring(pos + searchString.length);
480
- replacements.push({
481
- line: lineNum,
482
- column: pos
483
- });
484
- searchPos = pos + replaceString.length;
485
- }
486
- filePos += line.length + 1;
487
- }
488
- replacements.reverse();
489
- consumer.eachMapping((mapping)=>{
490
- for (const replacement of replacements){
491
- if (replacement.line === mapping.generatedLine && mapping.generatedColumn > replacement.column) {
492
- const offset = searchString.length - replaceString.length;
493
- mapping.generatedColumn -= offset;
494
- }
495
- }
496
- if (mapping.source) {
497
- const newMapping = {
498
- generated: {
499
- line: mapping.generatedLine,
500
- column: mapping.generatedColumn
501
- },
502
- original: {
503
- line: mapping.originalLine,
504
- column: mapping.originalColumn
505
- },
506
- source: mapping.source
507
- };
508
- return generator.addMapping(newMapping);
509
- }
510
- return mapping;
511
- });
512
- consumer.destroy();
513
- const updatedSourceMap = Object.assign(JSON.parse(generator.toString()), {
514
- names: originalMap.names,
515
- sourceRoot: originalMap.sourceRoot,
516
- sources: originalMap.sources,
517
- sourcesContent: originalMap.sourcesContent
518
- });
519
- return {
520
- map: JSON.stringify(updatedSourceMap),
521
- source: src
522
- };
523
- }
524
-
525
- function translateURLToSourcemapPaths(url, swSrc, swDest) {
526
- let destPath;
527
- let srcPath;
528
- let warning;
529
- if (url && !url.startsWith("data:")) {
530
- const possibleSrcPath = path.resolve(path.dirname(swSrc), url);
531
- if (fs.existsSync(possibleSrcPath)) {
532
- srcPath = toUnix(possibleSrcPath);
533
- destPath = toUnix(path.resolve(path.dirname(swDest), url));
534
- } else {
535
- warning = `${errors["cant-find-sourcemap"]} ${possibleSrcPath}`;
536
- }
537
- }
538
- return {
539
- destPath,
540
- srcPath,
541
- warning
542
- };
543
- }
544
-
545
- const injectManifest = async (config)=>{
546
- const options = await validateInjectManifestOptions(config);
547
- for (const file of [
548
- options.swSrc,
549
- options.swDest
550
- ]){
551
- options.globIgnores.push(rebasePath({
552
- file,
553
- baseDirectory: options.globDirectory
554
- }));
555
- }
556
- const globalRegexp = new RegExp(escapeRegExp(options.injectionPoint), "g");
557
- const { count, size, manifestEntries, warnings } = await getFileManifestEntries(options);
558
- let swFileContents;
559
- try {
560
- swFileContents = await fsp.readFile(options.swSrc, "utf8");
561
- } catch (error) {
562
- throw new Error(`${errors["invalid-sw-src"]} ${error instanceof Error && error.message ? error.message : ""}`);
563
- }
564
- const injectionResults = swFileContents.match(globalRegexp);
565
- const injectionPoint = options.injectionPoint ? options.injectionPoint : "";
566
- if (!injectionResults) {
567
- if (path.resolve(options.swSrc) === path.resolve(options.swDest)) {
568
- throw new Error(`${errors["same-src-and-dest"]} ${injectionPoint}`);
569
- }
570
- throw new Error(`${errors["injection-point-not-found"]} ${injectionPoint}`);
571
- }
572
- assert(injectionResults.length === 1, `${errors["multiple-injection-points"]} ${injectionPoint}`);
573
- const manifestString = manifestEntries === undefined ? "undefined" : JSON.stringify(manifestEntries);
574
- const filesToWrite = {};
575
- const url = getSourceMapURL(swFileContents);
576
- const { destPath, srcPath, warning } = translateURLToSourcemapPaths(url, options.swSrc, options.swDest);
577
- if (warning) {
578
- warnings.push(warning);
579
- }
580
- if (srcPath && destPath) {
581
- const originalMap = JSON.parse(await fsp.readFile(srcPath, "utf-8"));
582
- const { map, source } = await replaceAndUpdateSourceMap({
583
- originalMap,
584
- jsFilename: toUnix(path.basename(options.swDest)),
585
- originalSource: swFileContents,
586
- replaceString: manifestString,
587
- searchString: options.injectionPoint
588
- });
589
- filesToWrite[options.swDest] = source;
590
- filesToWrite[destPath] = map;
591
- } else {
592
- filesToWrite[options.swDest] = swFileContents.replace(globalRegexp, manifestString);
593
- }
594
- for (const [file, contents] of Object.entries(filesToWrite)){
595
- try {
596
- await fsp.mkdir(path.dirname(file), {
597
- recursive: true
598
- });
599
- } catch (error) {
600
- throw new Error(`${errors["unable-to-make-sw-directory"]} '${error instanceof Error && error.message ? error.message : ""}'`);
601
- }
602
- await fsp.writeFile(file, contents);
603
- }
604
- return {
605
- count,
606
- size,
607
- warnings,
608
- filePaths: Object.keys(filesToWrite).map((f)=>toUnix(path.resolve(f)))
609
- };
610
- };
611
-
612
- const stringify = JSON.stringify;
613
-
614
- export { errors, escapeRegExp, getFileManifestEntries, getManifest, getSourceMapURL, injectManifest, rebasePath, replaceAndUpdateSourceMap, stringify, transformManifest, translateURLToSourcemapPaths, validateGetManifestOptions, validateInjectManifestOptions };
@@ -1,13 +0,0 @@
1
- import { type Assignable, assertType, type Equals } from "./schema/assert-type.js";
2
- import { basePartial } from "./schema/base.js";
3
- import { SerwistConfigError, validationErrorMap } from "./schema/error.js";
4
- import { getManifestOptions } from "./schema/get-manifest.js";
5
- import { globPartial, optionalGlobDirectoryPartial, requiredGlobDirectoryPartial } from "./schema/glob.js";
6
- import { baseInjectPartial, injectManifestOptions } from "./schema/inject-manifest.js";
7
- import { manifestEntry } from "./schema/manifest-entry.js";
8
- import { manifestTransform, manifestTransformResult } from "./schema/manifest-transform.js";
9
- import { optionalSwDestPartial, requiredSwDestPartial } from "./schema/sw-dest.js";
10
- import { asyncFn, fn } from "./schema/utils.js";
11
- export { assertType, fn, asyncFn, basePartial, globPartial, baseInjectPartial as injectPartial, injectManifestOptions, getManifestOptions, manifestEntry, manifestTransform, manifestTransformResult, optionalGlobDirectoryPartial, requiredGlobDirectoryPartial, optionalSwDestPartial, requiredSwDestPartial, validationErrorMap, SerwistConfigError, };
12
- export type { Assignable, Equals };
13
- //# sourceMappingURL=index.schema.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.schema.d.ts","sourceRoot":"","sources":["../src/index.schema.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,UAAU,EAAE,UAAU,EAAE,KAAK,MAAM,EAAE,MAAM,yBAAyB,CAAC;AACnF,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC3E,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,4BAA4B,EAAE,4BAA4B,EAAE,MAAM,kBAAkB,CAAC;AAC3G,OAAO,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AACvF,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAE,iBAAiB,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAC5F,OAAO,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AACnF,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,mBAAmB,CAAC;AAEhD,OAAO,EACL,UAAU,EACV,EAAE,EACF,OAAO,EACP,WAAW,EACX,WAAW,EACX,iBAAiB,IAAI,aAAa,EAClC,qBAAqB,EACrB,kBAAkB,EAClB,aAAa,EACb,iBAAiB,EACjB,uBAAuB,EACvB,4BAA4B,EAC5B,4BAA4B,EAC5B,qBAAqB,EACrB,qBAAqB,EACrB,kBAAkB,EAClB,kBAAkB,GACnB,CAAC;AACF,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC"}
@@ -1,9 +0,0 @@
1
- export { a as asyncFn, b as basePartial, f as fn, g as globPartial, m as manifestEntry, c as manifestTransform, d as manifestTransformResult, o as optionalGlobDirectoryPartial, r as requiredGlobDirectoryPartial } from './chunks/glob.js';
2
- export { S as SerwistConfigError, v as validationErrorMap } from './chunks/constants.js';
3
- export { getManifestOptions } from './chunks/get-manifest.js';
4
- export { i as injectManifestOptions, b as injectPartial, o as optionalSwDestPartial, r as requiredSwDestPartial } from './chunks/inject-manifest.js';
5
- import 'zod';
6
-
7
- function assertType() {}
8
-
9
- export { assertType };
@@ -1,29 +0,0 @@
1
- import type { BuildResult, InjectManifestOptions } from "./types.js";
2
- /**
3
- * This method creates a list of URLs to precache, referred to as a "precache
4
- * manifest", based on the options you provide.
5
- *
6
- * The manifest is injected into the `swSrc` file, and the placeholder string
7
- * `injectionPoint` determines where in the file the manifest should go.
8
- *
9
- * The final service worker file, with the manifest injected, is written to
10
- * disk at `swDest`.
11
- *
12
- * This method will not compile or bundle your `swSrc` file; it just handles
13
- * injecting the manifest.
14
- *
15
- * ```
16
- * // The following lists some common options; see the rest of the documentation
17
- * // for the full set of options and defaults.
18
- * const {count, size, warnings} = await injectManifest({
19
- * dontCacheBustURLsMatching: [new RegExp('...')],
20
- * globDirectory: '...',
21
- * globPatterns: ['...', '...'],
22
- * maximumFileSizeToCacheInBytes: ...,
23
- * swDest: '...',
24
- * swSrc: '...',
25
- * });
26
- * ```
27
- */
28
- export declare const injectManifest: (config: InjectManifestOptions) => Promise<BuildResult>;
29
- //# sourceMappingURL=inject-manifest.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"inject-manifest.d.ts","sourceRoot":"","sources":["../src/inject-manifest.ts"],"names":[],"mappings":"AAoBA,OAAO,KAAK,EAAE,WAAW,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAC;AAErE;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,cAAc,GAAU,QAAQ,qBAAqB,KAAG,OAAO,CAAC,WAAW,CAwFvF,CAAC"}
@@ -1,12 +0,0 @@
1
- import type { ManifestEntry } from "../types.js";
2
- type AdditionalManifestEntriesTransform = (manifest: (ManifestEntry & {
3
- size: number;
4
- })[]) => {
5
- manifest: (ManifestEntry & {
6
- size: number;
7
- })[];
8
- warnings: string[];
9
- };
10
- export declare const additionalPrecacheEntriesTransform: (additionalPrecacheEntries: (ManifestEntry | string)[]) => AdditionalManifestEntriesTransform;
11
- export {};
12
- //# sourceMappingURL=additional-precache-entries-transform.d.ts.map