@next-font/plugin-vite 1.3.0 → 1.3.2

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 (61) hide show
  1. package/dist/{escodegen-DyMV8y05.js → escodegen-Bg18t0PG.js} +1 -1
  2. package/dist/index-67dkpRNt.js +79 -0
  3. package/dist/{index-zBNqiqVh.js → index-zyY5iDP6.js} +1 -1
  4. package/dist/index.js +1 -3
  5. package/package.json +1 -1
  6. package/dist/escodegen-BgZHbZlI.js +0 -5298
  7. package/dist/escodegen-BgZHbZlI.js.map +0 -1
  8. package/dist/escodegen-CE_3K55m.js +0 -5298
  9. package/dist/escodegen-CE_3K55m.js.map +0 -1
  10. package/dist/escodegen-CcjHPeru.js +0 -5298
  11. package/dist/escodegen-CcjHPeru.js.map +0 -1
  12. package/dist/escodegen-CvnByJYb.js +0 -5298
  13. package/dist/escodegen-CvnByJYb.js.map +0 -1
  14. package/dist/escodegen-CyyYl3Ru.js +0 -5298
  15. package/dist/escodegen-CyyYl3Ru.js.map +0 -1
  16. package/dist/escodegen-D-UqarBv.js +0 -5298
  17. package/dist/escodegen-D-UqarBv.js.map +0 -1
  18. package/dist/escodegen-D1ExFsOu.js +0 -5298
  19. package/dist/escodegen-D1ExFsOu.js.map +0 -1
  20. package/dist/escodegen-DhS8gxED.js +0 -5298
  21. package/dist/escodegen-DhS8gxED.js.map +0 -1
  22. package/dist/escodegen-o7sNOZ-d.js +0 -5298
  23. package/dist/escodegen-o7sNOZ-d.js.map +0 -1
  24. package/dist/index-B6M1BKem.js +0 -3852
  25. package/dist/index-B6M1BKem.js.map +0 -1
  26. package/dist/index-BBnr2Ij5.js +0 -6970
  27. package/dist/index-BBnr2Ij5.js.map +0 -1
  28. package/dist/index-BUL3xgiH.js +0 -3851
  29. package/dist/index-BUL3xgiH.js.map +0 -1
  30. package/dist/index-Bgbg2WYx.js +0 -6970
  31. package/dist/index-Bgbg2WYx.js.map +0 -1
  32. package/dist/index-BiSz54YK.js +0 -6970
  33. package/dist/index-BiSz54YK.js.map +0 -1
  34. package/dist/index-BjC6MXVP.js +0 -3851
  35. package/dist/index-BjC6MXVP.js.map +0 -1
  36. package/dist/index-BknOo0Zr.js +0 -6970
  37. package/dist/index-BknOo0Zr.js.map +0 -1
  38. package/dist/index-C-zBTUD_.js +0 -3852
  39. package/dist/index-C-zBTUD_.js.map +0 -1
  40. package/dist/index-C0NlOFro.js +0 -3851
  41. package/dist/index-C0NlOFro.js.map +0 -1
  42. package/dist/index-C7SN2-vF.js +0 -6970
  43. package/dist/index-C7SN2-vF.js.map +0 -1
  44. package/dist/index-CLLYtm7D.js +0 -3853
  45. package/dist/index-CLLYtm7D.js.map +0 -1
  46. package/dist/index-CZZp2BW0.js +0 -79
  47. package/dist/index-CyE6nKxy.js +0 -3856
  48. package/dist/index-CyE6nKxy.js.map +0 -1
  49. package/dist/index-D-QcVmRl.js +0 -3850
  50. package/dist/index-D-QcVmRl.js.map +0 -1
  51. package/dist/index-D15_W2rR.js +0 -6970
  52. package/dist/index-D15_W2rR.js.map +0 -1
  53. package/dist/index-Dgy5wars.js +0 -6970
  54. package/dist/index-Dgy5wars.js.map +0 -1
  55. package/dist/index-Dob7-G92.js +0 -6970
  56. package/dist/index-Dob7-G92.js.map +0 -1
  57. package/dist/index-PLAGUBZD.js +0 -6970
  58. package/dist/index-PLAGUBZD.js.map +0 -1
  59. package/dist/index-y2m5QvKY.js +0 -3851
  60. package/dist/index-y2m5QvKY.js.map +0 -1
  61. package/dist/index.js.map +0 -1
