@coderline/alphatab-vite 1.7.0-alpha.1617 → 1.7.0-alpha.1626

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.
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * alphaTab Vite Plugin v1.7.0-alpha.1617 (develop, build 1617)
2
+ * alphaTab Vite Plugin v1.7.0-alpha.1626 (develop, build 1626)
3
3
  *
4
4
  * Copyright © 2025, Daniel Kuschny and Contributors, All rights reserved.
5
5
  *
@@ -34,2328 +34,4 @@
34
34
  * @license
35
35
  */
36
36
 
37
- import * as fs from 'node:fs';
38
- import * as path from 'node:path';
39
- import path__default from 'node:path';
40
- import * as url from 'node:url';
41
- import { createHash } from 'node:crypto';
42
- import { normalizePath, BuildEnvironment } from 'vite';
43
-
44
- function copyAssetsPlugin(options) {
45
- let resolvedConfig;
46
- let output = false;
47
- return {
48
- name: 'vite-plugin-alphatab-copy',
49
- enforce: 'pre',
50
- configResolved(config) {
51
- resolvedConfig = config;
52
- },
53
- buildEnd() {
54
- // reset for watch mode
55
- output = false;
56
- },
57
- async buildStart() {
58
- // run copy only once even if multiple bundles are generated
59
- if (output) {
60
- return;
61
- }
62
- output = true;
63
- let alphaTabSourceDir = options.alphaTabSourceDir;
64
- if (!alphaTabSourceDir) {
65
- try {
66
- const isEsm = typeof import.meta.url === 'string';
67
- if (isEsm) {
68
- alphaTabSourceDir = url.fileURLToPath(import.meta.resolve('@coderline/alphatab'));
69
- }
70
- else {
71
- alphaTabSourceDir = require.resolve('@coderline/alphatab');
72
- }
73
- alphaTabSourceDir = path.resolve(alphaTabSourceDir, '..');
74
- }
75
- catch {
76
- alphaTabSourceDir = path.join(resolvedConfig.root, 'node_modules/@coderline/alphatab/dist/');
77
- }
78
- }
79
- let isValidAlphaTabSourceDir;
80
- if (alphaTabSourceDir) {
81
- try {
82
- await fs.promises.access(path.join(alphaTabSourceDir, 'alphaTab.mjs'), fs.constants.F_OK);
83
- isValidAlphaTabSourceDir = true;
84
- }
85
- catch {
86
- isValidAlphaTabSourceDir = false;
87
- }
88
- }
89
- else {
90
- isValidAlphaTabSourceDir = false;
91
- }
92
- if (!isValidAlphaTabSourceDir) {
93
- resolvedConfig.logger.error('Could not find alphaTab, please ensure it is installed into node_modules or configure alphaTabSourceDir');
94
- return;
95
- }
96
- const outputPath = (options.assetOutputDir ?? resolvedConfig.publicDir);
97
- if (!outputPath) {
98
- return;
99
- }
100
- async function copyFiles(subdir) {
101
- const fullDir = path.join(alphaTabSourceDir, subdir);
102
- const files = await fs.promises.readdir(fullDir, {
103
- withFileTypes: true
104
- });
105
- await fs.promises.mkdir(path.join(outputPath, subdir), {
106
- recursive: true
107
- });
108
- await Promise.all(files
109
- .filter(f => f.isFile())
110
- .map(async (file) => {
111
- // node v20.12.0 has parentPath pointing to the path (not the file)
112
- // see https://github.com/nodejs/node/pull/50976
113
- const sourceFilename = path.join(file.parentPath ?? file.path, file.name);
114
- await fs.promises.copyFile(sourceFilename, path.join(outputPath, subdir, file.name));
115
- }));
116
- }
117
- await Promise.all([copyFiles('font'), copyFiles('soundfont')]);
118
- }
119
- };
120
- }
121
-
122
- // src/vlq.ts
123
- var comma = ",".charCodeAt(0);
124
- var semicolon = ";".charCodeAt(0);
125
- var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
126
- var intToChar = new Uint8Array(64);
127
- var charToInt = new Uint8Array(128);
128
- for (let i = 0; i < chars.length; i++) {
129
- const c = chars.charCodeAt(i);
130
- intToChar[i] = c;
131
- charToInt[c] = i;
132
- }
133
- function encodeInteger(builder, num, relative) {
134
- let delta = num - relative;
135
- delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
136
- do {
137
- let clamped = delta & 31;
138
- delta >>>= 5;
139
- if (delta > 0) clamped |= 32;
140
- builder.write(intToChar[clamped]);
141
- } while (delta > 0);
142
- return num;
143
- }
144
-
145
- // src/strings.ts
146
- var bufLength = 1024 * 16;
147
- var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
148
- decode(buf) {
149
- const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
150
- return out.toString();
151
- }
152
- } : {
153
- decode(buf) {
154
- let out = "";
155
- for (let i = 0; i < buf.length; i++) {
156
- out += String.fromCharCode(buf[i]);
157
- }
158
- return out;
159
- }
160
- };
161
- var StringWriter = class {
162
- constructor() {
163
- this.pos = 0;
164
- this.out = "";
165
- this.buffer = new Uint8Array(bufLength);
166
- }
167
- write(v) {
168
- const { buffer } = this;
169
- buffer[this.pos++] = v;
170
- if (this.pos === bufLength) {
171
- this.out += td.decode(buffer);
172
- this.pos = 0;
173
- }
174
- }
175
- flush() {
176
- const { buffer, out, pos } = this;
177
- return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
178
- }
179
- };
180
- function encode(decoded) {
181
- const writer = new StringWriter();
182
- let sourcesIndex = 0;
183
- let sourceLine = 0;
184
- let sourceColumn = 0;
185
- let namesIndex = 0;
186
- for (let i = 0; i < decoded.length; i++) {
187
- const line = decoded[i];
188
- if (i > 0) writer.write(semicolon);
189
- if (line.length === 0) continue;
190
- let genColumn = 0;
191
- for (let j = 0; j < line.length; j++) {
192
- const segment = line[j];
193
- if (j > 0) writer.write(comma);
194
- genColumn = encodeInteger(writer, segment[0], genColumn);
195
- if (segment.length === 1) continue;
196
- sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
197
- sourceLine = encodeInteger(writer, segment[2], sourceLine);
198
- sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
199
- if (segment.length === 4) continue;
200
- namesIndex = encodeInteger(writer, segment[4], namesIndex);
201
- }
202
- }
203
- return writer.flush();
204
- }
205
-
206
- class BitSet {
207
- constructor(arg) {
208
- this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
209
- }
210
-
211
- add(n) {
212
- this.bits[n >> 5] |= 1 << (n & 31);
213
- }
214
-
215
- has(n) {
216
- return !!(this.bits[n >> 5] & (1 << (n & 31)));
217
- }
218
- }
219
-
220
- class Chunk {
221
- constructor(start, end, content) {
222
- this.start = start;
223
- this.end = end;
224
- this.original = content;
225
-
226
- this.intro = '';
227
- this.outro = '';
228
-
229
- this.content = content;
230
- this.storeName = false;
231
- this.edited = false;
232
-
233
- {
234
- this.previous = null;
235
- this.next = null;
236
- }
237
- }
238
-
239
- appendLeft(content) {
240
- this.outro += content;
241
- }
242
-
243
- appendRight(content) {
244
- this.intro = this.intro + content;
245
- }
246
-
247
- clone() {
248
- const chunk = new Chunk(this.start, this.end, this.original);
249
-
250
- chunk.intro = this.intro;
251
- chunk.outro = this.outro;
252
- chunk.content = this.content;
253
- chunk.storeName = this.storeName;
254
- chunk.edited = this.edited;
255
-
256
- return chunk;
257
- }
258
-
259
- contains(index) {
260
- return this.start < index && index < this.end;
261
- }
262
-
263
- eachNext(fn) {
264
- let chunk = this;
265
- while (chunk) {
266
- fn(chunk);
267
- chunk = chunk.next;
268
- }
269
- }
270
-
271
- eachPrevious(fn) {
272
- let chunk = this;
273
- while (chunk) {
274
- fn(chunk);
275
- chunk = chunk.previous;
276
- }
277
- }
278
-
279
- edit(content, storeName, contentOnly) {
280
- this.content = content;
281
- if (!contentOnly) {
282
- this.intro = '';
283
- this.outro = '';
284
- }
285
- this.storeName = storeName;
286
-
287
- this.edited = true;
288
-
289
- return this;
290
- }
291
-
292
- prependLeft(content) {
293
- this.outro = content + this.outro;
294
- }
295
-
296
- prependRight(content) {
297
- this.intro = content + this.intro;
298
- }
299
-
300
- reset() {
301
- this.intro = '';
302
- this.outro = '';
303
- if (this.edited) {
304
- this.content = this.original;
305
- this.storeName = false;
306
- this.edited = false;
307
- }
308
- }
309
-
310
- split(index) {
311
- const sliceIndex = index - this.start;
312
-
313
- const originalBefore = this.original.slice(0, sliceIndex);
314
- const originalAfter = this.original.slice(sliceIndex);
315
-
316
- this.original = originalBefore;
317
-
318
- const newChunk = new Chunk(index, this.end, originalAfter);
319
- newChunk.outro = this.outro;
320
- this.outro = '';
321
-
322
- this.end = index;
323
-
324
- if (this.edited) {
325
- // after split we should save the edit content record into the correct chunk
326
- // to make sure sourcemap correct
327
- // For example:
328
- // ' test'.trim()
329
- // split -> ' ' + 'test'
330
- // ✔️ edit -> '' + 'test'
331
- // ✖️ edit -> 'test' + ''
332
- // TODO is this block necessary?...
333
- newChunk.edit('', false);
334
- this.content = '';
335
- } else {
336
- this.content = originalBefore;
337
- }
338
-
339
- newChunk.next = this.next;
340
- if (newChunk.next) newChunk.next.previous = newChunk;
341
- newChunk.previous = this;
342
- this.next = newChunk;
343
-
344
- return newChunk;
345
- }
346
-
347
- toString() {
348
- return this.intro + this.content + this.outro;
349
- }
350
-
351
- trimEnd(rx) {
352
- this.outro = this.outro.replace(rx, '');
353
- if (this.outro.length) return true;
354
-
355
- const trimmed = this.content.replace(rx, '');
356
-
357
- if (trimmed.length) {
358
- if (trimmed !== this.content) {
359
- this.split(this.start + trimmed.length).edit('', undefined, true);
360
- if (this.edited) {
361
- // save the change, if it has been edited
362
- this.edit(trimmed, this.storeName, true);
363
- }
364
- }
365
- return true;
366
- } else {
367
- this.edit('', undefined, true);
368
-
369
- this.intro = this.intro.replace(rx, '');
370
- if (this.intro.length) return true;
371
- }
372
- }
373
-
374
- trimStart(rx) {
375
- this.intro = this.intro.replace(rx, '');
376
- if (this.intro.length) return true;
377
-
378
- const trimmed = this.content.replace(rx, '');
379
-
380
- if (trimmed.length) {
381
- if (trimmed !== this.content) {
382
- const newChunk = this.split(this.end - trimmed.length);
383
- if (this.edited) {
384
- // save the change, if it has been edited
385
- newChunk.edit(trimmed, this.storeName, true);
386
- }
387
- this.edit('', undefined, true);
388
- }
389
- return true;
390
- } else {
391
- this.edit('', undefined, true);
392
-
393
- this.outro = this.outro.replace(rx, '');
394
- if (this.outro.length) return true;
395
- }
396
- }
397
- }
398
-
399
- function getBtoa() {
400
- if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
401
- return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
402
- } else if (typeof Buffer === 'function') {
403
- return (str) => Buffer.from(str, 'utf-8').toString('base64');
404
- } else {
405
- return () => {
406
- throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
407
- };
408
- }
409
- }
410
-
411
- const btoa = /*#__PURE__*/ getBtoa();
412
-
413
- class SourceMap {
414
- constructor(properties) {
415
- this.version = 3;
416
- this.file = properties.file;
417
- this.sources = properties.sources;
418
- this.sourcesContent = properties.sourcesContent;
419
- this.names = properties.names;
420
- this.mappings = encode(properties.mappings);
421
- if (typeof properties.x_google_ignoreList !== 'undefined') {
422
- this.x_google_ignoreList = properties.x_google_ignoreList;
423
- }
424
- if (typeof properties.debugId !== 'undefined') {
425
- this.debugId = properties.debugId;
426
- }
427
- }
428
-
429
- toString() {
430
- return JSON.stringify(this);
431
- }
432
-
433
- toUrl() {
434
- return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
435
- }
436
- }
437
-
438
- function guessIndent(code) {
439
- const lines = code.split('\n');
440
-
441
- const tabbed = lines.filter((line) => /^\t+/.test(line));
442
- const spaced = lines.filter((line) => /^ {2,}/.test(line));
443
-
444
- if (tabbed.length === 0 && spaced.length === 0) {
445
- return null;
446
- }
447
-
448
- // More lines tabbed than spaced? Assume tabs, and
449
- // default to tabs in the case of a tie (or nothing
450
- // to go on)
451
- if (tabbed.length >= spaced.length) {
452
- return '\t';
453
- }
454
-
455
- // Otherwise, we need to guess the multiple
456
- const min = spaced.reduce((previous, current) => {
457
- const numSpaces = /^ +/.exec(current)[0].length;
458
- return Math.min(numSpaces, previous);
459
- }, Infinity);
460
-
461
- return new Array(min + 1).join(' ');
462
- }
463
-
464
- function getRelativePath(from, to) {
465
- const fromParts = from.split(/[/\\]/);
466
- const toParts = to.split(/[/\\]/);
467
-
468
- fromParts.pop(); // get dirname
469
-
470
- while (fromParts[0] === toParts[0]) {
471
- fromParts.shift();
472
- toParts.shift();
473
- }
474
-
475
- if (fromParts.length) {
476
- let i = fromParts.length;
477
- while (i--) fromParts[i] = '..';
478
- }
479
-
480
- return fromParts.concat(toParts).join('/');
481
- }
482
-
483
- const toString = Object.prototype.toString;
484
-
485
- function isObject(thing) {
486
- return toString.call(thing) === '[object Object]';
487
- }
488
-
489
- function getLocator(source) {
490
- const originalLines = source.split('\n');
491
- const lineOffsets = [];
492
-
493
- for (let i = 0, pos = 0; i < originalLines.length; i++) {
494
- lineOffsets.push(pos);
495
- pos += originalLines[i].length + 1;
496
- }
497
-
498
- return function locate(index) {
499
- let i = 0;
500
- let j = lineOffsets.length;
501
- while (i < j) {
502
- const m = (i + j) >> 1;
503
- if (index < lineOffsets[m]) {
504
- j = m;
505
- } else {
506
- i = m + 1;
507
- }
508
- }
509
- const line = i - 1;
510
- const column = index - lineOffsets[line];
511
- return { line, column };
512
- };
513
- }
514
-
515
- const wordRegex = /\w/;
516
-
517
- class Mappings {
518
- constructor(hires) {
519
- this.hires = hires;
520
- this.generatedCodeLine = 0;
521
- this.generatedCodeColumn = 0;
522
- this.raw = [];
523
- this.rawSegments = this.raw[this.generatedCodeLine] = [];
524
- this.pending = null;
525
- }
526
-
527
- addEdit(sourceIndex, content, loc, nameIndex) {
528
- if (content.length) {
529
- const contentLengthMinusOne = content.length - 1;
530
- let contentLineEnd = content.indexOf('\n', 0);
531
- let previousContentLineEnd = -1;
532
- // Loop through each line in the content and add a segment, but stop if the last line is empty,
533
- // else code afterwards would fill one line too many
534
- while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
535
- const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
536
- if (nameIndex >= 0) {
537
- segment.push(nameIndex);
538
- }
539
- this.rawSegments.push(segment);
540
-
541
- this.generatedCodeLine += 1;
542
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
543
- this.generatedCodeColumn = 0;
544
-
545
- previousContentLineEnd = contentLineEnd;
546
- contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
547
- }
548
-
549
- const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
550
- if (nameIndex >= 0) {
551
- segment.push(nameIndex);
552
- }
553
- this.rawSegments.push(segment);
554
-
555
- this.advance(content.slice(previousContentLineEnd + 1));
556
- } else if (this.pending) {
557
- this.rawSegments.push(this.pending);
558
- this.advance(content);
559
- }
560
-
561
- this.pending = null;
562
- }
563
-
564
- addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
565
- let originalCharIndex = chunk.start;
566
- let first = true;
567
- // when iterating each char, check if it's in a word boundary
568
- let charInHiresBoundary = false;
569
-
570
- while (originalCharIndex < chunk.end) {
571
- if (original[originalCharIndex] === '\n') {
572
- loc.line += 1;
573
- loc.column = 0;
574
- this.generatedCodeLine += 1;
575
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
576
- this.generatedCodeColumn = 0;
577
- first = true;
578
- charInHiresBoundary = false;
579
- } else {
580
- if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
581
- const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
582
-
583
- if (this.hires === 'boundary') {
584
- // in hires "boundary", group segments per word boundary than per char
585
- if (wordRegex.test(original[originalCharIndex])) {
586
- // for first char in the boundary found, start the boundary by pushing a segment
587
- if (!charInHiresBoundary) {
588
- this.rawSegments.push(segment);
589
- charInHiresBoundary = true;
590
- }
591
- } else {
592
- // for non-word char, end the boundary by pushing a segment
593
- this.rawSegments.push(segment);
594
- charInHiresBoundary = false;
595
- }
596
- } else {
597
- this.rawSegments.push(segment);
598
- }
599
- }
600
-
601
- loc.column += 1;
602
- this.generatedCodeColumn += 1;
603
- first = false;
604
- }
605
-
606
- originalCharIndex += 1;
607
- }
608
-
609
- this.pending = null;
610
- }
611
-
612
- advance(str) {
613
- if (!str) return;
614
-
615
- const lines = str.split('\n');
616
-
617
- if (lines.length > 1) {
618
- for (let i = 0; i < lines.length - 1; i++) {
619
- this.generatedCodeLine++;
620
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
621
- }
622
- this.generatedCodeColumn = 0;
623
- }
624
-
625
- this.generatedCodeColumn += lines[lines.length - 1].length;
626
- }
627
- }
628
-
629
- const n = '\n';
630
-
631
- const warned = {
632
- insertLeft: false,
633
- insertRight: false,
634
- storeName: false,
635
- };
636
-
637
- class MagicString {
638
- constructor(string, options = {}) {
639
- const chunk = new Chunk(0, string.length, string);
640
-
641
- Object.defineProperties(this, {
642
- original: { writable: true, value: string },
643
- outro: { writable: true, value: '' },
644
- intro: { writable: true, value: '' },
645
- firstChunk: { writable: true, value: chunk },
646
- lastChunk: { writable: true, value: chunk },
647
- lastSearchedChunk: { writable: true, value: chunk },
648
- byStart: { writable: true, value: {} },
649
- byEnd: { writable: true, value: {} },
650
- filename: { writable: true, value: options.filename },
651
- indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
652
- sourcemapLocations: { writable: true, value: new BitSet() },
653
- storedNames: { writable: true, value: {} },
654
- indentStr: { writable: true, value: undefined },
655
- ignoreList: { writable: true, value: options.ignoreList },
656
- offset: { writable: true, value: options.offset || 0 },
657
- });
658
-
659
- this.byStart[0] = chunk;
660
- this.byEnd[string.length] = chunk;
661
- }
662
-
663
- addSourcemapLocation(char) {
664
- this.sourcemapLocations.add(char);
665
- }
666
-
667
- append(content) {
668
- if (typeof content !== 'string') throw new TypeError('outro content must be a string');
669
-
670
- this.outro += content;
671
- return this;
672
- }
673
-
674
- appendLeft(index, content) {
675
- index = index + this.offset;
676
-
677
- if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
678
-
679
- this._split(index);
680
-
681
- const chunk = this.byEnd[index];
682
-
683
- if (chunk) {
684
- chunk.appendLeft(content);
685
- } else {
686
- this.intro += content;
687
- }
688
- return this;
689
- }
690
-
691
- appendRight(index, content) {
692
- index = index + this.offset;
693
-
694
- if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
695
-
696
- this._split(index);
697
-
698
- const chunk = this.byStart[index];
699
-
700
- if (chunk) {
701
- chunk.appendRight(content);
702
- } else {
703
- this.outro += content;
704
- }
705
- return this;
706
- }
707
-
708
- clone() {
709
- const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });
710
-
711
- let originalChunk = this.firstChunk;
712
- let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
713
-
714
- while (originalChunk) {
715
- cloned.byStart[clonedChunk.start] = clonedChunk;
716
- cloned.byEnd[clonedChunk.end] = clonedChunk;
717
-
718
- const nextOriginalChunk = originalChunk.next;
719
- const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
720
-
721
- if (nextClonedChunk) {
722
- clonedChunk.next = nextClonedChunk;
723
- nextClonedChunk.previous = clonedChunk;
724
-
725
- clonedChunk = nextClonedChunk;
726
- }
727
-
728
- originalChunk = nextOriginalChunk;
729
- }
730
-
731
- cloned.lastChunk = clonedChunk;
732
-
733
- if (this.indentExclusionRanges) {
734
- cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
735
- }
736
-
737
- cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
738
-
739
- cloned.intro = this.intro;
740
- cloned.outro = this.outro;
741
-
742
- return cloned;
743
- }
744
-
745
- generateDecodedMap(options) {
746
- options = options || {};
747
-
748
- const sourceIndex = 0;
749
- const names = Object.keys(this.storedNames);
750
- const mappings = new Mappings(options.hires);
751
-
752
- const locate = getLocator(this.original);
753
-
754
- if (this.intro) {
755
- mappings.advance(this.intro);
756
- }
757
-
758
- this.firstChunk.eachNext((chunk) => {
759
- const loc = locate(chunk.start);
760
-
761
- if (chunk.intro.length) mappings.advance(chunk.intro);
762
-
763
- if (chunk.edited) {
764
- mappings.addEdit(
765
- sourceIndex,
766
- chunk.content,
767
- loc,
768
- chunk.storeName ? names.indexOf(chunk.original) : -1,
769
- );
770
- } else {
771
- mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
772
- }
773
-
774
- if (chunk.outro.length) mappings.advance(chunk.outro);
775
- });
776
-
777
- return {
778
- file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
779
- sources: [
780
- options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
781
- ],
782
- sourcesContent: options.includeContent ? [this.original] : undefined,
783
- names,
784
- mappings: mappings.raw,
785
- x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
786
- };
787
- }
788
-
789
- generateMap(options) {
790
- return new SourceMap(this.generateDecodedMap(options));
791
- }
792
-
793
- _ensureindentStr() {
794
- if (this.indentStr === undefined) {
795
- this.indentStr = guessIndent(this.original);
796
- }
797
- }
798
-
799
- _getRawIndentString() {
800
- this._ensureindentStr();
801
- return this.indentStr;
802
- }
803
-
804
- getIndentString() {
805
- this._ensureindentStr();
806
- return this.indentStr === null ? '\t' : this.indentStr;
807
- }
808
-
809
- indent(indentStr, options) {
810
- const pattern = /^[^\r\n]/gm;
811
-
812
- if (isObject(indentStr)) {
813
- options = indentStr;
814
- indentStr = undefined;
815
- }
816
-
817
- if (indentStr === undefined) {
818
- this._ensureindentStr();
819
- indentStr = this.indentStr || '\t';
820
- }
821
-
822
- if (indentStr === '') return this; // noop
823
-
824
- options = options || {};
825
-
826
- // Process exclusion ranges
827
- const isExcluded = {};
828
-
829
- if (options.exclude) {
830
- const exclusions =
831
- typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
832
- exclusions.forEach((exclusion) => {
833
- for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
834
- isExcluded[i] = true;
835
- }
836
- });
837
- }
838
-
839
- let shouldIndentNextCharacter = options.indentStart !== false;
840
- const replacer = (match) => {
841
- if (shouldIndentNextCharacter) return `${indentStr}${match}`;
842
- shouldIndentNextCharacter = true;
843
- return match;
844
- };
845
-
846
- this.intro = this.intro.replace(pattern, replacer);
847
-
848
- let charIndex = 0;
849
- let chunk = this.firstChunk;
850
-
851
- while (chunk) {
852
- const end = chunk.end;
853
-
854
- if (chunk.edited) {
855
- if (!isExcluded[charIndex]) {
856
- chunk.content = chunk.content.replace(pattern, replacer);
857
-
858
- if (chunk.content.length) {
859
- shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
860
- }
861
- }
862
- } else {
863
- charIndex = chunk.start;
864
-
865
- while (charIndex < end) {
866
- if (!isExcluded[charIndex]) {
867
- const char = this.original[charIndex];
868
-
869
- if (char === '\n') {
870
- shouldIndentNextCharacter = true;
871
- } else if (char !== '\r' && shouldIndentNextCharacter) {
872
- shouldIndentNextCharacter = false;
873
-
874
- if (charIndex === chunk.start) {
875
- chunk.prependRight(indentStr);
876
- } else {
877
- this._splitChunk(chunk, charIndex);
878
- chunk = chunk.next;
879
- chunk.prependRight(indentStr);
880
- }
881
- }
882
- }
883
-
884
- charIndex += 1;
885
- }
886
- }
887
-
888
- charIndex = chunk.end;
889
- chunk = chunk.next;
890
- }
891
-
892
- this.outro = this.outro.replace(pattern, replacer);
893
-
894
- return this;
895
- }
896
-
897
- insert() {
898
- throw new Error(
899
- 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
900
- );
901
- }
902
-
903
- insertLeft(index, content) {
904
- if (!warned.insertLeft) {
905
- console.warn(
906
- 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
907
- );
908
- warned.insertLeft = true;
909
- }
910
-
911
- return this.appendLeft(index, content);
912
- }
913
-
914
- insertRight(index, content) {
915
- if (!warned.insertRight) {
916
- console.warn(
917
- 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
918
- );
919
- warned.insertRight = true;
920
- }
921
-
922
- return this.prependRight(index, content);
923
- }
924
-
925
- move(start, end, index) {
926
- start = start + this.offset;
927
- end = end + this.offset;
928
- index = index + this.offset;
929
-
930
- if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
931
-
932
- this._split(start);
933
- this._split(end);
934
- this._split(index);
935
-
936
- const first = this.byStart[start];
937
- const last = this.byEnd[end];
938
-
939
- const oldLeft = first.previous;
940
- const oldRight = last.next;
941
-
942
- const newRight = this.byStart[index];
943
- if (!newRight && last === this.lastChunk) return this;
944
- const newLeft = newRight ? newRight.previous : this.lastChunk;
945
-
946
- if (oldLeft) oldLeft.next = oldRight;
947
- if (oldRight) oldRight.previous = oldLeft;
948
-
949
- if (newLeft) newLeft.next = first;
950
- if (newRight) newRight.previous = last;
951
-
952
- if (!first.previous) this.firstChunk = last.next;
953
- if (!last.next) {
954
- this.lastChunk = first.previous;
955
- this.lastChunk.next = null;
956
- }
957
-
958
- first.previous = newLeft;
959
- last.next = newRight || null;
960
-
961
- if (!newLeft) this.firstChunk = first;
962
- if (!newRight) this.lastChunk = last;
963
- return this;
964
- }
965
-
966
- overwrite(start, end, content, options) {
967
- options = options || {};
968
- return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
969
- }
970
-
971
- update(start, end, content, options) {
972
- start = start + this.offset;
973
- end = end + this.offset;
974
-
975
- if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
976
-
977
- if (this.original.length !== 0) {
978
- while (start < 0) start += this.original.length;
979
- while (end < 0) end += this.original.length;
980
- }
981
-
982
- if (end > this.original.length) throw new Error('end is out of bounds');
983
- if (start === end)
984
- throw new Error(
985
- 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
986
- );
987
-
988
- this._split(start);
989
- this._split(end);
990
-
991
- if (options === true) {
992
- if (!warned.storeName) {
993
- console.warn(
994
- 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
995
- );
996
- warned.storeName = true;
997
- }
998
-
999
- options = { storeName: true };
1000
- }
1001
- const storeName = options !== undefined ? options.storeName : false;
1002
- const overwrite = options !== undefined ? options.overwrite : false;
1003
-
1004
- if (storeName) {
1005
- const original = this.original.slice(start, end);
1006
- Object.defineProperty(this.storedNames, original, {
1007
- writable: true,
1008
- value: true,
1009
- enumerable: true,
1010
- });
1011
- }
1012
-
1013
- const first = this.byStart[start];
1014
- const last = this.byEnd[end];
1015
-
1016
- if (first) {
1017
- let chunk = first;
1018
- while (chunk !== last) {
1019
- if (chunk.next !== this.byStart[chunk.end]) {
1020
- throw new Error('Cannot overwrite across a split point');
1021
- }
1022
- chunk = chunk.next;
1023
- chunk.edit('', false);
1024
- }
1025
-
1026
- first.edit(content, storeName, !overwrite);
1027
- } else {
1028
- // must be inserting at the end
1029
- const newChunk = new Chunk(start, end, '').edit(content, storeName);
1030
-
1031
- // TODO last chunk in the array may not be the last chunk, if it's moved...
1032
- last.next = newChunk;
1033
- newChunk.previous = last;
1034
- }
1035
- return this;
1036
- }
1037
-
1038
- prepend(content) {
1039
- if (typeof content !== 'string') throw new TypeError('outro content must be a string');
1040
-
1041
- this.intro = content + this.intro;
1042
- return this;
1043
- }
1044
-
1045
- prependLeft(index, content) {
1046
- index = index + this.offset;
1047
-
1048
- if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
1049
-
1050
- this._split(index);
1051
-
1052
- const chunk = this.byEnd[index];
1053
-
1054
- if (chunk) {
1055
- chunk.prependLeft(content);
1056
- } else {
1057
- this.intro = content + this.intro;
1058
- }
1059
- return this;
1060
- }
1061
-
1062
- prependRight(index, content) {
1063
- index = index + this.offset;
1064
-
1065
- if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
1066
-
1067
- this._split(index);
1068
-
1069
- const chunk = this.byStart[index];
1070
-
1071
- if (chunk) {
1072
- chunk.prependRight(content);
1073
- } else {
1074
- this.outro = content + this.outro;
1075
- }
1076
- return this;
1077
- }
1078
-
1079
- remove(start, end) {
1080
- start = start + this.offset;
1081
- end = end + this.offset;
1082
-
1083
- if (this.original.length !== 0) {
1084
- while (start < 0) start += this.original.length;
1085
- while (end < 0) end += this.original.length;
1086
- }
1087
-
1088
- if (start === end) return this;
1089
-
1090
- if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
1091
- if (start > end) throw new Error('end must be greater than start');
1092
-
1093
- this._split(start);
1094
- this._split(end);
1095
-
1096
- let chunk = this.byStart[start];
1097
-
1098
- while (chunk) {
1099
- chunk.intro = '';
1100
- chunk.outro = '';
1101
- chunk.edit('');
1102
-
1103
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1104
- }
1105
- return this;
1106
- }
1107
-
1108
- reset(start, end) {
1109
- start = start + this.offset;
1110
- end = end + this.offset;
1111
-
1112
- if (this.original.length !== 0) {
1113
- while (start < 0) start += this.original.length;
1114
- while (end < 0) end += this.original.length;
1115
- }
1116
-
1117
- if (start === end) return this;
1118
-
1119
- if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
1120
- if (start > end) throw new Error('end must be greater than start');
1121
-
1122
- this._split(start);
1123
- this._split(end);
1124
-
1125
- let chunk = this.byStart[start];
1126
-
1127
- while (chunk) {
1128
- chunk.reset();
1129
-
1130
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1131
- }
1132
- return this;
1133
- }
1134
-
1135
- lastChar() {
1136
- if (this.outro.length) return this.outro[this.outro.length - 1];
1137
- let chunk = this.lastChunk;
1138
- do {
1139
- if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
1140
- if (chunk.content.length) return chunk.content[chunk.content.length - 1];
1141
- if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
1142
- } while ((chunk = chunk.previous));
1143
- if (this.intro.length) return this.intro[this.intro.length - 1];
1144
- return '';
1145
- }
1146
-
1147
- lastLine() {
1148
- let lineIndex = this.outro.lastIndexOf(n);
1149
- if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
1150
- let lineStr = this.outro;
1151
- let chunk = this.lastChunk;
1152
- do {
1153
- if (chunk.outro.length > 0) {
1154
- lineIndex = chunk.outro.lastIndexOf(n);
1155
- if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
1156
- lineStr = chunk.outro + lineStr;
1157
- }
1158
-
1159
- if (chunk.content.length > 0) {
1160
- lineIndex = chunk.content.lastIndexOf(n);
1161
- if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
1162
- lineStr = chunk.content + lineStr;
1163
- }
1164
-
1165
- if (chunk.intro.length > 0) {
1166
- lineIndex = chunk.intro.lastIndexOf(n);
1167
- if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
1168
- lineStr = chunk.intro + lineStr;
1169
- }
1170
- } while ((chunk = chunk.previous));
1171
- lineIndex = this.intro.lastIndexOf(n);
1172
- if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
1173
- return this.intro + lineStr;
1174
- }
1175
-
1176
- slice(start = 0, end = this.original.length - this.offset) {
1177
- start = start + this.offset;
1178
- end = end + this.offset;
1179
-
1180
- if (this.original.length !== 0) {
1181
- while (start < 0) start += this.original.length;
1182
- while (end < 0) end += this.original.length;
1183
- }
1184
-
1185
- let result = '';
1186
-
1187
- // find start chunk
1188
- let chunk = this.firstChunk;
1189
- while (chunk && (chunk.start > start || chunk.end <= start)) {
1190
- // found end chunk before start
1191
- if (chunk.start < end && chunk.end >= end) {
1192
- return result;
1193
- }
1194
-
1195
- chunk = chunk.next;
1196
- }
1197
-
1198
- if (chunk && chunk.edited && chunk.start !== start)
1199
- throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
1200
-
1201
- const startChunk = chunk;
1202
- while (chunk) {
1203
- if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
1204
- result += chunk.intro;
1205
- }
1206
-
1207
- const containsEnd = chunk.start < end && chunk.end >= end;
1208
- if (containsEnd && chunk.edited && chunk.end !== end)
1209
- throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
1210
-
1211
- const sliceStart = startChunk === chunk ? start - chunk.start : 0;
1212
- const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
1213
-
1214
- result += chunk.content.slice(sliceStart, sliceEnd);
1215
-
1216
- if (chunk.outro && (!containsEnd || chunk.end === end)) {
1217
- result += chunk.outro;
1218
- }
1219
-
1220
- if (containsEnd) {
1221
- break;
1222
- }
1223
-
1224
- chunk = chunk.next;
1225
- }
1226
-
1227
- return result;
1228
- }
1229
-
1230
- // TODO deprecate this? not really very useful
1231
- snip(start, end) {
1232
- const clone = this.clone();
1233
- clone.remove(0, start);
1234
- clone.remove(end, clone.original.length);
1235
-
1236
- return clone;
1237
- }
1238
-
1239
- _split(index) {
1240
- if (this.byStart[index] || this.byEnd[index]) return;
1241
-
1242
- let chunk = this.lastSearchedChunk;
1243
- let previousChunk = chunk;
1244
- const searchForward = index > chunk.end;
1245
-
1246
- while (chunk) {
1247
- if (chunk.contains(index)) return this._splitChunk(chunk, index);
1248
-
1249
- chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
1250
-
1251
- // Prevent infinite loop (e.g. via empty chunks, where start === end)
1252
- if (chunk === previousChunk) return;
1253
-
1254
- previousChunk = chunk;
1255
- }
1256
- }
1257
-
1258
- _splitChunk(chunk, index) {
1259
- if (chunk.edited && chunk.content.length) {
1260
- // zero-length edited chunks are a special case (overlapping replacements)
1261
- const loc = getLocator(this.original)(index);
1262
- throw new Error(
1263
- `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
1264
- );
1265
- }
1266
-
1267
- const newChunk = chunk.split(index);
1268
-
1269
- this.byEnd[index] = chunk;
1270
- this.byStart[index] = newChunk;
1271
- this.byEnd[newChunk.end] = newChunk;
1272
-
1273
- if (chunk === this.lastChunk) this.lastChunk = newChunk;
1274
-
1275
- this.lastSearchedChunk = chunk;
1276
- return true;
1277
- }
1278
-
1279
- toString() {
1280
- let str = this.intro;
1281
-
1282
- let chunk = this.firstChunk;
1283
- while (chunk) {
1284
- str += chunk.toString();
1285
- chunk = chunk.next;
1286
- }
1287
-
1288
- return str + this.outro;
1289
- }
1290
-
1291
- isEmpty() {
1292
- let chunk = this.firstChunk;
1293
- do {
1294
- if (
1295
- (chunk.intro.length && chunk.intro.trim()) ||
1296
- (chunk.content.length && chunk.content.trim()) ||
1297
- (chunk.outro.length && chunk.outro.trim())
1298
- )
1299
- return false;
1300
- } while ((chunk = chunk.next));
1301
- return true;
1302
- }
1303
-
1304
- length() {
1305
- let chunk = this.firstChunk;
1306
- let length = 0;
1307
- do {
1308
- length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1309
- } while ((chunk = chunk.next));
1310
- return length;
1311
- }
1312
-
1313
- trimLines() {
1314
- return this.trim('[\\r\\n]');
1315
- }
1316
-
1317
- trim(charType) {
1318
- return this.trimStart(charType).trimEnd(charType);
1319
- }
1320
-
1321
- trimEndAborted(charType) {
1322
- const rx = new RegExp((charType || '\\s') + '+$');
1323
-
1324
- this.outro = this.outro.replace(rx, '');
1325
- if (this.outro.length) return true;
1326
-
1327
- let chunk = this.lastChunk;
1328
-
1329
- do {
1330
- const end = chunk.end;
1331
- const aborted = chunk.trimEnd(rx);
1332
-
1333
- // if chunk was trimmed, we have a new lastChunk
1334
- if (chunk.end !== end) {
1335
- if (this.lastChunk === chunk) {
1336
- this.lastChunk = chunk.next;
1337
- }
1338
-
1339
- this.byEnd[chunk.end] = chunk;
1340
- this.byStart[chunk.next.start] = chunk.next;
1341
- this.byEnd[chunk.next.end] = chunk.next;
1342
- }
1343
-
1344
- if (aborted) return true;
1345
- chunk = chunk.previous;
1346
- } while (chunk);
1347
-
1348
- return false;
1349
- }
1350
-
1351
- trimEnd(charType) {
1352
- this.trimEndAborted(charType);
1353
- return this;
1354
- }
1355
- trimStartAborted(charType) {
1356
- const rx = new RegExp('^' + (charType || '\\s') + '+');
1357
-
1358
- this.intro = this.intro.replace(rx, '');
1359
- if (this.intro.length) return true;
1360
-
1361
- let chunk = this.firstChunk;
1362
-
1363
- do {
1364
- const end = chunk.end;
1365
- const aborted = chunk.trimStart(rx);
1366
-
1367
- if (chunk.end !== end) {
1368
- // special case...
1369
- if (chunk === this.lastChunk) this.lastChunk = chunk.next;
1370
-
1371
- this.byEnd[chunk.end] = chunk;
1372
- this.byStart[chunk.next.start] = chunk.next;
1373
- this.byEnd[chunk.next.end] = chunk.next;
1374
- }
1375
-
1376
- if (aborted) return true;
1377
- chunk = chunk.next;
1378
- } while (chunk);
1379
-
1380
- return false;
1381
- }
1382
-
1383
- trimStart(charType) {
1384
- this.trimStartAborted(charType);
1385
- return this;
1386
- }
1387
-
1388
- hasChanged() {
1389
- return this.original !== this.toString();
1390
- }
1391
-
1392
- _replaceRegexp(searchValue, replacement) {
1393
- function getReplacement(match, str) {
1394
- if (typeof replacement === 'string') {
1395
- return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
1396
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
1397
- if (i === '$') return '$';
1398
- if (i === '&') return match[0];
1399
- const num = +i;
1400
- if (num < match.length) return match[+i];
1401
- return `$${i}`;
1402
- });
1403
- } else {
1404
- return replacement(...match, match.index, str, match.groups);
1405
- }
1406
- }
1407
- function matchAll(re, str) {
1408
- let match;
1409
- const matches = [];
1410
- while ((match = re.exec(str))) {
1411
- matches.push(match);
1412
- }
1413
- return matches;
1414
- }
1415
- if (searchValue.global) {
1416
- const matches = matchAll(searchValue, this.original);
1417
- matches.forEach((match) => {
1418
- if (match.index != null) {
1419
- const replacement = getReplacement(match, this.original);
1420
- if (replacement !== match[0]) {
1421
- this.overwrite(match.index, match.index + match[0].length, replacement);
1422
- }
1423
- }
1424
- });
1425
- } else {
1426
- const match = this.original.match(searchValue);
1427
- if (match && match.index != null) {
1428
- const replacement = getReplacement(match, this.original);
1429
- if (replacement !== match[0]) {
1430
- this.overwrite(match.index, match.index + match[0].length, replacement);
1431
- }
1432
- }
1433
- }
1434
- return this;
1435
- }
1436
-
1437
- _replaceString(string, replacement) {
1438
- const { original } = this;
1439
- const index = original.indexOf(string);
1440
-
1441
- if (index !== -1) {
1442
- this.overwrite(index, index + string.length, replacement);
1443
- }
1444
-
1445
- return this;
1446
- }
1447
-
1448
- replace(searchValue, replacement) {
1449
- if (typeof searchValue === 'string') {
1450
- return this._replaceString(searchValue, replacement);
1451
- }
1452
-
1453
- return this._replaceRegexp(searchValue, replacement);
1454
- }
1455
-
1456
- _replaceAllString(string, replacement) {
1457
- const { original } = this;
1458
- const stringLength = string.length;
1459
- for (
1460
- let index = original.indexOf(string);
1461
- index !== -1;
1462
- index = original.indexOf(string, index + stringLength)
1463
- ) {
1464
- const previous = original.slice(index, index + stringLength);
1465
- if (previous !== replacement) this.overwrite(index, index + stringLength, replacement);
1466
- }
1467
-
1468
- return this;
1469
- }
1470
-
1471
- replaceAll(searchValue, replacement) {
1472
- if (typeof searchValue === 'string') {
1473
- return this._replaceAllString(searchValue, replacement);
1474
- }
1475
-
1476
- if (!searchValue.global) {
1477
- throw new TypeError(
1478
- 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
1479
- );
1480
- }
1481
-
1482
- return this._replaceRegexp(searchValue, replacement);
1483
- }
1484
- }
1485
-
1486
- // index.ts for more details on contents and license of this file
1487
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L1302
1488
- function evalValue(rawValue) {
1489
- const fn = new Function(`
1490
- var console, exports, global, module, process, require
1491
- return (\n${rawValue}\n)
1492
- `);
1493
- return fn();
1494
- }
1495
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/shared/utils.ts#L31-L34
1496
- const postfixRE = /[?#].*$/;
1497
- function cleanUrl(url) {
1498
- return url.replace(postfixRE, '');
1499
- }
1500
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L393
1501
- function tryStatSync(file) {
1502
- try {
1503
- // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
1504
- return fs.statSync(file, { throwIfNoEntry: false });
1505
- }
1506
- catch {
1507
- // Ignore errors
1508
- }
1509
- return;
1510
- }
1511
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L1030
1512
- function getHash(text, length = 8) {
1513
- const h = createHash('sha256').update(text).digest('hex').substring(0, length);
1514
- if (length <= 64) {
1515
- return h;
1516
- }
1517
- return h.padEnd(length, '_');
1518
- }
1519
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/shared/utils.ts#L40
1520
- function withTrailingSlash(path) {
1521
- if (path[path.length - 1] !== '/') {
1522
- return `${path}/`;
1523
- }
1524
- return path;
1525
- }
1526
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L1268
1527
- function joinUrlSegments(a, b) {
1528
- if (!a || !b) {
1529
- return a || b || '';
1530
- }
1531
- if (a[a.length - 1] === '/') {
1532
- a = a.substring(0, a.length - 1);
1533
- }
1534
- if (b[0] !== '/') {
1535
- b = `/${b}`;
1536
- }
1537
- return a + b;
1538
- }
1539
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L1281
1540
- function removeLeadingSlash(str) {
1541
- return str[0] === '/' ? str.slice(1) : str;
1542
- }
1543
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L319
1544
- function injectQuery(builtUrl, query) {
1545
- const queryIndex = builtUrl.indexOf('?');
1546
- return builtUrl + (queryIndex === -1 ? '?' : '&') + query;
1547
- }
1548
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L1435
1549
- function partialEncodeURIPath(uri) {
1550
- if (uri.startsWith('data:')) {
1551
- return uri;
1552
- }
1553
- const filePath = cleanUrl(uri);
1554
- const postfix = filePath !== uri ? uri.slice(filePath.length) : '';
1555
- return filePath.replaceAll('%', '%25') + postfix;
1556
- }
1557
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L1424
1558
- function encodeURIPath(uri) {
1559
- if (uri.startsWith('data:')) {
1560
- return uri;
1561
- }
1562
- const filePath = cleanUrl(uri);
1563
- const postfix = filePath !== uri ? uri.slice(filePath.length) : '';
1564
- return encodeURI(filePath) + postfix;
1565
- }
1566
-
1567
- // index.ts for more details on contents and license of this file
1568
- const FS_PREFIX = '/@fs/';
1569
- async function fileToUrl(id, config) {
1570
- let rtn;
1571
- if (id.startsWith(withTrailingSlash(config.root))) {
1572
- // in project root, infer short public path
1573
- rtn = `/${path.posix.relative(config.root, id)}`;
1574
- }
1575
- else {
1576
- // outside of project root, use absolute fs path
1577
- // (this is special handled by the serve static middleware
1578
- rtn = path.posix.join(FS_PREFIX, id);
1579
- }
1580
- const base = joinUrlSegments(config.server?.origin ?? '', config.base);
1581
- return joinUrlSegments(base, removeLeadingSlash(rtn));
1582
- }
1583
-
1584
- // index.ts for more details on contents and license of this file
1585
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/constants.ts#L143
1586
- const METADATA_FILENAME = '_metadata.json';
1587
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/constants.ts#L63
1588
- const ENV_PUBLIC_PATH = '/@vite/env';
1589
- // https://github.com/vitejs/vite/blob/v6.1.1/packages/vite/src/node/constants.ts#L10C1-L38C32
1590
- const ROLLUP_HOOKS = [
1591
- 'options',
1592
- 'buildStart',
1593
- 'buildEnd',
1594
- 'renderStart',
1595
- 'renderError',
1596
- 'renderChunk',
1597
- 'writeBundle',
1598
- 'generateBundle',
1599
- 'banner',
1600
- 'footer',
1601
- 'augmentChunkHash',
1602
- 'outputOptions',
1603
- 'renderDynamicImport',
1604
- 'resolveFileUrl',
1605
- 'resolveImportMeta',
1606
- 'intro',
1607
- 'outro',
1608
- 'closeBundle',
1609
- 'closeWatcher',
1610
- 'load',
1611
- 'moduleParsed',
1612
- 'watchChange',
1613
- 'resolveDynamicImport',
1614
- 'resolveId',
1615
- 'shouldTransformCachedModule',
1616
- 'transform',
1617
- 'onLog'
1618
- ];
1619
-
1620
- // index.ts for more details on contents and license of this file
1621
- // https://github.com/vitejs/vite/blob/v6.1.1/packages/vite/src/node/plugins/index.ts#L161
1622
- // biome-ignore lint/complexity/noBannedTypes: Function type needed here
1623
- function getHookHandler(hook) {
1624
- return (typeof hook === 'object' ? hook.handler : hook);
1625
- }
1626
-
1627
- // index.ts for more details on contents and license of this file
1628
- const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
1629
- const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
1630
- const backSlashRegEx = /\\/g;
1631
- function escapeId(id) {
1632
- if (!needsEscapeRegEx.test(id)) {
1633
- return id;
1634
- }
1635
- return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
1636
- }
1637
- const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
1638
- const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.src || document.baseURI`);
1639
- const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
1640
- const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path)}'`);
1641
- const relativeUrlMechanisms = {
1642
- amd: relativePath => {
1643
- if (relativePath[0] !== '.') {
1644
- relativePath = `./${relativePath}`;
1645
- }
1646
- return getResolveUrl(`require.toUrl('${escapeId(relativePath)}'), document.baseURI`);
1647
- },
1648
- cjs: relativePath => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
1649
- es: relativePath => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', import.meta.url`),
1650
- iife: relativePath => getRelativeUrlFromDocument(relativePath),
1651
- // NOTE: make sure rollup generate `module` params
1652
- system: relativePath => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', module.meta.url`),
1653
- umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`
1654
- };
1655
- const customRelativeUrlMechanisms = {
1656
- ...relativeUrlMechanisms,
1657
- 'worker-iife': relativePath => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', self.location.href`)
1658
- };
1659
- function createToImportMetaURLBasedRelativeRuntime(format, isWorker) {
1660
- const formatLong = isWorker && format === 'iife' ? 'worker-iife' : format;
1661
- const toRelativePath = customRelativeUrlMechanisms[formatLong];
1662
- return (filename, importer) => ({
1663
- runtime: toRelativePath(path.posix.relative(path.dirname(importer), filename))
1664
- });
1665
- }
1666
- function toOutputFilePathInJS(filename, type, hostId, hostType, config, toRelative) {
1667
- const { renderBuiltUrl } = config.experimental;
1668
- let relative = config.base === '' || config.base === './';
1669
- if (renderBuiltUrl) {
1670
- const result = renderBuiltUrl(filename, {
1671
- hostId,
1672
- hostType,
1673
- type,
1674
- ssr: !!config.build.ssr
1675
- });
1676
- if (typeof result === 'object') {
1677
- if (result.runtime) {
1678
- return { runtime: result.runtime };
1679
- }
1680
- if (typeof result.relative === 'boolean') {
1681
- relative = result.relative;
1682
- }
1683
- }
1684
- else if (result) {
1685
- return result;
1686
- }
1687
- }
1688
- if (relative && !config.build.ssr) {
1689
- return toRelative(filename, hostId);
1690
- }
1691
- return joinUrlSegments(config.base, filename);
1692
- }
1693
- // https://github.com/vitejs/vite/blob/v6.1.1/packages/vite/src/node/build.ts#L1131
1694
- function injectEnvironmentToHooks(environment, plugin) {
1695
- const { resolveId, load, transform } = plugin;
1696
- const clone = { ...plugin };
1697
- for (const hook of Object.keys(clone)) {
1698
- switch (hook) {
1699
- case 'resolveId':
1700
- clone[hook] = wrapEnvironmentResolveId(environment, resolveId);
1701
- break;
1702
- case 'load':
1703
- clone[hook] = wrapEnvironmentLoad(environment, load);
1704
- break;
1705
- case 'transform':
1706
- clone[hook] = wrapEnvironmentTransform(environment, transform);
1707
- break;
1708
- default:
1709
- if (ROLLUP_HOOKS.includes(hook)) {
1710
- clone[hook] = wrapEnvironmentHook(environment, clone[hook]);
1711
- }
1712
- break;
1713
- }
1714
- }
1715
- return clone;
1716
- }
1717
- function wrapEnvironmentResolveId(environment, hook) {
1718
- if (!hook) {
1719
- return;
1720
- }
1721
- const fn = getHookHandler(hook);
1722
- const handler = function (id, importer, options) {
1723
- return fn.call(injectEnvironmentInContext(this, environment), id, importer, injectSsrFlag(options, environment));
1724
- };
1725
- if ('handler' in hook) {
1726
- return {
1727
- ...hook,
1728
- handler
1729
- };
1730
- }
1731
- return handler;
1732
- }
1733
- function wrapEnvironmentLoad(environment, hook) {
1734
- if (!hook) {
1735
- return;
1736
- }
1737
- const fn = getHookHandler(hook);
1738
- const handler = function (id, ...args) {
1739
- return fn.call(injectEnvironmentInContext(this, environment), id, injectSsrFlag(args[0], environment));
1740
- };
1741
- if ('handler' in hook) {
1742
- return {
1743
- ...hook,
1744
- handler
1745
- };
1746
- }
1747
- return handler;
1748
- }
1749
- function wrapEnvironmentTransform(environment, hook) {
1750
- if (!hook) {
1751
- return;
1752
- }
1753
- const fn = getHookHandler(hook);
1754
- const handler = function (code, importer, ...args) {
1755
- return fn.call(injectEnvironmentInContext(this, environment), code, importer, injectSsrFlag(args[0], environment));
1756
- };
1757
- if ('handler' in hook) {
1758
- return {
1759
- ...hook,
1760
- handler
1761
- };
1762
- }
1763
- return handler;
1764
- }
1765
- function wrapEnvironmentHook(environment, hook) {
1766
- if (!hook) {
1767
- return;
1768
- }
1769
- const fn = getHookHandler(hook);
1770
- if (typeof fn !== 'function') {
1771
- return hook;
1772
- }
1773
- const handler = function (...args) {
1774
- return fn.call(injectEnvironmentInContext(this, environment), ...args);
1775
- };
1776
- if ('handler' in hook) {
1777
- return {
1778
- ...hook,
1779
- handler
1780
- };
1781
- }
1782
- return handler;
1783
- }
1784
- function injectEnvironmentInContext(context, environment) {
1785
- context.environment ??= environment;
1786
- return context;
1787
- }
1788
- function injectSsrFlag(options, environment) {
1789
- const ssr = environment ? environment.config.consumer === 'server' : true;
1790
- return { ...(options ?? {}), ssr };
1791
- }
1792
-
1793
- // index.ts for more details on contents and license of this file
1794
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/fsUtils.ts#L388
1795
- function tryResolveRealFile(file, preserveSymlinks) {
1796
- const fileStat = tryStatSync(file);
1797
- if (fileStat?.isFile()) {
1798
- return file;
1799
- }
1800
- if (fileStat?.isSymbolicLink()) {
1801
- return preserveSymlinks ? file : fs.realpathSync(file);
1802
- }
1803
- return undefined;
1804
- }
1805
-
1806
- // index.ts for more details on contents and license of this file
1807
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/resolve.ts#L534
1808
- function splitFileAndPostfix(path) {
1809
- const file = cleanUrl(path);
1810
- return { file, postfix: path.slice(file.length) };
1811
- }
1812
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/resolve.ts#L566-L574
1813
- function tryFsResolve(fsPath, preserveSymlinks) {
1814
- const { file, postfix } = splitFileAndPostfix(fsPath);
1815
- const res = tryCleanFsResolve(file, preserveSymlinks);
1816
- if (res) {
1817
- return res + postfix;
1818
- }
1819
- return;
1820
- }
1821
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/resolve.ts#L580
1822
- function tryCleanFsResolve(file, preserveSymlinks) {
1823
- if (file.includes('node_modules')) {
1824
- return tryResolveRealFile(file, preserveSymlinks);
1825
- }
1826
- const normalizedResolved = tryResolveRealFile(normalizePath(file));
1827
- if (!normalizedResolved) {
1828
- return tryResolveRealFile(file, preserveSymlinks);
1829
- }
1830
- return normalizedResolved;
1831
- }
1832
-
1833
- // index.ts for more details on contents and license of this file
1834
- // https://github.com/Danielku15/vite/blob/88b7def341f12d07d7d4f83cbe3dc73cc8c6b7be/packages/vite/src/node/optimizer/index.ts#L1356
1835
- function tryOptimizedDepResolve(config, ssr, url, depId, preserveSymlinks) {
1836
- const optimizer = getDepsOptimizer(config, ssr);
1837
- if (optimizer?.isOptimizedDepFile(depId)) {
1838
- const depFile = cleanUrl(depId);
1839
- const info = optimizedDepInfoFromFile(optimizer.metadata, depFile);
1840
- const depSrc = info?.src;
1841
- if (depSrc) {
1842
- const resolvedFile = path.resolve(path.dirname(depSrc), url);
1843
- return tryFsResolve(resolvedFile, preserveSymlinks);
1844
- }
1845
- }
1846
- return undefined;
1847
- }
1848
- // https://github.com/Danielku15/vite/blob/88b7def341f12d07d7d4f83cbe3dc73cc8c6b7be/packages/vite/src/node/optimizer/optimizer.ts#L32-L40
1849
- const depsOptimizerMap = new WeakMap();
1850
- const devSsrDepsOptimizerMap = new WeakMap();
1851
- function getDepsOptimizer(config, ssr) {
1852
- const map = ssr ? devSsrDepsOptimizerMap : depsOptimizerMap;
1853
- let optimizer = map.get(config);
1854
- if (!optimizer) {
1855
- optimizer = createDepsOptimizer(config);
1856
- map.set(config, optimizer);
1857
- }
1858
- return optimizer;
1859
- }
1860
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/optimizer/optimizer.ts#L79
1861
- function createDepsOptimizer(config) {
1862
- const depsCacheDirPrefix = normalizePath(path.resolve(config.cacheDir, 'deps'));
1863
- const metadata = parseDepsOptimizerMetadata(fs.readFileSync(path.join(depsCacheDirPrefix, METADATA_FILENAME), 'utf8'), depsCacheDirPrefix);
1864
- const notImplemented = () => {
1865
- throw new Error('not implemented');
1866
- };
1867
- const depsOptimizer = {
1868
- async init() { },
1869
- metadata,
1870
- registerMissingImport: notImplemented,
1871
- run: notImplemented,
1872
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/optimizer/index.ts#L916
1873
- isOptimizedDepFile: id => id.startsWith(depsCacheDirPrefix),
1874
- isOptimizedDepUrl: notImplemented,
1875
- getOptimizedDepId: notImplemented,
1876
- close: notImplemented,
1877
- options: {}
1878
- };
1879
- return depsOptimizer;
1880
- }
1881
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/optimizer/index.ts#L944
1882
- function parseDepsOptimizerMetadata(jsonMetadata, depsCacheDir) {
1883
- const { hash, lockfileHash, configHash, browserHash, optimized, chunks } = JSON.parse(jsonMetadata, (key, value) => {
1884
- if (key === 'file' || key === 'src') {
1885
- return normalizePath(path.resolve(depsCacheDir, value));
1886
- }
1887
- return value;
1888
- });
1889
- if (!chunks || Object.values(optimized).some(depInfo => !depInfo.fileHash)) {
1890
- // outdated _metadata.json version, ignore
1891
- return;
1892
- }
1893
- const metadata = {
1894
- hash,
1895
- lockfileHash,
1896
- configHash,
1897
- browserHash,
1898
- optimized: {},
1899
- discovered: {},
1900
- chunks: {},
1901
- depInfoList: []
1902
- };
1903
- for (const id of Object.keys(optimized)) {
1904
- addOptimizedDepInfo(metadata, 'optimized', {
1905
- ...optimized[id],
1906
- id,
1907
- browserHash
1908
- });
1909
- }
1910
- for (const id of Object.keys(chunks)) {
1911
- addOptimizedDepInfo(metadata, 'chunks', {
1912
- ...chunks[id],
1913
- id,
1914
- browserHash,
1915
- needsInterop: false
1916
- });
1917
- }
1918
- return metadata;
1919
- }
1920
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/optimizer/index.ts#L322
1921
- function addOptimizedDepInfo(metadata, type, depInfo) {
1922
- metadata[type][depInfo.id] = depInfo;
1923
- metadata.depInfoList.push(depInfo);
1924
- return depInfo;
1925
- }
1926
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/optimizer/index.ts#L1248
1927
- function optimizedDepInfoFromFile(metadata, file) {
1928
- return metadata.depInfoList.find(depInfo => depInfo.file === file);
1929
- }
1930
-
1931
- // index.ts for more details on contents and license of this file
1932
- // biome-ignore lint/suspicious/noConstEnum: Exception where we use them
1933
- var AlphaTabWorkerTypes;
1934
- (function (AlphaTabWorkerTypes) {
1935
- AlphaTabWorkerTypes["WorkerClassic"] = "worker_classic";
1936
- AlphaTabWorkerTypes["WorkerModule"] = "worker_module";
1937
- AlphaTabWorkerTypes["AudioWorklet"] = "audio_worklet";
1938
- })(AlphaTabWorkerTypes || (AlphaTabWorkerTypes = {}));
1939
- const workerCache = new WeakMap();
1940
- const WORKER_FILE_ID = 'alphatab_worker';
1941
- const WORKER_ASSET_ID = '__ALPHATAB_WORKER_ASSET__';
1942
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/worker.ts#L47
1943
- function saveEmitWorkerAsset(config, asset) {
1944
- const workerMap = workerCache.get(config.mainConfig || config);
1945
- workerMap.assets.set(asset.fileName, asset);
1946
- }
1947
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/worker.ts#L161
1948
- async function workerFileToUrl(config, id) {
1949
- const workerMap = workerCache.get(config.mainConfig || config);
1950
- let fileName = workerMap.bundle.get(id);
1951
- if (!fileName) {
1952
- const outputChunk = await bundleWorkerEntry(config, id);
1953
- fileName = outputChunk.fileName;
1954
- saveEmitWorkerAsset(config, {
1955
- fileName,
1956
- source: outputChunk.code
1957
- });
1958
- workerMap.bundle.set(id, fileName);
1959
- }
1960
- return encodeWorkerAssetFileName(fileName, workerMap);
1961
- }
1962
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/worker.ts#L149
1963
- function encodeWorkerAssetFileName(fileName, workerCache) {
1964
- const { fileNameHash } = workerCache;
1965
- const hash = getHash(fileName);
1966
- if (!fileNameHash.get(hash)) {
1967
- fileNameHash.set(hash, fileName);
1968
- }
1969
- return `${WORKER_ASSET_ID}${hash}__`;
1970
- }
1971
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/worker.ts#L55
1972
- async function bundleWorkerEntry(config, id) {
1973
- const input = cleanUrl(id);
1974
- const bundleChain = config.bundleChain ?? [];
1975
- const newBundleChain = [...bundleChain, input];
1976
- if (bundleChain.includes(input)) {
1977
- throw new Error(`Circular worker imports detected. Vite does not support it. Import chain: ${newBundleChain.join(' -> ')}`);
1978
- }
1979
- // bundle the file as entry to support imports
1980
- const { rollup } = await import('rollup');
1981
- const { plugins, rollupOptions, format } = config.worker;
1982
- const workerConfig = await plugins(newBundleChain);
1983
- const workerEnvironment = new BuildEnvironment('client', workerConfig); // TODO: should this be 'worker'?
1984
- await workerEnvironment.init();
1985
- const bundle = await rollup({
1986
- ...rollupOptions,
1987
- input,
1988
- plugins: workerEnvironment.plugins.map(p => injectEnvironmentToHooks(workerEnvironment, p)),
1989
- preserveEntrySignatures: false
1990
- });
1991
- let chunk;
1992
- try {
1993
- const workerOutputConfig = config.worker.rollupOptions.output;
1994
- const workerConfig = workerOutputConfig
1995
- ? Array.isArray(workerOutputConfig)
1996
- ? workerOutputConfig[0] || {}
1997
- : workerOutputConfig
1998
- : {};
1999
- const { output: [outputChunk, ...outputChunks] } = await bundle.generate({
2000
- entryFileNames: path.posix.join(config.build.assetsDir, '[name]-[hash].js'),
2001
- chunkFileNames: path.posix.join(config.build.assetsDir, '[name]-[hash].js'),
2002
- assetFileNames: path.posix.join(config.build.assetsDir, '[name]-[hash].[ext]'),
2003
- ...workerConfig,
2004
- format,
2005
- sourcemap: config.build.sourcemap
2006
- });
2007
- chunk = outputChunk;
2008
- for (const outputChunk of outputChunks) {
2009
- if (outputChunk.type === 'asset') {
2010
- saveEmitWorkerAsset(config, outputChunk);
2011
- }
2012
- else if (outputChunk.type === 'chunk') {
2013
- saveEmitWorkerAsset(config, {
2014
- fileName: outputChunk.fileName,
2015
- source: outputChunk.code
2016
- });
2017
- }
2018
- }
2019
- }
2020
- finally {
2021
- await bundle.close();
2022
- }
2023
- return emitSourcemapForWorkerEntry(config, chunk);
2024
- }
2025
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/worker.ts#L124
2026
- function emitSourcemapForWorkerEntry(config, chunk) {
2027
- const { map: sourcemap } = chunk;
2028
- if (sourcemap) {
2029
- if (config.build.sourcemap === 'hidden' || config.build.sourcemap === true) {
2030
- const data = sourcemap.toString();
2031
- const mapFileName = `${chunk.fileName}.map`;
2032
- saveEmitWorkerAsset(config, {
2033
- fileName: mapFileName,
2034
- source: data
2035
- });
2036
- }
2037
- }
2038
- return chunk;
2039
- }
2040
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/worker.ts#L458
2041
- function isSameContent(a, b) {
2042
- if (typeof a === 'string') {
2043
- if (typeof b === 'string') {
2044
- return a === b;
2045
- }
2046
- return Buffer.from(a).equals(b);
2047
- }
2048
- return Buffer.from(b).equals(a);
2049
- }
2050
-
2051
- // This file contains a customized and adapted version of the Vite built-in workerImportMetaUrl plugin
2052
- // https://github.com/vitejs/vite/blob/main/packages/vite/src/node/plugins/workerImportMetaUrl.ts
2053
- // The main adaptions are:
2054
- // - Custom syntax detection for workers and audio worklets
2055
- // - Custom worker types and worker URLs to not overlap with the original plugin
2056
- // With https://github.com/vitejs/vite/pull/16422 integrated this custom code should not be needed anymore
2057
- // Original Sources Licensed under:
2058
- // MIT License
2059
- // Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors
2060
- // Permission is hereby granted, free of charge, to any person obtaining a copy
2061
- // of this software and associated documentation files (the "Software"), to deal
2062
- // in the Software without restriction, including without limitation the rights
2063
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
2064
- // copies of the Software, and to permit persons to whom the Software is
2065
- // furnished to do so, subject to the following conditions:
2066
- // The above copyright notice and this permission notice shall be included in all
2067
- // copies or substantial portions of the Software.
2068
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
2069
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2070
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
2071
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
2072
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2073
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2074
- // SOFTWARE.
2075
- const alphaTabWorkerPatterns = [
2076
- ['alphaTabWorker', 'new', 'alphaTabUrl', 'import.meta.url'],
2077
- ['alphaTabWorklet.addModule', 'new', 'alphaTabUrl', 'import.meta.url']
2078
- ];
2079
- function includesAlphaTabWorker(code) {
2080
- for (const pattern of alphaTabWorkerPatterns) {
2081
- let position = 0;
2082
- for (const match of pattern) {
2083
- position = code.indexOf(match, position);
2084
- if (position === -1) {
2085
- break;
2086
- }
2087
- }
2088
- if (position !== -1) {
2089
- return true;
2090
- }
2091
- }
2092
- return false;
2093
- }
2094
- function getWorkerType(code, match) {
2095
- if (match[1].includes('.addModule')) {
2096
- return AlphaTabWorkerTypes.AudioWorklet;
2097
- }
2098
- const endOfMatch = match.indices[0][1];
2099
- const startOfOptions = code.indexOf('{', endOfMatch);
2100
- if (startOfOptions === -1) {
2101
- return AlphaTabWorkerTypes.WorkerClassic;
2102
- }
2103
- const endOfOptions = code.indexOf('}', endOfMatch);
2104
- if (endOfOptions === -1) {
2105
- return AlphaTabWorkerTypes.WorkerClassic;
2106
- }
2107
- const endOfWorkerCreate = code.indexOf(')', endOfMatch);
2108
- if (startOfOptions > endOfWorkerCreate || endOfOptions > endOfWorkerCreate) {
2109
- return AlphaTabWorkerTypes.WorkerClassic;
2110
- }
2111
- let workerOptions = code.slice(startOfOptions, endOfOptions + 1);
2112
- try {
2113
- workerOptions = evalValue(workerOptions);
2114
- }
2115
- catch {
2116
- return AlphaTabWorkerTypes.WorkerClassic;
2117
- }
2118
- if (typeof workerOptions === 'object' && workerOptions?.type === 'module') {
2119
- return AlphaTabWorkerTypes.WorkerModule;
2120
- }
2121
- return AlphaTabWorkerTypes.WorkerClassic;
2122
- }
2123
- function importMetaUrlPlugin(options) {
2124
- let resolvedConfig;
2125
- let isBuild;
2126
- let preserveSymlinks;
2127
- const isWorkerActive = options.webWorkers !== false;
2128
- const isWorkletActive = options.audioWorklets !== false;
2129
- const isActive = isWorkerActive || isWorkletActive;
2130
- return {
2131
- name: 'vite-plugin-alphatab-url',
2132
- enforce: 'pre',
2133
- configResolved(config) {
2134
- resolvedConfig = config;
2135
- isBuild = config.command === 'build';
2136
- preserveSymlinks = config.resolve.preserveSymlinks;
2137
- },
2138
- shouldTransformCachedModule({ code }) {
2139
- if (isActive && isBuild && resolvedConfig.build.watch && includesAlphaTabWorker(code)) {
2140
- return true;
2141
- }
2142
- return;
2143
- },
2144
- async transform(code, id, options) {
2145
- if (!isActive || options?.ssr || !includesAlphaTabWorker(code)) {
2146
- return;
2147
- }
2148
- let s;
2149
- const alphaTabWorkerPattern = /\b(alphaTabWorker|alphaTabWorklet\.addModule)\s*\(\s*(new\s+[^ (]+alphaTabUrl\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*\))/dg;
2150
- let match = alphaTabWorkerPattern.exec(code);
2151
- while (match) {
2152
- const workerType = getWorkerType(code, match);
2153
- let typeActive = false;
2154
- switch (workerType) {
2155
- case AlphaTabWorkerTypes.WorkerClassic:
2156
- case AlphaTabWorkerTypes.WorkerModule:
2157
- typeActive = isWorkerActive;
2158
- break;
2159
- case AlphaTabWorkerTypes.AudioWorklet:
2160
- typeActive = isWorkletActive;
2161
- break;
2162
- }
2163
- if (!typeActive) {
2164
- match = alphaTabWorkerPattern.exec(code);
2165
- continue;
2166
- }
2167
- s ??= new MagicString(code);
2168
- const url = code.slice(match.indices[3][0] + 1, match.indices[3][1] - 1);
2169
- let file = path__default.resolve(path__default.dirname(id), url);
2170
- file =
2171
- tryFsResolve(file, preserveSymlinks) ??
2172
- tryOptimizedDepResolve(resolvedConfig, options?.ssr === true, url, id, preserveSymlinks) ??
2173
- file;
2174
- let builtUrl;
2175
- if (isBuild) {
2176
- builtUrl = await workerFileToUrl(resolvedConfig, file);
2177
- }
2178
- else {
2179
- builtUrl = await fileToUrl(cleanUrl(file), resolvedConfig);
2180
- builtUrl = injectQuery(builtUrl, `${WORKER_FILE_ID}&type=${workerType}`);
2181
- }
2182
- s.update(match.indices[3][0], match.indices[3][1],
2183
- // add `'' +` to skip vite:asset-import-meta-url plugin
2184
- `new URL('' + ${JSON.stringify(builtUrl)}, import.meta.url)`);
2185
- match = alphaTabWorkerPattern.exec(code);
2186
- }
2187
- if (s) {
2188
- return {
2189
- code: s.toString(),
2190
- map: resolvedConfig.command === 'build' && resolvedConfig.build.sourcemap
2191
- ? s.generateMap({ hires: 'boundary', source: id })
2192
- : null
2193
- };
2194
- }
2195
- return null;
2196
- }
2197
- };
2198
- }
2199
-
2200
- // This file contains a customized and adapted version of the Vite built-in worker plugin
2201
- // https://github.com/vitejs/vite/blob/main/packages/vite/src/node/plugins/worker.ts
2202
- // This is more or less a 1:1 copy of the original worker plugin with following adaptions:
2203
- // - Only handle syntax variants known to be used in alphaTab
2204
- // - Use the alphaTab URL markers
2205
- // - Some refactoring for better code understanding
2206
- // With https://github.com/vitejs/vite/pull/16422 integrated this custom code might not be needed anymore
2207
- // Some adjustment for audio worklet in vite might be needed to treat them as type "module" workers
2208
- // Original Sources Licensed under:
2209
- // MIT License
2210
- // Copyright (c) 2019-present, Yuxi (Evan) You and Vite contributors
2211
- // Permission is hereby granted, free of charge, to any person obtaining a copy
2212
- // of this software and associated documentation files (the "Software"), to deal
2213
- // in the Software without restriction, including without limitation the rights
2214
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
2215
- // copies of the Software, and to permit persons to whom the Software is
2216
- // furnished to do so, subject to the following conditions:
2217
- // The above copyright notice and this permission notice shall be included in all
2218
- // copies or substantial portions of the Software.
2219
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
2220
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2221
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
2222
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
2223
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2224
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2225
- // SOFTWARE.
2226
- const workerFileRE = new RegExp(`(?:\\?|&)${WORKER_FILE_ID}&type=(\\w+)(?:&|$)`);
2227
- const workerAssetUrlRE = new RegExp(`${WORKER_ASSET_ID}([a-z\\d]{8})__`, 'g');
2228
- function workerPlugin(options) {
2229
- let resolvedConfig;
2230
- let isBuild;
2231
- let isWorker;
2232
- const isWorkerActive = options.webWorkers !== false;
2233
- const isWorkletActive = options.audioWorklets !== false;
2234
- const isActive = isWorkerActive || isWorkletActive;
2235
- return {
2236
- name: 'vite-plugin-alphatab-worker',
2237
- configResolved(config) {
2238
- resolvedConfig = config;
2239
- isBuild = config.command === 'build';
2240
- isWorker = config.isWorker;
2241
- },
2242
- buildStart() {
2243
- if (!isActive || isWorker) {
2244
- return;
2245
- }
2246
- workerCache.set(resolvedConfig, {
2247
- assets: new Map(),
2248
- bundle: new Map(),
2249
- fileNameHash: new Map()
2250
- });
2251
- },
2252
- load(id) {
2253
- if (isActive && isBuild && id.includes(WORKER_FILE_ID)) {
2254
- return '';
2255
- }
2256
- return;
2257
- },
2258
- shouldTransformCachedModule({ id }) {
2259
- if (isActive && isBuild && resolvedConfig.build.watch && id.includes(WORKER_FILE_ID)) {
2260
- return true;
2261
- }
2262
- return;
2263
- },
2264
- async transform(raw, id) {
2265
- if (!isActive) {
2266
- return;
2267
- }
2268
- const match = workerFileRE.exec(id);
2269
- if (!match) {
2270
- return;
2271
- }
2272
- // inject env to worker file, might be needed by imported scripts
2273
- const envScriptPath = JSON.stringify(path.posix.join(resolvedConfig.base, ENV_PUBLIC_PATH));
2274
- const workerType = match[1];
2275
- let injectEnv = '';
2276
- switch (workerType) {
2277
- case AlphaTabWorkerTypes.WorkerClassic:
2278
- injectEnv = `importScripts(${envScriptPath})\n`;
2279
- break;
2280
- case AlphaTabWorkerTypes.WorkerModule:
2281
- case AlphaTabWorkerTypes.AudioWorklet:
2282
- injectEnv = `import ${envScriptPath}\n`;
2283
- break;
2284
- }
2285
- if (injectEnv) {
2286
- const s = new MagicString(raw);
2287
- s.prepend(injectEnv);
2288
- return {
2289
- code: s.toString(),
2290
- map: s.generateMap({ hires: 'boundary' })
2291
- };
2292
- }
2293
- return;
2294
- },
2295
- renderChunk(code, chunk, outputOptions) {
2296
- // when building the worker URLs are replaced with some placeholders
2297
- // here we replace those placeholders with the final file names respecting chunks
2298
- let s;
2299
- const result = () => {
2300
- return (s && {
2301
- code: s.toString(),
2302
- map: resolvedConfig.build.sourcemap ? s.generateMap({ hires: 'boundary' }) : null
2303
- });
2304
- };
2305
- workerAssetUrlRE.lastIndex = 0;
2306
- if (workerAssetUrlRE.test(code)) {
2307
- const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(outputOptions.format, resolvedConfig.isWorker);
2308
- s = new MagicString(code);
2309
- workerAssetUrlRE.lastIndex = 0;
2310
- // Replace "__VITE_WORKER_ASSET__5aa0ddc0__" using relative paths
2311
- const workerMap = workerCache.get(resolvedConfig.mainConfig || resolvedConfig);
2312
- const { fileNameHash } = workerMap;
2313
- let match = workerAssetUrlRE.exec(code);
2314
- while (match) {
2315
- const [full, hash] = match;
2316
- const filename = fileNameHash.get(hash);
2317
- const replacement = toOutputFilePathInJS(filename, 'asset', chunk.fileName, 'js', resolvedConfig, toRelativeRuntime);
2318
- const replacementString = typeof replacement === 'string'
2319
- ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1)
2320
- : `"+${replacement.runtime}+"`;
2321
- s.update(match.index, match.index + full.length, replacementString);
2322
- match = workerAssetUrlRE.exec(code);
2323
- }
2324
- }
2325
- return result();
2326
- },
2327
- generateBundle(_, bundle) {
2328
- if (isWorker) {
2329
- return;
2330
- }
2331
- const workerMap = workerCache.get(resolvedConfig);
2332
- for (const asset of workerMap.assets.values()) {
2333
- const duplicateAsset = bundle[asset.fileName];
2334
- if (duplicateAsset) {
2335
- const content = duplicateAsset.type === 'asset' ? duplicateAsset.source : duplicateAsset.code;
2336
- // don't emit if the file name and the content is same
2337
- if (isSameContent(content, asset.source)) {
2338
- return;
2339
- }
2340
- }
2341
- this.emitFile({
2342
- type: 'asset',
2343
- fileName: asset.fileName,
2344
- source: asset.source
2345
- });
2346
- }
2347
- workerMap.assets.clear();
2348
- }
2349
- };
2350
- }
2351
-
2352
- function alphaTab(options) {
2353
- const plugins = [];
2354
- options ??= {};
2355
- plugins.push(importMetaUrlPlugin(options));
2356
- plugins.push(workerPlugin(options));
2357
- plugins.push(copyAssetsPlugin(options));
2358
- return plugins;
2359
- }
2360
-
2361
- export { alphaTab };
37
+ export { alphaTab } from './alphaTabVitePlugin.mjs';