@@ -1,3856 +0,0 @@
1
- import { fileURLToPath } from 'node:url';
2
- import path from 'node:path';
3
- import require$$0, { win32, posix } from 'path';
4
- import require$$3 from 'crypto';
5
- import { isCSSRequest } from 'vite';
6
- import require$$0$1 from 'postcss';
7
-
8
- // From https://github.com/vercel/next.js/blob/a90f0c91d6063d25be513779cb21fb8892ba4201/packages/next/src/build/webpack/plugins/next-font-manifest-plugin.ts
9
- /**
10
- * When calling font functions with next/font, you can specify if you'd like the font to be preloaded (true by default).
11
- * e.g.: const inter = Inter({ subsets: ['latin'], preload: true })
12
- *
13
- * In that case, next-font-loader will emit the font file as [name].p.[ext] instead of [name].[ext]
14
- * This function returns those files from an array that can include both preloaded and non-preloaded files.
15
- */ function getPreloadedFontFiles(fontFiles) {
16
- return fontFiles.filter((file)=>/\.p\.(woff|woff2|eot|ttf|otf)$/.test(file));
17
- }
18
- /**
19
- * Similarly to getPreloadedFontFiles, but returns true if some of the files includes -s in the name.
20
- * This means that a font is using size adjust in its fallback font.
21
- * This was added to enable adding data-size-adjust="true" to the dom, used by the Google Aurora team to collect statistics.
22
- */ function getPageIsUsingSizeAdjust(fontFiles) {
23
- return fontFiles.some((file)=>file.includes('-s'));
24
- }
25
-
26
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
27
-
28
- function getDefaultExportFromCjs (x) {
29
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
30
- }
31
-
32
- const normalizePathRegExp = new RegExp(`\\${win32.sep}`, 'g');
33
- const normalizePath = function normalizePath(filename) {
34
- return filename.replace(normalizePathRegExp, posix.sep);
35
- };
36
- const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
37
- const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
38
- const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
39
- forbiddenIdentifiers.add('');
40
- const makeLegalIdentifier = function makeLegalIdentifier(str) {
41
- let identifier = str.replace(/-(\w)/g, (_, letter)=>letter.toUpperCase()).replace(/[^$_a-zA-Z0-9]/g, '_');
42
- if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {
43
- identifier = `_${identifier}`;
44
- }
45
- return identifier || '_';
46
- };
47
- function stringify$1(obj) {
48
- return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char)=>`\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
49
- }
50
- function serializeArray(arr, indent, baseIndent) {
51
- let output = '[';
52
- const separator = indent ? `\n${baseIndent}${indent}` : '';
53
- for(let i = 0; i < arr.length; i++){
54
- const key = arr[i];
55
- output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`;
56
- }
57
- return `${output}${indent ? `\n${baseIndent}` : ''}]`;
58
- }
59
- function serializeObject(obj, indent, baseIndent) {
60
- let output = '{';
61
- const separator = indent ? `\n${baseIndent}${indent}` : '';
62
- const entries = Object.entries(obj);
63
- for(let i = 0; i < entries.length; i++){
64
- const [key, value] = entries[i];
65
- const stringKey = makeLegalIdentifier(key) === key ? key : stringify$1(key);
66
- output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`;
67
- }
68
- return `${output}${indent ? `\n${baseIndent}` : ''}}`;
69
- }
70
- function serialize(obj, indent, baseIndent) {
71
- if (typeof obj === 'object' && obj !== null) {
72
- if (Array.isArray(obj)) return serializeArray(obj, indent, baseIndent);
73
- if (obj instanceof Date) return `new Date(${obj.getTime()})`;
74
- if (obj instanceof RegExp) return obj.toString();
75
- return serializeObject(obj, indent, baseIndent);
76
- }
77
- if (typeof obj === 'number') {
78
- if (obj === Infinity) return 'Infinity';
79
- if (obj === -Infinity) return '-Infinity';
80
- if (obj === 0) return 1 / obj === Infinity ? '0' : '-0';
81
- if (obj !== obj) return 'NaN'; // eslint-disable-line no-self-compare
82
- }
83
- if (typeof obj === 'symbol') {
84
- const key = Symbol.keyFor(obj);
85
- // eslint-disable-next-line no-undefined
86
- if (key !== undefined) return `Symbol.for(${stringify$1(key)})`;
87
- }
88
- if (typeof obj === 'bigint') return `${obj}n`;
89
- return stringify$1(obj);
90
- }
91
- // isWellFormed exists from Node.js 20
92
- const hasStringIsWellFormed = 'isWellFormed' in String.prototype;
93
- function isWellFormedString(input) {
94
- // @ts-expect-error String::isWellFormed exists from ES2024. tsconfig lib is set to ES6
95
- if (hasStringIsWellFormed) return input.isWellFormed();
96
- // https://github.com/tc39/proposal-is-usv-string/blob/main/README.md#algorithm
97
- return !/\p{Surrogate}/u.test(input);
98
- }
99
- const dataToEsm = function dataToEsm(data, options = {}) {
100
- var _a, _b;
101
- const t = options.compact ? '' : 'indent' in options ? options.indent : '\t';
102
- const _ = options.compact ? '' : ' ';
103
- const n = options.compact ? '' : '\n';
104
- const declarationType = options.preferConst ? 'const' : 'var';
105
- if (options.namedExports === false || typeof data !== 'object' || Array.isArray(data) || data instanceof Date || data instanceof RegExp || data === null) {
106
- const code = serialize(data, options.compact ? null : t, '');
107
- const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape
108
- return `export default${magic}${code};`;
109
- }
110
- let maxUnderbarPrefixLength = 0;
111
- for (const key of Object.keys(data)){
112
- const underbarPrefixLength = (_b = (_a = /^(_+)/.exec(key)) === null || _a === void 0 ? void 0 : _a[0].length) !== null && _b !== void 0 ? _b : 0;
113
- if (underbarPrefixLength > maxUnderbarPrefixLength) {
114
- maxUnderbarPrefixLength = underbarPrefixLength;
115
- }
116
- }
117
- const arbitraryNamePrefix = `${'_'.repeat(maxUnderbarPrefixLength + 1)}arbitrary`;
118
- let namedExportCode = '';
119
- const defaultExportRows = [];
120
- const arbitraryNameExportRows = [];
121
- for (const [key, value] of Object.entries(data)){
122
- if (key === makeLegalIdentifier(key)) {
123
- if (options.objectShorthand) defaultExportRows.push(key);
124
- else defaultExportRows.push(`${key}:${_}${key}`);
125
- namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
126
- } else {
127
- defaultExportRows.push(`${stringify$1(key)}:${_}${serialize(value, options.compact ? null : t, '')}`);
128
- if (options.includeArbitraryNames && isWellFormedString(key)) {
129
- const variableName = `${arbitraryNamePrefix}${arbitraryNameExportRows.length}`;
130
- namedExportCode += `${declarationType} ${variableName}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
131
- arbitraryNameExportRows.push(`${variableName} as ${JSON.stringify(key)}`);
132
- }
133
- }
134
- }
135
- const arbitraryExportCode = arbitraryNameExportRows.length > 0 ? `export${_}{${n}${t}${arbitraryNameExportRows.join(`,${n}${t}`)}${n}};${n}` : '';
136
- const defaultExportCode = `export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
137
- return `${namedExportCode}${arbitraryExportCode}${defaultExportCode}`;
138
- };
139
-
140
- var lib = {};
141
-
142
- var isUrlRequest_1;
143
- var hasRequiredIsUrlRequest;
144
-
145
- function requireIsUrlRequest () {
146
- if (hasRequiredIsUrlRequest) return isUrlRequest_1;
147
- hasRequiredIsUrlRequest = 1;
148
- const path = require$$0;
149
- function isUrlRequest(url) {
150
- // An URL is not an request if
151
- // 1. Allow `data URI`
152
- if (/^data:/i.test(url)) {
153
- return true;
154
- }
155
- // 2. It's an absolute url and it is not `windows` path like `C:\dir\file`
156
- if (/^[a-z][a-z0-9+.-]*:/i.test(url) && !path.win32.isAbsolute(url)) {
157
- return false;
158
- }
159
- // 3. It's a protocol-relative
160
- if (/^\/\//.test(url)) {
161
- return false;
162
- }
163
- // 4. It's some kind of url for a template
164
- if (/^#/.test(url)) {
165
- return false;
166
- }
167
- return true;
168
- }
169
- isUrlRequest_1 = isUrlRequest;
170
- return isUrlRequest_1;
171
- }
172
-
173
- var urlToRequest_1;
174
- var hasRequiredUrlToRequest;
175
-
176
- function requireUrlToRequest () {
177
- if (hasRequiredUrlToRequest) return urlToRequest_1;
178
- hasRequiredUrlToRequest = 1;
179
- // we can't use path.win32.isAbsolute because it also matches paths starting with a forward slash
180
- const matchNativeWin32Path = /^[A-Z]:[/\\]|^\\\\/i;
181
- function urlToRequest(url, root) {
182
- // Do not rewrite an empty url
183
- if (url === "") {
184
- return "";
185
- }
186
- const moduleRequestRegex = /^[^?]*~/;
187
- let request;
188
- if (matchNativeWin32Path.test(url)) {
189
- // absolute windows path, keep it
190
- request = url;
191
- } else if (root !== undefined && root !== false && /^\//.test(url)) {
192
- // if root is set and the url is root-relative
193
- switch(typeof root){
194
- // 1. root is a string: root is prefixed to the url
195
- case "string":
196
- // special case: `~` roots convert to module request
197
- if (moduleRequestRegex.test(root)) {
198
- request = root.replace(/([^~/])$/, "$1/") + url.slice(1);
199
- } else {
200
- request = root + url;
201
- }
202
- break;
203
- // 2. root is `true`: absolute paths are allowed
204
- // *nix only, windows-style absolute paths are always allowed as they doesn't start with a `/`
205
- case "boolean":
206
- request = url;
207
- break;
208
- default:
209
- throw new Error("Unexpected parameters to loader-utils 'urlToRequest': url = " + url + ", root = " + root + ".");
210
- }
211
- } else if (/^\.\.?\//.test(url)) {
212
- // A relative url stays
213
- request = url;
214
- } else {
215
- // every other url is threaded like a relative url
216
- request = "./" + url;
217
- }
218
- // A `~` makes the url an module
219
- if (moduleRequestRegex.test(request)) {
220
- request = request.replace(moduleRequestRegex, "");
221
- }
222
- return request;
223
- }
224
- urlToRequest_1 = urlToRequest;
225
- return urlToRequest_1;
226
- }
227
-
228
- var wasmHash = {exports: {}};
229
-
230
- /*
231
- MIT License http://www.opensource.org/licenses/mit-license.php
232
- Author Tobias Koppers @sokra
233
- */
234
-
235
- var hasRequiredWasmHash;
236
-
237
- function requireWasmHash () {
238
- if (hasRequiredWasmHash) return wasmHash.exports;
239
- hasRequiredWasmHash = 1;
240
- // 65536 is the size of a wasm memory page
241
- // 64 is the maximum chunk size for every possible wasm hash implementation
242
- // 4 is the maximum number of bytes per char for string encoding (max is utf-8)
243
- // ~3 makes sure that it's always a block of 4 chars, so avoid partially encoded bytes for base64
244
- const MAX_SHORT_STRING = Math.floor((65536 - 64) / 4) & -4;
245
- class WasmHash {
246
- /**
247
- * @param {WebAssembly.Instance} instance wasm instance
248
- * @param {WebAssembly.Instance[]} instancesPool pool of instances
249
- * @param {number} chunkSize size of data chunks passed to wasm
250
- * @param {number} digestSize size of digest returned by wasm
251
- */ constructor(instance, instancesPool, chunkSize, digestSize){
252
- const exports = /** @type {any} */ instance.exports;
253
- exports.init();
254
- this.exports = exports;
255
- this.mem = Buffer.from(exports.memory.buffer, 0, 65536);
256
- this.buffered = 0;
257
- this.instancesPool = instancesPool;
258
- this.chunkSize = chunkSize;
259
- this.digestSize = digestSize;
260
- }
261
- reset() {
262
- this.buffered = 0;
263
- this.exports.init();
264
- }
265
- /**
266
- * @param {Buffer | string} data data
267
- * @param {BufferEncoding=} encoding encoding
268
- * @returns {this} itself
269
- */ update(data, encoding) {
270
- if (typeof data === "string") {
271
- while(data.length > MAX_SHORT_STRING){
272
- this._updateWithShortString(data.slice(0, MAX_SHORT_STRING), encoding);
273
- data = data.slice(MAX_SHORT_STRING);
274
- }
275
- this._updateWithShortString(data, encoding);
276
- return this;
277
- }
278
- this._updateWithBuffer(data);
279
- return this;
280
- }
281
- /**
282
- * @param {string} data data
283
- * @param {BufferEncoding=} encoding encoding
284
- * @returns {void}
285
- */ _updateWithShortString(data, encoding) {
286
- const { exports, buffered, mem, chunkSize } = this;
287
- let endPos;
288
- if (data.length < 70) {
289
- if (!encoding || encoding === "utf-8" || encoding === "utf8") {
290
- endPos = buffered;
291
- for(let i = 0; i < data.length; i++){
292
- const cc = data.charCodeAt(i);
293
- if (cc < 0x80) {
294
- mem[endPos++] = cc;
295
- } else if (cc < 0x800) {
296
- mem[endPos] = cc >> 6 | 0xc0;
297
- mem[endPos + 1] = cc & 0x3f | 0x80;
298
- endPos += 2;
299
- } else {
300
- // bail-out for weird chars
301
- endPos += mem.write(data.slice(i), endPos, encoding);
302
- break;
303
- }
304
- }
305
- } else if (encoding === "latin1") {
306
- endPos = buffered;
307
- for(let i = 0; i < data.length; i++){
308
- const cc = data.charCodeAt(i);
309
- mem[endPos++] = cc;
310
- }
311
- } else {
312
- endPos = buffered + mem.write(data, buffered, encoding);
313
- }
314
- } else {
315
- endPos = buffered + mem.write(data, buffered, encoding);
316
- }
317
- if (endPos < chunkSize) {
318
- this.buffered = endPos;
319
- } else {
320
- const l = endPos & ~(this.chunkSize - 1);
321
- exports.update(l);
322
- const newBuffered = endPos - l;
323
- this.buffered = newBuffered;
324
- if (newBuffered > 0) {
325
- mem.copyWithin(0, l, endPos);
326
- }
327
- }
328
- }
329
- /**
330
- * @param {Buffer} data data
331
- * @returns {void}
332
- */ _updateWithBuffer(data) {
333
- const { exports, buffered, mem } = this;
334
- const length = data.length;
335
- if (buffered + length < this.chunkSize) {
336
- data.copy(mem, buffered, 0, length);
337
- this.buffered += length;
338
- } else {
339
- const l = buffered + length & ~(this.chunkSize - 1);
340
- if (l > 65536) {
341
- let i = 65536 - buffered;
342
- data.copy(mem, buffered, 0, i);
343
- exports.update(65536);
344
- const stop = l - buffered - 65536;
345
- while(i < stop){
346
- data.copy(mem, 0, i, i + 65536);
347
- exports.update(65536);
348
- i += 65536;
349
- }
350
- data.copy(mem, 0, i, l - buffered);
351
- exports.update(l - buffered - i);
352
- } else {
353
- data.copy(mem, buffered, 0, l - buffered);
354
- exports.update(l);
355
- }
356
- const newBuffered = length + buffered - l;
357
- this.buffered = newBuffered;
358
- if (newBuffered > 0) {
359
- data.copy(mem, 0, length - newBuffered, length);
360
- }
361
- }
362
- }
363
- digest(type) {
364
- const { exports, buffered, mem, digestSize } = this;
365
- exports.final(buffered);
366
- this.instancesPool.push(this);
367
- const hex = mem.toString("latin1", 0, digestSize);
368
- if (type === "hex") {
369
- return hex;
370
- }
371
- if (type === "binary" || !type) {
372
- return Buffer.from(hex, "hex");
373
- }
374
- return Buffer.from(hex, "hex").toString(type);
375
- }
376
- }
377
- const create = (wasmModule, instancesPool, chunkSize, digestSize)=>{
378
- if (instancesPool.length > 0) {
379
- const old = instancesPool.pop();
380
- old.reset();
381
- return old;
382
- } else {
383
- return new WasmHash(new WebAssembly.Instance(wasmModule), instancesPool, chunkSize, digestSize);
384
- }
385
- };
386
- wasmHash.exports = create;
387
- wasmHash.exports.MAX_SHORT_STRING = MAX_SHORT_STRING;
388
- return wasmHash.exports;
389
- }
390
-
391
- /*
392
- MIT License http://www.opensource.org/licenses/mit-license.php
393
- Author Tobias Koppers @sokra
394
- */
395
-
396
- var xxhash64_1;
397
- var hasRequiredXxhash64;
398
-
399
- function requireXxhash64 () {
400
- if (hasRequiredXxhash64) return xxhash64_1;
401
- hasRequiredXxhash64 = 1;
402
- const create = requireWasmHash();
403
- //#region wasm code: xxhash64 (../../../assembly/hash/xxhash64.asm.ts) --initialMemory 1
404
- const xxhash64 = new WebAssembly.Module(Buffer.from(// 1173 bytes
405
- "AGFzbQEAAAABCAJgAX8AYAAAAwQDAQAABQMBAAEGGgV+AUIAC34BQgALfgFCAAt+AUIAC34BQgALByIEBGluaXQAAAZ1cGRhdGUAAQVmaW5hbAACBm1lbW9yeQIACrUIAzAAQtbrgu7q/Yn14AAkAELP1tO+0ser2UIkAUIAJAJC+erQ0OfJoeThACQDQgAkBAvUAQIBfwR+IABFBEAPCyMEIACtfCQEIwAhAiMBIQMjAiEEIwMhBQNAIAIgASkDAELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiECIAMgASkDCELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEDIAQgASkDEELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEEIAUgASkDGELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEFIAAgAUEgaiIBSw0ACyACJAAgAyQBIAQkAiAFJAMLqwYCAX8EfiMEQgBSBH4jACICQgGJIwEiA0IHiXwjAiIEQgyJfCMDIgVCEol8IAJCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0gA0LP1tO+0ser2UJ+Qh+JQoeVr6+Ytt6bnn9+hUKHla+vmLbem55/fkKdo7Xqg7GNivoAfSAEQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IAVCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0FQsXP2bLx5brqJwsjBCAArXx8IQIDQCABQQhqIABNBEAgAiABKQMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQhuJQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IQIgAUEIaiEBDAELCyABQQRqIABNBEACfyACIAE1AgBCh5Wvr5i23puef36FQheJQs/W077Sx6vZQn5C+fPd8Zn2masWfCECIAFBBGoLIQELA0AgACABRwRAIAIgATEAAELFz9my8eW66id+hUILiUKHla+vmLbem55/fiECIAFBAWohAQwBCwtBACACIAJCIYiFQs/W077Sx6vZQn4iAiACQh2IhUL5893xmfaZqxZ+IgIgAkIgiIUiAkIgiCIDQv//A4NCIIYgA0KAgPz/D4NCEIiEIgNC/4GAgPAfg0IQhiADQoD+g4CA4D+DQgiIhCIDQo+AvIDwgcAHg0IIhiADQvCBwIeAnoD4AINCBIiEIgNChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IANCsODAgYOGjJgwhHw3AwBBCCACQv////8PgyICQv//A4NCIIYgAkKAgPz/D4NCEIiEIgJC/4GAgPAfg0IQhiACQoD+g4CA4D+DQgiIhCICQo+AvIDwgcAHg0IIhiACQvCBwIeAnoD4AINCBIiEIgJChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IAJCsODAgYOGjJgwhHw3AwAL", "base64"));
406
- //#endregion
407
- xxhash64_1 = create.bind(null, xxhash64, [], 32, 16);
408
- return xxhash64_1;
409
- }
410
-
411
- var BatchedHash_1;
412
- var hasRequiredBatchedHash;
413
-
414
- function requireBatchedHash () {
415
- if (hasRequiredBatchedHash) return BatchedHash_1;
416
- hasRequiredBatchedHash = 1;
417
- const MAX_SHORT_STRING = requireWasmHash().MAX_SHORT_STRING;
418
- class BatchedHash {
419
- constructor(hash){
420
- this.string = undefined;
421
- this.encoding = undefined;
422
- this.hash = hash;
423
- }
424
- /**
425
- * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
426
- * @param {string|Buffer} data data
427
- * @param {string=} inputEncoding data encoding
428
- * @returns {this} updated hash
429
- */ update(data, inputEncoding) {
430
- if (this.string !== undefined) {
431
- if (typeof data === "string" && inputEncoding === this.encoding && this.string.length + data.length < MAX_SHORT_STRING) {
432
- this.string += data;
433
- return this;
434
- }
435
- this.hash.update(this.string, this.encoding);
436
- this.string = undefined;
437
- }
438
- if (typeof data === "string") {
439
- if (data.length < MAX_SHORT_STRING && // base64 encoding is not valid since it may contain padding chars
440
- (!inputEncoding || !inputEncoding.startsWith("ba"))) {
441
- this.string = data;
442
- this.encoding = inputEncoding;
443
- } else {
444
- this.hash.update(data, inputEncoding);
445
- }
446
- } else {
447
- this.hash.update(data);
448
- }
449
- return this;
450
- }
451
- /**
452
- * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
453
- * @param {string=} encoding encoding of the return value
454
- * @returns {string|Buffer} digest
455
- */ digest(encoding) {
456
- if (this.string !== undefined) {
457
- this.hash.update(this.string, this.encoding);
458
- }
459
- return this.hash.digest(encoding);
460
- }
461
- }
462
- BatchedHash_1 = BatchedHash;
463
- return BatchedHash_1;
464
- }
465
-
466
- /*
467
- MIT License http://www.opensource.org/licenses/mit-license.php
468
- Author Tobias Koppers @sokra
469
- */
470
-
471
- var md4_1;
472
- var hasRequiredMd4;
473
-
474
- function requireMd4 () {
475
- if (hasRequiredMd4) return md4_1;
476
- hasRequiredMd4 = 1;
477
- const create = requireWasmHash();
478
- //#region wasm code: md4 (../../../assembly/hash/md4.asm.ts) --initialMemory 1
479
- const md4 = new WebAssembly.Module(Buffer.from(// 2150 bytes
480
- "AGFzbQEAAAABCAJgAX8AYAAAAwUEAQAAAAUDAQABBhoFfwFBAAt/AUEAC38BQQALfwFBAAt/AUEACwciBARpbml0AAAGdXBkYXRlAAIFZmluYWwAAwZtZW1vcnkCAAqFEAQmAEGBxpS6BiQBQYnXtv5+JAJB/rnrxXkkA0H2qMmBASQEQQAkAAvMCgEYfyMBIQojAiEGIwMhByMEIQgDQCAAIAVLBEAgBSgCCCINIAcgBiAFKAIEIgsgCCAHIAUoAgAiDCAKIAggBiAHIAhzcXNqakEDdyIDIAYgB3Nxc2pqQQd3IgEgAyAGc3FzampBC3chAiAFKAIUIg8gASACIAUoAhAiCSADIAEgBSgCDCIOIAYgAyACIAEgA3Nxc2pqQRN3IgQgASACc3FzampBA3ciAyACIARzcXNqakEHdyEBIAUoAiAiEiADIAEgBSgCHCIRIAQgAyAFKAIYIhAgAiAEIAEgAyAEc3FzampBC3ciAiABIANzcXNqakETdyIEIAEgAnNxc2pqQQN3IQMgBSgCLCIVIAQgAyAFKAIoIhQgAiAEIAUoAiQiEyABIAIgAyACIARzcXNqakEHdyIBIAMgBHNxc2pqQQt3IgIgASADc3FzampBE3chBCAPIBAgCSAVIBQgEyAFKAI4IhYgAiAEIAUoAjQiFyABIAIgBSgCMCIYIAMgASAEIAEgAnNxc2pqQQN3IgEgAiAEc3FzampBB3ciAiABIARzcXNqakELdyIDIAkgAiAMIAEgBSgCPCIJIAQgASADIAEgAnNxc2pqQRN3IgEgAiADcnEgAiADcXJqakGZ84nUBWpBA3ciAiABIANycSABIANxcmpqQZnzidQFakEFdyIEIAEgAnJxIAEgAnFyaiASakGZ84nUBWpBCXciAyAPIAQgCyACIBggASADIAIgBHJxIAIgBHFyampBmfOJ1AVqQQ13IgEgAyAEcnEgAyAEcXJqakGZ84nUBWpBA3ciAiABIANycSABIANxcmpqQZnzidQFakEFdyIEIAEgAnJxIAEgAnFyampBmfOJ1AVqQQl3IgMgECAEIAIgFyABIAMgAiAEcnEgAiAEcXJqakGZ84nUBWpBDXciASADIARycSADIARxcmogDWpBmfOJ1AVqQQN3IgIgASADcnEgASADcXJqakGZ84nUBWpBBXciBCABIAJycSABIAJxcmpqQZnzidQFakEJdyIDIBEgBCAOIAIgFiABIAMgAiAEcnEgAiAEcXJqakGZ84nUBWpBDXciASADIARycSADIARxcmpqQZnzidQFakEDdyICIAEgA3JxIAEgA3FyampBmfOJ1AVqQQV3IgQgASACcnEgASACcXJqakGZ84nUBWpBCXciAyAMIAIgAyAJIAEgAyACIARycSACIARxcmpqQZnzidQFakENdyIBcyAEc2pqQaHX5/YGakEDdyICIAQgASACcyADc2ogEmpBodfn9gZqQQl3IgRzIAFzampBodfn9gZqQQt3IgMgAiADIBggASADIARzIAJzampBodfn9gZqQQ93IgFzIARzaiANakGh1+f2BmpBA3ciAiAUIAQgASACcyADc2pqQaHX5/YGakEJdyIEcyABc2pqQaHX5/YGakELdyIDIAsgAiADIBYgASADIARzIAJzampBodfn9gZqQQ93IgFzIARzampBodfn9gZqQQN3IgIgEyAEIAEgAnMgA3NqakGh1+f2BmpBCXciBHMgAXNqakGh1+f2BmpBC3chAyAKIA4gAiADIBcgASADIARzIAJzampBodfn9gZqQQ93IgFzIARzampBodfn9gZqQQN3IgJqIQogBiAJIAEgESADIAIgFSAEIAEgAnMgA3NqakGh1+f2BmpBCXciBHMgAXNqakGh1+f2BmpBC3ciAyAEcyACc2pqQaHX5/YGakEPd2ohBiADIAdqIQcgBCAIaiEIIAVBQGshBQwBCwsgCiQBIAYkAiAHJAMgCCQECw0AIAAQASMAIABqJAAL/wQCA38BfiMAIABqrUIDhiEEIABByABqQUBxIgJBCGshAyAAIgFBAWohACABQYABOgAAA0AgACACSUEAIABBB3EbBEAgAEEAOgAAIABBAWohAAwBCwsDQCAAIAJJBEAgAEIANwMAIABBCGohAAwBCwsgAyAENwMAIAIQAUEAIwGtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIwKtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEQIwOtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEYIwStIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAAs=", "base64"));
481
- //#endregion
482
- md4_1 = create.bind(null, md4, [], 64, 32);
483
- return md4_1;
484
- }
485
-
486
- var BulkUpdateDecorator_1;
487
- var hasRequiredBulkUpdateDecorator;
488
-
489
- function requireBulkUpdateDecorator () {
490
- if (hasRequiredBulkUpdateDecorator) return BulkUpdateDecorator_1;
491
- hasRequiredBulkUpdateDecorator = 1;
492
- const BULK_SIZE = 2000;
493
- // We are using an object instead of a Map as this will stay static during the runtime
494
- // so access to it can be optimized by v8
495
- const digestCaches = {};
496
- class BulkUpdateDecorator {
497
- /**
498
- * @param {Hash | function(): Hash} hashOrFactory function to create a hash
499
- * @param {string=} hashKey key for caching
500
- */ constructor(hashOrFactory, hashKey){
501
- this.hashKey = hashKey;
502
- if (typeof hashOrFactory === "function") {
503
- this.hashFactory = hashOrFactory;
504
- this.hash = undefined;
505
- } else {
506
- this.hashFactory = undefined;
507
- this.hash = hashOrFactory;
508
- }
509
- this.buffer = "";
510
- }
511
- /**
512
- * Update hash {@link https://nodejs.org/api/crypto.html#crypto_hash_update_data_inputencoding}
513
- * @param {string|Buffer} data data
514
- * @param {string=} inputEncoding data encoding
515
- * @returns {this} updated hash
516
- */ update(data, inputEncoding) {
517
- if (inputEncoding !== undefined || typeof data !== "string" || data.length > BULK_SIZE) {
518
- if (this.hash === undefined) {
519
- this.hash = this.hashFactory();
520
- }
521
- if (this.buffer.length > 0) {
522
- this.hash.update(this.buffer);
523
- this.buffer = "";
524
- }
525
- this.hash.update(data, inputEncoding);
526
- } else {
527
- this.buffer += data;
528
- if (this.buffer.length > BULK_SIZE) {
529
- if (this.hash === undefined) {
530
- this.hash = this.hashFactory();
531
- }
532
- this.hash.update(this.buffer);
533
- this.buffer = "";
534
- }
535
- }
536
- return this;
537
- }
538
- /**
539
- * Calculates the digest {@link https://nodejs.org/api/crypto.html#crypto_hash_digest_encoding}
540
- * @param {string=} encoding encoding of the return value
541
- * @returns {string|Buffer} digest
542
- */ digest(encoding) {
543
- let digestCache;
544
- const buffer = this.buffer;
545
- if (this.hash === undefined) {
546
- // short data for hash, we can use caching
547
- const cacheKey = `${this.hashKey}-${encoding}`;
548
- digestCache = digestCaches[cacheKey];
549
- if (digestCache === undefined) {
550
- digestCache = digestCaches[cacheKey] = new Map();
551
- }
552
- const cacheEntry = digestCache.get(buffer);
553
- if (cacheEntry !== undefined) {
554
- return cacheEntry;
555
- }
556
- this.hash = this.hashFactory();
557
- }
558
- if (buffer.length > 0) {
559
- this.hash.update(buffer);
560
- }
561
- const digestResult = this.hash.digest(encoding);
562
- if (digestCache !== undefined) {
563
- digestCache.set(buffer, digestResult);
564
- }
565
- return digestResult;
566
- }
567
- }
568
- BulkUpdateDecorator_1 = BulkUpdateDecorator;
569
- return BulkUpdateDecorator_1;
570
- }
571
-
572
- var getHashDigest_1;
573
- var hasRequiredGetHashDigest;
574
-
575
- function requireGetHashDigest () {
576
- if (hasRequiredGetHashDigest) return getHashDigest_1;
577
- hasRequiredGetHashDigest = 1;
578
- const baseEncodeTables = {
579
- 26: "abcdefghijklmnopqrstuvwxyz",
580
- 32: "123456789abcdefghjkmnpqrstuvwxyz",
581
- 36: "0123456789abcdefghijklmnopqrstuvwxyz",
582
- 49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ",
583
- 52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
584
- 58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ",
585
- 62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
586
- 64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"
587
- };
588
- /**
589
- * @param {Uint32Array} uint32Array Treated as a long base-0x100000000 number, little endian
590
- * @param {number} divisor The divisor
591
- * @return {number} Modulo (remainder) of the division
592
- */ function divmod32(uint32Array, divisor) {
593
- let carry = 0;
594
- for(let i = uint32Array.length - 1; i >= 0; i--){
595
- const value = carry * 0x100000000 + uint32Array[i];
596
- carry = value % divisor;
597
- uint32Array[i] = Math.floor(value / divisor);
598
- }
599
- return carry;
600
- }
601
- function encodeBufferToBase(buffer, base, length) {
602
- const encodeTable = baseEncodeTables[base];
603
- if (!encodeTable) {
604
- throw new Error("Unknown encoding base" + base);
605
- }
606
- // Input bits are only enough to generate this many characters
607
- const limit = Math.ceil(buffer.length * 8 / Math.log2(base));
608
- length = Math.min(length, limit);
609
- // Most of the crypto digests (if not all) has length a multiple of 4 bytes.
610
- // Fewer numbers in the array means faster math.
611
- const uint32Array = new Uint32Array(Math.ceil(buffer.length / 4));
612
- // Make sure the input buffer data is copied and is not mutated by reference.
613
- // divmod32() would corrupt the BulkUpdateDecorator cache otherwise.
614
- buffer.copy(Buffer.from(uint32Array.buffer));
615
- let output = "";
616
- for(let i = 0; i < length; i++){
617
- output = encodeTable[divmod32(uint32Array, base)] + output;
618
- }
619
- return output;
620
- }
621
- let crypto = undefined;
622
- let createXXHash64 = undefined;
623
- let createMd4 = undefined;
624
- let BatchedHash = undefined;
625
- let BulkUpdateDecorator = undefined;
626
- function getHashDigest(buffer, algorithm, digestType, maxLength) {
627
- algorithm = algorithm || "xxhash64";
628
- maxLength = maxLength || 9999;
629
- let hash;
630
- if (algorithm === "xxhash64") {
631
- if (createXXHash64 === undefined) {
632
- createXXHash64 = requireXxhash64();
633
- if (BatchedHash === undefined) {
634
- BatchedHash = requireBatchedHash();
635
- }
636
- }
637
- hash = new BatchedHash(createXXHash64());
638
- } else if (algorithm === "md4") {
639
- if (createMd4 === undefined) {
640
- createMd4 = requireMd4();
641
- if (BatchedHash === undefined) {
642
- BatchedHash = requireBatchedHash();
643
- }
644
- }
645
- hash = new BatchedHash(createMd4());
646
- } else if (algorithm === "native-md4") {
647
- if (typeof crypto === "undefined") {
648
- crypto = require$$3;
649
- if (BulkUpdateDecorator === undefined) {
650
- BulkUpdateDecorator = requireBulkUpdateDecorator();
651
- }
652
- }
653
- hash = new BulkUpdateDecorator(()=>crypto.createHash("md4"), "md4");
654
- } else {
655
- if (typeof crypto === "undefined") {
656
- crypto = require$$3;
657
- if (BulkUpdateDecorator === undefined) {
658
- BulkUpdateDecorator = requireBulkUpdateDecorator();
659
- }
660
- }
661
- hash = new BulkUpdateDecorator(()=>crypto.createHash(algorithm), algorithm);
662
- }
663
- hash.update(buffer);
664
- if (digestType === "base26" || digestType === "base32" || digestType === "base36" || digestType === "base49" || digestType === "base52" || digestType === "base58" || digestType === "base62" || digestType === "base64safe") {
665
- return encodeBufferToBase(hash.digest(), digestType === "base64safe" ? 64 : digestType.substr(4), maxLength);
666
- }
667
- return hash.digest(digestType || "hex").substr(0, maxLength);
668
- }
669
- getHashDigest_1 = getHashDigest;
670
- return getHashDigest_1;
671
- }
672
-
673
- var interpolateName_1;
674
- var hasRequiredInterpolateName;
675
-
676
- function requireInterpolateName () {
677
- if (hasRequiredInterpolateName) return interpolateName_1;
678
- hasRequiredInterpolateName = 1;
679
- const path = require$$0;
680
- const getHashDigest = requireGetHashDigest();
681
- function interpolateName(loaderContext, name, options = {}) {
682
- let filename;
683
- const hasQuery = loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1;
684
- if (typeof name === "function") {
685
- filename = name(loaderContext.resourcePath, hasQuery ? loaderContext.resourceQuery : undefined);
686
- } else {
687
- filename = name || "[hash].[ext]";
688
- }
689
- const context = options.context;
690
- const content = options.content;
691
- const regExp = options.regExp;
692
- let ext = "bin";
693
- let basename = "file";
694
- let directory = "";
695
- let folder = "";
696
- let query = "";
697
- if (loaderContext.resourcePath) {
698
- const parsed = path.parse(loaderContext.resourcePath);
699
- let resourcePath = loaderContext.resourcePath;
700
- if (parsed.ext) {
701
- ext = parsed.ext.substr(1);
702
- }
703
- if (parsed.dir) {
704
- basename = parsed.name;
705
- resourcePath = parsed.dir + path.sep;
706
- }
707
- if (typeof context !== "undefined") {
708
- directory = path.relative(context, resourcePath + "_").replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
709
- directory = directory.substr(0, directory.length - 1);
710
- } else {
711
- directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
712
- }
713
- if (directory.length <= 1) {
714
- directory = "";
715
- } else {
716
- // directory.length > 1
717
- folder = path.basename(directory);
718
- }
719
- }
720
- if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) {
721
- query = loaderContext.resourceQuery;
722
- const hashIdx = query.indexOf("#");
723
- if (hashIdx >= 0) {
724
- query = query.substr(0, hashIdx);
725
- }
726
- }
727
- let url = filename;
728
- if (content) {
729
- // Match hash template
730
- url = url// `hash` and `contenthash` are same in `loader-utils` context
731
- // let's keep `hash` for backward compatibility
732
- .replace(/\[(?:([^[:\]]+):)?(?:hash|contenthash)(?::([a-z]+\d*(?:safe)?))?(?::(\d+))?\]/gi, (all, hashType, digestType, maxLength)=>getHashDigest(content, hashType, digestType, parseInt(maxLength, 10)));
733
- }
734
- url = url.replace(/\[ext\]/gi, ()=>ext).replace(/\[name\]/gi, ()=>basename).replace(/\[path\]/gi, ()=>directory).replace(/\[folder\]/gi, ()=>folder).replace(/\[query\]/gi, ()=>query);
735
- if (regExp && loaderContext.resourcePath) {
736
- const match = loaderContext.resourcePath.match(new RegExp(regExp));
737
- match && match.forEach((matched, i)=>{
738
- url = url.replace(new RegExp("\\[" + i + "\\]", "ig"), matched);
739
- });
740
- }
741
- if (typeof loaderContext.options === "object" && typeof loaderContext.options.customInterpolateName === "function") {
742
- url = loaderContext.options.customInterpolateName.call(loaderContext, url, name, options);
743
- }
744
- return url;
745
- }
746
- interpolateName_1 = interpolateName;
747
- return interpolateName_1;
748
- }
749
-
750
- var hasRequiredLib;
751
-
752
- function requireLib () {
753
- if (hasRequiredLib) return lib;
754
- hasRequiredLib = 1;
755
- const isUrlRequest = requireIsUrlRequest();
756
- const urlToRequest = requireUrlToRequest();
757
- const getHashDigest = requireGetHashDigest();
758
- const interpolateName = requireInterpolateName();
759
- lib.urlToRequest = urlToRequest;
760
- lib.getHashDigest = getHashDigest;
761
- lib.interpolateName = interpolateName;
762
- lib.isUrlRequest = isUrlRequest;
763
- return lib;
764
- }
765
-
766
- var libExports = requireLib();
767
- var loaderUtils = /*@__PURE__*/getDefaultExportFromCjs(libExports);
768
-
769
- // src/vlq.ts
770
- var comma = ",".charCodeAt(0);
771
- var semicolon = ";".charCodeAt(0);
772
- var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
773
- var intToChar = new Uint8Array(64);
774
- var charToInt = new Uint8Array(128);
775
- for(let i = 0; i < chars.length; i++){
776
- const c = chars.charCodeAt(i);
777
- intToChar[i] = c;
778
- charToInt[c] = i;
779
- }
780
- function encodeInteger(builder, num, relative) {
781
- let delta = num - relative;
782
- delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
783
- do {
784
- let clamped = delta & 31;
785
- delta >>>= 5;
786
- if (delta > 0) clamped |= 32;
787
- builder.write(intToChar[clamped]);
788
- }while (delta > 0)
789
- return num;
790
- }
791
- // src/strings.ts
792
- var bufLength = 1024 * 16;
793
- var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
794
- decode (buf) {
795
- const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
796
- return out.toString();
797
- }
798
- } : {
799
- decode (buf) {
800
- let out = "";
801
- for(let i = 0; i < buf.length; i++){
802
- out += String.fromCharCode(buf[i]);
803
- }
804
- return out;
805
- }
806
- };
807
- var StringWriter = class {
808
- constructor(){
809
- this.pos = 0;
810
- this.out = "";
811
- this.buffer = new Uint8Array(bufLength);
812
- }
813
- write(v) {
814
- const { buffer } = this;
815
- buffer[this.pos++] = v;
816
- if (this.pos === bufLength) {
817
- this.out += td.decode(buffer);
818
- this.pos = 0;
819
- }
820
- }
821
- flush() {
822
- const { buffer, out, pos } = this;
823
- return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
824
- }
825
- };
826
- function encode$1(decoded) {
827
- const writer = new StringWriter();
828
- let sourcesIndex = 0;
829
- let sourceLine = 0;
830
- let sourceColumn = 0;
831
- let namesIndex = 0;
832
- for(let i = 0; i < decoded.length; i++){
833
- const line = decoded[i];
834
- if (i > 0) writer.write(semicolon);
835
- if (line.length === 0) continue;
836
- let genColumn = 0;
837
- for(let j = 0; j < line.length; j++){
838
- const segment = line[j];
839
- if (j > 0) writer.write(comma);
840
- genColumn = encodeInteger(writer, segment[0], genColumn);
841
- if (segment.length === 1) continue;
842
- sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
843
- sourceLine = encodeInteger(writer, segment[2], sourceLine);
844
- sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
845
- if (segment.length === 4) continue;
846
- namesIndex = encodeInteger(writer, segment[4], namesIndex);
847
- }
848
- }
849
- return writer.flush();
850
- }
851
-
852
- class BitSet {
853
- constructor(arg){
854
- this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
855
- }
856
- add(n) {
857
- this.bits[n >> 5] |= 1 << (n & 31);
858
- }
859
- has(n) {
860
- return !!(this.bits[n >> 5] & 1 << (n & 31));
861
- }
862
- }
863
- class Chunk {
864
- constructor(start, end, content){
865
- this.start = start;
866
- this.end = end;
867
- this.original = content;
868
- this.intro = '';
869
- this.outro = '';
870
- this.content = content;
871
- this.storeName = false;
872
- this.edited = false;
873
- {
874
- this.previous = null;
875
- this.next = null;
876
- }
877
- }
878
- appendLeft(content) {
879
- this.outro += content;
880
- }
881
- appendRight(content) {
882
- this.intro = this.intro + content;
883
- }
884
- clone() {
885
- const chunk = new Chunk(this.start, this.end, this.original);
886
- chunk.intro = this.intro;
887
- chunk.outro = this.outro;
888
- chunk.content = this.content;
889
- chunk.storeName = this.storeName;
890
- chunk.edited = this.edited;
891
- return chunk;
892
- }
893
- contains(index) {
894
- return this.start < index && index < this.end;
895
- }
896
- eachNext(fn) {
897
- let chunk = this;
898
- while(chunk){
899
- fn(chunk);
900
- chunk = chunk.next;
901
- }
902
- }
903
- eachPrevious(fn) {
904
- let chunk = this;
905
- while(chunk){
906
- fn(chunk);
907
- chunk = chunk.previous;
908
- }
909
- }
910
- edit(content, storeName, contentOnly) {
911
- this.content = content;
912
- if (!contentOnly) {
913
- this.intro = '';
914
- this.outro = '';
915
- }
916
- this.storeName = storeName;
917
- this.edited = true;
918
- return this;
919
- }
920
- prependLeft(content) {
921
- this.outro = content + this.outro;
922
- }
923
- prependRight(content) {
924
- this.intro = content + this.intro;
925
- }
926
- reset() {
927
- this.intro = '';
928
- this.outro = '';
929
- if (this.edited) {
930
- this.content = this.original;
931
- this.storeName = false;
932
- this.edited = false;
933
- }
934
- }
935
- split(index) {
936
- const sliceIndex = index - this.start;
937
- const originalBefore = this.original.slice(0, sliceIndex);
938
- const originalAfter = this.original.slice(sliceIndex);
939
- this.original = originalBefore;
940
- const newChunk = new Chunk(index, this.end, originalAfter);
941
- newChunk.outro = this.outro;
942
- this.outro = '';
943
- this.end = index;
944
- if (this.edited) {
945
- // after split we should save the edit content record into the correct chunk
946
- // to make sure sourcemap correct
947
- // For example:
948
- // ' test'.trim()
949
- // split -> ' ' + 'test'
950
- // ✔️ edit -> '' + 'test'
951
- // ✖️ edit -> 'test' + ''
952
- // TODO is this block necessary?...
953
- newChunk.edit('', false);
954
- this.content = '';
955
- } else {
956
- this.content = originalBefore;
957
- }
958
- newChunk.next = this.next;
959
- if (newChunk.next) newChunk.next.previous = newChunk;
960
- newChunk.previous = this;
961
- this.next = newChunk;
962
- return newChunk;
963
- }
964
- toString() {
965
- return this.intro + this.content + this.outro;
966
- }
967
- trimEnd(rx) {
968
- this.outro = this.outro.replace(rx, '');
969
- if (this.outro.length) return true;
970
- const trimmed = this.content.replace(rx, '');
971
- if (trimmed.length) {
972
- if (trimmed !== this.content) {
973
- this.split(this.start + trimmed.length).edit('', undefined, true);
974
- if (this.edited) {
975
- // save the change, if it has been edited
976
- this.edit(trimmed, this.storeName, true);
977
- }
978
- }
979
- return true;
980
- } else {
981
- this.edit('', undefined, true);
982
- this.intro = this.intro.replace(rx, '');
983
- if (this.intro.length) return true;
984
- }
985
- }
986
- trimStart(rx) {
987
- this.intro = this.intro.replace(rx, '');
988
- if (this.intro.length) return true;
989
- const trimmed = this.content.replace(rx, '');
990
- if (trimmed.length) {
991
- if (trimmed !== this.content) {
992
- const newChunk = this.split(this.end - trimmed.length);
993
- if (this.edited) {
994
- // save the change, if it has been edited
995
- newChunk.edit(trimmed, this.storeName, true);
996
- }
997
- this.edit('', undefined, true);
998
- }
999
- return true;
1000
- } else {
1001
- this.edit('', undefined, true);
1002
- this.outro = this.outro.replace(rx, '');
1003
- if (this.outro.length) return true;
1004
- }
1005
- }
1006
- }
1007
- function getBtoa() {
1008
- if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
1009
- return (str)=>globalThis.btoa(unescape(encodeURIComponent(str)));
1010
- } else if (typeof Buffer === 'function') {
1011
- return (str)=>Buffer.from(str, 'utf-8').toString('base64');
1012
- } else {
1013
- return ()=>{
1014
- throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
1015
- };
1016
- }
1017
- }
1018
- const btoa = /*#__PURE__*/ getBtoa();
1019
- class SourceMap {
1020
- constructor(properties){
1021
- this.version = 3;
1022
- this.file = properties.file;
1023
- this.sources = properties.sources;
1024
- this.sourcesContent = properties.sourcesContent;
1025
- this.names = properties.names;
1026
- this.mappings = encode$1(properties.mappings);
1027
- if (typeof properties.x_google_ignoreList !== 'undefined') {
1028
- this.x_google_ignoreList = properties.x_google_ignoreList;
1029
- }
1030
- if (typeof properties.debugId !== 'undefined') {
1031
- this.debugId = properties.debugId;
1032
- }
1033
- }
1034
- toString() {
1035
- return JSON.stringify(this);
1036
- }
1037
- toUrl() {
1038
- return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
1039
- }
1040
- }
1041
- function guessIndent(code) {
1042
- const lines = code.split('\n');
1043
- const tabbed = lines.filter((line)=>/^\t+/.test(line));
1044
- const spaced = lines.filter((line)=>/^ {2,}/.test(line));
1045
- if (tabbed.length === 0 && spaced.length === 0) {
1046
- return null;
1047
- }
1048
- // More lines tabbed than spaced? Assume tabs, and
1049
- // default to tabs in the case of a tie (or nothing
1050
- // to go on)
1051
- if (tabbed.length >= spaced.length) {
1052
- return '\t';
1053
- }
1054
- // Otherwise, we need to guess the multiple
1055
- const min = spaced.reduce((previous, current)=>{
1056
- const numSpaces = /^ +/.exec(current)[0].length;
1057
- return Math.min(numSpaces, previous);
1058
- }, Infinity);
1059
- return new Array(min + 1).join(' ');
1060
- }
1061
- function getRelativePath(from, to) {
1062
- const fromParts = from.split(/[/\\]/);
1063
- const toParts = to.split(/[/\\]/);
1064
- fromParts.pop(); // get dirname
1065
- while(fromParts[0] === toParts[0]){
1066
- fromParts.shift();
1067
- toParts.shift();
1068
- }
1069
- if (fromParts.length) {
1070
- let i = fromParts.length;
1071
- while(i--)fromParts[i] = '..';
1072
- }
1073
- return fromParts.concat(toParts).join('/');
1074
- }
1075
- const toString = Object.prototype.toString;
1076
- function isObject(thing) {
1077
- return toString.call(thing) === '[object Object]';
1078
- }
1079
- function getLocator(source) {
1080
- const originalLines = source.split('\n');
1081
- const lineOffsets = [];
1082
- for(let i = 0, pos = 0; i < originalLines.length; i++){
1083
- lineOffsets.push(pos);
1084
- pos += originalLines[i].length + 1;
1085
- }
1086
- return function locate(index) {
1087
- let i = 0;
1088
- let j = lineOffsets.length;
1089
- while(i < j){
1090
- const m = i + j >> 1;
1091
- if (index < lineOffsets[m]) {
1092
- j = m;
1093
- } else {
1094
- i = m + 1;
1095
- }
1096
- }
1097
- const line = i - 1;
1098
- const column = index - lineOffsets[line];
1099
- return {
1100
- line,
1101
- column
1102
- };
1103
- };
1104
- }
1105
- const wordRegex = /\w/;
1106
- class Mappings {
1107
- constructor(hires){
1108
- this.hires = hires;
1109
- this.generatedCodeLine = 0;
1110
- this.generatedCodeColumn = 0;
1111
- this.raw = [];
1112
- this.rawSegments = this.raw[this.generatedCodeLine] = [];
1113
- this.pending = null;
1114
- }
1115
- addEdit(sourceIndex, content, loc, nameIndex) {
1116
- if (content.length) {
1117
- const contentLengthMinusOne = content.length - 1;
1118
- let contentLineEnd = content.indexOf('\n', 0);
1119
- let previousContentLineEnd = -1;
1120
- // Loop through each line in the content and add a segment, but stop if the last line is empty,
1121
- // else code afterwards would fill one line too many
1122
- while(contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd){
1123
- const segment = [
1124
- this.generatedCodeColumn,
1125
- sourceIndex,
1126
- loc.line,
1127
- loc.column
1128
- ];
1129
- if (nameIndex >= 0) {
1130
- segment.push(nameIndex);
1131
- }
1132
- this.rawSegments.push(segment);
1133
- this.generatedCodeLine += 1;
1134
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
1135
- this.generatedCodeColumn = 0;
1136
- previousContentLineEnd = contentLineEnd;
1137
- contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
1138
- }
1139
- const segment = [
1140
- this.generatedCodeColumn,
1141
- sourceIndex,
1142
- loc.line,
1143
- loc.column
1144
- ];
1145
- if (nameIndex >= 0) {
1146
- segment.push(nameIndex);
1147
- }
1148
- this.rawSegments.push(segment);
1149
- this.advance(content.slice(previousContentLineEnd + 1));
1150
- } else if (this.pending) {
1151
- this.rawSegments.push(this.pending);
1152
- this.advance(content);
1153
- }
1154
- this.pending = null;
1155
- }
1156
- addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
1157
- let originalCharIndex = chunk.start;
1158
- let first = true;
1159
- // when iterating each char, check if it's in a word boundary
1160
- let charInHiresBoundary = false;
1161
- while(originalCharIndex < chunk.end){
1162
- if (original[originalCharIndex] === '\n') {
1163
- loc.line += 1;
1164
- loc.column = 0;
1165
- this.generatedCodeLine += 1;
1166
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
1167
- this.generatedCodeColumn = 0;
1168
- first = true;
1169
- charInHiresBoundary = false;
1170
- } else {
1171
- if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
1172
- const segment = [
1173
- this.generatedCodeColumn,
1174
- sourceIndex,
1175
- loc.line,
1176
- loc.column
1177
- ];
1178
- if (this.hires === 'boundary') {
1179
- // in hires "boundary", group segments per word boundary than per char
1180
- if (wordRegex.test(original[originalCharIndex])) {
1181
- // for first char in the boundary found, start the boundary by pushing a segment
1182
- if (!charInHiresBoundary) {
1183
- this.rawSegments.push(segment);
1184
- charInHiresBoundary = true;
1185
- }
1186
- } else {
1187
- // for non-word char, end the boundary by pushing a segment
1188
- this.rawSegments.push(segment);
1189
- charInHiresBoundary = false;
1190
- }
1191
- } else {
1192
- this.rawSegments.push(segment);
1193
- }
1194
- }
1195
- loc.column += 1;
1196
- this.generatedCodeColumn += 1;
1197
- first = false;
1198
- }
1199
- originalCharIndex += 1;
1200
- }
1201
- this.pending = null;
1202
- }
1203
- advance(str) {
1204
- if (!str) return;
1205
- const lines = str.split('\n');
1206
- if (lines.length > 1) {
1207
- for(let i = 0; i < lines.length - 1; i++){
1208
- this.generatedCodeLine++;
1209
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
1210
- }
1211
- this.generatedCodeColumn = 0;
1212
- }
1213
- this.generatedCodeColumn += lines[lines.length - 1].length;
1214
- }
1215
- }
1216
- const n = '\n';
1217
- const warned = {
1218
- insertLeft: false,
1219
- insertRight: false,
1220
- storeName: false
1221
- };
1222
- class MagicString {
1223
- constructor(string, options = {}){
1224
- const chunk = new Chunk(0, string.length, string);
1225
- Object.defineProperties(this, {
1226
- original: {
1227
- writable: true,
1228
- value: string
1229
- },
1230
- outro: {
1231
- writable: true,
1232
- value: ''
1233
- },
1234
- intro: {
1235
- writable: true,
1236
- value: ''
1237
- },
1238
- firstChunk: {
1239
- writable: true,
1240
- value: chunk
1241
- },
1242
- lastChunk: {
1243
- writable: true,
1244
- value: chunk
1245
- },
1246
- lastSearchedChunk: {
1247
- writable: true,
1248
- value: chunk
1249
- },
1250
- byStart: {
1251
- writable: true,
1252
- value: {}
1253
- },
1254
- byEnd: {
1255
- writable: true,
1256
- value: {}
1257
- },
1258
- filename: {
1259
- writable: true,
1260
- value: options.filename
1261
- },
1262
- indentExclusionRanges: {
1263
- writable: true,
1264
- value: options.indentExclusionRanges
1265
- },
1266
- sourcemapLocations: {
1267
- writable: true,
1268
- value: new BitSet()
1269
- },
1270
- storedNames: {
1271
- writable: true,
1272
- value: {}
1273
- },
1274
- indentStr: {
1275
- writable: true,
1276
- value: undefined
1277
- },
1278
- ignoreList: {
1279
- writable: true,
1280
- value: options.ignoreList
1281
- },
1282
- offset: {
1283
- writable: true,
1284
- value: options.offset || 0
1285
- }
1286
- });
1287
- this.byStart[0] = chunk;
1288
- this.byEnd[string.length] = chunk;
1289
- }
1290
- addSourcemapLocation(char) {
1291
- this.sourcemapLocations.add(char);
1292
- }
1293
- append(content) {
1294
- if (typeof content !== 'string') throw new TypeError('outro content must be a string');
1295
- this.outro += content;
1296
- return this;
1297
- }
1298
- appendLeft(index, content) {
1299
- index = index + this.offset;
1300
- if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
1301
- this._split(index);
1302
- const chunk = this.byEnd[index];
1303
- if (chunk) {
1304
- chunk.appendLeft(content);
1305
- } else {
1306
- this.intro += content;
1307
- }
1308
- return this;
1309
- }
1310
- appendRight(index, content) {
1311
- index = index + this.offset;
1312
- if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
1313
- this._split(index);
1314
- const chunk = this.byStart[index];
1315
- if (chunk) {
1316
- chunk.appendRight(content);
1317
- } else {
1318
- this.outro += content;
1319
- }
1320
- return this;
1321
- }
1322
- clone() {
1323
- const cloned = new MagicString(this.original, {
1324
- filename: this.filename,
1325
- offset: this.offset
1326
- });
1327
- let originalChunk = this.firstChunk;
1328
- let clonedChunk = cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone();
1329
- while(originalChunk){
1330
- cloned.byStart[clonedChunk.start] = clonedChunk;
1331
- cloned.byEnd[clonedChunk.end] = clonedChunk;
1332
- const nextOriginalChunk = originalChunk.next;
1333
- const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
1334
- if (nextClonedChunk) {
1335
- clonedChunk.next = nextClonedChunk;
1336
- nextClonedChunk.previous = clonedChunk;
1337
- clonedChunk = nextClonedChunk;
1338
- }
1339
- originalChunk = nextOriginalChunk;
1340
- }
1341
- cloned.lastChunk = clonedChunk;
1342
- if (this.indentExclusionRanges) {
1343
- cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
1344
- }
1345
- cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
1346
- cloned.intro = this.intro;
1347
- cloned.outro = this.outro;
1348
- return cloned;
1349
- }
1350
- generateDecodedMap(options) {
1351
- options = options || {};
1352
- const sourceIndex = 0;
1353
- const names = Object.keys(this.storedNames);
1354
- const mappings = new Mappings(options.hires);
1355
- const locate = getLocator(this.original);
1356
- if (this.intro) {
1357
- mappings.advance(this.intro);
1358
- }
1359
- this.firstChunk.eachNext((chunk)=>{
1360
- const loc = locate(chunk.start);
1361
- if (chunk.intro.length) mappings.advance(chunk.intro);
1362
- if (chunk.edited) {
1363
- mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
1364
- } else {
1365
- mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
1366
- }
1367
- if (chunk.outro.length) mappings.advance(chunk.outro);
1368
- });
1369
- return {
1370
- file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
1371
- sources: [
1372
- options.source ? getRelativePath(options.file || '', options.source) : options.file || ''
1373
- ],
1374
- sourcesContent: options.includeContent ? [
1375
- this.original
1376
- ] : undefined,
1377
- names,
1378
- mappings: mappings.raw,
1379
- x_google_ignoreList: this.ignoreList ? [
1380
- sourceIndex
1381
- ] : undefined
1382
- };
1383
- }
1384
- generateMap(options) {
1385
- return new SourceMap(this.generateDecodedMap(options));
1386
- }
1387
- _ensureindentStr() {
1388
- if (this.indentStr === undefined) {
1389
- this.indentStr = guessIndent(this.original);
1390
- }
1391
- }
1392
- _getRawIndentString() {
1393
- this._ensureindentStr();
1394
- return this.indentStr;
1395
- }
1396
- getIndentString() {
1397
- this._ensureindentStr();
1398
- return this.indentStr === null ? '\t' : this.indentStr;
1399
- }
1400
- indent(indentStr, options) {
1401
- const pattern = /^[^\r\n]/gm;
1402
- if (isObject(indentStr)) {
1403
- options = indentStr;
1404
- indentStr = undefined;
1405
- }
1406
- if (indentStr === undefined) {
1407
- this._ensureindentStr();
1408
- indentStr = this.indentStr || '\t';
1409
- }
1410
- if (indentStr === '') return this; // noop
1411
- options = options || {};
1412
- // Process exclusion ranges
1413
- const isExcluded = {};
1414
- if (options.exclude) {
1415
- const exclusions = typeof options.exclude[0] === 'number' ? [
1416
- options.exclude
1417
- ] : options.exclude;
1418
- exclusions.forEach((exclusion)=>{
1419
- for(let i = exclusion[0]; i < exclusion[1]; i += 1){
1420
- isExcluded[i] = true;
1421
- }
1422
- });
1423
- }
1424
- let shouldIndentNextCharacter = options.indentStart !== false;
1425
- const replacer = (match)=>{
1426
- if (shouldIndentNextCharacter) return `${indentStr}${match}`;
1427
- shouldIndentNextCharacter = true;
1428
- return match;
1429
- };
1430
- this.intro = this.intro.replace(pattern, replacer);
1431
- let charIndex = 0;
1432
- let chunk = this.firstChunk;
1433
- while(chunk){
1434
- const end = chunk.end;
1435
- if (chunk.edited) {
1436
- if (!isExcluded[charIndex]) {
1437
- chunk.content = chunk.content.replace(pattern, replacer);
1438
- if (chunk.content.length) {
1439
- shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
1440
- }
1441
- }
1442
- } else {
1443
- charIndex = chunk.start;
1444
- while(charIndex < end){
1445
- if (!isExcluded[charIndex]) {
1446
- const char = this.original[charIndex];
1447
- if (char === '\n') {
1448
- shouldIndentNextCharacter = true;
1449
- } else if (char !== '\r' && shouldIndentNextCharacter) {
1450
- shouldIndentNextCharacter = false;
1451
- if (charIndex === chunk.start) {
1452
- chunk.prependRight(indentStr);
1453
- } else {
1454
- this._splitChunk(chunk, charIndex);
1455
- chunk = chunk.next;
1456
- chunk.prependRight(indentStr);
1457
- }
1458
- }
1459
- }
1460
- charIndex += 1;
1461
- }
1462
- }
1463
- charIndex = chunk.end;
1464
- chunk = chunk.next;
1465
- }
1466
- this.outro = this.outro.replace(pattern, replacer);
1467
- return this;
1468
- }
1469
- insert() {
1470
- throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
1471
- }
1472
- insertLeft(index, content) {
1473
- if (!warned.insertLeft) {
1474
- console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead');
1475
- warned.insertLeft = true;
1476
- }
1477
- return this.appendLeft(index, content);
1478
- }
1479
- insertRight(index, content) {
1480
- if (!warned.insertRight) {
1481
- console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead');
1482
- warned.insertRight = true;
1483
- }
1484
- return this.prependRight(index, content);
1485
- }
1486
- move(start, end, index) {
1487
- start = start + this.offset;
1488
- end = end + this.offset;
1489
- index = index + this.offset;
1490
- if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
1491
- this._split(start);
1492
- this._split(end);
1493
- this._split(index);
1494
- const first = this.byStart[start];
1495
- const last = this.byEnd[end];
1496
- const oldLeft = first.previous;
1497
- const oldRight = last.next;
1498
- const newRight = this.byStart[index];
1499
- if (!newRight && last === this.lastChunk) return this;
1500
- const newLeft = newRight ? newRight.previous : this.lastChunk;
1501
- if (oldLeft) oldLeft.next = oldRight;
1502
- if (oldRight) oldRight.previous = oldLeft;
1503
- if (newLeft) newLeft.next = first;
1504
- if (newRight) newRight.previous = last;
1505
- if (!first.previous) this.firstChunk = last.next;
1506
- if (!last.next) {
1507
- this.lastChunk = first.previous;
1508
- this.lastChunk.next = null;
1509
- }
1510
- first.previous = newLeft;
1511
- last.next = newRight || null;
1512
- if (!newLeft) this.firstChunk = first;
1513
- if (!newRight) this.lastChunk = last;
1514
- return this;
1515
- }
1516
- overwrite(start, end, content, options) {
1517
- options = options || {};
1518
- return this.update(start, end, content, {
1519
- ...options,
1520
- overwrite: !options.contentOnly
1521
- });
1522
- }
1523
- update(start, end, content, options) {
1524
- start = start + this.offset;
1525
- end = end + this.offset;
1526
- if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
1527
- if (this.original.length !== 0) {
1528
- while(start < 0)start += this.original.length;
1529
- while(end < 0)end += this.original.length;
1530
- }
1531
- if (end > this.original.length) throw new Error('end is out of bounds');
1532
- if (start === end) throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead');
1533
- this._split(start);
1534
- this._split(end);
1535
- if (options === true) {
1536
- if (!warned.storeName) {
1537
- console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string');
1538
- warned.storeName = true;
1539
- }
1540
- options = {
1541
- storeName: true
1542
- };
1543
- }
1544
- const storeName = options !== undefined ? options.storeName : false;
1545
- const overwrite = options !== undefined ? options.overwrite : false;
1546
- if (storeName) {
1547
- const original = this.original.slice(start, end);
1548
- Object.defineProperty(this.storedNames, original, {
1549
- writable: true,
1550
- value: true,
1551
- enumerable: true
1552
- });
1553
- }
1554
- const first = this.byStart[start];
1555
- const last = this.byEnd[end];
1556
- if (first) {
1557
- let chunk = first;
1558
- while(chunk !== last){
1559
- if (chunk.next !== this.byStart[chunk.end]) {
1560
- throw new Error('Cannot overwrite across a split point');
1561
- }
1562
- chunk = chunk.next;
1563
- chunk.edit('', false);
1564
- }
1565
- first.edit(content, storeName, !overwrite);
1566
- } else {
1567
- // must be inserting at the end
1568
- const newChunk = new Chunk(start, end, '').edit(content, storeName);
1569
- // TODO last chunk in the array may not be the last chunk, if it's moved...
1570
- last.next = newChunk;
1571
- newChunk.previous = last;
1572
- }
1573
- return this;
1574
- }
1575
- prepend(content) {
1576
- if (typeof content !== 'string') throw new TypeError('outro content must be a string');
1577
- this.intro = content + this.intro;
1578
- return this;
1579
- }
1580
- prependLeft(index, content) {
1581
- index = index + this.offset;
1582
- if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
1583
- this._split(index);
1584
- const chunk = this.byEnd[index];
1585
- if (chunk) {
1586
- chunk.prependLeft(content);
1587
- } else {
1588
- this.intro = content + this.intro;
1589
- }
1590
- return this;
1591
- }
1592
- prependRight(index, content) {
1593
- index = index + this.offset;
1594
- if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
1595
- this._split(index);
1596
- const chunk = this.byStart[index];
1597
- if (chunk) {
1598
- chunk.prependRight(content);
1599
- } else {
1600
- this.outro = content + this.outro;
1601
- }
1602
- return this;
1603
- }
1604
- remove(start, end) {
1605
- start = start + this.offset;
1606
- end = end + this.offset;
1607
- if (this.original.length !== 0) {
1608
- while(start < 0)start += this.original.length;
1609
- while(end < 0)end += this.original.length;
1610
- }
1611
- if (start === end) return this;
1612
- if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
1613
- if (start > end) throw new Error('end must be greater than start');
1614
- this._split(start);
1615
- this._split(end);
1616
- let chunk = this.byStart[start];
1617
- while(chunk){
1618
- chunk.intro = '';
1619
- chunk.outro = '';
1620
- chunk.edit('');
1621
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1622
- }
1623
- return this;
1624
- }
1625
- reset(start, end) {
1626
- start = start + this.offset;
1627
- end = end + this.offset;
1628
- if (this.original.length !== 0) {
1629
- while(start < 0)start += this.original.length;
1630
- while(end < 0)end += this.original.length;
1631
- }
1632
- if (start === end) return this;
1633
- if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
1634
- if (start > end) throw new Error('end must be greater than start');
1635
- this._split(start);
1636
- this._split(end);
1637
- let chunk = this.byStart[start];
1638
- while(chunk){
1639
- chunk.reset();
1640
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1641
- }
1642
- return this;
1643
- }
1644
- lastChar() {
1645
- if (this.outro.length) return this.outro[this.outro.length - 1];
1646
- let chunk = this.lastChunk;
1647
- do {
1648
- if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
1649
- if (chunk.content.length) return chunk.content[chunk.content.length - 1];
1650
- if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
1651
- }while (chunk = chunk.previous)
1652
- if (this.intro.length) return this.intro[this.intro.length - 1];
1653
- return '';
1654
- }
1655
- lastLine() {
1656
- let lineIndex = this.outro.lastIndexOf(n);
1657
- if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
1658
- let lineStr = this.outro;
1659
- let chunk = this.lastChunk;
1660
- do {
1661
- if (chunk.outro.length > 0) {
1662
- lineIndex = chunk.outro.lastIndexOf(n);
1663
- if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
1664
- lineStr = chunk.outro + lineStr;
1665
- }
1666
- if (chunk.content.length > 0) {
1667
- lineIndex = chunk.content.lastIndexOf(n);
1668
- if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
1669
- lineStr = chunk.content + lineStr;
1670
- }
1671
- if (chunk.intro.length > 0) {
1672
- lineIndex = chunk.intro.lastIndexOf(n);
1673
- if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
1674
- lineStr = chunk.intro + lineStr;
1675
- }
1676
- }while (chunk = chunk.previous)
1677
- lineIndex = this.intro.lastIndexOf(n);
1678
- if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
1679
- return this.intro + lineStr;
1680
- }
1681
- slice(start = 0, end = this.original.length - this.offset) {
1682
- start = start + this.offset;
1683
- end = end + this.offset;
1684
- if (this.original.length !== 0) {
1685
- while(start < 0)start += this.original.length;
1686
- while(end < 0)end += this.original.length;
1687
- }
1688
- let result = '';
1689
- // find start chunk
1690
- let chunk = this.firstChunk;
1691
- while(chunk && (chunk.start > start || chunk.end <= start)){
1692
- // found end chunk before start
1693
- if (chunk.start < end && chunk.end >= end) {
1694
- return result;
1695
- }
1696
- chunk = chunk.next;
1697
- }
1698
- if (chunk && chunk.edited && chunk.start !== start) throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
1699
- const startChunk = chunk;
1700
- while(chunk){
1701
- if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
1702
- result += chunk.intro;
1703
- }
1704
- const containsEnd = chunk.start < end && chunk.end >= end;
1705
- if (containsEnd && chunk.edited && chunk.end !== end) throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
1706
- const sliceStart = startChunk === chunk ? start - chunk.start : 0;
1707
- const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
1708
- result += chunk.content.slice(sliceStart, sliceEnd);
1709
- if (chunk.outro && (!containsEnd || chunk.end === end)) {
1710
- result += chunk.outro;
1711
- }
1712
- if (containsEnd) {
1713
- break;
1714
- }
1715
- chunk = chunk.next;
1716
- }
1717
- return result;
1718
- }
1719
- // TODO deprecate this? not really very useful
1720
- snip(start, end) {
1721
- const clone = this.clone();
1722
- clone.remove(0, start);
1723
- clone.remove(end, clone.original.length);
1724
- return clone;
1725
- }
1726
- _split(index) {
1727
- if (this.byStart[index] || this.byEnd[index]) return;
1728
- let chunk = this.lastSearchedChunk;
1729
- const searchForward = index > chunk.end;
1730
- while(chunk){
1731
- if (chunk.contains(index)) return this._splitChunk(chunk, index);
1732
- chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
1733
- }
1734
- }
1735
- _splitChunk(chunk, index) {
1736
- if (chunk.edited && chunk.content.length) {
1737
- // zero-length edited chunks are a special case (overlapping replacements)
1738
- const loc = getLocator(this.original)(index);
1739
- throw new Error(`Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`);
1740
- }
1741
- const newChunk = chunk.split(index);
1742
- this.byEnd[index] = chunk;
1743
- this.byStart[index] = newChunk;
1744
- this.byEnd[newChunk.end] = newChunk;
1745
- if (chunk === this.lastChunk) this.lastChunk = newChunk;
1746
- this.lastSearchedChunk = chunk;
1747
- return true;
1748
- }
1749
- toString() {
1750
- let str = this.intro;
1751
- let chunk = this.firstChunk;
1752
- while(chunk){
1753
- str += chunk.toString();
1754
- chunk = chunk.next;
1755
- }
1756
- return str + this.outro;
1757
- }
1758
- isEmpty() {
1759
- let chunk = this.firstChunk;
1760
- do {
1761
- if (chunk.intro.length && chunk.intro.trim() || chunk.content.length && chunk.content.trim() || chunk.outro.length && chunk.outro.trim()) return false;
1762
- }while (chunk = chunk.next)
1763
- return true;
1764
- }
1765
- length() {
1766
- let chunk = this.firstChunk;
1767
- let length = 0;
1768
- do {
1769
- length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1770
- }while (chunk = chunk.next)
1771
- return length;
1772
- }
1773
- trimLines() {
1774
- return this.trim('[\\r\\n]');
1775
- }
1776
- trim(charType) {
1777
- return this.trimStart(charType).trimEnd(charType);
1778
- }
1779
- trimEndAborted(charType) {
1780
- const rx = new RegExp((charType || '\\s') + '+$');
1781
- this.outro = this.outro.replace(rx, '');
1782
- if (this.outro.length) return true;
1783
- let chunk = this.lastChunk;
1784
- do {
1785
- const end = chunk.end;
1786
- const aborted = chunk.trimEnd(rx);
1787
- // if chunk was trimmed, we have a new lastChunk
1788
- if (chunk.end !== end) {
1789
- if (this.lastChunk === chunk) {
1790
- this.lastChunk = chunk.next;
1791
- }
1792
- this.byEnd[chunk.end] = chunk;
1793
- this.byStart[chunk.next.start] = chunk.next;
1794
- this.byEnd[chunk.next.end] = chunk.next;
1795
- }
1796
- if (aborted) return true;
1797
- chunk = chunk.previous;
1798
- }while (chunk)
1799
- return false;
1800
- }
1801
- trimEnd(charType) {
1802
- this.trimEndAborted(charType);
1803
- return this;
1804
- }
1805
- trimStartAborted(charType) {
1806
- const rx = new RegExp('^' + (charType || '\\s') + '+');
1807
- this.intro = this.intro.replace(rx, '');
1808
- if (this.intro.length) return true;
1809
- let chunk = this.firstChunk;
1810
- do {
1811
- const end = chunk.end;
1812
- const aborted = chunk.trimStart(rx);
1813
- if (chunk.end !== end) {
1814
- // special case...
1815
- if (chunk === this.lastChunk) this.lastChunk = chunk.next;
1816
- this.byEnd[chunk.end] = chunk;
1817
- this.byStart[chunk.next.start] = chunk.next;
1818
- this.byEnd[chunk.next.end] = chunk.next;
1819
- }
1820
- if (aborted) return true;
1821
- chunk = chunk.next;
1822
- }while (chunk)
1823
- return false;
1824
- }
1825
- trimStart(charType) {
1826
- this.trimStartAborted(charType);
1827
- return this;
1828
- }
1829
- hasChanged() {
1830
- return this.original !== this.toString();
1831
- }
1832
- _replaceRegexp(searchValue, replacement) {
1833
- function getReplacement(match, str) {
1834
- if (typeof replacement === 'string') {
1835
- return replacement.replace(/\$(\$|&|\d+)/g, (_, i)=>{
1836
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
1837
- if (i === '$') return '$';
1838
- if (i === '&') return match[0];
1839
- const num = +i;
1840
- if (num < match.length) return match[+i];
1841
- return `$${i}`;
1842
- });
1843
- } else {
1844
- return replacement(...match, match.index, str, match.groups);
1845
- }
1846
- }
1847
- function matchAll(re, str) {
1848
- let match;
1849
- const matches = [];
1850
- while(match = re.exec(str)){
1851
- matches.push(match);
1852
- }
1853
- return matches;
1854
- }
1855
- if (searchValue.global) {
1856
- const matches = matchAll(searchValue, this.original);
1857
- matches.forEach((match)=>{
1858
- if (match.index != null) {
1859
- const replacement = getReplacement(match, this.original);
1860
- if (replacement !== match[0]) {
1861
- this.overwrite(match.index, match.index + match[0].length, replacement);
1862
- }
1863
- }
1864
- });
1865
- } else {
1866
- const match = this.original.match(searchValue);
1867
- if (match && match.index != null) {
1868
- const replacement = getReplacement(match, this.original);
1869
- if (replacement !== match[0]) {
1870
- this.overwrite(match.index, match.index + match[0].length, replacement);
1871
- }
1872
- }
1873
- }
1874
- return this;
1875
- }
1876
- _replaceString(string, replacement) {
1877
- const { original } = this;
1878
- const index = original.indexOf(string);
1879
- if (index !== -1) {
1880
- this.overwrite(index, index + string.length, replacement);
1881
- }
1882
- return this;
1883
- }
1884
- replace(searchValue, replacement) {
1885
- if (typeof searchValue === 'string') {
1886
- return this._replaceString(searchValue, replacement);
1887
- }
1888
- return this._replaceRegexp(searchValue, replacement);
1889
- }
1890
- _replaceAllString(string, replacement) {
1891
- const { original } = this;
1892
- const stringLength = string.length;
1893
- for(let index = original.indexOf(string); index !== -1; index = original.indexOf(string, index + stringLength)){
1894
- const previous = original.slice(index, index + stringLength);
1895
- if (previous !== replacement) this.overwrite(index, index + stringLength, replacement);
1896
- }
1897
- return this;
1898
- }
1899
- replaceAll(searchValue, replacement) {
1900
- if (typeof searchValue === 'string') {
1901
- return this._replaceAllString(searchValue, replacement);
1902
- }
1903
- if (!searchValue.global) {
1904
- throw new TypeError('MagicString.prototype.replaceAll called with a non-global RegExp argument');
1905
- }
1906
- return this._replaceRegexp(searchValue, replacement);
1907
- }
1908
- }
1909
-
1910
- const token = '%[a-f0-9]{2}';
1911
- const singleMatcher = new RegExp('(' + token + ')|([^%]+?)', 'gi');
1912
- const multiMatcher = new RegExp('(' + token + ')+', 'gi');
1913
- function decodeComponents(components, split) {
1914
- try {
1915
- // Try to decode the entire string first
1916
- return [
1917
- decodeURIComponent(components.join(''))
1918
- ];
1919
- } catch {
1920
- // Do nothing
1921
- }
1922
- if (components.length === 1) {
1923
- return components;
1924
- }
1925
- split = split || 1;
1926
- // Split the array in 2 parts
1927
- const left = components.slice(0, split);
1928
- const right = components.slice(split);
1929
- return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));
1930
- }
1931
- function decode$1(input) {
1932
- try {
1933
- return decodeURIComponent(input);
1934
- } catch {
1935
- let tokens = input.match(singleMatcher) || [];
1936
- for(let i = 1; i < tokens.length; i++){
1937
- input = decodeComponents(tokens, i).join('');
1938
- tokens = input.match(singleMatcher) || [];
1939
- }
1940
- return input;
1941
- }
1942
- }
1943
- function customDecodeURIComponent(input) {
1944
- // Keep track of all the replacements and prefill the map with the `BOM`
1945
- const replaceMap = {
1946
- '%FE%FF': '\uFFFD\uFFFD',
1947
- '%FF%FE': '\uFFFD\uFFFD'
1948
- };
1949
- let match = multiMatcher.exec(input);
1950
- while(match){
1951
- try {
1952
- // Decode as big chunks as possible
1953
- replaceMap[match[0]] = decodeURIComponent(match[0]);
1954
- } catch {
1955
- const result = decode$1(match[0]);
1956
- if (result !== match[0]) {
1957
- replaceMap[match[0]] = result;
1958
- }
1959
- }
1960
- match = multiMatcher.exec(input);
1961
- }
1962
- // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else
1963
- replaceMap['%C2'] = '\uFFFD';
1964
- const entries = Object.keys(replaceMap);
1965
- for (const key of entries){
1966
- // Replace all decoded components
1967
- input = input.replace(new RegExp(key, 'g'), replaceMap[key]);
1968
- }
1969
- return input;
1970
- }
1971
- function decodeUriComponent(encodedURI) {
1972
- if (typeof encodedURI !== 'string') {
1973
- throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`');
1974
- }
1975
- try {
1976
- // Try the built in decoder first
1977
- return decodeURIComponent(encodedURI);
1978
- } catch {
1979
- // Fallback to a more advanced decoder
1980
- return customDecodeURIComponent(encodedURI);
1981
- }
1982
- }
1983
-
1984
- function includeKeys(object, predicate) {
1985
- const result = {};
1986
- if (Array.isArray(predicate)) {
1987
- for (const key of predicate){
1988
- const descriptor = Object.getOwnPropertyDescriptor(object, key);
1989
- if (descriptor?.enumerable) {
1990
- Object.defineProperty(result, key, descriptor);
1991
- }
1992
- }
1993
- } else {
1994
- // `Reflect.ownKeys()` is required to retrieve symbol properties
1995
- for (const key of Reflect.ownKeys(object)){
1996
- const descriptor = Object.getOwnPropertyDescriptor(object, key);
1997
- if (descriptor.enumerable) {
1998
- const value = object[key];
1999
- if (predicate(key, value, object)) {
2000
- Object.defineProperty(result, key, descriptor);
2001
- }
2002
- }
2003
- }
2004
- }
2005
- return result;
2006
- }
2007
-
2008
- function splitOnFirst(string, separator) {
2009
- if (!(typeof string === 'string' && typeof separator === 'string')) {
2010
- throw new TypeError('Expected the arguments to be of type `string`');
2011
- }
2012
- if (string === '' || separator === '') {
2013
- return [];
2014
- }
2015
- const separatorIndex = string.indexOf(separator);
2016
- if (separatorIndex === -1) {
2017
- return [];
2018
- }
2019
- return [
2020
- string.slice(0, separatorIndex),
2021
- string.slice(separatorIndex + separator.length)
2022
- ];
2023
- }
2024
-
2025
- const isNullOrUndefined = (value)=>value === null || value === undefined;
2026
- // eslint-disable-next-line unicorn/prefer-code-point
2027
- const strictUriEncode = (string)=>encodeURIComponent(string).replaceAll(/[!'()*]/g, (x)=>`%${x.charCodeAt(0).toString(16).toUpperCase()}`);
2028
- const encodeFragmentIdentifier = Symbol('encodeFragmentIdentifier');
2029
- function encoderForArrayFormat(options) {
2030
- switch(options.arrayFormat){
2031
- case 'index':
2032
- {
2033
- return (key)=>(result, value)=>{
2034
- const index = result.length;
2035
- if (value === undefined || options.skipNull && value === null || options.skipEmptyString && value === '') {
2036
- return result;
2037
- }
2038
- if (value === null) {
2039
- return [
2040
- ...result,
2041
- [
2042
- encode(key, options),
2043
- '[',
2044
- index,
2045
- ']'
2046
- ].join('')
2047
- ];
2048
- }
2049
- return [
2050
- ...result,
2051
- [
2052
- encode(key, options),
2053
- '[',
2054
- encode(index, options),
2055
- ']=',
2056
- encode(value, options)
2057
- ].join('')
2058
- ];
2059
- };
2060
- }
2061
- case 'bracket':
2062
- {
2063
- return (key)=>(result, value)=>{
2064
- if (value === undefined || options.skipNull && value === null || options.skipEmptyString && value === '') {
2065
- return result;
2066
- }
2067
- if (value === null) {
2068
- return [
2069
- ...result,
2070
- [
2071
- encode(key, options),
2072
- '[]'
2073
- ].join('')
2074
- ];
2075
- }
2076
- return [
2077
- ...result,
2078
- [
2079
- encode(key, options),
2080
- '[]=',
2081
- encode(value, options)
2082
- ].join('')
2083
- ];
2084
- };
2085
- }
2086
- case 'colon-list-separator':
2087
- {
2088
- return (key)=>(result, value)=>{
2089
- if (value === undefined || options.skipNull && value === null || options.skipEmptyString && value === '') {
2090
- return result;
2091
- }
2092
- if (value === null) {
2093
- return [
2094
- ...result,
2095
- [
2096
- encode(key, options),
2097
- ':list='
2098
- ].join('')
2099
- ];
2100
- }
2101
- return [
2102
- ...result,
2103
- [
2104
- encode(key, options),
2105
- ':list=',
2106
- encode(value, options)
2107
- ].join('')
2108
- ];
2109
- };
2110
- }
2111
- case 'comma':
2112
- case 'separator':
2113
- case 'bracket-separator':
2114
- {
2115
- const keyValueSeparator = options.arrayFormat === 'bracket-separator' ? '[]=' : '=';
2116
- return (key)=>(result, value)=>{
2117
- if (value === undefined || options.skipNull && value === null || options.skipEmptyString && value === '') {
2118
- return result;
2119
- }
2120
- // Translate null to an empty string so that it doesn't serialize as 'null'
2121
- value = value === null ? '' : value;
2122
- if (result.length === 0) {
2123
- return [
2124
- [
2125
- encode(key, options),
2126
- keyValueSeparator,
2127
- encode(value, options)
2128
- ].join('')
2129
- ];
2130
- }
2131
- return [
2132
- [
2133
- result,
2134
- encode(value, options)
2135
- ].join(options.arrayFormatSeparator)
2136
- ];
2137
- };
2138
- }
2139
- default:
2140
- {
2141
- return (key)=>(result, value)=>{
2142
- if (value === undefined || options.skipNull && value === null || options.skipEmptyString && value === '') {
2143
- return result;
2144
- }
2145
- if (value === null) {
2146
- return [
2147
- ...result,
2148
- encode(key, options)
2149
- ];
2150
- }
2151
- return [
2152
- ...result,
2153
- [
2154
- encode(key, options),
2155
- '=',
2156
- encode(value, options)
2157
- ].join('')
2158
- ];
2159
- };
2160
- }
2161
- }
2162
- }
2163
- function parserForArrayFormat(options) {
2164
- let result;
2165
- switch(options.arrayFormat){
2166
- case 'index':
2167
- {
2168
- return (key, value, accumulator)=>{
2169
- result = /\[(\d*)]$/.exec(key);
2170
- key = key.replace(/\[\d*]$/, '');
2171
- if (!result) {
2172
- accumulator[key] = value;
2173
- return;
2174
- }
2175
- if (accumulator[key] === undefined) {
2176
- accumulator[key] = {};
2177
- }
2178
- accumulator[key][result[1]] = value;
2179
- };
2180
- }
2181
- case 'bracket':
2182
- {
2183
- return (key, value, accumulator)=>{
2184
- result = /(\[])$/.exec(key);
2185
- key = key.replace(/\[]$/, '');
2186
- if (!result) {
2187
- accumulator[key] = value;
2188
- return;
2189
- }
2190
- if (accumulator[key] === undefined) {
2191
- accumulator[key] = [
2192
- value
2193
- ];
2194
- return;
2195
- }
2196
- accumulator[key] = [
2197
- ...accumulator[key],
2198
- value
2199
- ];
2200
- };
2201
- }
2202
- case 'colon-list-separator':
2203
- {
2204
- return (key, value, accumulator)=>{
2205
- result = /(:list)$/.exec(key);
2206
- key = key.replace(/:list$/, '');
2207
- if (!result) {
2208
- accumulator[key] = value;
2209
- return;
2210
- }
2211
- if (accumulator[key] === undefined) {
2212
- accumulator[key] = [
2213
- value
2214
- ];
2215
- return;
2216
- }
2217
- accumulator[key] = [
2218
- ...accumulator[key],
2219
- value
2220
- ];
2221
- };
2222
- }
2223
- case 'comma':
2224
- case 'separator':
2225
- {
2226
- return (key, value, accumulator)=>{
2227
- const isArray = typeof value === 'string' && value.includes(options.arrayFormatSeparator);
2228
- const isEncodedArray = typeof value === 'string' && !isArray && decode(value, options).includes(options.arrayFormatSeparator);
2229
- value = isEncodedArray ? decode(value, options) : value;
2230
- const newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map((item)=>decode(item, options)) : value === null ? value : decode(value, options);
2231
- accumulator[key] = newValue;
2232
- };
2233
- }
2234
- case 'bracket-separator':
2235
- {
2236
- return (key, value, accumulator)=>{
2237
- const isArray = /(\[])$/.test(key);
2238
- key = key.replace(/\[]$/, '');
2239
- if (!isArray) {
2240
- accumulator[key] = value ? decode(value, options) : value;
2241
- return;
2242
- }
2243
- const arrayValue = value === null ? [] : decode(value, options).split(options.arrayFormatSeparator);
2244
- if (accumulator[key] === undefined) {
2245
- accumulator[key] = arrayValue;
2246
- return;
2247
- }
2248
- accumulator[key] = [
2249
- ...accumulator[key],
2250
- ...arrayValue
2251
- ];
2252
- };
2253
- }
2254
- default:
2255
- {
2256
- return (key, value, accumulator)=>{
2257
- if (accumulator[key] === undefined) {
2258
- accumulator[key] = value;
2259
- return;
2260
- }
2261
- accumulator[key] = [
2262
- ...[
2263
- accumulator[key]
2264
- ].flat(),
2265
- value
2266
- ];
2267
- };
2268
- }
2269
- }
2270
- }
2271
- function validateArrayFormatSeparator(value) {
2272
- if (typeof value !== 'string' || value.length !== 1) {
2273
- throw new TypeError('arrayFormatSeparator must be single character string');
2274
- }
2275
- }
2276
- function encode(value, options) {
2277
- if (options.encode) {
2278
- return options.strict ? strictUriEncode(value) : encodeURIComponent(value);
2279
- }
2280
- return value;
2281
- }
2282
- function decode(value, options) {
2283
- if (options.decode) {
2284
- return decodeUriComponent(value);
2285
- }
2286
- return value;
2287
- }
2288
- function keysSorter(input) {
2289
- if (Array.isArray(input)) {
2290
- return input.sort();
2291
- }
2292
- if (typeof input === 'object') {
2293
- return keysSorter(Object.keys(input)).sort((a, b)=>Number(a) - Number(b)).map((key)=>input[key]);
2294
- }
2295
- return input;
2296
- }
2297
- function removeHash(input) {
2298
- const hashStart = input.indexOf('#');
2299
- if (hashStart !== -1) {
2300
- input = input.slice(0, hashStart);
2301
- }
2302
- return input;
2303
- }
2304
- function getHash(url) {
2305
- let hash = '';
2306
- const hashStart = url.indexOf('#');
2307
- if (hashStart !== -1) {
2308
- hash = url.slice(hashStart);
2309
- }
2310
- return hash;
2311
- }
2312
- function parseValue(value, options, type) {
2313
- if (type === 'string' && typeof value === 'string') {
2314
- return value;
2315
- }
2316
- if (typeof type === 'function' && typeof value === 'string') {
2317
- return type(value);
2318
- }
2319
- if (type === 'boolean' && value === null) {
2320
- return true;
2321
- }
2322
- if (type === 'boolean' && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) {
2323
- return value.toLowerCase() === 'true';
2324
- }
2325
- if (type === 'boolean' && value !== null && (value.toLowerCase() === '1' || value.toLowerCase() === '0')) {
2326
- return value.toLowerCase() === '1';
2327
- }
2328
- if (type === 'string[]' && options.arrayFormat !== 'none' && typeof value === 'string') {
2329
- return [
2330
- value
2331
- ];
2332
- }
2333
- if (type === 'number[]' && options.arrayFormat !== 'none' && !Number.isNaN(Number(value)) && typeof value === 'string' && value.trim() !== '') {
2334
- return [
2335
- Number(value)
2336
- ];
2337
- }
2338
- if (type === 'number' && !Number.isNaN(Number(value)) && typeof value === 'string' && value.trim() !== '') {
2339
- return Number(value);
2340
- }
2341
- if (options.parseBooleans && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) {
2342
- return value.toLowerCase() === 'true';
2343
- }
2344
- if (options.parseNumbers && !Number.isNaN(Number(value)) && typeof value === 'string' && value.trim() !== '') {
2345
- return Number(value);
2346
- }
2347
- return value;
2348
- }
2349
- function extract(input) {
2350
- input = removeHash(input);
2351
- const queryStart = input.indexOf('?');
2352
- if (queryStart === -1) {
2353
- return '';
2354
- }
2355
- return input.slice(queryStart + 1);
2356
- }
2357
- function parse(query, options) {
2358
- options = {
2359
- decode: true,
2360
- sort: true,
2361
- arrayFormat: 'none',
2362
- arrayFormatSeparator: ',',
2363
- parseNumbers: false,
2364
- parseBooleans: false,
2365
- types: Object.create(null),
2366
- ...options
2367
- };
2368
- validateArrayFormatSeparator(options.arrayFormatSeparator);
2369
- const formatter = parserForArrayFormat(options);
2370
- // Create an object with no prototype
2371
- const returnValue = Object.create(null);
2372
- if (typeof query !== 'string') {
2373
- return returnValue;
2374
- }
2375
- query = query.trim().replace(/^[?#&]/, '');
2376
- if (!query) {
2377
- return returnValue;
2378
- }
2379
- for (const parameter of query.split('&')){
2380
- if (parameter === '') {
2381
- continue;
2382
- }
2383
- const parameter_ = options.decode ? parameter.replaceAll('+', ' ') : parameter;
2384
- let [key, value] = splitOnFirst(parameter_, '=');
2385
- if (key === undefined) {
2386
- key = parameter_;
2387
- }
2388
- // Missing `=` should be `null`:
2389
- // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
2390
- value = value === undefined ? null : [
2391
- 'comma',
2392
- 'separator',
2393
- 'bracket-separator'
2394
- ].includes(options.arrayFormat) ? value : decode(value, options);
2395
- formatter(decode(key, options), value, returnValue);
2396
- }
2397
- for (const [key, value] of Object.entries(returnValue)){
2398
- if (typeof value === 'object' && value !== null && options.types[key] !== 'string') {
2399
- for (const [key2, value2] of Object.entries(value)){
2400
- const type = options.types[key] ? options.types[key].replace('[]', '') : undefined;
2401
- value[key2] = parseValue(value2, options, type);
2402
- }
2403
- } else if (typeof value === 'object' && value !== null && options.types[key] === 'string') {
2404
- returnValue[key] = Object.values(value).join(options.arrayFormatSeparator);
2405
- } else {
2406
- returnValue[key] = parseValue(value, options, options.types[key]);
2407
- }
2408
- }
2409
- if (options.sort === false) {
2410
- return returnValue;
2411
- }
2412
- // TODO: Remove the use of `reduce`.
2413
- // eslint-disable-next-line unicorn/no-array-reduce
2414
- return (options.sort === true ? Object.keys(returnValue).sort() : Object.keys(returnValue).sort(options.sort)).reduce((result, key)=>{
2415
- const value = returnValue[key];
2416
- result[key] = Boolean(value) && typeof value === 'object' && !Array.isArray(value) ? keysSorter(value) : value;
2417
- return result;
2418
- }, Object.create(null));
2419
- }
2420
- function stringify(object, options) {
2421
- if (!object) {
2422
- return '';
2423
- }
2424
- options = {
2425
- encode: true,
2426
- strict: true,
2427
- arrayFormat: 'none',
2428
- arrayFormatSeparator: ',',
2429
- ...options
2430
- };
2431
- validateArrayFormatSeparator(options.arrayFormatSeparator);
2432
- const shouldFilter = (key)=>options.skipNull && isNullOrUndefined(object[key]) || options.skipEmptyString && object[key] === '';
2433
- const formatter = encoderForArrayFormat(options);
2434
- const objectCopy = {};
2435
- for (const [key, value] of Object.entries(object)){
2436
- if (!shouldFilter(key)) {
2437
- objectCopy[key] = value;
2438
- }
2439
- }
2440
- const keys = Object.keys(objectCopy);
2441
- if (options.sort !== false) {
2442
- keys.sort(options.sort);
2443
- }
2444
- return keys.map((key)=>{
2445
- const value = object[key];
2446
- if (value === undefined) {
2447
- return '';
2448
- }
2449
- if (value === null) {
2450
- return encode(key, options);
2451
- }
2452
- if (Array.isArray(value)) {
2453
- if (value.length === 0 && options.arrayFormat === 'bracket-separator') {
2454
- return encode(key, options) + '[]';
2455
- }
2456
- return value.reduce(formatter(key), []).join('&');
2457
- }
2458
- return encode(key, options) + '=' + encode(value, options);
2459
- }).filter((x)=>x.length > 0).join('&');
2460
- }
2461
- function parseUrl(url, options) {
2462
- options = {
2463
- decode: true,
2464
- ...options
2465
- };
2466
- let [url_, hash] = splitOnFirst(url, '#');
2467
- if (url_ === undefined) {
2468
- url_ = url;
2469
- }
2470
- return {
2471
- url: url_?.split('?')?.[0] ?? '',
2472
- query: parse(extract(url), options),
2473
- ...options && options.parseFragmentIdentifier && hash ? {
2474
- fragmentIdentifier: decode(hash, options)
2475
- } : {}
2476
- };
2477
- }
2478
- function stringifyUrl(object, options) {
2479
- options = {
2480
- encode: true,
2481
- strict: true,
2482
- [encodeFragmentIdentifier]: true,
2483
- ...options
2484
- };
2485
- const url = removeHash(object.url).split('?')[0] || '';
2486
- const queryFromUrl = extract(object.url);
2487
- const query = {
2488
- ...parse(queryFromUrl, {
2489
- sort: false,
2490
- ...options
2491
- }),
2492
- ...object.query
2493
- };
2494
- let queryString = stringify(query, options);
2495
- queryString &&= `?${queryString}`;
2496
- let hash = getHash(object.url);
2497
- if (typeof object.fragmentIdentifier === 'string') {
2498
- const urlObjectForFragmentEncode = new URL(url);
2499
- urlObjectForFragmentEncode.hash = object.fragmentIdentifier;
2500
- hash = options[encodeFragmentIdentifier] ? urlObjectForFragmentEncode.hash : `#${object.fragmentIdentifier}`;
2501
- }
2502
- return `${url}${queryString}${hash}`;
2503
- }
2504
- function pick(input, filter, options) {
2505
- options = {
2506
- parseFragmentIdentifier: true,
2507
- [encodeFragmentIdentifier]: false,
2508
- ...options
2509
- };
2510
- const { url, query, fragmentIdentifier } = parseUrl(input, options);
2511
- return stringifyUrl({
2512
- url,
2513
- query: includeKeys(query, filter),
2514
- fragmentIdentifier
2515
- }, options);
2516
- }
2517
- function exclude(input, filter, options) {
2518
- const exclusionFilter = Array.isArray(filter) ? (key)=>!filter.includes(key) : (key, value)=>!filter(key, value);
2519
- return pick(input, exclusionFilter, options);
2520
- }
2521
-
2522
- var queryString = {
2523
- __proto__: null,
2524
- exclude: exclude,
2525
- extract: extract,
2526
- parse: parse,
2527
- parseUrl: parseUrl,
2528
- pick: pick,
2529
- stringify: stringify,
2530
- stringifyUrl: stringifyUrl
2531
- };
2532
-
2533
- var postcssNextFont = {};
2534
-
2535
- var hasRequiredPostcssNextFont;
2536
-
2537
- function requirePostcssNextFont () {
2538
- if (hasRequiredPostcssNextFont) return postcssNextFont;
2539
- hasRequiredPostcssNextFont = 1;
2540
- (function (exports) {
2541
- Object.defineProperty(exports, "__esModule", {
2542
- value: true
2543
- });
2544
- Object.defineProperty(exports, "default", {
2545
- enumerable: true,
2546
- get: function() {
2547
- return _default;
2548
- }
2549
- });
2550
- const _postcss = /*#__PURE__*/ _interop_require_default(require$$0$1);
2551
- function _interop_require_default(obj) {
2552
- return obj && obj.__esModule ? obj : {
2553
- default: obj
2554
- };
2555
- }
2556
- /**
2557
- * The next/font postcss plugin receives the @font-face declarations returned from the next/font loaders.
2558
- *
2559
- * It hashes the font-family name to make it unguessable, it shouldn't be globally accessible.
2560
- * If it were global, we wouldn't be able to tell which pages are using which fonts when generating preload tags.
2561
- *
2562
- * If the font loader returned fallback metrics, generate a fallback @font-face.
2563
- *
2564
- * If the font loader returned a variable name, add a CSS class that declares a variable containing the font and fallback fonts.
2565
- *
2566
- * Lastly, it adds the font-family to the exports object.
2567
- * This enables you to access the actual font-family name, not just through the CSS class.
2568
- * e.g:
2569
- * const inter = Inter({ subsets: ['latin'] })
2570
- * inter.style.fontFamily // => '__Inter_123456'
2571
- */ const postcssNextFontPlugin = ({ exports: exports1, fallbackFonts = [], adjustFontFallback, variable, weight, style })=>{
2572
- return {
2573
- postcssPlugin: 'postcss-next-font',
2574
- Once (root) {
2575
- let fontFamily;
2576
- const normalizeFamily = (family)=>{
2577
- return family.replace(/['"]/g, '');
2578
- };
2579
- const formatFamily = (family)=>{
2580
- return `'${family}'`;
2581
- };
2582
- // Hash font-family names
2583
- for (const node of root.nodes){
2584
- if (node.type === 'atrule' && node.name === 'font-face') {
2585
- const familyNode = node.nodes.find((decl)=>decl.prop === 'font-family');
2586
- if (!familyNode) {
2587
- continue;
2588
- }
2589
- if (!fontFamily) {
2590
- fontFamily = normalizeFamily(familyNode.value);
2591
- }
2592
- familyNode.value = formatFamily(fontFamily);
2593
- }
2594
- }
2595
- if (!fontFamily) {
2596
- throw Object.defineProperty(new Error("Font loaders must return one or more @font-face's"), "__NEXT_ERROR_CODE", {
2597
- value: "E428",
2598
- enumerable: false,
2599
- configurable: true
2600
- });
2601
- }
2602
- // Add fallback @font-face with the provided override values
2603
- let adjustFontFallbackFamily;
2604
- if (adjustFontFallback) {
2605
- adjustFontFallbackFamily = formatFamily(`${fontFamily} Fallback`);
2606
- const fallbackFontFace = _postcss.default.atRule({
2607
- name: 'font-face'
2608
- });
2609
- const { fallbackFont, ascentOverride, descentOverride, lineGapOverride, sizeAdjust } = adjustFontFallback;
2610
- fallbackFontFace.nodes = [
2611
- new _postcss.default.Declaration({
2612
- prop: 'font-family',
2613
- value: adjustFontFallbackFamily
2614
- }),
2615
- new _postcss.default.Declaration({
2616
- prop: 'src',
2617
- value: `local("${fallbackFont}")`
2618
- }),
2619
- ...ascentOverride ? [
2620
- new _postcss.default.Declaration({
2621
- prop: 'ascent-override',
2622
- value: ascentOverride
2623
- })
2624
- ] : [],
2625
- ...descentOverride ? [
2626
- new _postcss.default.Declaration({
2627
- prop: 'descent-override',
2628
- value: descentOverride
2629
- })
2630
- ] : [],
2631
- ...lineGapOverride ? [
2632
- new _postcss.default.Declaration({
2633
- prop: 'line-gap-override',
2634
- value: lineGapOverride
2635
- })
2636
- ] : [],
2637
- ...sizeAdjust ? [
2638
- new _postcss.default.Declaration({
2639
- prop: 'size-adjust',
2640
- value: sizeAdjust
2641
- })
2642
- ] : []
2643
- ];
2644
- root.nodes.push(fallbackFontFace);
2645
- }
2646
- // Variable fonts can define ranges of values
2647
- const isRange = (value)=>value.trim().includes(' ');
2648
- // Format the font families to be used in the CSS
2649
- const formattedFontFamilies = [
2650
- formatFamily(fontFamily),
2651
- ...adjustFontFallbackFamily ? [
2652
- adjustFontFallbackFamily
2653
- ] : [],
2654
- ...fallbackFonts
2655
- ].join(', ');
2656
- // Add class with family, weight and style
2657
- const classRule = new _postcss.default.Rule({
2658
- selector: '.className'
2659
- });
2660
- classRule.nodes = [
2661
- new _postcss.default.Declaration({
2662
- prop: 'font-family',
2663
- value: formattedFontFamilies
2664
- }),
2665
- // If the font only has one weight or style, we can set it on the class
2666
- ...weight && !isRange(weight) ? [
2667
- new _postcss.default.Declaration({
2668
- prop: 'font-weight',
2669
- value: weight
2670
- })
2671
- ] : [],
2672
- ...style && !isRange(style) ? [
2673
- new _postcss.default.Declaration({
2674
- prop: 'font-style',
2675
- value: style
2676
- })
2677
- ] : []
2678
- ];
2679
- root.nodes.push(classRule);
2680
- // Add CSS class that defines a variable with the font families
2681
- if (variable) {
2682
- const varialbeRule = new _postcss.default.Rule({
2683
- selector: '.variable'
2684
- });
2685
- varialbeRule.nodes = [
2686
- new _postcss.default.Declaration({
2687
- prop: variable,
2688
- value: formattedFontFamilies
2689
- })
2690
- ];
2691
- root.nodes.push(varialbeRule);
2692
- }
2693
- // Export @font-face values as is
2694
- exports1.push({
2695
- name: 'style',
2696
- value: {
2697
- fontFamily: formattedFontFamilies,
2698
- fontWeight: !Number.isNaN(Number(weight)) ? Number(weight) : undefined,
2699
- fontStyle: style && !isRange(style) ? style : undefined
2700
- }
2701
- });
2702
- }
2703
- };
2704
- };
2705
- postcssNextFontPlugin.postcss = true;
2706
- const _default = postcssNextFontPlugin;
2707
- } (postcssNextFont));
2708
- return postcssNextFont;
2709
- }
2710
-
2711
- var postcssNextFontExports = requirePostcssNextFont();
2712
- var postcssNextFontPlugin = /*@__PURE__*/getDefaultExportFromCjs(postcssNextFontExports);
2713
-
2714
- const getQuerySuffix = (id)=>{
2715
- const queryStart = id.indexOf('?');
2716
- if (queryStart === -1) {
2717
- return '';
2718
- }
2719
- return id.slice(queryStart);
2720
- };
2721
- const removeQuerySuffix = (id)=>{
2722
- const queryStart = id.indexOf('?');
2723
- if (queryStart === -1) {
2724
- return id;
2725
- }
2726
- return id.slice(0, queryStart);
2727
- };
2728
- const createCachedImport = (imp)=>{
2729
- let cached;
2730
- return ()=>{
2731
- if (!cached) {
2732
- cached = imp().then((module)=>{
2733
- cached = module;
2734
- return module;
2735
- });
2736
- }
2737
- return cached;
2738
- };
2739
- };
2740
- // Main wrapper function
2741
- const tryCatch = async (promise)=>{
2742
- try {
2743
- const data = await promise;
2744
- return {
2745
- data,
2746
- error: null
2747
- };
2748
- } catch (error) {
2749
- return {
2750
- data: null,
2751
- error: error
2752
- };
2753
- }
2754
- };
2755
- const importResolve = async (id)=>import.meta.resolve(removeQuerySuffix(id));
2756
- /**
2757
- * Encodes the URI path portion (ignores part after ? or #)
2758
- */ function encodeURIPath(uri) {
2759
- if (uri.startsWith('data:')) return uri;
2760
- const filePath = cleanUrl(uri);
2761
- const postfix = filePath !== uri ? uri.slice(filePath.length) : '';
2762
- return encodeURI(filePath) + postfix;
2763
- }
2764
- const postfixRE = /[?#].*$/;
2765
- function cleanUrl(url) {
2766
- return url.replace(postfixRE, '');
2767
- }
2768
- const fontNameToUrl = (fontName)=>{
2769
- return [
2770
- ''
2771
- ].concat([
2772
- '_next',
2773
- fontName
2774
- ].filter(Boolean)).join('/');
2775
- };
2776
- const normalizeTargetCssId = (id)=>{
2777
- return queryString.stringifyUrl({
2778
- url: removeQuerySuffix(id),
2779
- query: pickKeys(queryString.parse(getQuerySuffix(id)), [
2780
- 'arguments',
2781
- 'path',
2782
- 'import',
2783
- 'variableName'
2784
- ])
2785
- });
2786
- };
2787
- const pickKeys = (obj, keys)=>{
2788
- return Object.fromEntries(Object.entries(obj).filter(([key])=>keys.includes(key)));
2789
- };
2790
-
2791
- const importPostcssModules = createCachedImport(()=>import('./index-BknOo0Zr.js').then(function (n) { return n.i; }));
2792
- const importPostcss = createCachedImport(()=>import('postcss'));
2793
- const nextFontPostcss = async (relativePathFromRoot, { css, fallbackFonts, weight, style, adjustFontFallback, variable })=>{
2794
- // Exports will be exported as is from css-loader instead of a CSS module export
2795
- // const exports: { name: any; value: any }[] = [];
2796
- // Generate a hash from the CSS content. Used to generate classnames
2797
- const fontFamilyHash = loaderUtils.getHashDigest(Buffer.from(css), 'sha1', 'hex', 6);
2798
- let modules;
2799
- // biome-ignore lint/suspicious/noExplicitAny: unknown put from nextjs function
2800
- const exports = [];
2801
- const result = await runPostCss({
2802
- postcssPlugins: [
2803
- (postcssNextFontPlugin.default || postcssNextFontPlugin)({
2804
- exports,
2805
- fallbackFonts,
2806
- weight,
2807
- style,
2808
- adjustFontFallback,
2809
- variable
2810
- }),
2811
- (await importPostcssModules()).default({
2812
- generateScopedName: (originalClassName)=>{
2813
- // hash from next-font-loader
2814
- return `__${originalClassName}_${fontFamilyHash}`;
2815
- },
2816
- getJSON (_cssFileName, _modules, _outputFileName) {
2817
- modules = _modules;
2818
- }
2819
- })
2820
- ],
2821
- postcssOptions: {
2822
- from: relativePathFromRoot
2823
- },
2824
- code: css
2825
- });
2826
- return {
2827
- exports,
2828
- ...result,
2829
- modules
2830
- };
2831
- };
2832
- const runPostCss = async ({ postcssPlugins = [], postcssOptions = {}, code })=>{
2833
- let postcssResult;
2834
- try {
2835
- const postcss = await importPostcss();
2836
- // postcss is an unbundled dep and should be lazy imported
2837
- postcssResult = await postcss.default(postcssPlugins).process(code, postcssOptions);
2838
- } catch (e) {
2839
- if (typeof e === 'object' && e !== null && 'message' in e && 'file' in e && 'line' in e && 'column' in e && typeof e.column === 'number') {
2840
- throw Object.assign({}, {
2841
- message: `[postcss] ${e.message}`,
2842
- code,
2843
- loc: {
2844
- file: e.file,
2845
- line: e.line,
2846
- column: e.column - 1
2847
- }
2848
- });
2849
- }
2850
- }
2851
- return {
2852
- code: postcssResult.css,
2853
- map: {
2854
- mappings: ''
2855
- }
2856
- };
2857
- };
2858
-
2859
- const googleLoader = createCachedImport(()=>import('next-font/google/loader').then((mod)=>mod.default));
2860
- const localLoader = createCachedImport(()=>import('next-font/local/loader').then((mod)=>mod.default));
2861
- const nextFontLoaderPlugin = ({ nextFontManifest, fontImports, onFinished })=>{
2862
- let config = null;
2863
- const fileToFontNames = new Map();
2864
- const loaderCache = {
2865
- google: {
2866
- css: new Map(),
2867
- font: new Map()
2868
- },
2869
- local: {
2870
- css: new Map(),
2871
- font: new Map()
2872
- }
2873
- };
2874
- const fontLoaders = [
2875
- [
2876
- 'next-font/google/target.css',
2877
- googleLoader(),
2878
- loaderCache.google
2879
- ],
2880
- [
2881
- 'next-font/local/target.css',
2882
- localLoader(),
2883
- loaderCache.local
2884
- ]
2885
- ];
2886
- const targetCssMap = new Map();
2887
- const removeTargetCss = (id)=>{
2888
- targetCssMap.delete(id);
2889
- const { path: relativePathFromRoot } = queryString.parse(getQuerySuffix(id));
2890
- const absPath = path.join(config.root, relativePathFromRoot);
2891
- const fontNames = fileToFontNames.get(absPath)?.[id];
2892
- if (fontNames) {
2893
- if (nextFontManifest[absPath]) {
2894
- nextFontManifest[absPath] = nextFontManifest[absPath].filter((font)=>!fontNames.includes(font));
2895
- }
2896
- for (const fontName of fontNames){
2897
- fontFileMap.set(fontNameToUrl(fontName), Object.assign({}, fontFileMap.get(fontNameToUrl(fontName)), {
2898
- serve: false
2899
- }));
2900
- }
2901
- }
2902
- };
2903
- const fontFileMap = new Map();
2904
- let lastEnv = null;
2905
- let calledFinished = false;
2906
- const resetCalledFinished = ()=>{
2907
- calledFinished = false;
2908
- };
2909
- return [
2910
- {
2911
- resetCalledFinished,
2912
- removeTargetCss
2913
- },
2914
- [
2915
- {
2916
- name: 'next-font:loader:scan',
2917
- enforce: 'pre',
2918
- async configResolved (resolvedConfig) {
2919
- config = resolvedConfig;
2920
- },
2921
- configureServer (server) {
2922
- return ()=>{
2923
- server.middlewares.use((req, res, next)=>{
2924
- if (!req.originalUrl) return next();
2925
- const font = fontFileMap.get(req.originalUrl);
2926
- if (font?.serve) {
2927
- res.end(font.content);
2928
- } else next();
2929
- });
2930
- };
2931
- }
2932
- },
2933
- {
2934
- name: 'next-font:loader',
2935
- load: {
2936
- order: 'pre',
2937
- async handler (id, opts) {
2938
- if (!/\.css(?:$|\?)/.test(id)) return null;
2939
- const { data: resolvedId, error } = await tryCatch(importResolve(removeQuerySuffix(id)));
2940
- if (error) return null;
2941
- const pair = fontLoaders.find((id)=>import.meta.resolve(id[0]) === resolvedId);
2942
- if (!pair) return null;
2943
- const [, fontLoader, cache] = pair;
2944
- const normalizedId = normalizeTargetCssId(id);
2945
- const isDev = config?.command === 'serve';
2946
- if (// unnecessary to load the same file in dev mode
2947
- isDev && targetCssMap.has(normalizedId) && lastEnv === this.environment.name) return;
2948
- lastEnv = this.environment.name;
2949
- const { path: relativePathFromRoot, import: functionName, arguments: stringifiedArguments, variableName } = queryString.parse(getQuerySuffix(id));
2950
- const data = JSON.parse(stringifiedArguments);
2951
- const fontNames = [];
2952
- const emitFontFile = (content, ext, preload, isUsingSizeAdjust)=>{
2953
- const name = loaderUtils.interpolateName(// @ts-expect-error
2954
- {}, `static/media/[hash]${isUsingSizeAdjust ? '-s' : ''}${preload ? '.p' : ''}.${ext}`, {
2955
- content
2956
- });
2957
- fontNames.push(name);
2958
- const outputPath = fontNameToUrl(name);
2959
- if (!isDev) {
2960
- this.emitFile({
2961
- type: 'asset',
2962
- fileName: outputPath.slice(1),
2963
- source: content
2964
- });
2965
- }
2966
- fontFileMap.set(outputPath, {
2967
- content,
2968
- serve: isDev
2969
- });
2970
- return outputPath;
2971
- };
2972
- const absPath = path.join(config.root, relativePathFromRoot);
2973
- const fontData = await (await fontLoader)({
2974
- functionName,
2975
- variableName,
2976
- data,
2977
- emitFontFile,
2978
- loaderContext: this,
2979
- cache,
2980
- isDev,
2981
- isServer: opts?.ssr ?? false,
2982
- resolve: (src)=>{
2983
- return path.join(path.dirname(absPath), src.startsWith('.') ? src : `./${src}`);
2984
- }
2985
- });
2986
- const normalizedAbsPath = normalizePath(absPath);
2987
- fileToFontNames.set(normalizedAbsPath, {
2988
- ...fileToFontNames.get(normalizedAbsPath),
2989
- [normalizedId]: Array.from(new Set((fileToFontNames.get(normalizedAbsPath)?.[normalizedId] || []).concat(fontNames)))
2990
- });
2991
- const targetCss = await nextFontPostcss(relativePathFromRoot, fontData);
2992
- if (fontImports[normalizedAbsPath]) {
2993
- for (const fontImport of fontImports[normalizedAbsPath]){
2994
- if (fileURLToPath(import.meta.resolve(removeQuerySuffix(fontImport.id))).concat(getQuerySuffix(fontImport.id)) === encodeURIPath(id)) {
2995
- fontImport.css = targetCss.code;
2996
- }
2997
- }
2998
- if (!calledFinished && !Object.values(fontImports).flat().filter((i)=>!i.css).length) {
2999
- await onFinished(fileToFontNames).finally(()=>{
3000
- calledFinished = true;
3001
- });
3002
- }
3003
- }
3004
- targetCssMap.set(normalizedId, targetCss);
3005
- }
3006
- },
3007
- transform: {
3008
- order: 'post',
3009
- async handler (_code, id, opts) {
3010
- if (!/\.css(?:$|\?)/.test(id)) return null;
3011
- const normalizedId = normalizeTargetCssId(id);
3012
- const targetCss = targetCssMap.get(normalizedId);
3013
- if (!targetCss) return null;
3014
- const { modules, code: css, exports } = targetCss;
3015
- const modulesCode = dataToEsm(Object.assign({}, modules, Object.fromEntries(exports.map((e)=>[
3016
- e.name,
3017
- e.value
3018
- ]))), {
3019
- namedExports: true,
3020
- preferConst: true
3021
- });
3022
- const map = config?.css.devSourcemap ? new MagicString(css).generateMap({
3023
- hires: true
3024
- }) : undefined;
3025
- if (config?.command === 'serve' && !opts?.ssr) {
3026
- const code = [
3027
- `import { updateStyle as __vite__updateStyle, removeStyle as __vite__removeStyle } from ${JSON.stringify(path.posix.join(config.base, '/@vite/client'))}`,
3028
- `const __vite__id = ${JSON.stringify(id)}`,
3029
- `const __vite__css = ${JSON.stringify(css)}`,
3030
- `__vite__updateStyle(__vite__id, __vite__css)`,
3031
- modulesCode,
3032
- `if (import.meta.hot) {
3033
- import.meta.hot.accept()
3034
- import.meta.hot.prune(() => __vite__removeStyle(__vite__id))
3035
- }`
3036
- ].join('\n');
3037
- return {
3038
- code,
3039
- map
3040
- };
3041
- }
3042
- return {
3043
- code: modulesCode,
3044
- map,
3045
- moduleSideEffects: false
3046
- };
3047
- }
3048
- }
3049
- },
3050
- {
3051
- name: 'next-font:build',
3052
- apply: 'build',
3053
- renderChunk: {
3054
- order: 'post',
3055
- async handler (_code, chunk) {
3056
- const resolvedModuleIds = (await Promise.all(chunk.moduleIds.map(async (moduleId)=>this.resolve(moduleId).then((resolved)=>resolved?.id)))).filter(Boolean);
3057
- if (resolvedModuleIds.length) {
3058
- const targetCss = resolvedModuleIds.map((id)=>Object.assign({}, targetCssMap.get(normalizeTargetCssId(id)) ?? {}, {
3059
- id
3060
- })).filter((t)=>t != null && 'code' in t && typeof t.code === 'string');
3061
- const chunkCSS = targetCss.map((t)=>t.code).join();
3062
- function ensureFileExt(name, ext) {
3063
- return normalizePath(path.format({
3064
- ...path.parse(name),
3065
- base: undefined,
3066
- ext
3067
- }));
3068
- }
3069
- if (chunkCSS) {
3070
- const cssFullAssetName = ensureFileExt(chunk.name, '.css');
3071
- // if facadeModuleId doesn't exist or doesn't have a CSS extension,
3072
- // that means a JS entry file imports a CSS file.
3073
- // in this case, only use the filename for the CSS chunk name like JS chunks.
3074
- const cssAssetName = chunk.isEntry && (!chunk.facadeModuleId || !isCSSRequest(chunk.facadeModuleId)) ? path.basename(cssFullAssetName) : cssFullAssetName;
3075
- // emit corresponding css file
3076
- const referenceId = this.emitFile({
3077
- type: 'asset',
3078
- name: cssAssetName,
3079
- source: chunkCSS
3080
- });
3081
- chunk.viteMetadata.importedCss.add(this.getFileName(referenceId));
3082
- }
3083
- }
3084
- return null;
3085
- }
3086
- }
3087
- }
3088
- ]
3089
- ];
3090
- };
3091
-
3092
- const nextFontManifestPlugin = ({ nextFontManifest })=>{
3093
- let config = null;
3094
- return [
3095
- {
3096
- name: 'next-font:manifest',
3097
- configResolved (resolvedConfig) {
3098
- config = resolvedConfig;
3099
- },
3100
- transform: {
3101
- order: 'post',
3102
- async handler (_code, id) {
3103
- const { data: resolvedId, error } = await tryCatch(importResolve(id));
3104
- if (error != null || resolvedId == null) return;
3105
- if (resolvedId === import.meta.resolve('next-font/manifest')) {
3106
- return [
3107
- `function encodeURIPath(file) {
3108
- return file
3109
- .split('/')
3110
- .map((p) => encodeURIComponent(p))
3111
- .join('/')
3112
- }`,
3113
- `const injectedFontPreloadTags = new Set();`,
3114
- `const __NEXT_FONT_MANIFEST__ = ${JSON.stringify(nextFontManifest, null, 2)};`,
3115
- dataToEsm({
3116
- manifest: undefined,
3117
- getPreloadableFonts: undefined,
3118
- getFontMetadata: undefined
3119
- }, {
3120
- preferConst: true,
3121
- namedExports: true
3122
- }).replace('export const manifest = undefined;', `export const manifest = Object.freeze(__NEXT_FONT_MANIFEST__);`).replace('export const getPreloadableFonts = undefined;', `export const getPreloadableFonts = (filePath) => {
3123
- if (!manifest || !filePath) return null;
3124
- const fontFiles = new Set();
3125
- let foundFontUsage = false;
3126
- const preloadedFontFiles = manifest[filePath];
3127
- if (preloadedFontFiles) {
3128
- foundFontUsage = true;
3129
- for (let fontFile of preloadedFontFiles) {
3130
- fontFile = \`/${config.build.assetsDir}/_next/\${fontFile}\`;
3131
- fontFiles.add(fontFile);
3132
- injectedFontPreloadTags.add(fontFile);
3133
- }
3134
- }
3135
- if (fontFiles.size) {
3136
- return [...fontFiles].sort();
3137
- } else if (foundFontUsage && injectedFontPreloadTags.size === 0) {
3138
- return [];
3139
- } else {
3140
- return null;
3141
- }
3142
- }`).replace('export const getFontMetadata = undefined;', `export const getFontMetadata = (filePath) => {
3143
- const metadata = {
3144
- preload: [],
3145
- preconnect: []
3146
- };
3147
- const preloadedFontFiles = filePath
3148
- ? getPreloadableFonts(filePath)
3149
- : null;
3150
- if (preloadedFontFiles) {
3151
- if (preloadedFontFiles.length) {
3152
- for (let i = 0; i < preloadedFontFiles.length; i++) {
3153
- const fontFilename = preloadedFontFiles[i];
3154
- const ext = /.(woff|woff2|eot|ttf|otf)$/.exec(fontFilename)[1];
3155
- const type = \`font/\${ext}\`;
3156
- const href = encodeURIPath(fontFilename);
3157
-
3158
- metadata.preload.push({
3159
- href,
3160
- type,
3161
- crossOrigin: undefined,
3162
- nonce: undefined
3163
- });
3164
- }
3165
- } else {
3166
- try {
3167
- let url = new URL('/' + '${config.build.assetsDir}');
3168
- metadata.preconnect.push({
3169
- href: url.origin,
3170
- crossOrigin: undefined,
3171
- nonce: undefined
3172
- });
3173
- } catch (error) {
3174
- // assetPrefix must not be a fully qualified domain name. We assume
3175
- // we should preconnect to same origin instead
3176
- metadata.preconnect.push({
3177
- href: '/',
3178
- crossOrigin: '',
3179
- nonce: null
3180
- });
3181
- }
3182
- }
3183
- }
3184
-
3185
- return metadata;
3186
- }`),
3187
- `if (import.meta.hot) import.meta.hot.accept(${JSON.stringify(id)}, () => {
3188
- manifest = __NEXT_FONT_MANIFEST__;
3189
- })`
3190
- ].join('\n');
3191
- }
3192
- }
3193
- }
3194
- }
3195
- ];
3196
- };
3197
-
3198
- /**
3199
- * @typedef { import('estree').Node} Node
3200
- * @typedef {{
3201
- * skip: () => void;
3202
- * remove: () => void;
3203
- * replace: (node: Node) => void;
3204
- * }} WalkerContext
3205
- */ class WalkerBase {
3206
- constructor(){
3207
- /** @type {boolean} */ this.should_skip = false;
3208
- /** @type {boolean} */ this.should_remove = false;
3209
- /** @type {Node | null} */ this.replacement = null;
3210
- /** @type {WalkerContext} */ this.context = {
3211
- skip: ()=>this.should_skip = true,
3212
- remove: ()=>this.should_remove = true,
3213
- replace: (node)=>this.replacement = node
3214
- };
3215
- }
3216
- /**
3217
- * @template {Node} Parent
3218
- * @param {Parent | null | undefined} parent
3219
- * @param {keyof Parent | null | undefined} prop
3220
- * @param {number | null | undefined} index
3221
- * @param {Node} node
3222
- */ replace(parent, prop, index, node) {
3223
- if (parent && prop) {
3224
- if (index != null) {
3225
- /** @type {Array<Node>} */ parent[prop][index] = node;
3226
- } else {
3227
- /** @type {Node} */ parent[prop] = node;
3228
- }
3229
- }
3230
- }
3231
- /**
3232
- * @template {Node} Parent
3233
- * @param {Parent | null | undefined} parent
3234
- * @param {keyof Parent | null | undefined} prop
3235
- * @param {number | null | undefined} index
3236
- */ remove(parent, prop, index) {
3237
- if (parent && prop) {
3238
- if (index !== null && index !== undefined) {
3239
- /** @type {Array<Node>} */ parent[prop].splice(index, 1);
3240
- } else {
3241
- delete parent[prop];
3242
- }
3243
- }
3244
- }
3245
- }
3246
-
3247
- /**
3248
- * @typedef { import('estree').Node} Node
3249
- * @typedef { import('./walker.js').WalkerContext} WalkerContext
3250
- * @typedef {(
3251
- * this: WalkerContext,
3252
- * node: Node,
3253
- * parent: Node | null,
3254
- * key: string | number | symbol | null | undefined,
3255
- * index: number | null | undefined
3256
- * ) => void} SyncHandler
3257
- */ class SyncWalker extends WalkerBase {
3258
- /**
3259
- *
3260
- * @param {SyncHandler} [enter]
3261
- * @param {SyncHandler} [leave]
3262
- */ constructor(enter, leave){
3263
- super();
3264
- /** @type {boolean} */ this.should_skip = false;
3265
- /** @type {boolean} */ this.should_remove = false;
3266
- /** @type {Node | null} */ this.replacement = null;
3267
- /** @type {WalkerContext} */ this.context = {
3268
- skip: ()=>this.should_skip = true,
3269
- remove: ()=>this.should_remove = true,
3270
- replace: (node)=>this.replacement = node
3271
- };
3272
- /** @type {SyncHandler | undefined} */ this.enter = enter;
3273
- /** @type {SyncHandler | undefined} */ this.leave = leave;
3274
- }
3275
- /**
3276
- * @template {Node} Parent
3277
- * @param {Node} node
3278
- * @param {Parent | null} parent
3279
- * @param {keyof Parent} [prop]
3280
- * @param {number | null} [index]
3281
- * @returns {Node | null}
3282
- */ visit(node, parent, prop, index) {
3283
- if (node) {
3284
- if (this.enter) {
3285
- const _should_skip = this.should_skip;
3286
- const _should_remove = this.should_remove;
3287
- const _replacement = this.replacement;
3288
- this.should_skip = false;
3289
- this.should_remove = false;
3290
- this.replacement = null;
3291
- this.enter.call(this.context, node, parent, prop, index);
3292
- if (this.replacement) {
3293
- node = this.replacement;
3294
- this.replace(parent, prop, index, node);
3295
- }
3296
- if (this.should_remove) {
3297
- this.remove(parent, prop, index);
3298
- }
3299
- const skipped = this.should_skip;
3300
- const removed = this.should_remove;
3301
- this.should_skip = _should_skip;
3302
- this.should_remove = _should_remove;
3303
- this.replacement = _replacement;
3304
- if (skipped) return node;
3305
- if (removed) return null;
3306
- }
3307
- /** @type {keyof Node} */ let key;
3308
- for(key in node){
3309
- /** @type {unknown} */ const value = node[key];
3310
- if (value && typeof value === 'object') {
3311
- if (Array.isArray(value)) {
3312
- const nodes = /** @type {Array<unknown>} */ value;
3313
- for(let i = 0; i < nodes.length; i += 1){
3314
- const item = nodes[i];
3315
- if (isNode(item)) {
3316
- if (!this.visit(item, node, key, i)) {
3317
- // removed
3318
- i--;
3319
- }
3320
- }
3321
- }
3322
- } else if (isNode(value)) {
3323
- this.visit(value, node, key, null);
3324
- }
3325
- }
3326
- }
3327
- if (this.leave) {
3328
- const _replacement = this.replacement;
3329
- const _should_remove = this.should_remove;
3330
- this.replacement = null;
3331
- this.should_remove = false;
3332
- this.leave.call(this.context, node, parent, prop, index);
3333
- if (this.replacement) {
3334
- node = this.replacement;
3335
- this.replace(parent, prop, index, node);
3336
- }
3337
- if (this.should_remove) {
3338
- this.remove(parent, prop, index);
3339
- }
3340
- const removed = this.should_remove;
3341
- this.replacement = _replacement;
3342
- this.should_remove = _should_remove;
3343
- if (removed) return null;
3344
- }
3345
- }
3346
- return node;
3347
- }
3348
- }
3349
- /**
3350
- * Ducktype a node.
3351
- *
3352
- * @param {unknown} value
3353
- * @returns {value is Node}
3354
- */ function isNode(value) {
3355
- return value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string';
3356
- }
3357
-
3358
- /**
3359
- * @typedef {import('estree').Node} Node
3360
- * @typedef {import('./sync.js').SyncHandler} SyncHandler
3361
- * @typedef {import('./async.js').AsyncHandler} AsyncHandler
3362
- */ /**
3363
- * @param {Node} ast
3364
- * @param {{
3365
- * enter?: SyncHandler
3366
- * leave?: SyncHandler
3367
- * }} walker
3368
- * @returns {Node | null}
3369
- */ function walk(ast, { enter, leave }) {
3370
- const instance = new SyncWalker(enter, leave);
3371
- return instance.visit(ast, null);
3372
- }
3373
-
3374
- class FindFunctionsOutsideModuleScope {
3375
- constructor({ state }){
3376
- this.state = state;
3377
- }
3378
- visit(ast) {
3379
- walk(ast, {
3380
- enter: (node)=>{
3381
- if (node.type === 'Identifier') {
3382
- this.visitIdent(node);
3383
- }
3384
- }
3385
- });
3386
- }
3387
- visitIdent(ident) {
3388
- if (ident.name in this.state.fontFunctions && !this.state.fontFunctionsInAllowedScope.includes(ident.start)) {
3389
- throw new Error('Font loaders must be called and assigned to a const in the module scope');
3390
- }
3391
- }
3392
- }
3393
-
3394
- class FontFunctionsCollector {
3395
- constructor({ state, fontLoaders, remapImports }){
3396
- this.state = state;
3397
- this.fontLoaders = fontLoaders;
3398
- this.remapImports = remapImports;
3399
- }
3400
- visit(ast) {
3401
- walk(ast, {
3402
- enter: (node)=>{
3403
- if (node.type === 'ImportDeclaration') {
3404
- this.visitImportDecl(node);
3405
- }
3406
- }
3407
- });
3408
- }
3409
- visitImportDecl(importDecl) {
3410
- if (typeof importDecl.source.value !== 'string') return;
3411
- let resolvedId = null;
3412
- try {
3413
- resolvedId = import.meta.resolve(removeQuerySuffix(this.remapImports[importDecl.source.value] || importDecl.source.value));
3414
- } catch {}
3415
- if (resolvedId != null && this.fontLoaders.map((fontLoader)=>import.meta.resolve(fontLoader)).includes(resolvedId)) {
3416
- this.state.removeableModuleItems.push(importDecl.start);
3417
- for (const specifier of importDecl.specifiers){
3418
- const { local, functionName } = (()=>{
3419
- switch(specifier.type){
3420
- case 'ImportSpecifier':
3421
- {
3422
- const { local, imported } = specifier;
3423
- const functionName = imported.type === 'Identifier' ? imported.name : local.name;
3424
- return {
3425
- local,
3426
- functionName
3427
- };
3428
- }
3429
- case 'ImportDefaultSpecifier':
3430
- {
3431
- const { local } = specifier;
3432
- return {
3433
- local
3434
- };
3435
- }
3436
- case 'ImportNamespaceSpecifier':
3437
- {
3438
- throw new Error("Font loaders can't have namespace imports");
3439
- }
3440
- }
3441
- })();
3442
- this.state.fontFunctionsInAllowedScope.push(local.start);
3443
- this.state.fontFunctions[local.name] = {
3444
- functionName,
3445
- loader: importDecl.source.value
3446
- };
3447
- }
3448
- }
3449
- }
3450
- }
3451
-
3452
- const o = new WeakMap;
3453
- let u = 0;
3454
- function stableHash(t) {
3455
- const i = typeof t, s = t && t.constructor, c = s === Date;
3456
- if (Object(t) === t && !c && s != RegExp) {
3457
- let e = o.get(t);
3458
- if (e) return e;
3459
- e = ++u + "~", o.set(t, e);
3460
- let n;
3461
- if (s === Array) {
3462
- for(e = "@", n = 0; n < t.length; n++)e += stableHash(t[n]) + ",";
3463
- o.set(t, e);
3464
- } else if (s === Object) {
3465
- e = "#";
3466
- const f = Object.keys(t).sort();
3467
- for(; (n = f.pop()) !== void 0;)t[n] !== void 0 && (e += n + ":" + stableHash(t[n]) + ",");
3468
- o.set(t, e);
3469
- }
3470
- return e;
3471
- }
3472
- return c ? t.toJSON() : i === "symbol" ? t.toString() : i === "string" ? JSON.stringify(t) : "" + t;
3473
- }
3474
-
3475
- const DUMMY_SP = {
3476
- start: 0,
3477
- end: 0
3478
- };
3479
-
3480
- const exprToJson = (expr)=>{
3481
- switch(expr.type){
3482
- case 'Literal':
3483
- return expr.value;
3484
- case 'ObjectExpression':
3485
- return objectLitToJson(expr);
3486
- case 'ArrayExpression':
3487
- {
3488
- const elements = expr.elements.map((e)=>{
3489
- if (e) {
3490
- if (e.type === 'SpreadElement') throw new Error('Unexpected spread');
3491
- return exprToJson(e);
3492
- } else {
3493
- throw new Error('Unexpected empty value in array');
3494
- }
3495
- });
3496
- return elements;
3497
- }
3498
- default:
3499
- throw new Error('Font loader values must be explicitly written literals.');
3500
- }
3501
- };
3502
- const objectLitToJson = (objectLit)=>{
3503
- const values = {};
3504
- for (const prop of objectLit.properties){
3505
- if (prop.type === 'SpreadElement') throw new Error('Unexpected spread');
3506
- if (prop.kind !== 'init') throw new Error('Unexpected key');
3507
- if (prop.key.type !== 'Identifier') throw new Error('Unexpected object key type');
3508
- values[prop.key.name] = exprToJson(prop.value);
3509
- }
3510
- return values;
3511
- };
3512
-
3513
- class FontImportsGenerator {
3514
- constructor({ state, id, remapImports }){
3515
- this.state = state;
3516
- this.id = id;
3517
- this.remapImports = remapImports;
3518
- }
3519
- visit(ast) {
3520
- walk(ast, {
3521
- enter: (node)=>{
3522
- if (node.type === 'VariableDeclaration') {
3523
- this.checkVarDecl(node);
3524
- }
3525
- if (node.type === 'VariableDeclaration') {
3526
- if (this.checkVarDecl(node) != null) this.state.removeableModuleItems.push(node.start);
3527
- }
3528
- if (node.type === 'ExportNamedDeclaration' || node.type === 'ExportDefaultDeclaration') {
3529
- const exportDecl = node;
3530
- if (exportDecl.declaration?.type === 'VariableDeclaration') {
3531
- const varDecl = exportDecl.declaration;
3532
- const ident = this.checkVarDecl(varDecl);
3533
- if (ident) {
3534
- this.state.removeableModuleItems.push(exportDecl.start);
3535
- this.state.fontExports.push({
3536
- type: 'ExportNamedDeclaration',
3537
- specifiers: [
3538
- {
3539
- type: 'ExportSpecifier',
3540
- local: ident,
3541
- exported: {
3542
- name: ident.name,
3543
- type: 'Identifier',
3544
- ...DUMMY_SP
3545
- },
3546
- ...DUMMY_SP
3547
- }
3548
- ],
3549
- attributes: [],
3550
- ...DUMMY_SP
3551
- });
3552
- }
3553
- }
3554
- }
3555
- }
3556
- });
3557
- }
3558
- checkVarDecl(varDecl) {
3559
- const decl = varDecl.declarations[0];
3560
- const ident = decl?.id;
3561
- const expr = decl?.init;
3562
- if (expr?.type === 'CallExpression') {
3563
- const callExpr = expr;
3564
- const importDecl = this.checkCallExpr(callExpr, ident);
3565
- if (importDecl) {
3566
- if (varDecl.kind !== 'const') throw new Error('Font loader calls must be assigned to a const');
3567
- if (!ident) throw new Error('Font loader calls must be assigned to an identifier');
3568
- importDecl.specifiers = [
3569
- {
3570
- type: 'ImportDefaultSpecifier',
3571
- local: ident,
3572
- ...DUMMY_SP
3573
- }
3574
- ];
3575
- if (!this.state.fontImports.map(stableHash).includes(stableHash(importDecl))) {
3576
- // @ts-expect-error
3577
- this.state.fontImports.push(importDecl);
3578
- }
3579
- return ident;
3580
- }
3581
- }
3582
- }
3583
- checkCallExpr(callExpr, variableName) {
3584
- if (callExpr.callee.type === 'Identifier') {
3585
- const ident = callExpr.callee;
3586
- const fontFunction = this.state.fontFunctions[ident.name];
3587
- if (fontFunction) {
3588
- this.state.fontFunctionsInAllowedScope.push(ident.start);
3589
- const json = callExpr.arguments.map((expr_or_spread)=>{
3590
- if (expr_or_spread.type === 'SpreadElement') throw new Error("Font loaders don't accept spreads");
3591
- return exprToJson(expr_or_spread);
3592
- });
3593
- const functionName = fontFunction.functionName ?? '';
3594
- const queryJson = {
3595
- path: this.id,
3596
- import: functionName,
3597
- arguments: json,
3598
- variableName: variableName?.name ?? ''
3599
- };
3600
- return {
3601
- type: 'ImportDeclaration',
3602
- source: {
3603
- type: 'Literal',
3604
- value: queryString.stringifyUrl({
3605
- url: path.posix.join(this.remapImports[fontFunction.loader] || fontFunction.loader, 'target.css'),
3606
- query: Object.assign({}, queryJson, {
3607
- arguments: JSON.stringify(queryJson.arguments)
3608
- })
3609
- }),
3610
- ...DUMMY_SP
3611
- },
3612
- specifiers: [],
3613
- attributes: [],
3614
- ...DUMMY_SP
3615
- };
3616
- }
3617
- }
3618
- }
3619
- }
3620
-
3621
- const visit = ({ ast, fontLoaders, id, remapImports })=>{
3622
- const state = new Proxy({
3623
- removeableModuleItems: [],
3624
- fontFunctionsInAllowedScope: [],
3625
- fontFunctions: {},
3626
- fontImports: [],
3627
- fontExports: []
3628
- }, {
3629
- set (target, prop, value) {
3630
- target[prop] = value;
3631
- return true;
3632
- },
3633
- get (target, prop) {
3634
- return target[prop];
3635
- }
3636
- });
3637
- const functionsCollector = new FontFunctionsCollector({
3638
- state,
3639
- fontLoaders,
3640
- remapImports
3641
- });
3642
- functionsCollector.visit(ast);
3643
- if (state.removeableModuleItems.length > 0) {
3644
- const importGenerator = new FontImportsGenerator({
3645
- state,
3646
- id,
3647
- remapImports
3648
- });
3649
- importGenerator.visit(ast);
3650
- const wrongScope = new FindFunctionsOutsideModuleScope({
3651
- state
3652
- });
3653
- wrongScope.visit(ast);
3654
- const isRemovable = (node)=>{
3655
- return state.removeableModuleItems.includes(node.start);
3656
- };
3657
- // @ts-expect-error
3658
- const firstRemovableIndex = ast.body.findIndex(isRemovable);
3659
- // Remove marked module items
3660
- walk(ast, {
3661
- enter (node) {
3662
- // @ts-expect-error
3663
- if (isRemovable(node)) this.remove();
3664
- }
3665
- });
3666
- // Add font imports and exports
3667
- ast.body.splice(firstRemovableIndex, 0, ...state.fontImports);
3668
- ast.body.push(...state.fontExports);
3669
- return {
3670
- changed: true,
3671
- state
3672
- };
3673
- }
3674
- return {
3675
- changed: false,
3676
- state
3677
- };
3678
- };
3679
-
3680
- const importEscodegen = createCachedImport(()=>// @ts-expect-error
3681
- import('./escodegen-BgZHbZlI.js').then(function (n) { return n.e; }));
3682
- const nextFontTransformerPlugin = ({ fontImports, onFontImportsChanged })=>{
3683
- let config = null;
3684
- const rewriteNextFontImport = {
3685
- '@next/font/google': 'next-font/google',
3686
- '@next/font/local': 'next-font/local',
3687
- 'next/font/google': 'next-font/google',
3688
- 'next/font/local': 'next-font/local'
3689
- };
3690
- const importedLoaders = [
3691
- 'next-font/google',
3692
- 'next-font/local'
3693
- ];
3694
- return [
3695
- {
3696
- name: 'next-font:transform',
3697
- async configResolved (resolvedConfig) {
3698
- config = resolvedConfig;
3699
- },
3700
- async transform (code, id) {
3701
- if (!/\.(?:j|t)sx?$|\.mjs$/.test(id)) return null;
3702
- const parse = async ()=>this.parse(code, {
3703
- jsx: true
3704
- });
3705
- const { data: ast, error } = await tryCatch(parse());
3706
- if (error) {
3707
- this.error(error);
3708
- }
3709
- if (!ast) return;
3710
- const { changed, state } = visit({
3711
- ast,
3712
- fontLoaders: importedLoaders,
3713
- id: path.relative(config.root, id),
3714
- remapImports: rewriteNextFontImport
3715
- });
3716
- if (!changed) return;
3717
- const nextFontImports = state.fontImports.map((i)=>i.source.value);
3718
- const previousFontImports = fontImports[id];
3719
- if (previousFontImports) {
3720
- const importsChanged = nextFontImports.some((i)=>!previousFontImports.some((p)=>p.id === i));
3721
- if (importsChanged) {
3722
- onFontImportsChanged(id, nextFontImports, previousFontImports.map((i)=>i.id));
3723
- }
3724
- }
3725
- fontImports[id] = nextFontImports.map((i)=>({
3726
- id: i
3727
- }));
3728
- const escodegen = await importEscodegen();
3729
- const s = new MagicString('');
3730
- for (const node of ast.body){
3731
- s.append(escodegen.generate(node));
3732
- s.append('\n');
3733
- }
3734
- return {
3735
- code: s.toString()
3736
- };
3737
- }
3738
- }
3739
- ];
3740
- };
3741
-
3742
- const nextFont = ()=>{
3743
- const servers = [];
3744
- const fontImports = new Proxy({}, {
3745
- get (t, p, r) {
3746
- return Reflect.get(t, p, r);
3747
- },
3748
- set (t, p, v, r) {
3749
- return Reflect.set(t, p, v, r);
3750
- }
3751
- });
3752
- const nextFontManifest = {
3753
- isUsingSizeAdjust: false
3754
- };
3755
- const reloadManifest = ()=>{
3756
- for (const server of servers){
3757
- const manifestId = fileURLToPath(import.meta.resolve('next-font/manifest'));
3758
- const manifestMod = server.moduleGraph.getModuleById(manifestId);
3759
- if (manifestMod) {
3760
- server.reloadModule(manifestMod);
3761
- server.moduleGraph.invalidateModule(manifestMod);
3762
- server.moduleGraph.onFileChange(manifestId);
3763
- server.ws.send({
3764
- type: 'full-reload',
3765
- path: manifestId
3766
- });
3767
- }
3768
- }
3769
- };
3770
- const onFinished = async (fileToFontNames)=>{
3771
- for (const [id, targetCss] of fileToFontNames){
3772
- for (const fontFiles of Object.values(targetCss)){
3773
- // Look if size-adjust fallback font is being used
3774
- if (!nextFontManifest.isUsingSizeAdjust) {
3775
- nextFontManifest.isUsingSizeAdjust = getPageIsUsingSizeAdjust(fontFiles);
3776
- }
3777
- const preloadedFontFiles = getPreloadedFontFiles(fontFiles);
3778
- // Add an entry of the module's font files in the manifest.
3779
- // We'll add an entry even if no files should preload.
3780
- // When an entry is present but empty, instead of preloading the font files, a preconnect tag is added.
3781
- if (fontFiles.length > 0) {
3782
- nextFontManifest[id] ||= [];
3783
- nextFontManifest[id] = Array.from(new Set(nextFontManifest[id].concat(preloadedFontFiles)));
3784
- }
3785
- }
3786
- }
3787
- reloadManifest();
3788
- };
3789
- const [{ resetCalledFinished, removeTargetCss }, loaderPlugin] = nextFontLoaderPlugin({
3790
- nextFontManifest,
3791
- fontImports,
3792
- onFinished
3793
- });
3794
- return [
3795
- {
3796
- name: 'next-font:scan',
3797
- configureServer (server) {
3798
- servers.push(server);
3799
- }
3800
- },
3801
- nextFontTransformerPlugin({
3802
- fontImports,
3803
- onFontImportsChanged: async (_id, newValue, previousValue)=>{
3804
- resetCalledFinished();
3805
- const removed = previousValue.filter((p)=>!newValue.includes(p));
3806
- for (const server of servers){
3807
- for (const id of removed){
3808
- const resolvedId = fileURLToPath(import.meta.resolve(removeQuerySuffix(id))) + getQuerySuffix(id);
3809
- removeTargetCss(normalizeTargetCssId(resolvedId));
3810
- const module = server.moduleGraph.getModuleById(resolvedId);
3811
- if (module) {
3812
- server.moduleGraph.onFileDelete(resolvedId);
3813
- server.ws.send({
3814
- type: 'prune',
3815
- paths: [
3816
- resolvedId
3817
- ]
3818
- });
3819
- server.ws.send({
3820
- type: 'update',
3821
- updates: [
3822
- {
3823
- type: 'css-update',
3824
- path: resolvedId,
3825
- acceptedPath: resolvedId,
3826
- timestamp: Date.now()
3827
- },
3828
- {
3829
- type: 'css-update',
3830
- path: id,
3831
- acceptedPath: id,
3832
- timestamp: Date.now()
3833
- }
3834
- ]
3835
- });
3836
- // server.moduleGraph.invalidateModule(module)
3837
- server.reloadModule(module);
3838
- server.ws.send({
3839
- type: 'full-reload',
3840
- path: resolvedId
3841
- });
3842
- }
3843
- }
3844
- reloadManifest();
3845
- }
3846
- }
3847
- }),
3848
- loaderPlugin,
3849
- nextFontManifestPlugin({
3850
- nextFontManifest
3851
- })
3852
- ];
3853
- };
3854
-
3855
- export { commonjsGlobal as c, getDefaultExportFromCjs as g, nextFont as n, requireInterpolateName as r };
3856
- //# sourceMappingURL=index-CyE6nKxy.js.map