@prostojs/rewrite 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,3987 +1,853 @@
1
+ import { Node, printTree, textContent } from "@prostojs/parser";
2
+ import { Minimatch } from "minimatch";
3
+ //#region src/constants.ts
1
4
  const htmlVoidTags = [
2
- 'area',
3
- 'base',
4
- 'br',
5
- 'col',
6
- 'command',
7
- 'embed',
8
- 'hr',
9
- 'img',
10
- 'input',
11
- 'keygen',
12
- 'link',
13
- 'meta',
14
- 'param',
15
- 'source',
16
- 'track',
17
- 'wbr',
5
+ "area",
6
+ "base",
7
+ "br",
8
+ "col",
9
+ "command",
10
+ "embed",
11
+ "hr",
12
+ "img",
13
+ "input",
14
+ "keygen",
15
+ "link",
16
+ "meta",
17
+ "param",
18
+ "source",
19
+ "track",
20
+ "wbr"
18
21
  ];
19
- const htmlTextTags = [
20
- 'script',
21
- 'style',
22
- ];
23
-
24
- const errorMessage = 'Work with files supported only in NodeJS environment.';
22
+ const htmlTextTags = ["script", "style"];
23
+ //#endregion
24
+ //#region src/files.ts
25
+ const errorMessage = "Work with files supported only in NodeJS environment.";
26
+ let _fs;
27
+ let _path;
28
+ async function getFs() {
29
+ if (!_fs) _fs = await import("fs");
30
+ return _fs;
31
+ }
32
+ async function getPath() {
33
+ if (!_path) _path = await import("path");
34
+ return _path;
35
+ }
25
36
  async function readDir(dirPath) {
26
- if (__NODE_JS__) {
27
- const path = await import('path');
28
- const fs = await import('fs');
29
- async function* getFiles(dir) {
30
- const dirents = await fs.promises.readdir(dir, { withFileTypes: true });
31
- for (const dirent of dirents) {
32
- const res = path.resolve(dir, dirent.name);
33
- if (dirent.isDirectory()) {
34
- yield* getFiles(res);
35
- }
36
- else {
37
- yield res;
38
- }
39
- }
40
- }
41
- return getFiles(dirPath);
42
- }
43
- throw new Error(errorMessage);
37
+ if (__NODE_JS__) {
38
+ const path = await getPath();
39
+ const fs = await getFs();
40
+ async function* getFiles(dir) {
41
+ const dirents = await fs.promises.readdir(dir, { withFileTypes: true });
42
+ for (const dirent of dirents) {
43
+ const res = path.resolve(dir, dirent.name);
44
+ if (dirent.isDirectory()) yield* getFiles(res);
45
+ else yield res;
46
+ }
47
+ }
48
+ return getFiles(dirPath);
49
+ }
50
+ throw new Error(errorMessage);
44
51
  }
45
52
  async function readFile(filePath) {
46
- if (__NODE_JS__) {
47
- const fs = await import('fs');
48
- return new Promise((resolve, reject) => {
49
- fs.exists(filePath, (yes) => {
50
- if (yes) {
51
- fs.readFile(filePath, (err, file) => {
52
- if (err)
53
- return reject(err);
54
- resolve(file.toString());
55
- });
56
- }
57
- else {
58
- reject('File ' + filePath + ' does not exist.');
59
- }
60
- });
61
- });
62
- }
63
- throw new Error(errorMessage);
53
+ if (__NODE_JS__) {
54
+ const fs = await getFs();
55
+ try {
56
+ return (await fs.promises.readFile(filePath)).toString();
57
+ } catch {
58
+ throw new Error("File " + filePath + " does not exist.");
59
+ }
60
+ }
61
+ throw new Error(errorMessage);
64
62
  }
65
63
  async function writeFile(targetPath, data) {
66
- if (__NODE_JS__) {
67
- const path = await import('path');
68
- const fs = await import('fs');
69
- const dirname = path.dirname(targetPath);
70
- await fs.promises.mkdir(dirname, { recursive: true });
71
- await fs.promises.writeFile(targetPath, data);
72
- return;
73
- }
74
- throw new Error(errorMessage);
64
+ if (__NODE_JS__) {
65
+ const path = await getPath();
66
+ const fs = await getFs();
67
+ const dirname = path.dirname(targetPath);
68
+ await fs.promises.mkdir(dirname, { recursive: true });
69
+ await fs.promises.writeFile(targetPath, data);
70
+ return;
71
+ }
72
+ throw new Error(errorMessage);
75
73
  }
76
74
  async function copyFile(filePath, targetPath) {
77
- if (__NODE_JS__) {
78
- if (filePath === targetPath)
79
- return;
80
- const path = await import('path');
81
- const fs = await import('fs');
82
- const dirname = path.dirname(targetPath);
83
- await fs.promises.mkdir(dirname, { recursive: true });
84
- await fs.promises.copyFile(filePath, targetPath);
85
- return;
86
- }
87
- throw new Error(errorMessage);
75
+ if (__NODE_JS__) {
76
+ if (filePath === targetPath) return;
77
+ const path = await getPath();
78
+ const fs = await getFs();
79
+ const dirname = path.dirname(targetPath);
80
+ await fs.promises.mkdir(dirname, { recursive: true });
81
+ await fs.promises.copyFile(filePath, targetPath);
82
+ return;
83
+ }
84
+ throw new Error(errorMessage);
88
85
  }
89
86
  async function pathResolve(p) {
90
- if (__NODE_JS__) {
91
- const path = await import('path');
92
- return path.resolve(p);
93
- }
94
- throw new Error(errorMessage);
87
+ if (__NODE_JS__) return (await getPath()).resolve(p);
88
+ throw new Error(errorMessage);
95
89
  }
96
90
  async function pathJoin(...parts) {
97
- if (__NODE_JS__) {
98
- const path = await import('path');
99
- return path.join(...parts);
100
- }
101
- throw new Error(errorMessage);
102
- }
103
-
104
- const dim = '';
105
- const reset = '';
106
- class ProstoTree {
107
- constructor(options) {
108
- var _a, _b, _c, _d;
109
- const label = (options === null || options === void 0 ? void 0 : options.label) || 'label';
110
- const children = (options === null || options === void 0 ? void 0 : options.children) || 'children';
111
- const branchWidth = typeof (options === null || options === void 0 ? void 0 : options.branchWidth) === 'number' ? options === null || options === void 0 ? void 0 : options.branchWidth : 2;
112
- const hLine = (((_a = options === null || options === void 0 ? void 0 : options.branches) === null || _a === void 0 ? void 0 : _a.hLine) || '─').repeat(branchWidth - 1);
113
- const branches = {
114
- end: ((_b = options === null || options === void 0 ? void 0 : options.branches) === null || _b === void 0 ? void 0 : _b.end) || dim + '└',
115
- middle: ((_c = options === null || options === void 0 ? void 0 : options.branches) === null || _c === void 0 ? void 0 : _c.middle) || dim + '├',
116
- vLine: ((_d = options === null || options === void 0 ? void 0 : options.branches) === null || _d === void 0 ? void 0 : _d.vLine) || dim + '│',
117
- hLine,
118
- };
119
- this.options = {
120
- label: label,
121
- children: children,
122
- renderLabel: (options === null || options === void 0 ? void 0 : options.renderLabel) || (n => typeof n === 'string' ? n : n[label]),
123
- branches,
124
- branchWidth,
125
- };
126
- }
127
- _render(root, opts) {
128
- const { children, renderLabel } = this.options;
129
- let s = `${renderLabel(root, '')}\n`;
130
- const { end, middle, vLine, hLine } = this.options.branches;
131
- const endBranch = end + hLine + reset + ' ';
132
- const middleBranch = middle + hLine + reset + ' ';
133
- const { branchWidth } = this.options;
134
- if (root) {
135
- treeNode(root);
136
- }
137
- function treeNode(node, behind = '', level = 1) {
138
- const items = (node && node[children]);
139
- const count = items && items.length || 0;
140
- if (items) {
141
- if ((opts === null || opts === void 0 ? void 0 : opts.level) && opts.level < level) {
142
- s += behind + endBranch + renderCollapsedChildren(items.length) + '\n';
143
- }
144
- else {
145
- let itemsToRender = items;
146
- const collapsedCount = Math.max(0, count - ((opts === null || opts === void 0 ? void 0 : opts.childrenLimit) || count));
147
- if ((opts === null || opts === void 0 ? void 0 : opts.childrenLimit) && count > opts.childrenLimit) {
148
- itemsToRender = opts.showLast ? items.slice(count - opts.childrenLimit) : items.slice(0, opts.childrenLimit);
149
- }
150
- if (collapsedCount && (opts === null || opts === void 0 ? void 0 : opts.showLast))
151
- s += behind + middleBranch + renderCollapsedChildren(collapsedCount) + '\n';
152
- itemsToRender.forEach((childNode, i) => {
153
- const last = i + 1 === count;
154
- const branch = last ? endBranch : middleBranch;
155
- const nextBehind = behind + (last ? ' ' : vLine) + ' '.repeat(branchWidth);
156
- s += behind + branch + renderLabel(childNode, nextBehind) + '\n';
157
- if (typeof childNode === 'object') {
158
- treeNode(childNode, nextBehind, level + 1);
159
- }
160
- });
161
- if (collapsedCount && !(opts === null || opts === void 0 ? void 0 : opts.showLast))
162
- s += behind + endBranch + renderCollapsedChildren(collapsedCount) + '\n';
163
- }
164
- }
165
- }
166
- return s;
167
- }
168
- render(root, opts) {
169
- return this._render(root, opts);
170
- }
171
- print(root, opts) {
172
- const s = this.render(root, opts);
173
- console.log(s);
174
- return s;
175
- }
176
- }
177
- function renderCollapsedChildren(count) {
178
- return dim + '+ ' + '' + count.toString() + ` item${count === 1 ? '' : 's'}` + reset;
179
- }
180
-
181
- function renderCodeFragment(lines, options) {
182
- const row = (options.row || 1) - 1;
183
- const rowEnd = options.rowEnd ? options.rowEnd - 1 : -1;
184
- const limit = Math.min(options.limit || 6, lines.length);
185
- const offset = Math.min(options.offset || 3, lines.length);
186
- const error = options.error;
187
- const errorEnd = options.errorEnd;
188
- let output = '';
189
- const delta = rowEnd - row;
190
- const maxIndex = lines.length;
191
- if (delta > limit) {
192
- let longestLine = 0;
193
- const newLimit = Math.floor(limit / 2);
194
- for (let i = 0; i < newLimit + offset; i++) {
195
- const index = row + i - offset;
196
- const line = lines[index] || '';
197
- longestLine = Math.max(line.length, longestLine);
198
- output += renderLine(line, index < maxIndex ? index + 1 : '', index === row ? error : undefined, index === row || index === rowEnd ? 'bold' : '');
199
- }
200
- let output2 = '';
201
- for (let i = newLimit + offset; i > 0; i--) {
202
- const index = rowEnd - i + offset;
203
- const line = lines[index] || '';
204
- longestLine = Math.max(line.length, longestLine);
205
- output2 += renderLine(line, index < maxIndex ? index + 1 : '', index === rowEnd ? errorEnd : undefined, index === row || index === rowEnd ? 'bold' : '');
206
- }
207
- output += renderLine('—'.repeat(longestLine), '———', undefined, 'dim') + output2;
208
- }
209
- else {
210
- for (let i = 0; i < limit + offset; i++) {
211
- const index = row + i - offset;
212
- if (index <= lines.length + 1) {
213
- const errorCol = index === row ? error : index === rowEnd ? errorEnd : undefined;
214
- output += renderLine(lines[index], index < maxIndex ? index + 1 : '', errorCol, index === row || index === rowEnd ? 'bold' : '');
215
- }
216
- }
217
- }
218
- return output;
219
- }
220
- function lineStyles(s) {
221
- return '' + (s || '')
222
- .replace(/([a-z_]+)/ig, '' + '$1' + '\x1b[39;33m')
223
- .replace(/([\=\.\/'"`\:\+]+)/ig, '' + '$1' + '');
224
- }
225
- function lineStylesError(s) {
226
- return '' + (s || '') + '';
227
- }
228
- function renderLine(line, index, error, style = '') {
229
- const st = (style === 'bold' ? '' : '') + (style === 'dim' ? '' : '');
230
- if (typeof error === 'number') {
231
- const errorLength = (/[\.-\s\(\)\*\/\+\{\}\[\]\?\'\"\`\<\>]/.exec(line.slice(error + 1)) || { index: line.length - error }).index + 1;
232
- return renderLineNumber(index, true) +
233
- st +
234
- lineStyles(line.slice(0, error)) +
235
- lineStylesError(line.slice(error, error + errorLength)) +
236
- lineStyles(line.slice(error + errorLength)) +
237
- renderLineNumber('', true) + ' '.repeat(error) + '' + '' + '~'.repeat(Math.max(1, errorLength));
238
- }
239
- return renderLineNumber(index, undefined, style === 'bold') + st + lineStyles(line);
240
- }
241
- function renderLineNumber(i, isError = false, bold = false) {
242
- let s = ' ';
243
- const sep = i === '———';
244
- if (i && i > 0 || typeof i === 'string') {
245
- s = ' ' + String(i);
246
- }
247
- s = s.slice(s.length - 5);
248
- return '\n' + '' + (sep ? '' : '') +
249
- (isError ? '' + '' : (bold ? '' : '')) +
250
- s + (sep ? i : ' | ') + '';
251
- }
252
-
253
- function escapeRegex$1(s) {
254
- return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
255
- }
256
-
257
- class ProstoParserNodeBase {
258
- addRecognizes(...args) {
259
- for (const node of args) {
260
- if (!this.options.recognizes)
261
- this.options.recognizes = [];
262
- if (!this.options.recognizes.includes(node)) {
263
- this.options.recognizes.push(node);
264
- }
265
- }
266
- return this;
267
- }
268
- addAbsorbs(node, rule = 'append') {
269
- this.options.absorbs = this.options.absorbs || {};
270
- if (Array.isArray(node)) {
271
- node.forEach(n => {
272
- this.options.absorbs[n.id] = rule;
273
- this.addRecognizes(n);
274
- });
275
- }
276
- else {
277
- this.options.absorbs[node.id] = rule;
278
- this.addRecognizes(node);
279
- }
280
- return this;
281
- }
282
- addPopsAfterNode(...args) {
283
- for (const node of args) {
284
- if (!this.options.popsAfterNode)
285
- this.options.popsAfterNode = [];
286
- if (!this.options.popsAfterNode.includes(node)) {
287
- this.options.popsAfterNode.push(node);
288
- }
289
- }
290
- this.addRecognizes(...args);
291
- return this;
292
- }
293
- addHoistChildren(...args) {
294
- if (!this.options.hoistChildren)
295
- this.options.hoistChildren = [];
296
- this.options.hoistChildren.push(...args);
297
- return this;
298
- }
299
- set icon(value) {
300
- this.options.icon = value;
301
- }
302
- set label(value) {
303
- this.options.label = value;
304
- }
305
- get startsWith() {
306
- return this.options.startsWith;
307
- }
308
- set startsWith(value) {
309
- this.options.startsWith = value;
310
- }
311
- get endsWith() {
312
- return this.options.endsWith;
313
- }
314
- set endsWith(value) {
315
- this.options.endsWith = value;
316
- }
317
- getPopsAtEOFSource() {
318
- return this.options.popsAtEOFSource;
319
- }
320
- popsAtEOFSource(value) {
321
- this.options.popsAtEOFSource = value;
322
- return this;
323
- }
324
- get absorbs() {
325
- return this.options.absorbs;
326
- }
327
- get badToken() {
328
- return this.options.badToken;
329
- }
330
- set badToken(value) {
331
- this.options.badToken = value;
332
- }
333
- get skipToken() {
334
- return this.options.skipToken;
335
- }
336
- set skipToken(value) {
337
- this.options.skipToken = value;
338
- }
339
- get recognizes() {
340
- return this.options.recognizes || [];
341
- }
342
- set recognizes(value) {
343
- this.options.recognizes = value;
344
- }
345
- get hoistChildren() {
346
- return this.options.hoistChildren || [];
347
- }
348
- set hoistChildren(value) {
349
- this.options.hoistChildren = value;
350
- }
351
- getMapContent() {
352
- return this.options.mapContent;
353
- }
354
- mapContent(key, value = 'copy') {
355
- this.options.mapContent = this.options.mapContent || {};
356
- this.options.mapContent[key] = value;
357
- return this;
358
- }
359
- onMatch(value) {
360
- this.options.onMatch = value;
361
- return this;
362
- }
363
- onAppendContent(value) {
364
- this.options.onAppendContent = value;
365
- return this;
366
- }
367
- onAfterChildParse(value) {
368
- this.options.onAfterChildParse = value;
369
- return this;
370
- }
371
- onBeforeChildParse(value) {
372
- this.options.onBeforeChildParse = value;
373
- return this;
374
- }
375
- onMatchStartToken(value) {
376
- if (this.options.startsWith) {
377
- this.options.startsWith.onMatchToken = value;
378
- }
379
- return this;
380
- }
381
- onMatchEndToken(value) {
382
- if (this.options.endsWith) {
383
- this.options.endsWith.onMatchToken = value;
384
- }
385
- return this;
386
- }
387
- initCustomData(value) {
388
- this.options.initCustomData = value;
389
- return this;
390
- }
391
- onPop(value) {
392
- this.options.onPop = value;
393
- return this;
394
- }
395
- get popsAfterNode() {
396
- return this.options.popsAfterNode || [];
397
- }
398
- set popsAfterNode(nodes) {
399
- this.options.popsAfterNode = nodes;
400
- }
401
- clearStartsWith() {
402
- delete this.options.startsWith;
403
- return this;
404
- }
405
- clearEndsWith() {
406
- delete this.options.endsWith;
407
- return this;
408
- }
409
- clearPopsAtEOFSource() {
410
- delete this.options.popsAtEOFSource;
411
- return this;
412
- }
413
- clearBadToken() {
414
- delete this.options.badToken;
415
- return this;
416
- }
417
- clearSkipToken() {
418
- delete this.options.skipToken;
419
- return this;
420
- }
421
- clearAbsorbs(node) {
422
- if (this.options.absorbs) {
423
- if (node && Array.isArray(node)) {
424
- for (const n of node) {
425
- delete this.options.absorbs[n.id];
426
- }
427
- }
428
- else if (node) {
429
- delete this.options.absorbs[node.id];
430
- }
431
- else {
432
- this.options.absorbs = {};
433
- }
434
- }
435
- return this;
436
- }
437
- clearRecognizes(...args) {
438
- var _a;
439
- if (args.length) {
440
- this.options.recognizes = (_a = this.options.recognizes) === null || _a === void 0 ? void 0 : _a.filter(n => !args.includes(n));
441
- }
442
- else {
443
- this.options.recognizes = [];
444
- }
445
- return this;
446
- }
447
- clearHoistChildren() {
448
- delete this.options.hoistChildren;
449
- return this;
450
- }
451
- clearMapContent() {
452
- delete this.options.mapContent;
453
- return this;
454
- }
455
- removeOnPop() {
456
- delete this.options.onPop;
457
- return this;
458
- }
459
- removeOnMatch() {
460
- delete this.options.onMatch;
461
- return this;
462
- }
463
- removeOnAppendContent() {
464
- delete this.options.onAppendContent;
465
- return this;
466
- }
467
- removeOnBeforeChildParse() {
468
- delete this.options.onBeforeChildParse;
469
- return this;
470
- }
471
- removeOnAfterChildParse() {
472
- delete this.options.onAfterChildParse;
473
- return this;
474
- }
475
- fireNodeMatched(matched, cbData) {
476
- return this.options.startsWith ? this.fireMatched(this.options.startsWith, matched, cbData) : { confirmed: true };
477
- }
478
- fireNodeEndMatched(matched, cbData) {
479
- return this.options.endsWith ? this.fireMatched(this.options.endsWith, matched, cbData) : { confirmed: true };
480
- }
481
- fireMatched(descr, matched, cbData) {
482
- const { omit, eject, onMatchToken } = descr;
483
- let cbResult = true;
484
- if (onMatchToken) {
485
- cbResult = onMatchToken({
486
- ...cbData,
487
- matched,
488
- });
489
- }
490
- const cbOmit = typeof cbResult === 'object' ? cbResult.omit : undefined;
491
- const cbEject = typeof cbResult === 'object' ? cbResult.eject : undefined;
492
- return {
493
- omit: cbOmit !== undefined ? cbOmit : omit,
494
- eject: cbEject !== undefined ? cbEject : eject,
495
- confirmed: cbResult !== false,
496
- };
497
- }
498
- getStartTokenRg() {
499
- return this.getRgOutOfTokenDescriptor(this.options.startsWith);
500
- }
501
- getEndTokenRg() {
502
- return this.getRgOutOfTokenDescriptor(this.options.endsWith);
503
- }
504
- getConstraintTokens() {
505
- return {
506
- skip: this.getRgOutOfTokenDescriptor(this.options.skipToken ? { token: this.options.skipToken } : undefined) || undefined,
507
- bad: this.getRgOutOfTokenDescriptor(this.options.badToken ? { token: this.options.badToken } : undefined) || undefined,
508
- };
509
- }
510
- getRgOutOfTokenDescriptor(descr) {
511
- if (descr) {
512
- const prefix = descr.ignoreBackSlashed ? /(?<=(?:^|[^\\])(?:\\\\)*)/.source : '';
513
- let token;
514
- if (typeof descr.token === 'function') {
515
- token = descr.token(this);
516
- }
517
- else {
518
- token = descr.token;
519
- }
520
- if (token instanceof RegExp) {
521
- return new RegExp(prefix + token.source, token.flags);
522
- }
523
- else {
524
- return new RegExp(`${prefix}(?:${[token].flat().map(t => escapeRegex$1(t)).join('|')})`);
525
- }
526
- }
527
- }
528
- }
529
-
530
- class ProstoHoistManager {
531
- constructor() {
532
- this.data = {};
533
- }
534
- addHoistOptions(ctx) {
535
- if (ctx.hoistChildren) {
536
- ctx.hoistChildren.forEach(options => {
537
- const nodeId = typeof options.node === 'object' ? options.node.id : options.node;
538
- const hoist = this.data[nodeId] = (this.data[nodeId] || {});
539
- if (hoist) {
540
- hoist[ctx.index] = {
541
- options,
542
- context: ctx,
543
- };
544
- }
545
- });
546
- }
547
- }
548
- removeHoistOptions(ctx) {
549
- if (ctx.hoistChildren) {
550
- ctx.hoistChildren.forEach(options => {
551
- const nodeId = typeof options.node === 'object' ? options.node.id : options.node;
552
- const hoist = this.data[nodeId];
553
- if (hoist) {
554
- delete hoist[ctx.index];
555
- }
556
- });
557
- }
558
- }
559
- processHoistOptions(ctx) {
560
- const id = ctx.node.id;
561
- const hoist = this.data[id];
562
- if (hoist) {
563
- Object.keys(hoist).map(i => hoist[i]).forEach(({ options, context }) => {
564
- const customData = context.getCustomData();
565
- if (options.deep === true || Number(options.deep) >= (ctx.level - context.level)) {
566
- if (options.asArray) {
567
- const hoisted = customData[options.as] = (customData[options.as] || []);
568
- if (!Array.isArray(hoisted)) {
569
- if (!options.onConflict || options.onConflict === 'error') {
570
- throw new Error(`Can not hoist "${ctx.node.name}" to "${context.node.name}" as "${options.as}". "${options.as}" already exists and it is not an Array Type.`);
571
- }
572
- else if (options.onConflict === 'overwrite') {
573
- customData[options.as] = [doTheMapRule(options, ctx)];
574
- }
575
- else if (options.onConflict !== 'ignore') {
576
- throw new Error(`Unsupported hoisting option onConflict "${options.onConflict}"`);
577
- }
578
- }
579
- else {
580
- hoisted.push(doTheMapRule(options, ctx));
581
- }
582
- }
583
- else {
584
- if (customData[options.as]) {
585
- if (!options.onConflict || options.onConflict === 'error') {
586
- throw new Error(`Can not hoist multiple "${ctx.node.name}" to "${context.node.name}" as "${options.as}". "${options.as}" already exists.`);
587
- }
588
- else if (options.onConflict === 'overwrite') {
589
- customData[options.as] = doTheMapRule(options, ctx);
590
- }
591
- else if (options.onConflict !== 'ignore') {
592
- throw new Error(`Unsupported hoisting option onConflict "${options.onConflict}"`);
593
- }
594
- }
595
- else {
596
- customData[options.as] = doTheMapRule(options, ctx);
597
- }
598
- }
599
- if (options.removeChildFromContent) {
600
- context.content = context.content.filter(c => c !== ctx);
601
- }
602
- }
603
- });
604
- }
605
- function doTheMapRule(options, ctx) {
606
- var _a;
607
- if (typeof options.mapRule === 'function') {
608
- return options.mapRule(ctx);
609
- }
610
- if (options.mapRule === 'content.join') {
611
- return ctx.content.join('');
612
- }
613
- if ((_a = options.mapRule) === null || _a === void 0 ? void 0 : _a.startsWith('customData')) {
614
- const key = options.mapRule.slice(11);
615
- if (key) {
616
- return ctx.getCustomData()[key];
617
- }
618
- else {
619
- return ctx.getCustomData();
620
- }
621
- }
622
- return ctx;
623
- }
624
- }
625
- }
626
-
627
- const banner = '' + '[parser]' + '';
628
- class ProstoParserContext {
629
- constructor(root) {
630
- this.root = root;
631
- this.nodes = {};
632
- this.pos = 0;
633
- this.index = 0;
634
- this.behind = '';
635
- this.here = '';
636
- this.src = '';
637
- this.stack = [];
638
- this.l = 0;
639
- this.hoistManager = new ProstoHoistManager();
640
- this.context = root;
641
- }
642
- parse(src) {
643
- this.src = src,
644
- this.here = src,
645
- this.l = src.length;
646
- const cache = {};
647
- while (this.pos < this.l) {
648
- const searchTokens = this.context.getSearchTokens();
649
- let closestIndex = Number.MAX_SAFE_INTEGER;
650
- let closestToken;
651
- let matched;
652
- for (const t of searchTokens) {
653
- const key = t.g.source;
654
- t.g.lastIndex = this.pos;
655
- let cached = cache[key];
656
- if (cached === null)
657
- continue;
658
- if (cached && cached.index < this.pos) {
659
- cached = null;
660
- delete cache[key];
661
- }
662
- if (!cached) {
663
- cached = t.g.exec(this.src);
664
- if (cached || (this.pos === 0 && !cached)) {
665
- cache[key] = cached;
666
- }
667
- }
668
- if (cached && cached.index < closestIndex) {
669
- closestIndex = cached.index;
670
- matched = cached;
671
- closestToken = t;
672
- if (closestIndex === this.pos)
673
- break;
674
- }
675
- }
676
- if (closestToken && matched) {
677
- const toAppend = this.src.slice(this.pos, closestIndex);
678
- if (toAppend) {
679
- this.context.appendContent(toAppend);
680
- this.jump(toAppend.length);
681
- }
682
- const matchedToken = matched[0];
683
- if (closestToken.node) {
684
- const { omit, eject, confirmed } = closestToken.node.fireNodeMatched(matched, this.getCallbackData(matched));
685
- if (!confirmed)
686
- continue;
687
- let toAppend = '';
688
- if (eject) {
689
- this.context.appendContent(matchedToken);
690
- }
691
- else if (!omit) {
692
- toAppend = matchedToken;
693
- }
694
- this.jump(matchedToken.length);
695
- this.pushNewContext(closestToken.node, toAppend ? [toAppend] : []);
696
- this.context.fireOnMatch(matched);
697
- continue;
698
- }
699
- else {
700
- const { omit, eject, confirmed } = this.context.fireNodeEndMatched(matched, this.getCallbackData(matched));
701
- if (!confirmed)
702
- continue;
703
- if (!eject && !omit) {
704
- this.context.appendContent(matchedToken);
705
- }
706
- if (!eject) {
707
- this.jump(matchedToken.length);
708
- }
709
- this.context.mapNamedGroups(matched);
710
- this.pop();
711
- continue;
712
- }
713
- }
714
- else {
715
- this.context.appendContent(this.here);
716
- this.jump(this.here.length);
717
- }
718
- }
719
- if (this.context !== this.root) {
720
- while (this.context.getPopsAtEOFSource() && this.stack.length > 0)
721
- this.pop();
722
- }
723
- if (this.context !== this.root) {
724
- this.panicBlock(`Unexpected end of the source string while parsing "${this.context.node.name}" (${this.context.index}) node.`);
725
- }
726
- return this.root;
727
- }
728
- pop() {
729
- const parentContext = this.stack.pop();
730
- this.context.fireOnPop();
731
- if (parentContext) {
732
- parentContext.fireAfterChildParse(this.context);
733
- parentContext.fireAbsorb(this.context);
734
- this.context.cleanup();
735
- const node = this.context.node;
736
- this.context = parentContext;
737
- if (parentContext.popsAfterNode.includes(node)) {
738
- this.pop();
739
- }
740
- }
741
- else {
742
- this.context.cleanup();
743
- }
744
- }
745
- pushNewContext(newNode, content) {
746
- this.index++;
747
- const ctx = newNode.createContext(this.index, this.stack.length + 1, this);
748
- ctx.content = content;
749
- this.context.fireBeforeChildParse(ctx);
750
- this.context.pushChild(ctx);
751
- this.stack.push(this.context);
752
- this.hoistManager.addHoistOptions(this.context);
753
- this.context = ctx;
754
- return ctx;
755
- }
756
- fromStack(depth = 0) {
757
- return this.stack[this.stack.length - depth - 1];
758
- }
759
- jump(n = 1) {
760
- this.pos += n;
761
- this.behind = this.src.slice(0, this.pos);
762
- this.here = this.src.slice(this.pos, this.l);
763
- return this.pos;
764
- }
765
- getCallbackData(matched) {
766
- return {
767
- parserContext: this,
768
- context: this.context,
769
- matched,
770
- customData: this.context.getCustomData(),
771
- };
772
- }
773
- getPosition(offset = 0) {
774
- var _a;
775
- const past = this.src.slice(0, this.pos + offset).split('\n');
776
- const row = past.length;
777
- const col = ((_a = past.pop()) === null || _a === void 0 ? void 0 : _a.length) || 0;
778
- return {
779
- row, col, pos: this.pos,
780
- };
781
- }
782
- panic(message, errorBackOffset = 0) {
783
- if (this.pos > 0) {
784
- const { row, col } = this.getPosition(-errorBackOffset);
785
- console.error(banner + '', message, '');
786
- console.log(this.context.toTree({ childrenLimit: 5, showLast: true, level: 1 }));
787
- console.error(renderCodeFragment(this.src.split('\n'), {
788
- row: row,
789
- error: col,
790
- }));
791
- }
792
- throw new Error(message);
793
- }
794
- panicBlock(message, topBackOffset = 0, bottomBackOffset = 0) {
795
- if (this.pos > 0) {
796
- const { row, col } = this.getPosition(-bottomBackOffset);
797
- console.error(banner + '', message, '');
798
- console.log(this.context.toTree({ childrenLimit: 13, showLast: true, level: 12 }));
799
- console.error(renderCodeFragment(this.src.split('\n'), {
800
- row: this.context.startPos.row,
801
- error: this.context.startPos.col - topBackOffset,
802
- rowEnd: row,
803
- errorEnd: col,
804
- }));
805
- }
806
- throw new Error(message);
807
- }
808
- }
809
-
810
- const styles = {
811
- banner: (s) => '' + s + '',
812
- text: (s) => '' + s + '',
813
- valuesDim: (s) => '' + '' + s + '' + '',
814
- boolean: (s) => '' + s + '',
815
- booleanDim: (s) => '' + '' + s + '' + '',
816
- underscore: (s) => '' + s + '',
817
- values: (s) => (typeof s === 'string' ? '' : '') + cut(s.toString(), 30) + '',
818
- nodeDim: (s) => '' + '' + s + '' + '',
819
- node: (s) => '' + s + '',
820
- };
821
- const stringOutputLimit = 70;
822
- const parserTree = new ProstoTree({
823
- children: 'content',
824
- renderLabel: (context) => {
825
- if (typeof context === 'string') {
826
- return styles.text('«' + cut(context, stringOutputLimit) + '' + '»');
827
- }
828
- else if (typeof context === 'object' && context instanceof ProstoParserNodeContext) {
829
- let keys = '';
830
- const data = context.getCustomData();
831
- Object.keys(data).forEach(key => {
832
- const val = data[key];
833
- if (typeof val === 'string' || typeof val === 'number') {
834
- keys += ' ' + styles.valuesDim(key + '(') + styles.values(val) + styles.valuesDim(')');
835
- }
836
- else if (Array.isArray(val)) {
837
- keys += ' ' + styles.valuesDim(key + `[${val.length}]`);
838
- }
839
- else if (typeof val === 'object') {
840
- keys += ' ' + styles.valuesDim(`{ ${key} }`);
841
- }
842
- else if (typeof val === 'boolean' && val) {
843
- const st = key ? styles.boolean : styles.booleanDim;
844
- keys += ' ' + `${styles.underscore(st(key))}${st(val ? '☑' : '☐')}`;
845
- }
846
- });
847
- return styles.node(context.icon + (context.label ? ' ' : '')) + styles.nodeDim(context.label) + keys;
848
- }
849
- return '';
850
- },
851
- });
852
- function cut(s, n) {
853
- const c = s.replace(/\n/g, '\\n');
854
- if (c.length <= n)
855
- return c;
856
- return c.slice(0, n) + '' + '…';
857
- }
858
-
859
- class ProstoParserNodeContext extends ProstoParserNodeBase {
860
- constructor(_node, index, level, parserContext) {
861
- super();
862
- this._node = _node;
863
- this.index = index;
864
- this.level = level;
865
- this.content = [];
866
- this._customData = {};
867
- this.hasNodes = [];
868
- this.count = {};
869
- this.mapContentRules = {
870
- 'first': (content) => content[0],
871
- 'shift': (content) => content.shift(),
872
- 'pop': (content) => content.pop(),
873
- 'last': (content) => content[content.length - 1],
874
- 'join': (content) => content.join(''),
875
- 'join-clear': (content) => content.splice(0).join(''),
876
- 'copy': (content) => content,
877
- };
878
- this.options = _node.getOptions();
879
- if (this.options.initCustomData) {
880
- this._customData = this.options.initCustomData();
881
- }
882
- this._label = this.options.label || '';
883
- this._icon = this.options.icon || '◦';
884
- this.parserContext = parserContext || new ProstoParserContext(this);
885
- if (parserContext) {
886
- this.parent = parserContext.context || parserContext.root;
887
- }
888
- this.startPos = this.parserContext.getPosition();
889
- this.endPos = this.parserContext.getPosition();
890
- }
891
- getOptions() {
892
- return this.options;
893
- }
894
- extractCustomDataTree() {
895
- let content = this.content;
896
- if (this.contentCopiedTo) {
897
- content = this.customData[this.contentCopiedTo];
898
- }
899
- if (Array.isArray(content)) {
900
- return content.map(c => {
901
- if (typeof c === 'string') {
902
- return c;
903
- }
904
- else {
905
- return extract(c);
906
- }
907
- });
908
- }
909
- else {
910
- const c = content;
911
- if (c instanceof ProstoParserNodeContext) {
912
- return extract(c);
913
- }
914
- else {
915
- return content;
916
- }
917
- }
918
- function extract(c) {
919
- const cd = { ...c.getCustomData() };
920
- if (c.contentCopiedTo) {
921
- cd[c.contentCopiedTo] = c.extractCustomDataTree();
922
- }
923
- return cd;
924
- }
925
- }
926
- getPrevNode(n = 1) {
927
- if (this.parent) {
928
- const index = this.parent.content.findIndex(n => n === this) - n;
929
- if (index >= 0)
930
- return this.parent.content[index];
931
- }
932
- }
933
- getPrevContext(n = 1) {
934
- if (this.parent) {
935
- const contexts = this.parent.content.filter(n => n instanceof ProstoParserNodeContext);
936
- const index = contexts.findIndex(n => n === this) - n;
937
- if (index >= 0)
938
- return contexts[index];
939
- }
940
- }
941
- set icon(value) {
942
- this._icon = value;
943
- }
944
- get icon() {
945
- return this._icon;
946
- }
947
- set label(value) {
948
- this._label = value;
949
- }
950
- get label() {
951
- return this._label;
952
- }
953
- getCustomData() {
954
- return this._customData;
955
- }
956
- get customData() {
957
- return this._customData;
958
- }
959
- get nodeId() {
960
- return this._node.id;
961
- }
962
- get node() {
963
- return this._node;
964
- }
965
- toTree(options) {
966
- return parserTree.render(this, options);
967
- }
968
- getSearchTokens() {
969
- var _a;
970
- const rg = this.getEndTokenRg();
971
- const tokens = rg ? [{
972
- rg,
973
- y: addFlag(rg, 'y'),
974
- g: addFlag(rg, 'g'),
975
- }] : [];
976
- (_a = this.options.recognizes) === null || _a === void 0 ? void 0 : _a.forEach(node => {
977
- const rg = node.getStartTokenRg();
978
- if (rg) {
979
- tokens.push({
980
- rg,
981
- y: addFlag(rg, 'y'),
982
- g: addFlag(rg, 'g'),
983
- node,
984
- });
985
- }
986
- });
987
- function addFlag(rg, f) {
988
- return new RegExp(rg.source, rg.flags + f);
989
- }
990
- return tokens;
991
- }
992
- appendContent(input) {
993
- let s = input;
994
- this.endPos = this.parserContext.getPosition();
995
- let { skip, bad } = this.getConstraintTokens();
996
- skip = skip ? new RegExp(skip.source, skip.flags + 'g') : skip;
997
- bad = bad ? new RegExp(bad.source, bad.flags + 'g') : bad;
998
- if (skip) {
999
- s = s.replace(skip, '');
1000
- }
1001
- if (bad) {
1002
- const m = bad.exec(s);
1003
- if (m) {
1004
- this.parserContext.jump(m.index);
1005
- this.parserContext.panic(`The token "${m[0].replace(/"/g, '\\"')}" is not allowed in "${this.node.name}".`);
1006
- }
1007
- }
1008
- s = this.fireOnAppendContent(s);
1009
- if (s) {
1010
- this.content.push(s);
1011
- }
1012
- }
1013
- cleanup() {
1014
- this.options = null;
1015
- }
1016
- pushChild(child) {
1017
- const absorbRule = this.options.absorbs && this.options.absorbs[child.node.id];
1018
- if (!absorbRule) {
1019
- this.content.push(child);
1020
- }
1021
- }
1022
- fireAbsorb(child) {
1023
- const absorbRule = this.options.absorbs && this.options.absorbs[child.node.id];
1024
- if (absorbRule) {
1025
- switch (absorbRule) {
1026
- case 'append':
1027
- this.content.push(...child.content);
1028
- break;
1029
- case 'join':
1030
- this.appendContent(child.content.join(''));
1031
- break;
1032
- default:
1033
- const [action, target] = absorbRule.split('->');
1034
- const cd = this.getCustomData();
1035
- if (action === 'copy') {
1036
- cd[target] = child.content;
1037
- }
1038
- else if (action === 'join') {
1039
- cd[target] = child.content.join('');
1040
- }
1041
- else {
1042
- this.parserContext.panic(`Absorb action "${action}" is not supported.`);
1043
- }
1044
- }
1045
- }
1046
- }
1047
- has(node) {
1048
- return this.hasNodes.includes(node);
1049
- }
1050
- countOf(node) {
1051
- return this.count[node.id] || 0;
1052
- }
1053
- mapNamedGroups(matched) {
1054
- if (matched.groups) {
1055
- const cd = this.getCustomData();
1056
- for (const [key, value] of Object.entries(matched.groups)) {
1057
- if (key === 'content') {
1058
- this.appendContent(value);
1059
- }
1060
- else {
1061
- cd[key] = value;
1062
- }
1063
- }
1064
- }
1065
- }
1066
- fireOnPop() {
1067
- this.endPos = this.parserContext.getPosition();
1068
- this.processMappings();
1069
- const data = this.parserContext.getCallbackData();
1070
- this.node.beforeOnPop(data);
1071
- if (this.options.onPop) {
1072
- this.options.onPop(data);
1073
- }
1074
- }
1075
- fireOnMatch(matched) {
1076
- this.mapNamedGroups(matched);
1077
- const data = this.parserContext.getCallbackData(matched);
1078
- this.node.beforeOnMatch(data);
1079
- if (this.options.onMatch) {
1080
- return this.options.onMatch(data);
1081
- }
1082
- }
1083
- fireBeforeChildParse(child) {
1084
- const data = this.parserContext.getCallbackData();
1085
- this.node.beforeOnBeforeChildParse(child, data);
1086
- if (this.options.onBeforeChildParse) {
1087
- return this.options.onBeforeChildParse(child, data);
1088
- }
1089
- }
1090
- fireAfterChildParse(child) {
1091
- if (!this.hasNodes.includes(child.node)) {
1092
- this.hasNodes.push(child.node);
1093
- }
1094
- this.count[child.node.id] = this.count[child.node.id] || 0;
1095
- this.count[child.node.id]++;
1096
- const data = this.parserContext.getCallbackData();
1097
- this.node.beforeOnAfterChildParse(child, data);
1098
- if (this.options.onAfterChildParse) {
1099
- return this.options.onAfterChildParse(child, data);
1100
- }
1101
- }
1102
- fireOnAppendContent(s) {
1103
- let _s = s;
1104
- const data = this.parserContext.getCallbackData();
1105
- _s = this.node.beforeOnAppendContent(_s, data);
1106
- if (this.options.onAppendContent) {
1107
- _s = this.options.onAppendContent(_s, data);
1108
- }
1109
- return _s;
1110
- }
1111
- processMappings() {
1112
- this.parserContext.hoistManager.removeHoistOptions(this);
1113
- this.parserContext.hoistManager.processHoistOptions(this);
1114
- this.processMapContent();
1115
- }
1116
- processMapContent() {
1117
- const targetNodeOptions = this.options;
1118
- if (targetNodeOptions.mapContent) {
1119
- Object.keys(targetNodeOptions.mapContent).forEach((key) => {
1120
- const keyOfT = key;
1121
- if (targetNodeOptions.mapContent && targetNodeOptions.mapContent[keyOfT]) {
1122
- const mapRule = targetNodeOptions.mapContent[keyOfT];
1123
- if (typeof mapRule === 'function') {
1124
- this._customData[keyOfT] = mapRule(this.content);
1125
- }
1126
- else {
1127
- const ruleKey = mapRule;
1128
- if (ruleKey === 'copy')
1129
- this.contentCopiedTo = keyOfT;
1130
- this._customData[keyOfT] = this.mapContentRules[ruleKey](this.content);
1131
- }
1132
- if (!this.contentCopiedTo && (typeof mapRule === 'function' || ['first', 'shift', 'pop', 'last'].includes(mapRule))) {
1133
- this.contentCopiedTo = keyOfT;
1134
- }
1135
- }
1136
- });
1137
- }
1138
- }
1139
- }
1140
-
1141
- let idCounter = 0;
1142
- class ProstoParserNode extends ProstoParserNodeBase {
1143
- constructor(options) {
1144
- super();
1145
- this.options = options;
1146
- this.id = idCounter++;
1147
- }
1148
- getOptions() {
1149
- return {
1150
- label: this.options.label || '',
1151
- icon: this.options.icon || '',
1152
- startsWith: (this.options.startsWith ? { ...this.options.startsWith } : this.options.startsWith),
1153
- endsWith: (this.options.endsWith ? { ...this.options.endsWith } : this.options.endsWith),
1154
- popsAfterNode: [...(this.options.popsAfterNode || [])],
1155
- popsAtEOFSource: this.options.popsAtEOFSource || false,
1156
- badToken: this.options.badToken || '',
1157
- skipToken: this.options.skipToken || '',
1158
- recognizes: [...(this.options.recognizes || [])],
1159
- hoistChildren: [...(this.options.hoistChildren || [])],
1160
- mapContent: {
1161
- ...this.options.mapContent,
1162
- },
1163
- onPop: this.options.onPop,
1164
- onMatch: this.options.onMatch,
1165
- onAppendContent: this.options.onAppendContent,
1166
- onAfterChildParse: this.options.onAfterChildParse,
1167
- onBeforeChildParse: this.options.onBeforeChildParse,
1168
- initCustomData: this.options.initCustomData,
1169
- absorbs: this.options.absorbs,
1170
- };
1171
- }
1172
- createContext(index, level, rootContext) {
1173
- return new ProstoParserNodeContext(this, index, level, rootContext);
1174
- }
1175
- get name() {
1176
- return this.constructor.name + '[' + this.id.toString() + ']' + '(' + (this.options.label || this.options.icon || '') + ')';
1177
- }
1178
- parse(source) {
1179
- return this.createContext(0, 0).parserContext.parse(source);
1180
- }
1181
- beforeOnPop(data) {
1182
- }
1183
- beforeOnMatch(data) {
1184
- }
1185
- beforeOnAppendContent(s, data) {
1186
- return s;
1187
- }
1188
- beforeOnAfterChildParse(child, data) {
1189
- }
1190
- beforeOnBeforeChildParse(child, data) {
1191
- }
1192
- }
1193
-
1194
- class BasicNode extends ProstoParserNode {
1195
- constructor(options) {
1196
- var _a, _b;
1197
- const startsWith = (options === null || options === void 0 ? void 0 : options.tokens) ? { token: options === null || options === void 0 ? void 0 : options.tokens[0] } : undefined;
1198
- const endsWith = (options === null || options === void 0 ? void 0 : options.tokens) ? { token: options === null || options === void 0 ? void 0 : options.tokens[1] } : undefined;
1199
- const [startOption, endOption] = ((_a = options.tokenOE) === null || _a === void 0 ? void 0 : _a.split('-')) || [];
1200
- const [startBSlash, endBSlash] = ((_b = options.backSlash) === null || _b === void 0 ? void 0 : _b.split('-')) || [];
1201
- if (startsWith) {
1202
- startsWith.omit = startOption === 'omit';
1203
- startsWith.eject = startOption === 'eject';
1204
- startsWith.ignoreBackSlashed = startBSlash === 'ignore';
1205
- }
1206
- if (endsWith) {
1207
- endsWith.omit = endOption === 'omit';
1208
- endsWith.eject = endOption === 'eject';
1209
- endsWith.ignoreBackSlashed = endBSlash === 'ignore';
1210
- }
1211
- super({
1212
- icon: options.icon || '',
1213
- label: typeof options.label === 'string' ? options.label : '',
1214
- startsWith,
1215
- endsWith,
1216
- badToken: options.badToken,
1217
- skipToken: options.skipToken,
1218
- });
1219
- if (options.recursive) {
1220
- this.addAbsorbs(this, 'join');
1221
- }
1222
- }
1223
- }
1224
-
1225
- const stringNodeOptions = {
1226
- label: '',
1227
- icon: '"',
1228
- tokens: [/(?<quote>["'`])/, ({ customData }) => customData.quote || ''],
1229
- backSlash: '-ignore',
91
+ if (__NODE_JS__) return (await getPath()).join(...parts);
92
+ throw new Error(errorMessage);
93
+ }
94
+ //#endregion
95
+ //#region src/string-expression.ts
96
+ const quoteEndRegex$1 = {
97
+ "\"": /(?<=(?<!\\)(?:\\\\)*)"/,
98
+ "'": /(?<=(?<!\\)(?:\\\\)*)'/,
99
+ "`": /(?<=(?<!\\)(?:\\\\)*)`/
1230
100
  };
1231
- const stringNode = new BasicNode(stringNodeOptions);
101
+ const stringNode = new Node({
102
+ name: "string",
103
+ start: { token: /(?<quote>["'`])/ },
104
+ end: { token: (ctx) => {
105
+ const q = ctx.node.data.quote;
106
+ if (!q) return "";
107
+ return quoteEndRegex$1[q] || "";
108
+ } },
109
+ data: { quote: "" }
110
+ });
1232
111
  function stringExpressionNodeFactory(interpolationDelimiters) {
1233
- return new BasicNode({
1234
- label: 'string',
1235
- icon: '≈',
1236
- tokens: [interpolationDelimiters[0], interpolationDelimiters[1]],
1237
- tokenOE: 'omit-omit',
1238
- })
1239
- .addAbsorbs(stringNode, 'join')
1240
- .mapContent('expression', 'join-clear')
1241
- .onPop(({ parserContext, customData: { expression } }) => {
1242
- try {
1243
- new Function(expression);
1244
- }
1245
- catch (e) {
1246
- parserContext.panic('Invalid expression: ' + e.message, expression.length + interpolationDelimiters[0].length + interpolationDelimiters[1].length);
1247
- }
1248
- })
1249
- .initCustomData(() => ({
1250
- expression: '',
1251
- code: ({ customData }, level = 0) => ' '.repeat(level * 2) + `__ += ${customData.expression.trim()}\n`,
1252
- }));
1253
- }
1254
-
112
+ return new Node({
113
+ name: "string-expression",
114
+ start: {
115
+ token: interpolationDelimiters[0],
116
+ omit: true
117
+ },
118
+ end: {
119
+ token: interpolationDelimiters[1],
120
+ omit: true
121
+ },
122
+ recognizes: [stringNode],
123
+ data: {
124
+ expression: "",
125
+ code: (node, level = 0) => " ".repeat(level * 2) + `__ += ${node.data.expression.trim()}\n`
126
+ }
127
+ }).onClose((node) => {
128
+ node.data.expression = node.content.map((c) => {
129
+ if (typeof c === "string") return c;
130
+ return textContent(c);
131
+ }).join("");
132
+ node.content.length = 0;
133
+ try {
134
+ new Function(node.data.expression);
135
+ } catch (e) {
136
+ throw new Error("Invalid expression: " + e.message);
137
+ }
138
+ });
139
+ }
140
+ //#endregion
141
+ //#region src/utils.ts
1255
142
  function escapeRegex(s) {
1256
- return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
143
+ return s.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
1257
144
  }
1258
145
  function debug(message) {
1259
- console.log('' + '' + '' + '[rewrite] DEBUG: ' + message + '');
146
+ console.log(__DYE_YELLOW__ + __DYE_BOLD__ + __DYE_DIM__ + "[rewrite] DEBUG: " + message + __DYE_RESET__);
147
+ }
148
+ //#endregion
149
+ //#region src/rw-common.ts
150
+ function genFunc(code) {
151
+ try {
152
+ return new Function("__ctx__", "process", "window", "global", "require", code);
153
+ } catch (e) {
154
+ console.error(e.message);
155
+ console.error(e.stack);
156
+ throw e;
157
+ }
158
+ }
159
+ /** @deprecated Use genFunc instead */
160
+ const genSafeFunc = genFunc;
161
+ function escapeString(s) {
162
+ return s.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\n/g, "\\n").replace(/\$/g, "\\$");
1260
163
  }
1261
-
1262
- function genSafeFunc(code) {
1263
- try {
1264
- return new Function('__ctx__', 'process', 'window', 'global', 'require', code);
1265
- }
1266
- catch (e) {
1267
- console.error(e.message);
1268
- console.error(e.stack);
1269
- throw e;
1270
- }
1271
- }
1272
- function escapeString(s) { return s.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\n/g, '\\n').replace(/\$/g, '\\$'); }
1273
164
  function pushString(s) {
1274
- return `__ += \`${escapeString(s)}\`\n`;
1275
- }
1276
- function renderCode(context, level = 1) {
1277
- let s = '';
1278
- let result = '';
1279
- function renderS() {
1280
- if (s) {
1281
- result += indent + pushString(s);
1282
- s = '';
1283
- }
1284
- }
1285
- const indent = ' '.repeat(level * 2);
1286
- context.content.forEach(c => {
1287
- if (typeof c === 'string') {
1288
- s += c;
1289
- }
1290
- else {
1291
- renderS();
1292
- const data = c.getCustomData();
1293
- if (data.openCode) {
1294
- result += indent + data.openCode;
1295
- }
1296
- if (data.code) {
1297
- result += data.code(c, level);
1298
- }
1299
- result += renderCode(c, level + (data.openCode ? 1 : 0));
1300
- if (data.closeCode) {
1301
- result += indent + data.closeCode;
1302
- }
1303
- }
1304
- });
1305
- renderS();
1306
- return result;
165
+ return `__ += \`${escapeString(s)}\`\n`;
166
+ }
167
+ function renderCode(parsed, level = 1) {
168
+ let s = "";
169
+ let result = "";
170
+ function renderS() {
171
+ if (s) {
172
+ result += indent + pushString(s);
173
+ s = "";
174
+ }
175
+ }
176
+ const indent = " ".repeat(level * 2);
177
+ parsed.content.forEach((c) => {
178
+ if (typeof c === "string") s += c;
179
+ else {
180
+ renderS();
181
+ const data = c.data;
182
+ if (data.openCode) result += indent + data.openCode;
183
+ if (data.code) result += data.code(c, level);
184
+ result += renderCode(c, level + (data.openCode ? 1 : 0));
185
+ if (data.closeCode) result += indent + data.closeCode;
186
+ }
187
+ });
188
+ renderS();
189
+ return result;
190
+ }
191
+ function buildRewriter(rootNode, codeGen, cacheSize = 128) {
192
+ const cache = /* @__PURE__ */ new Map();
193
+ function getFunc(source) {
194
+ let func = cache.get(source);
195
+ if (func) return func;
196
+ const code = codeGen(source);
197
+ const compiled = genFunc(code);
198
+ func = (context) => {
199
+ try {
200
+ return compiled(context);
201
+ } catch (e) {
202
+ throwErrorFromFunction(e, code);
203
+ }
204
+ };
205
+ if (cache.size >= cacheSize) {
206
+ const firstKey = cache.keys().next().value;
207
+ if (firstKey !== void 0) cache.delete(firstKey);
208
+ }
209
+ cache.set(source, func);
210
+ return func;
211
+ }
212
+ function print(source) {
213
+ return console.log(printTree(rootNode.parse(source)));
214
+ }
215
+ return {
216
+ genRewriteCode: codeGen,
217
+ genRewriteFunction: getFunc,
218
+ printAsTree: print,
219
+ rewrite: (source, context) => getFunc(source)(context || {})
220
+ };
221
+ }
222
+ const coalesceRe = /__ \+= `([^`]*)`\n\s*__ \+= `/g;
223
+ function coalesceStrings(code) {
224
+ let prev = "";
225
+ while (prev !== code) {
226
+ prev = code;
227
+ code = code.replace(coalesceRe, "__ += `$1");
228
+ }
229
+ return code;
1307
230
  }
1308
231
  function getRewriter(rootNode, debug$1 = false) {
1309
- function getCode(source) {
1310
- const result = rootNode.parse(source);
1311
- if (debug$1) {
1312
- debug('Parsed tree view:\n' + result.toTree());
1313
- }
1314
- return 'let __ = \'\'\n' +
1315
- 'let __v = \'\'\n' +
1316
- 'with (__ctx__) {\n' +
1317
- renderCode(result) +
1318
- '}\n' +
1319
- 'return __';
1320
- }
1321
- function getFunc(source) {
1322
- const code = getCode(source);
1323
- const func = genSafeFunc(code);
1324
- return (context) => {
1325
- try {
1326
- return func(context);
1327
- }
1328
- catch (e) {
1329
- throwErrorFromFunction(e, code);
1330
- }
1331
- };
1332
- }
1333
- function print(source) {
1334
- return console.log(rootNode.parse(source).toTree());
1335
- }
1336
- return {
1337
- genRewriteCode: getCode,
1338
- genRewriteFunction: getFunc,
1339
- printAsTree: print,
1340
- rewrite: (source, context) => getFunc(source)(context || {}),
1341
- };
232
+ return buildRewriter(rootNode, (source) => {
233
+ const result = rootNode.parse(source);
234
+ if (debug$1) debug("Parsed tree view:\n" + printTree(result));
235
+ return "let __ = ''\nlet __v = ''\nwith (__ctx__) {\n" + coalesceStrings(renderCode(result)) + "}\nreturn __";
236
+ });
1342
237
  }
1343
238
  function throwErrorFromFunction(e, code) {
1344
- var _a;
1345
- const relevantLine = ((_a = e.stack) === null || _a === void 0 ? void 0 : _a.split('\n')[1]) || '';
1346
- const regex = /<anonymous>:(\d+):(\d+)\)/g;
1347
- const match = regex.exec(relevantLine);
1348
- if (match) {
1349
- const row = parseInt(match[1], 10) - 2;
1350
- const col = parseInt(match[2], 10) - 1;
1351
- const output = renderCodeFragment(code.split('\n'), {
1352
- row,
1353
- error: col,
1354
- });
1355
- console.error('' + e.message + '');
1356
- console.error(output);
1357
- }
1358
- throw e;
1359
- }
1360
- function getStringExpressionRewriter(interpolationDelimiters = ['{{', '}}']) {
1361
- const stringExpression = stringExpressionNodeFactory(interpolationDelimiters);
1362
- const rootNode = new BasicNode({}).addRecognizes(stringExpression);
1363
- function getCode(source) {
1364
- const result = rootNode.parse(source);
1365
- return 'let __ = []\n' +
1366
- 'with (__ctx__) {\n' +
1367
- result.content.map(c => `__.push(${typeof c === 'string'
1368
- ? `\`${escapeString(c)}\``
1369
- : `${c.getCustomData().expression}`})`).join('\n ') +
1370
- '}\n' +
1371
- 'return __.length === 1 ? __[0] : __.join(\'\')';
1372
- }
1373
- function getFunc(source) {
1374
- const code = getCode(source);
1375
- const func = genSafeFunc(code);
1376
- return (context) => {
1377
- try {
1378
- return func(context);
1379
- }
1380
- catch (e) {
1381
- throwErrorFromFunction(e, code);
1382
- }
1383
- };
1384
- }
1385
- function print(source) {
1386
- return console.log(rootNode.parse(source).toTree());
1387
- }
1388
- return {
1389
- genRewriteCode: getCode,
1390
- genRewriteFunction: getFunc,
1391
- printAsTree: print,
1392
- rewrite: (source, context) => getFunc(source)(context || {}),
1393
- };
1394
- }
1395
-
1396
- const docTypeNodeOptions = {
1397
- label: 'Document Type',
1398
- tokens: ['<!DOCTYPE ', '>'],
1399
- };
1400
- const cDataNodeOptions = {
1401
- icon: '<![CDATA[',
1402
- tokens: ['<![CDATA[', ']]>'],
1403
- };
1404
- const commentNodeOptions = {
1405
- label: 'comment',
1406
- icon: '“',
1407
- tokens: ['<!--', '-->'],
1408
- };
1409
- const valueNodeOptions = {
1410
- label: 'value',
1411
- icon: '=',
1412
- tokens: [/=(?<quote>["'`])/, ({ customData }) => customData.quote || ''],
1413
- backSlash: '-ignore',
1414
- tokenOE: 'omit-omit',
1415
- };
1416
- const valueNode = new BasicNode(valueNodeOptions);
1417
- const unquotedValueNodeOptions = {
1418
- label: 'value',
1419
- icon: '=',
1420
- tokens: [/=(?<content>\w+)/, /[\s\/\>]/],
1421
- tokenOE: 'omit-eject',
1422
- };
1423
- const unquotedValueNode = new BasicNode(unquotedValueNodeOptions);
1424
- const innerNodeOptions = {
1425
- label: 'inner',
1426
- tokens: ['>', '</'],
1427
- tokenOE: '-eject',
1428
- };
239
+ const relevantLine = e.stack?.split("\n")[1] || "";
240
+ const match = /<anonymous>:(\d+):(\d+)\)/g.exec(relevantLine);
241
+ if (match) {
242
+ const row = parseInt(match[1], 10) - 2;
243
+ const col = parseInt(match[2], 10) - 1;
244
+ const output = renderCodeFragmentSimple(code.split("\n"), row, col);
245
+ console.error(__DYE_RED_BRIGHT__ + e.message + __DYE_COLOR_OFF__);
246
+ console.error(output);
247
+ }
248
+ throw e;
249
+ }
250
+ function renderCodeFragmentSimple(lines, row, errorCol) {
251
+ const start = Math.max(0, row - 2);
252
+ const end = Math.min(lines.length, row + 3);
253
+ let output = "";
254
+ for (let i = start; i < end; i++) {
255
+ const lineNum = String(i + 1).padStart(4, " ");
256
+ output += `${lineNum}${i === row ? " > " : " "}${lines[i]}\n`;
257
+ if (i === row && errorCol >= 0) output += " " + " ".repeat(errorCol) + "^\n";
258
+ }
259
+ return output;
260
+ }
261
+ function getStringExpressionRewriter(interpolationDelimiters = ["{{", "}}"]) {
262
+ const rootNode = new Node({
263
+ name: "string-expr-root",
264
+ recognizes: [stringExpressionNodeFactory(interpolationDelimiters)],
265
+ eofClose: true
266
+ });
267
+ return buildRewriter(rootNode, (source) => {
268
+ return "let __ = []\nwith (__ctx__) {\n" + rootNode.parse(source).content.map((c) => `__.push(${typeof c === "string" ? `\`${escapeString(c)}\`` : `${c.data.expression}`})`).join("\n ") + "}\nreturn __.length === 1 ? __[0] : __.join('')";
269
+ });
270
+ }
271
+ //#endregion
272
+ //#region src/rw-html-parser.ts
1429
273
  const htmlBlockTypes = [
1430
- {
1431
- key: 'for',
1432
- exprRequired: true,
1433
- compatible: ['if'],
1434
- opening: true,
1435
- renderOpen: (v) => `for (${v || ''}) {\n`,
1436
- },
1437
- {
1438
- key: 'if',
1439
- exprRequired: true,
1440
- compatible: ['for'],
1441
- opening: true,
1442
- renderOpen: (v) => `if (${v || ''}) {\n`,
1443
- },
1444
- {
1445
- key: 'else-if',
1446
- closingKey: 'IF',
1447
- exprRequired: true,
1448
- opening: false,
1449
- overtakes: ['if', 'else-if'],
1450
- renderOpen: (v) => `} else if (${v || ''}) {\n`,
1451
- },
1452
- {
1453
- key: 'else',
1454
- closingKey: 'IF',
1455
- exprRequired: false,
1456
- opening: false,
1457
- overtakes: ['if', 'else-if'],
1458
- renderOpen: () => '} else {\n',
1459
- },
274
+ {
275
+ key: "for",
276
+ exprRequired: true,
277
+ compatible: ["if"],
278
+ opening: true,
279
+ renderOpen: (v) => `for (${v || ""}) {\n`
280
+ },
281
+ {
282
+ key: "if",
283
+ exprRequired: true,
284
+ compatible: ["for"],
285
+ opening: true,
286
+ renderOpen: (v) => `if (${v || ""}) {\n`
287
+ },
288
+ {
289
+ key: "else-if",
290
+ closingKey: "IF",
291
+ exprRequired: true,
292
+ opening: false,
293
+ overtakes: ["if", "else-if"],
294
+ renderOpen: (v) => `} else if (${v || ""}) {\n`
295
+ },
296
+ {
297
+ key: "else",
298
+ closingKey: "IF",
299
+ exprRequired: false,
300
+ opening: false,
301
+ overtakes: ["if", "else-if"],
302
+ renderOpen: () => "} else {\n"
303
+ }
1460
304
  ];
1461
305
  const htmlBlockTypesO = {};
1462
- htmlBlockTypes.forEach(b => htmlBlockTypesO[b.key] = b);
306
+ htmlBlockTypes.forEach((b) => htmlBlockTypesO[b.key] = b);
1463
307
  const getHtmlParser = (opts, recognizeTextDirective = false) => {
1464
- const rootNode = new BasicNode({ icon: 'Html Mode' });
1465
- const docTypeNode = new BasicNode(docTypeNodeOptions);
1466
- const cDataNode = new BasicNode(cDataNodeOptions);
1467
- const commentNode = new BasicNode(commentNodeOptions);
1468
- const innerNode = new BasicNode(innerNodeOptions);
1469
- const stringExpressionNode = stringExpressionNodeFactory(opts.exprDelimeters);
1470
- const attrNode = attributeNodeFactory();
1471
- const attrBlockOperationNode = attributeNodeFactory('↳', opts.blockOperation, 'block');
1472
- const attrExprNode = attributeNodeFactory('≈', opts.attrExpression, 'expr');
1473
- const attrNodes = [attrBlockOperationNode, attrExprNode, attrNode];
1474
- const textDirectiveNode = new BasicNode({
1475
- icon: 'T',
1476
- tokens: [
1477
- new RegExp(`^\\s*(?:<!--)${escapeRegex(opts.directive)}\\s*text-mode-on\\s*-->\\s*$`, 'm'),
1478
- new RegExp(`^\\s*(?:<!--)${escapeRegex(opts.directive)}\\s*text-mode-off\\s*-->\\s*$`, 'm'),
1479
- ],
1480
- tokenOE: 'omit-omit',
1481
- })
1482
- .onMatch(({ parserContext }) => parserContext.jump())
1483
- .onPop(({ parserContext }) => parserContext.jump());
1484
- const tagNode = new BasicNode({
1485
- tokens: [
1486
- /<(?<tag>[\w:\-\.]+)/,
1487
- ({ customData }) => {
1488
- if (customData.isVoid)
1489
- return /\/?>\s*/;
1490
- if (customData.isText)
1491
- return new RegExp(`\\s*<\\/(?<endTag>${escapeRegex(customData.tag)})\\s*>\\s*`);
1492
- return /(?:\/\>|\<\/(?<endTag>[\w:\-\.]+)\s*\>\s*)/;
1493
- },
1494
- ],
1495
- })
1496
- .onMatch(({ context, customData }) => {
1497
- context.icon = customData.tag,
1498
- customData.isVoid = opts.voidTags.includes(customData.tag);
1499
- customData.isText = opts.textTags.includes(customData.tag);
1500
- if (customData.isVoid) {
1501
- context.clearRecognizes(innerNode);
1502
- }
1503
- if (customData.isText && !recognizeTextDirective) {
1504
- context.addAbsorbs(innerNode, 'join');
1505
- }
1506
- })
1507
- .onBeforeChildParse((child, { customData }) => {
1508
- if (customData.isText && child.node === innerNode) {
1509
- child.clearRecognizes();
1510
- if (recognizeTextDirective) {
1511
- child.addRecognizes(textDirectiveNode);
1512
- }
1513
- child.removeOnAppendContent();
1514
- child.endsWith = {
1515
- token: new RegExp(`<\\/(?<endTag>${escapeRegex(customData.tag)})\\s*>`),
1516
- eject: true,
1517
- };
1518
- }
1519
- })
1520
- .onAfterChildParse((child, { context }) => {
1521
- if (child.node === innerNode) {
1522
- context.clearRecognizes();
1523
- }
1524
- })
1525
- .onPop(({ customData: { isVoid, tag, endTag, operations }, parserContext, customData, context }) => {
1526
- var _a, _b;
1527
- if (operations && operations.length) {
1528
- operations = operations.sort((a) => a.key === 'for' ? -1 : 1);
1529
- customData.operation = operations[0].key;
1530
- for (let i = 0; i < operations.length; i++) {
1531
- const { key, value } = operations[i];
1532
- const descr = htmlBlockTypesO[key];
1533
- if (!descr) {
1534
- parserContext.panicBlock(`Unknown block operation "${key}".`, tag.length, tag.length + 1);
1535
- }
1536
- if (descr.exprRequired && !value) {
1537
- parserContext.panicBlock(`Expression required for "${key}" operation.`, tag.length, tag.length + 1);
1538
- }
1539
- if (!descr.exprRequired && !!value) {
1540
- parserContext.panicBlock(`Unexpected expression for "${key}" operation.`, tag.length, tag.length + 1);
1541
- }
1542
- if (descr.overtakes) {
1543
- const prevNode = context.getPrevNode();
1544
- const prevContext = context.getPrevContext();
1545
- if (typeof prevNode === 'string' && prevNode.replace(/[\s\n\r]/g, '')) {
1546
- parserContext.panicBlock(`Unexpected block operation "${descr.key}".`, tag.length, tag.length + 1);
1547
- }
1548
- if (!prevContext ||
1549
- !descr.overtakes.includes(prevContext.getCustomData().operation)) {
1550
- parserContext.panicBlock(`Unexpected block operation "${descr.key}".`, tag.length, tag.length + 1);
1551
- }
1552
- const prevData = prevContext.getCustomData();
1553
- prevData.closeCode = '';
1554
- }
1555
- }
1556
- if (operations.length === 1) {
1557
- const descr = htmlBlockTypesO[operations[0].key];
1558
- customData.openCode = descr.renderOpen(operations[0].value);
1559
- customData.closeCode = '}\n';
1560
- }
1561
- else if (operations.length === 2) {
1562
- const descr1 = htmlBlockTypesO[operations[0].key];
1563
- const descr2 = htmlBlockTypesO[operations[1].key];
1564
- if (!((_a = descr1.compatible) === null || _a === void 0 ? void 0 : _a.includes(descr2.key)) || !((_b = descr2.compatible) === null || _b === void 0 ? void 0 : _b.includes(descr1.key))) {
1565
- parserContext.panicBlock(`Block operation "${descr1.key}" is not compatible with "${descr2.key}".`, tag.length, tag.length + 1);
1566
- }
1567
- customData.openCode = descr1.renderOpen(operations[0].value) + descr2.renderOpen(operations[1].value);
1568
- customData.closeCode = '}\n}\n';
1569
- }
1570
- else {
1571
- parserContext.panicBlock(`Too many block operations "${operations.map(o => o.key).join(', ')}".`, tag.length, tag.length + 1);
1572
- }
1573
- }
1574
- if (!isVoid && typeof endTag === 'string' && tag !== endTag) {
1575
- parserContext.panicBlock(`Open tag <${tag}> and closing tag </${endTag}> must be equal.`, tag.length || 0, endTag.length + 1);
1576
- }
1577
- })
1578
- .addRecognizes(innerNode, ...attrNodes)
1579
- .addHoistChildren({
1580
- node: attrBlockOperationNode,
1581
- as: 'operations',
1582
- asArray: true,
1583
- deep: 1,
1584
- mapRule: 'customData',
1585
- });
1586
- if (recognizeTextDirective) {
1587
- rootNode.addRecognizes(textDirectiveNode);
1588
- innerNode.addRecognizes(textDirectiveNode);
1589
- cDataNode.addRecognizes(textDirectiveNode);
1590
- }
1591
- rootNode.addRecognizes(docTypeNode, commentNode, tagNode, stringExpressionNode);
1592
- innerNode.addRecognizes(commentNode, cDataNode, tagNode, stringExpressionNode);
1593
- commentNode.addRecognizes(stringExpressionNode);
1594
- cDataNode.addRecognizes(stringExpressionNode);
1595
- return {
1596
- rootNode,
1597
- innerNode,
1598
- commentNode,
1599
- cDataNode,
1600
- docTypeNode,
1601
- stringExpressionNode,
1602
- attrNode,
1603
- attrBlockOperationNode,
1604
- attrExprNode,
1605
- tagNode,
1606
- textDirectiveNode,
1607
- };
308
+ const stringExpressionNode = stringExpressionNodeFactory(opts.exprDelimiters);
309
+ const docTypeNode = new Node({
310
+ name: "doctype",
311
+ start: "<!DOCTYPE ",
312
+ end: ">"
313
+ });
314
+ const cDataNode = new Node({
315
+ name: "cdata",
316
+ start: "<![CDATA[",
317
+ end: "]]>",
318
+ recognizes: [stringExpressionNode]
319
+ });
320
+ const commentNode = new Node({
321
+ name: "comment",
322
+ start: "<!--",
323
+ end: "-->",
324
+ recognizes: [stringExpressionNode]
325
+ });
326
+ const attrNode = attributeNodeFactory();
327
+ const attrBlockOperationNode = attributeNodeFactory("↳", opts.blockOperation, "block");
328
+ const attrExprNode = attributeNodeFactory("≈", opts.attrExpression, "expr");
329
+ const attrNodes = [
330
+ attrBlockOperationNode,
331
+ attrExprNode,
332
+ attrNode
333
+ ];
334
+ const textDirectiveNode = new Node({
335
+ name: "text-directive",
336
+ start: {
337
+ token: new RegExp(`^\\s*(?:<!--)${escapeRegex(opts.directive)}\\s*text-mode-on\\s*-->\\s*$\\n?`, "m"),
338
+ omit: true
339
+ },
340
+ end: {
341
+ token: new RegExp(`^\\s*(?:<!--)${escapeRegex(opts.directive)}\\s*text-mode-off\\s*-->\\s*$\\n?`, "m"),
342
+ omit: true
343
+ }
344
+ });
345
+ const innerNode = new Node({
346
+ name: "inner",
347
+ start: { token: (ctx) => {
348
+ const parentData = ctx.parent?.data;
349
+ if (parentData?.isText || parentData?.isVoid) return /\b\B/;
350
+ return ">";
351
+ } },
352
+ end: {
353
+ token: "</",
354
+ eject: true
355
+ },
356
+ recognizes: [
357
+ commentNode,
358
+ cDataNode,
359
+ stringExpressionNode
360
+ ]
361
+ });
362
+ const textInnerNode = new Node({
363
+ name: "textInner",
364
+ start: { token: (ctx) => {
365
+ if ((ctx.parent?.data)?.isText) return ">";
366
+ return /\b\B/;
367
+ } },
368
+ end: {
369
+ token: "</",
370
+ eject: true
371
+ }
372
+ });
373
+ const tagNode = new Node({
374
+ name: "tag",
375
+ start: { token: /<(?<tag>[\w:\-.]+)/ },
376
+ end: { token: (ctx) => {
377
+ const data = ctx.node.data;
378
+ if (data.isVoid) return /\/?>\s*/;
379
+ if (data.isText) return new RegExp(`\\s*<\\/(?<endTag>${escapeRegex(data.tag)})\\s*>\\s*`);
380
+ return /(?:\/>|<\/(?<endTag>[\w:\-.]+)\s*>\s*)/;
381
+ } },
382
+ data: {
383
+ tag: "",
384
+ code: () => ""
385
+ },
386
+ recognizes: [...attrNodes]
387
+ }).onOpen((node) => {
388
+ node.data.isVoid = opts.voidTags.includes(node.data.tag);
389
+ node.data.isText = opts.textTags.includes(node.data.tag);
390
+ }).onChild((child, parent) => {
391
+ if (child.node === attrBlockOperationNode) {
392
+ if (!parent.data.operations) parent.data.operations = [];
393
+ parent.data.operations.push(child.data);
394
+ }
395
+ }).onClose((node) => {
396
+ const { isVoid, tag, endTag, operations } = node.data;
397
+ let ops = operations;
398
+ if (ops && ops.length) {
399
+ ops = ops.sort((a) => a.key === "for" ? -1 : 1);
400
+ node.data.operation = ops[0].key;
401
+ for (let i = 0; i < ops.length; i++) {
402
+ const { key, value } = ops[i];
403
+ const descr = htmlBlockTypesO[key];
404
+ if (!descr) throw new Error(`Unknown block operation "${key}".`);
405
+ if (descr.exprRequired && !value) throw new Error(`Expression required for "${key}" operation.`);
406
+ if (!descr.exprRequired && !!value) throw new Error(`Unexpected expression for "${key}" operation.`);
407
+ if (descr.overtakes) {
408
+ const parentContent = node.parent?.content;
409
+ if (parentContent) {
410
+ let prevSibling = null;
411
+ for (let j = parentContent.length - 1; j >= 0; j--) {
412
+ const item = parentContent[j];
413
+ if (item === node) continue;
414
+ if (typeof item === "string") {
415
+ if (item.replace(/[\s\n\r]/g, "")) throw new Error(`Unexpected block operation "${descr.key}".`);
416
+ } else {
417
+ prevSibling = item;
418
+ break;
419
+ }
420
+ }
421
+ if (!prevSibling || !descr.overtakes.includes(prevSibling.data.operation)) throw new Error(`Unexpected block operation "${descr.key}".`);
422
+ const prevData = prevSibling.data;
423
+ prevData.closeCode = "";
424
+ }
425
+ }
426
+ }
427
+ if (ops.length === 1) {
428
+ const descr = htmlBlockTypesO[ops[0].key];
429
+ node.data.openCode = descr.renderOpen(ops[0].value);
430
+ node.data.closeCode = "}\n";
431
+ } else if (ops.length === 2) {
432
+ const descr1 = htmlBlockTypesO[ops[0].key];
433
+ const descr2 = htmlBlockTypesO[ops[1].key];
434
+ if (!descr1.compatible?.includes(descr2.key) || !descr2.compatible?.includes(descr1.key)) throw new Error(`Block operation "${descr1.key}" is not compatible with "${descr2.key}".`);
435
+ node.data.openCode = descr1.renderOpen(ops[0].value) + descr2.renderOpen(ops[1].value);
436
+ node.data.closeCode = "}\n}\n";
437
+ } else throw new Error(`Too many block operations "${ops.map((o) => o.key).join(", ")}".`);
438
+ }
439
+ if (!isVoid && typeof endTag === "string" && tag !== endTag) throw new Error(`Open tag <${tag}> and closing tag </${endTag}> must be equal.`);
440
+ });
441
+ tagNode.recognize(textInnerNode, innerNode);
442
+ innerNode.recognize(tagNode);
443
+ if (recognizeTextDirective) {
444
+ innerNode.recognize(textDirectiveNode);
445
+ cDataNode.recognize(textDirectiveNode);
446
+ textInnerNode.recognize(textDirectiveNode);
447
+ }
448
+ const rootNode = new Node({
449
+ name: "html-root",
450
+ eofClose: true,
451
+ recognizes: [
452
+ docTypeNode,
453
+ commentNode,
454
+ tagNode,
455
+ stringExpressionNode
456
+ ]
457
+ });
458
+ if (recognizeTextDirective) rootNode.recognize(textDirectiveNode);
459
+ return {
460
+ rootNode,
461
+ innerNode,
462
+ commentNode,
463
+ cDataNode,
464
+ docTypeNode,
465
+ stringExpressionNode,
466
+ attrNode,
467
+ attrBlockOperationNode,
468
+ attrExprNode,
469
+ tagNode,
470
+ textDirectiveNode
471
+ };
1608
472
  };
1609
473
  const getHtmlRewriter = (opts, debug = false) => {
1610
- return getRewriter(getHtmlParser(opts).rootNode, debug);
474
+ return getRewriter(getHtmlParser(opts).rootNode, debug);
1611
475
  };
1612
- function attributeNodeFactory(icon = '=', prefix, type = 'plain') {
1613
- const attrNodeOptions = {
1614
- label: '',
1615
- icon,
1616
- tokens: [
1617
- prefix ? new RegExp(`${escapeRegex(prefix)}(?<key>[\\w:\\-\\.]+)`) : /(?<key>[\w:\-\.]+)/,
1618
- /[\s\n\/>]/,
1619
- ],
1620
- tokenOE: 'omit-eject',
1621
- };
1622
- const quoteEsc = {
1623
- '"': '&quot;',
1624
- '\'': '&apos;',
1625
- };
1626
- function escapeVal(value, quote) {
1627
- let v = '';
1628
- if (value) {
1629
- v += '=';
1630
- v += quote ? (quote + value.replace(new RegExp(quote, 'g'), quoteEsc[quote]) + quote) : value;
1631
- }
1632
- return v;
1633
- }
1634
- const children = [unquotedValueNode, valueNode];
1635
- const codeFuncs = {
1636
- plain: ({ customData: { key, value, quote } }, level = 0) => {
1637
- return ' '.repeat(level * 2) + pushString(key + escapeVal(value, quote));
1638
- },
1639
- block: () => '',
1640
- expr: ({ customData: { key, value, quote } }, level = 0) => {
1641
- const q = (quote || '');
1642
- const indent = ' '.repeat(level * 2);
1643
- let s = indent + '__v = ' + (value || '\'\'') + '\n';
1644
- s += indent + 'if (typeof __v === \'boolean\') {\n';
1645
- s += indent + ` if (__v) __ += \`${key}\`\n`;
1646
- s += indent + '} else {\n';
1647
- s += indent + ` __ += \`${key}=${q}` + '${' + ` (__v || '').replace(/${q}/g, '${quoteEsc[q]}') }${q}\`\n`;
1648
- s += indent + '}\n';
1649
- return s;
1650
- },
1651
- };
1652
- const attrNode = new BasicNode(attrNodeOptions)
1653
- .addPopsAfterNode(...children)
1654
- .addHoistChildren({
1655
- node: valueNode,
1656
- as: 'quote',
1657
- deep: 1,
1658
- mapRule: 'customData.quote',
1659
- })
1660
- .onPop(({ parserContext, customData: { value, quote } }) => {
1661
- if (type === 'expr' && value) {
1662
- try {
1663
- new Function(value);
1664
- }
1665
- catch (e) {
1666
- parserContext.panic('Invalid expression: ' + e.message, value.length + 1);
1667
- }
1668
- }
1669
- if (type === 'expr' && !quote) {
1670
- parserContext.panic('Expression must be quoted.', (value === null || value === void 0 ? void 0 : value.length) || 1);
1671
- }
1672
- })
1673
- .addAbsorbs(children, 'join->value')
1674
- .initCustomData(() => ({
1675
- key: '',
1676
- code: codeFuncs[type],
1677
- }));
1678
- return attrNode;
1679
- }
1680
-
476
+ const quoteEndRegex = {
477
+ "\"": /(?<=(?<!\\)(?:\\\\)*)"/,
478
+ "'": /(?<=(?<!\\)(?:\\\\)*)'/,
479
+ "`": /(?<=(?<!\\)(?:\\\\)*)`/
480
+ };
481
+ const quoteReplaceRegex = {
482
+ "\"": /"/g,
483
+ "'": /'/g
484
+ };
485
+ function attributeNodeFactory(icon = "=", prefix, type = "plain") {
486
+ const valueNode = new Node({
487
+ name: `${icon}-value`,
488
+ start: {
489
+ token: /=(?<quote>["'`])/,
490
+ omit: true
491
+ },
492
+ end: {
493
+ token: (ctx) => {
494
+ const q = ctx.node.data.quote;
495
+ if (!q) return "";
496
+ return quoteEndRegex[q] || "";
497
+ },
498
+ omit: true
499
+ },
500
+ data: { quote: "" }
501
+ });
502
+ const unquotedValueNode = new Node({
503
+ name: `${icon}-unquoted-value`,
504
+ start: {
505
+ token: /=(?<content>\w+)/,
506
+ omit: true
507
+ },
508
+ end: {
509
+ token: /[\s/>]/,
510
+ eject: true
511
+ },
512
+ data: { content: "" }
513
+ });
514
+ const quoteEsc = {
515
+ "\"": "&quot;",
516
+ "'": "&apos;"
517
+ };
518
+ function escapeVal(value, quote) {
519
+ let v = "";
520
+ if (value) {
521
+ v += "=";
522
+ v += quote ? quote + value.replace(quoteReplaceRegex[quote], quoteEsc[quote]) + quote : value;
523
+ }
524
+ return v;
525
+ }
526
+ return new Node({
527
+ name: `attr-${type}`,
528
+ start: {
529
+ token: prefix ? new RegExp(`${escapeRegex(prefix)}(?<key>[\\w:\\-\\.]+)`) : /(?<key>[\w:\-.]+)/,
530
+ omit: true
531
+ },
532
+ end: {
533
+ token: /[\s\n/>]/,
534
+ eject: true
535
+ },
536
+ recognizes: [unquotedValueNode, valueNode],
537
+ data: {
538
+ key: "",
539
+ code: {
540
+ plain: (node, level = 0) => {
541
+ const { key, value, quote } = node.data;
542
+ return " ".repeat(level * 2) + pushString(key + escapeVal(value, quote));
543
+ },
544
+ block: () => "",
545
+ expr: (node, level = 0) => {
546
+ const { key, value, quote } = node.data;
547
+ const q = quote || "";
548
+ const indent = " ".repeat(level * 2);
549
+ let s = indent + "__v = " + (value || "''") + "\n";
550
+ s += indent + "if (typeof __v === 'boolean') {\n";
551
+ s += indent + ` if (__v) __ += \`${key}\`\n`;
552
+ s += indent + "} else {\n";
553
+ s += indent + ` __ += \`${key}=${q}\${ (__v || '').replace(/${q}/g, '${quoteEsc[q]}') }${q}\`\n`;
554
+ s += indent + "}\n";
555
+ return s;
556
+ }
557
+ }[type]
558
+ }
559
+ }).onChild((child, parent) => {
560
+ if (child.node === valueNode) {
561
+ parent.data.quote = child.data.quote;
562
+ parent.data.value = textContent(child);
563
+ } else if (child.node === unquotedValueNode) parent.data.value = child.data.content;
564
+ const idx = parent.content.indexOf(child);
565
+ if (idx >= 0) parent.content.splice(idx, 1);
566
+ }).onClose((node) => {
567
+ node.content.length = 0;
568
+ if (type === "expr" && node.data.value) try {
569
+ new Function(node.data.value);
570
+ } catch (e) {
571
+ throw new Error("Invalid expression: " + e.message);
572
+ }
573
+ if (type === "expr" && !node.data.quote) throw new Error("Expression must be quoted.");
574
+ });
575
+ }
576
+ //#endregion
577
+ //#region src/rw-text-parser.ts
1681
578
  const textBlockTypes = [
1682
- {
1683
- key: 'FOR',
1684
- exprRequired: true,
1685
- opening: true,
1686
- code: ({ customData }) => `for ${customData.expression} {\n`,
1687
- },
1688
- {
1689
- key: 'IF',
1690
- exprRequired: true,
1691
- opening: true,
1692
- code: ({ customData }) => `if ${customData.expression} {\n`,
1693
- },
1694
- {
1695
- key: 'ELSEIF',
1696
- closingKey: 'IF',
1697
- exprRequired: true,
1698
- opening: false,
1699
- overtakes: ['IF', 'ELSEIF'],
1700
- code: ({ customData }) => `} else if ${customData.expression} {\n`,
1701
- },
1702
- {
1703
- key: 'ELSE',
1704
- closingKey: 'IF',
1705
- exprRequired: false,
1706
- opening: false,
1707
- overtakes: ['IF', 'ELSEIF'],
1708
- code: () => '} else {\n',
1709
- },
579
+ {
580
+ key: "FOR",
581
+ exprRequired: true,
582
+ opening: true,
583
+ code: (node) => `for ${node.data.expression} {\n`
584
+ },
585
+ {
586
+ key: "IF",
587
+ exprRequired: true,
588
+ opening: true,
589
+ code: (node) => `if ${node.data.expression} {\n`
590
+ },
591
+ {
592
+ key: "ELSEIF",
593
+ closingKey: "IF",
594
+ exprRequired: true,
595
+ opening: false,
596
+ overtakes: ["IF", "ELSEIF"],
597
+ code: (node) => `} else if ${node.data.expression} {\n`
598
+ },
599
+ {
600
+ key: "ELSE",
601
+ closingKey: "IF",
602
+ exprRequired: false,
603
+ opening: false,
604
+ overtakes: ["IF", "ELSEIF"],
605
+ code: () => "} else {\n"
606
+ }
1710
607
  ];
1711
608
  const textBlockTypesO = {};
1712
- textBlockTypes.forEach(b => textBlockTypesO[b.key] = b);
609
+ textBlockTypes.forEach((b) => textBlockTypesO[b.key] = b);
1713
610
  const getTextParser = (opts, recognizeHtmlDirective = false) => {
1714
- const rootNode = new BasicNode({ icon: 'Text Mode' });
1715
- const stringExpressionNode = stringExpressionNodeFactory(opts.exprDelimeters);
1716
- const blockOperationNode = new BasicNode({
1717
- label: '',
1718
- icon: '↳',
1719
- tokens: [
1720
- new RegExp(`^\\s*(?:\\/\\/|#)${escapeRegex(opts.blockOperation)}\\s*(?<block>\\w+[^\\S\\r\\n]*\\w*)[^\\S\\r\\n]*(?<expression>\\(.*\\))?(?<rest>[^\\n]*)?$`, 'm'),
1721
- new RegExp(`^\\s*(?:\\/\\/|#)${escapeRegex(opts.blockOperation)}\\s*(?<endBlock>END[^\\S\\r\\n]*\\w*)[^\\S\\r\\n]*(?<endExpression>\\(.*\\))?(?<endRest>[^\\n]*)?$`, 'm'),
1722
- ],
1723
- tokenOE: 'omit-omit',
1724
- })
1725
- .onMatchStartToken(({ customData, parserContext, matched }) => {
1726
- const { block, expression, rest } = matched.groups;
1727
- const descr = textBlockTypesO[block.replace(/[\s\n]/g, '')];
1728
- if (!descr) {
1729
- parserContext.panic(`Unknown block operation "${block.trim()}".`, -matched[0].indexOf(block));
1730
- }
1731
- if (descr.exprRequired && !expression) {
1732
- parserContext.panic(`Expression required for "${block.trim()}" operation.`, -matched[0].length);
1733
- }
1734
- if (!descr.exprRequired && !!expression) {
1735
- parserContext.panic(`Unexpected expression for "${block.trim()}" operation.`, -matched[0].indexOf(expression));
1736
- }
1737
- if (rest) {
1738
- parserContext.panic(`Unexpected text "${rest}" in "${block.trim()}" operation.`, -matched[0].length + rest.length);
1739
- }
1740
- if (descr.opening) {
1741
- return true;
1742
- }
1743
- if (descr.overtakes && descr.overtakes.includes(customData.block)) {
1744
- parserContext.pop();
1745
- return true;
1746
- }
1747
- if (customData.block) {
1748
- parserContext.panic(`Unexpected block operation "${block.trim()}" after "${customData.block}" block.`);
1749
- }
1750
- else {
1751
- parserContext.panic(`Unexpected block operation "${block.trim()}".`);
1752
- }
1753
- })
1754
- .onMatch(({ customData, context, parserContext }) => {
1755
- customData.block = customData.block.replace(/[\s\n]/g, '');
1756
- customData.descr = textBlockTypesO[customData.block];
1757
- customData.openCode = customData.descr.code(context);
1758
- parserContext.jump();
1759
- })
1760
- .onPop(({ parserContext }) => parserContext.jump())
1761
- .onMatchEndToken(({ customData, matched, parserContext }) => {
1762
- const { endBlock } = matched.groups;
1763
- const endKey = 'END' + (customData.descr.closingKey || customData.descr.key);
1764
- if (endKey !== endBlock.replace(/[\s\n]/g, '')) {
1765
- parserContext.panic('Wrong closing block instruction ' + endBlock, matched[0].length);
1766
- }
1767
- customData.closeCode = '}\n';
1768
- return true;
1769
- })
1770
- .popsAtEOFSource(true);
1771
- const revealNode = new BasicNode({
1772
- icon: ':',
1773
- tokens: [
1774
- new RegExp(`^\\s*(?:\\/\\/|#)${escapeRegex(opts.revealLine)}[^\\S\\r\\n]*`, 'm'),
1775
- /$/m,
1776
- ],
1777
- tokenOE: 'omit-',
1778
- })
1779
- .addRecognizes(stringExpressionNode)
1780
- .popsAtEOFSource(true);
1781
- const ignoreDirectiveNode = new BasicNode({
1782
- icon: ':',
1783
- tokens: [
1784
- new RegExp(`^\\s*(?:\\/\\/|#)${escapeRegex(opts.directive)}\\s*ignore-next-line\\s*$`, 'm'),
1785
- /^[^\n]*$/m,
1786
- ],
1787
- tokenOE: 'omit-',
1788
- })
1789
- .popsAtEOFSource(true);
1790
- const htmlDirectiveNode = new BasicNode({
1791
- icon: 'H',
1792
- tokens: [
1793
- new RegExp(`^\\s*(?:\\/\\/|#)${escapeRegex(opts.directive)}\\s*html-mode-on\\s*$`, 'm'),
1794
- new RegExp(`^\\s*(?:\\/\\/|#)${escapeRegex(opts.directive)}\\s*html-mode-off\\s*$`, 'm'),
1795
- ],
1796
- tokenOE: 'omit-omit',
1797
- })
1798
- .onMatch(({ parserContext }) => parserContext.jump())
1799
- .onPop(({ parserContext }) => parserContext.jump());
1800
- blockOperationNode.addRecognizes(ignoreDirectiveNode, blockOperationNode, revealNode, stringExpressionNode);
1801
- rootNode.addRecognizes(ignoreDirectiveNode, blockOperationNode, revealNode, stringExpressionNode);
1802
- if (recognizeHtmlDirective) {
1803
- rootNode.addRecognizes(htmlDirectiveNode);
1804
- blockOperationNode.addRecognizes(htmlDirectiveNode);
1805
- }
1806
- return {
1807
- stringExpressionNode,
1808
- revealNode,
1809
- ignoreDirectiveNode,
1810
- blockOperationNode,
1811
- rootNode,
1812
- htmlDirectiveNode,
1813
- };
611
+ const rootNode = new Node({
612
+ name: "text-root",
613
+ eofClose: true
614
+ });
615
+ const stringExpressionNode = stringExpressionNodeFactory(opts.exprDelimiters);
616
+ const esc = escapeRegex(opts.blockOperation);
617
+ const blockStartPattern = new RegExp(`^\\s*(?:\\/\\/|#)${esc}\\s*(?<block>(?!END)\\w+[^\\S\\r\\n]*\\w*)[^\\S\\r\\n]*(?<expression>\\(.*\\))?(?<rest>[^\\n]*)?$\\n?`, "m");
618
+ const blockEndPattern = new RegExp(`^\\s*(?:\\/\\/|#)${esc}\\s*(?<endBlock>END[^\\S\\r\\n]*\\w*)[^\\S\\r\\n]*(?<endExpression>\\(.*\\))?(?<endRest>[^\\n]*)?$\\n?`, "m");
619
+ const blockOvertakePattern = new RegExp(`^\\s*(?:\\/\\/|#)${esc}\\s*(?:ELSE\\s*IF|ELSE)[^\\S\\r\\n]*(?:\\(.*\\))?[^\\n]*$`, "m");
620
+ const blockOperationNode = new Node({
621
+ name: "block-operation",
622
+ start: {
623
+ token: () => blockStartPattern,
624
+ omit: true
625
+ },
626
+ end: [{
627
+ token: blockEndPattern,
628
+ omit: true
629
+ }, {
630
+ token: (ctx) => {
631
+ const block = ctx.node.data.block?.replace(/[\s\n]/g, "");
632
+ if (block === "IF" || block === "ELSEIF") return blockOvertakePattern;
633
+ return /\b\B/;
634
+ },
635
+ eject: true
636
+ }],
637
+ eofClose: true,
638
+ data: {
639
+ block: "",
640
+ expression: "",
641
+ rest: "",
642
+ descr: null,
643
+ endBlock: "",
644
+ endExpression: "",
645
+ endRest: "",
646
+ code: () => "",
647
+ openCode: "",
648
+ closeCode: ""
649
+ }
650
+ }).onOpen((node) => {
651
+ const block = node.data.block.replace(/[\s\n]/g, "");
652
+ const { expression, rest } = node.data;
653
+ const descr = textBlockTypesO[block];
654
+ if (!descr) throw new Error(`Unknown block operation "${block.trim()}".`);
655
+ if (descr.exprRequired && !expression) throw new Error(`Expression required for "${block.trim()}" operation.`);
656
+ if (!descr.exprRequired && !!expression) throw new Error(`Unexpected expression for "${block.trim()}" operation.`);
657
+ if (rest) throw new Error(`Unexpected text "${rest}" in "${block.trim()}" operation.`);
658
+ if (!descr.opening) {
659
+ const parentContent = node.parent?.content;
660
+ if (parentContent) {
661
+ let prevSiblingNode = null;
662
+ for (let j = parentContent.length - 1; j >= 0; j--) {
663
+ const item = parentContent[j];
664
+ if (typeof item === "string") {
665
+ if (item.replace(/[\s\n\r]/g, "")) throw new Error(`Unexpected block operation "${block.trim()}".`);
666
+ } else {
667
+ prevSiblingNode = item;
668
+ break;
669
+ }
670
+ }
671
+ if (!prevSiblingNode || !descr.overtakes?.includes(prevSiblingNode.data.block)) throw new Error(`Unexpected block operation "${block.trim()}".`);
672
+ prevSiblingNode.data.closeCode = "";
673
+ } else throw new Error(`Unexpected block operation "${block.trim()}".`);
674
+ }
675
+ node.data.block = block;
676
+ node.data.descr = descr;
677
+ node.data.openCode = descr.code(node);
678
+ }).onClose((node, match) => {
679
+ if (match?.groups?.endBlock) {
680
+ const endBlock = match.groups.endBlock.replace(/[\s\n]/g, "");
681
+ if ("END" + (node.data.descr.closingKey || node.data.descr.key) !== endBlock) throw new Error("Wrong closing block instruction " + match.groups.endBlock);
682
+ }
683
+ node.data.closeCode = "}\n";
684
+ });
685
+ const revealNode = new Node({
686
+ name: "reveal",
687
+ start: {
688
+ token: new RegExp(`^\\s*(?:\\/\\/|#)${escapeRegex(opts.revealLine)}[^\\S\\r\\n]*`, "m"),
689
+ omit: true
690
+ },
691
+ end: { token: /$/m },
692
+ eofClose: true,
693
+ recognizes: [stringExpressionNode]
694
+ });
695
+ const ignoreDirectiveNode = new Node({
696
+ name: "ignore-directive",
697
+ start: {
698
+ token: new RegExp(`^\\s*(?:\\/\\/|#)${escapeRegex(opts.directive)}\\s*ignore-next-line\\s*$\\n?`, "m"),
699
+ omit: true
700
+ },
701
+ end: { token: /^[^\n]*$/m },
702
+ eofClose: true
703
+ });
704
+ const htmlDirectiveNode = new Node({
705
+ name: "html-directive",
706
+ start: {
707
+ token: new RegExp(`^\\s*(?:\\/\\/|#)${escapeRegex(opts.directive)}\\s*html-mode-on\\s*$\\n?`, "m"),
708
+ omit: true
709
+ },
710
+ end: {
711
+ token: new RegExp(`^\\s*(?:\\/\\/|#)${escapeRegex(opts.directive)}\\s*html-mode-off\\s*$\\n?`, "m"),
712
+ omit: true
713
+ }
714
+ });
715
+ blockOperationNode.recognize(ignoreDirectiveNode, blockOperationNode, revealNode, stringExpressionNode);
716
+ rootNode.recognize(ignoreDirectiveNode, blockOperationNode, revealNode, stringExpressionNode);
717
+ if (recognizeHtmlDirective) {
718
+ rootNode.recognize(htmlDirectiveNode);
719
+ blockOperationNode.recognize(htmlDirectiveNode);
720
+ }
721
+ return {
722
+ stringExpressionNode,
723
+ revealNode,
724
+ ignoreDirectiveNode,
725
+ blockOperationNode,
726
+ rootNode,
727
+ htmlDirectiveNode
728
+ };
1814
729
  };
1815
730
  const getTextRewriter = (opts, debug = false) => {
1816
- return getRewriter(getTextParser(opts).rootNode, debug);
731
+ return getRewriter(getTextParser(opts).rootNode, debug);
1817
732
  };
1818
-
1819
- function getDefaultExportFromCjs (x) {
1820
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
1821
- }
1822
-
1823
- var balancedMatch = balanced$1;
1824
- function balanced$1(a, b, str) {
1825
- if (a instanceof RegExp) a = maybeMatch(a, str);
1826
- if (b instanceof RegExp) b = maybeMatch(b, str);
1827
-
1828
- var r = range(a, b, str);
1829
-
1830
- return r && {
1831
- start: r[0],
1832
- end: r[1],
1833
- pre: str.slice(0, r[0]),
1834
- body: str.slice(r[0] + a.length, r[1]),
1835
- post: str.slice(r[1] + b.length)
1836
- };
1837
- }
1838
-
1839
- function maybeMatch(reg, str) {
1840
- var m = str.match(reg);
1841
- return m ? m[0] : null;
1842
- }
1843
-
1844
- balanced$1.range = range;
1845
- function range(a, b, str) {
1846
- var begs, beg, left, right, result;
1847
- var ai = str.indexOf(a);
1848
- var bi = str.indexOf(b, ai + 1);
1849
- var i = ai;
1850
-
1851
- if (ai >= 0 && bi > 0) {
1852
- if(a===b) {
1853
- return [ai, bi];
1854
- }
1855
- begs = [];
1856
- left = str.length;
1857
-
1858
- while (i >= 0 && !result) {
1859
- if (i == ai) {
1860
- begs.push(i);
1861
- ai = str.indexOf(a, i + 1);
1862
- } else if (begs.length == 1) {
1863
- result = [ begs.pop(), bi ];
1864
- } else {
1865
- beg = begs.pop();
1866
- if (beg < left) {
1867
- left = beg;
1868
- right = bi;
1869
- }
1870
-
1871
- bi = str.indexOf(b, i + 1);
1872
- }
1873
-
1874
- i = ai < bi && ai >= 0 ? ai : bi;
1875
- }
1876
-
1877
- if (begs.length) {
1878
- result = [ left, right ];
1879
- }
1880
- }
1881
-
1882
- return result;
1883
- }
1884
-
1885
- var balanced = balancedMatch;
1886
-
1887
- var braceExpansion = expandTop;
1888
-
1889
- var escSlash = '\0SLASH'+Math.random()+'\0';
1890
- var escOpen = '\0OPEN'+Math.random()+'\0';
1891
- var escClose = '\0CLOSE'+Math.random()+'\0';
1892
- var escComma = '\0COMMA'+Math.random()+'\0';
1893
- var escPeriod = '\0PERIOD'+Math.random()+'\0';
1894
-
1895
- function numeric(str) {
1896
- return parseInt(str, 10) == str
1897
- ? parseInt(str, 10)
1898
- : str.charCodeAt(0);
1899
- }
1900
-
1901
- function escapeBraces(str) {
1902
- return str.split('\\\\').join(escSlash)
1903
- .split('\\{').join(escOpen)
1904
- .split('\\}').join(escClose)
1905
- .split('\\,').join(escComma)
1906
- .split('\\.').join(escPeriod);
1907
- }
1908
-
1909
- function unescapeBraces(str) {
1910
- return str.split(escSlash).join('\\')
1911
- .split(escOpen).join('{')
1912
- .split(escClose).join('}')
1913
- .split(escComma).join(',')
1914
- .split(escPeriod).join('.');
1915
- }
1916
-
1917
-
1918
- // Basically just str.split(","), but handling cases
1919
- // where we have nested braced sections, which should be
1920
- // treated as individual members, like {a,{b,c},d}
1921
- function parseCommaParts(str) {
1922
- if (!str)
1923
- return [''];
1924
-
1925
- var parts = [];
1926
- var m = balanced('{', '}', str);
1927
-
1928
- if (!m)
1929
- return str.split(',');
1930
-
1931
- var pre = m.pre;
1932
- var body = m.body;
1933
- var post = m.post;
1934
- var p = pre.split(',');
1935
-
1936
- p[p.length-1] += '{' + body + '}';
1937
- var postParts = parseCommaParts(post);
1938
- if (post.length) {
1939
- p[p.length-1] += postParts.shift();
1940
- p.push.apply(p, postParts);
1941
- }
1942
-
1943
- parts.push.apply(parts, p);
1944
-
1945
- return parts;
1946
- }
1947
-
1948
- function expandTop(str) {
1949
- if (!str)
1950
- return [];
1951
-
1952
- // I don't know why Bash 4.3 does this, but it does.
1953
- // Anything starting with {} will have the first two bytes preserved
1954
- // but *only* at the top level, so {},a}b will not expand to anything,
1955
- // but a{},b}c will be expanded to [a}c,abc].
1956
- // One could argue that this is a bug in Bash, but since the goal of
1957
- // this module is to match Bash's rules, we escape a leading {}
1958
- if (str.substr(0, 2) === '{}') {
1959
- str = '\\{\\}' + str.substr(2);
1960
- }
1961
-
1962
- return expand(escapeBraces(str), true).map(unescapeBraces);
1963
- }
1964
-
1965
- function embrace(str) {
1966
- return '{' + str + '}';
1967
- }
1968
- function isPadded(el) {
1969
- return /^-?0\d/.test(el);
1970
- }
1971
-
1972
- function lte(i, y) {
1973
- return i <= y;
1974
- }
1975
- function gte(i, y) {
1976
- return i >= y;
1977
- }
1978
-
1979
- function expand(str, isTop) {
1980
- var expansions = [];
1981
-
1982
- var m = balanced('{', '}', str);
1983
- if (!m) return [str];
1984
-
1985
- // no need to expand pre, since it is guaranteed to be free of brace-sets
1986
- var pre = m.pre;
1987
- var post = m.post.length
1988
- ? expand(m.post, false)
1989
- : [''];
1990
-
1991
- if (/\$$/.test(m.pre)) {
1992
- for (var k = 0; k < post.length; k++) {
1993
- var expansion = pre+ '{' + m.body + '}' + post[k];
1994
- expansions.push(expansion);
1995
- }
1996
- } else {
1997
- var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
1998
- var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
1999
- var isSequence = isNumericSequence || isAlphaSequence;
2000
- var isOptions = m.body.indexOf(',') >= 0;
2001
- if (!isSequence && !isOptions) {
2002
- // {a},b}
2003
- if (m.post.match(/,.*\}/)) {
2004
- str = m.pre + '{' + m.body + escClose + m.post;
2005
- return expand(str);
2006
- }
2007
- return [str];
2008
- }
2009
-
2010
- var n;
2011
- if (isSequence) {
2012
- n = m.body.split(/\.\./);
2013
- } else {
2014
- n = parseCommaParts(m.body);
2015
- if (n.length === 1) {
2016
- // x{{a,b}}y ==> x{a}y x{b}y
2017
- n = expand(n[0], false).map(embrace);
2018
- if (n.length === 1) {
2019
- return post.map(function(p) {
2020
- return m.pre + n[0] + p;
2021
- });
2022
- }
2023
- }
2024
- }
2025
-
2026
- // at this point, n is the parts, and we know it's not a comma set
2027
- // with a single entry.
2028
- var N;
2029
-
2030
- if (isSequence) {
2031
- var x = numeric(n[0]);
2032
- var y = numeric(n[1]);
2033
- var width = Math.max(n[0].length, n[1].length);
2034
- var incr = n.length == 3
2035
- ? Math.abs(numeric(n[2]))
2036
- : 1;
2037
- var test = lte;
2038
- var reverse = y < x;
2039
- if (reverse) {
2040
- incr *= -1;
2041
- test = gte;
2042
- }
2043
- var pad = n.some(isPadded);
2044
-
2045
- N = [];
2046
-
2047
- for (var i = x; test(i, y); i += incr) {
2048
- var c;
2049
- if (isAlphaSequence) {
2050
- c = String.fromCharCode(i);
2051
- if (c === '\\')
2052
- c = '';
2053
- } else {
2054
- c = String(i);
2055
- if (pad) {
2056
- var need = width - c.length;
2057
- if (need > 0) {
2058
- var z = new Array(need + 1).join('0');
2059
- if (i < 0)
2060
- c = '-' + z + c.slice(1);
2061
- else
2062
- c = z + c;
2063
- }
2064
- }
2065
- }
2066
- N.push(c);
2067
- }
2068
- } else {
2069
- N = [];
2070
-
2071
- for (var j = 0; j < n.length; j++) {
2072
- N.push.apply(N, expand(n[j], false));
2073
- }
2074
- }
2075
-
2076
- for (var j = 0; j < N.length; j++) {
2077
- for (var k = 0; k < post.length; k++) {
2078
- var expansion = pre + N[j] + post[k];
2079
- if (!isTop || isSequence || expansion)
2080
- expansions.push(expansion);
2081
- }
2082
- }
2083
- }
2084
-
2085
- return expansions;
2086
- }
2087
-
2088
- var expand$1 = /*@__PURE__*/getDefaultExportFromCjs(braceExpansion);
2089
-
2090
- const MAX_PATTERN_LENGTH = 1024 * 64;
2091
- const assertValidPattern = (pattern) => {
2092
- if (typeof pattern !== 'string') {
2093
- throw new TypeError('invalid pattern');
2094
- }
2095
- if (pattern.length > MAX_PATTERN_LENGTH) {
2096
- throw new TypeError('pattern is too long');
2097
- }
2098
- };
2099
-
2100
- // translate the various posix character classes into unicode properties
2101
- // this works across all unicode locales
2102
- // { <posix class>: [<translation>, /u flag required, negated]
2103
- const posixClasses = {
2104
- '[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
2105
- '[:alpha:]': ['\\p{L}\\p{Nl}', true],
2106
- '[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
2107
- '[:blank:]': ['\\p{Zs}\\t', true],
2108
- '[:cntrl:]': ['\\p{Cc}', true],
2109
- '[:digit:]': ['\\p{Nd}', true],
2110
- '[:graph:]': ['\\p{Z}\\p{C}', true, true],
2111
- '[:lower:]': ['\\p{Ll}', true],
2112
- '[:print:]': ['\\p{C}', true],
2113
- '[:punct:]': ['\\p{P}', true],
2114
- '[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
2115
- '[:upper:]': ['\\p{Lu}', true],
2116
- '[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
2117
- '[:xdigit:]': ['A-Fa-f0-9', false],
2118
- };
2119
- // only need to escape a few things inside of brace expressions
2120
- // escapes: [ \ ] -
2121
- const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
2122
- // escape all regexp magic characters
2123
- const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
2124
- // everything has already been escaped, we just have to join
2125
- const rangesToString = (ranges) => ranges.join('');
2126
- // takes a glob string at a posix brace expression, and returns
2127
- // an equivalent regular expression source, and boolean indicating
2128
- // whether the /u flag needs to be applied, and the number of chars
2129
- // consumed to parse the character class.
2130
- // This also removes out of order ranges, and returns ($.) if the
2131
- // entire class just no good.
2132
- const parseClass = (glob, position) => {
2133
- const pos = position;
2134
- /* c8 ignore start */
2135
- if (glob.charAt(pos) !== '[') {
2136
- throw new Error('not in a brace expression');
2137
- }
2138
- /* c8 ignore stop */
2139
- const ranges = [];
2140
- const negs = [];
2141
- let i = pos + 1;
2142
- let sawStart = false;
2143
- let uflag = false;
2144
- let escaping = false;
2145
- let negate = false;
2146
- let endPos = pos;
2147
- let rangeStart = '';
2148
- WHILE: while (i < glob.length) {
2149
- const c = glob.charAt(i);
2150
- if ((c === '!' || c === '^') && i === pos + 1) {
2151
- negate = true;
2152
- i++;
2153
- continue;
2154
- }
2155
- if (c === ']' && sawStart && !escaping) {
2156
- endPos = i + 1;
2157
- break;
2158
- }
2159
- sawStart = true;
2160
- if (c === '\\') {
2161
- if (!escaping) {
2162
- escaping = true;
2163
- i++;
2164
- continue;
2165
- }
2166
- // escaped \ char, fall through and treat like normal char
2167
- }
2168
- if (c === '[' && !escaping) {
2169
- // either a posix class, a collation equivalent, or just a [
2170
- for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
2171
- if (glob.startsWith(cls, i)) {
2172
- // invalid, [a-[] is fine, but not [a-[:alpha]]
2173
- if (rangeStart) {
2174
- return ['$.', false, glob.length - pos, true];
2175
- }
2176
- i += cls.length;
2177
- if (neg)
2178
- negs.push(unip);
2179
- else
2180
- ranges.push(unip);
2181
- uflag = uflag || u;
2182
- continue WHILE;
2183
- }
2184
- }
2185
- }
2186
- // now it's just a normal character, effectively
2187
- escaping = false;
2188
- if (rangeStart) {
2189
- // throw this range away if it's not valid, but others
2190
- // can still match.
2191
- if (c > rangeStart) {
2192
- ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
2193
- }
2194
- else if (c === rangeStart) {
2195
- ranges.push(braceEscape(c));
2196
- }
2197
- rangeStart = '';
2198
- i++;
2199
- continue;
2200
- }
2201
- // now might be the start of a range.
2202
- // can be either c-d or c-] or c<more...>] or c] at this point
2203
- if (glob.startsWith('-]', i + 1)) {
2204
- ranges.push(braceEscape(c + '-'));
2205
- i += 2;
2206
- continue;
2207
- }
2208
- if (glob.startsWith('-', i + 1)) {
2209
- rangeStart = c;
2210
- i += 2;
2211
- continue;
2212
- }
2213
- // not the start of a range, just a single character
2214
- ranges.push(braceEscape(c));
2215
- i++;
2216
- }
2217
- if (endPos < i) {
2218
- // didn't see the end of the class, not a valid class,
2219
- // but might still be valid as a literal match.
2220
- return ['', false, 0, false];
2221
- }
2222
- // if we got no ranges and no negates, then we have a range that
2223
- // cannot possibly match anything, and that poisons the whole glob
2224
- if (!ranges.length && !negs.length) {
2225
- return ['$.', false, glob.length - pos, true];
2226
- }
2227
- // if we got one positive range, and it's a single character, then that's
2228
- // not actually a magic pattern, it's just that one literal character.
2229
- // we should not treat that as "magic", we should just return the literal
2230
- // character. [_] is a perfectly valid way to escape glob magic chars.
2231
- if (negs.length === 0 &&
2232
- ranges.length === 1 &&
2233
- /^\\?.$/.test(ranges[0]) &&
2234
- !negate) {
2235
- const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
2236
- return [regexpEscape(r), false, endPos - pos, false];
2237
- }
2238
- const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
2239
- const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
2240
- const comb = ranges.length && negs.length
2241
- ? '(' + sranges + '|' + snegs + ')'
2242
- : ranges.length
2243
- ? sranges
2244
- : snegs;
2245
- return [comb, uflag, endPos - pos, true];
2246
- };
2247
-
2248
- /**
2249
- * Un-escape a string that has been escaped with {@link escape}.
2250
- *
2251
- * If the {@link windowsPathsNoEscape} option is used, then square-brace
2252
- * escapes are removed, but not backslash escapes. For example, it will turn
2253
- * the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
2254
- * becuase `\` is a path separator in `windowsPathsNoEscape` mode.
2255
- *
2256
- * When `windowsPathsNoEscape` is not set, then both brace escapes and
2257
- * backslash escapes are removed.
2258
- *
2259
- * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
2260
- * or unescaped.
2261
- */
2262
- const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
2263
- return windowsPathsNoEscape
2264
- ? s.replace(/\[([^\/\\])\]/g, '$1')
2265
- : s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
2266
- };
2267
-
2268
- // parse a single path portion
2269
- const types = new Set(['!', '?', '+', '*', '@']);
2270
- const isExtglobType = (c) => types.has(c);
2271
- // Patterns that get prepended to bind to the start of either the
2272
- // entire string, or just a single path portion, to prevent dots
2273
- // and/or traversal patterns, when needed.
2274
- // Exts don't need the ^ or / bit, because the root binds that already.
2275
- const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
2276
- const startNoDot = '(?!\\.)';
2277
- // characters that indicate a start of pattern needs the "no dots" bit,
2278
- // because a dot *might* be matched. ( is not in the list, because in
2279
- // the case of a child extglob, it will handle the prevention itself.
2280
- const addPatternStart = new Set(['[', '.']);
2281
- // cases where traversal is A-OK, no dot prevention needed
2282
- const justDots = new Set(['..', '.']);
2283
- const reSpecials = new Set('().*{}+?[]^$\\!');
2284
- const regExpEscape$1 = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
2285
- // any single thing other than /
2286
- const qmark$1 = '[^/]';
2287
- // * => any number of characters
2288
- const star$1 = qmark$1 + '*?';
2289
- // use + when we need to ensure that *something* matches, because the * is
2290
- // the only thing in the path portion.
2291
- const starNoEmpty = qmark$1 + '+?';
2292
- // remove the \ chars that we added if we end up doing a nonmagic compare
2293
- // const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
2294
- class AST {
2295
- type;
2296
- #root;
2297
- #hasMagic;
2298
- #uflag = false;
2299
- #parts = [];
2300
- #parent;
2301
- #parentIndex;
2302
- #negs;
2303
- #filledNegs = false;
2304
- #options;
2305
- #toString;
2306
- // set to true if it's an extglob with no children
2307
- // (which really means one child of '')
2308
- #emptyExt = false;
2309
- constructor(type, parent, options = {}) {
2310
- this.type = type;
2311
- // extglobs are inherently magical
2312
- if (type)
2313
- this.#hasMagic = true;
2314
- this.#parent = parent;
2315
- this.#root = this.#parent ? this.#parent.#root : this;
2316
- this.#options = this.#root === this ? options : this.#root.#options;
2317
- this.#negs = this.#root === this ? [] : this.#root.#negs;
2318
- if (type === '!' && !this.#root.#filledNegs)
2319
- this.#negs.push(this);
2320
- this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
2321
- }
2322
- get hasMagic() {
2323
- /* c8 ignore start */
2324
- if (this.#hasMagic !== undefined)
2325
- return this.#hasMagic;
2326
- /* c8 ignore stop */
2327
- for (const p of this.#parts) {
2328
- if (typeof p === 'string')
2329
- continue;
2330
- if (p.type || p.hasMagic)
2331
- return (this.#hasMagic = true);
2332
- }
2333
- // note: will be undefined until we generate the regexp src and find out
2334
- return this.#hasMagic;
2335
- }
2336
- // reconstructs the pattern
2337
- toString() {
2338
- if (this.#toString !== undefined)
2339
- return this.#toString;
2340
- if (!this.type) {
2341
- return (this.#toString = this.#parts.map(p => String(p)).join(''));
2342
- }
2343
- else {
2344
- return (this.#toString =
2345
- this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
2346
- }
2347
- }
2348
- #fillNegs() {
2349
- /* c8 ignore start */
2350
- if (this !== this.#root)
2351
- throw new Error('should only call on root');
2352
- if (this.#filledNegs)
2353
- return this;
2354
- /* c8 ignore stop */
2355
- // call toString() once to fill this out
2356
- this.toString();
2357
- this.#filledNegs = true;
2358
- let n;
2359
- while ((n = this.#negs.pop())) {
2360
- if (n.type !== '!')
2361
- continue;
2362
- // walk up the tree, appending everthing that comes AFTER parentIndex
2363
- let p = n;
2364
- let pp = p.#parent;
2365
- while (pp) {
2366
- for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
2367
- for (const part of n.#parts) {
2368
- /* c8 ignore start */
2369
- if (typeof part === 'string') {
2370
- throw new Error('string part in extglob AST??');
2371
- }
2372
- /* c8 ignore stop */
2373
- part.copyIn(pp.#parts[i]);
2374
- }
2375
- }
2376
- p = pp;
2377
- pp = p.#parent;
2378
- }
2379
- }
2380
- return this;
2381
- }
2382
- push(...parts) {
2383
- for (const p of parts) {
2384
- if (p === '')
2385
- continue;
2386
- /* c8 ignore start */
2387
- if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
2388
- throw new Error('invalid part: ' + p);
2389
- }
2390
- /* c8 ignore stop */
2391
- this.#parts.push(p);
2392
- }
2393
- }
2394
- toJSON() {
2395
- const ret = this.type === null
2396
- ? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
2397
- : [this.type, ...this.#parts.map(p => p.toJSON())];
2398
- if (this.isStart() && !this.type)
2399
- ret.unshift([]);
2400
- if (this.isEnd() &&
2401
- (this === this.#root ||
2402
- (this.#root.#filledNegs && this.#parent?.type === '!'))) {
2403
- ret.push({});
2404
- }
2405
- return ret;
2406
- }
2407
- isStart() {
2408
- if (this.#root === this)
2409
- return true;
2410
- // if (this.type) return !!this.#parent?.isStart()
2411
- if (!this.#parent?.isStart())
2412
- return false;
2413
- if (this.#parentIndex === 0)
2414
- return true;
2415
- // if everything AHEAD of this is a negation, then it's still the "start"
2416
- const p = this.#parent;
2417
- for (let i = 0; i < this.#parentIndex; i++) {
2418
- const pp = p.#parts[i];
2419
- if (!(pp instanceof AST && pp.type === '!')) {
2420
- return false;
2421
- }
2422
- }
2423
- return true;
2424
- }
2425
- isEnd() {
2426
- if (this.#root === this)
2427
- return true;
2428
- if (this.#parent?.type === '!')
2429
- return true;
2430
- if (!this.#parent?.isEnd())
2431
- return false;
2432
- if (!this.type)
2433
- return this.#parent?.isEnd();
2434
- // if not root, it'll always have a parent
2435
- /* c8 ignore start */
2436
- const pl = this.#parent ? this.#parent.#parts.length : 0;
2437
- /* c8 ignore stop */
2438
- return this.#parentIndex === pl - 1;
2439
- }
2440
- copyIn(part) {
2441
- if (typeof part === 'string')
2442
- this.push(part);
2443
- else
2444
- this.push(part.clone(this));
2445
- }
2446
- clone(parent) {
2447
- const c = new AST(this.type, parent);
2448
- for (const p of this.#parts) {
2449
- c.copyIn(p);
2450
- }
2451
- return c;
2452
- }
2453
- static #parseAST(str, ast, pos, opt) {
2454
- let escaping = false;
2455
- let inBrace = false;
2456
- let braceStart = -1;
2457
- let braceNeg = false;
2458
- if (ast.type === null) {
2459
- // outside of a extglob, append until we find a start
2460
- let i = pos;
2461
- let acc = '';
2462
- while (i < str.length) {
2463
- const c = str.charAt(i++);
2464
- // still accumulate escapes at this point, but we do ignore
2465
- // starts that are escaped
2466
- if (escaping || c === '\\') {
2467
- escaping = !escaping;
2468
- acc += c;
2469
- continue;
2470
- }
2471
- if (inBrace) {
2472
- if (i === braceStart + 1) {
2473
- if (c === '^' || c === '!') {
2474
- braceNeg = true;
2475
- }
2476
- }
2477
- else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
2478
- inBrace = false;
2479
- }
2480
- acc += c;
2481
- continue;
2482
- }
2483
- else if (c === '[') {
2484
- inBrace = true;
2485
- braceStart = i;
2486
- braceNeg = false;
2487
- acc += c;
2488
- continue;
2489
- }
2490
- if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
2491
- ast.push(acc);
2492
- acc = '';
2493
- const ext = new AST(c, ast);
2494
- i = AST.#parseAST(str, ext, i, opt);
2495
- ast.push(ext);
2496
- continue;
2497
- }
2498
- acc += c;
2499
- }
2500
- ast.push(acc);
2501
- return i;
2502
- }
2503
- // some kind of extglob, pos is at the (
2504
- // find the next | or )
2505
- let i = pos + 1;
2506
- let part = new AST(null, ast);
2507
- const parts = [];
2508
- let acc = '';
2509
- while (i < str.length) {
2510
- const c = str.charAt(i++);
2511
- // still accumulate escapes at this point, but we do ignore
2512
- // starts that are escaped
2513
- if (escaping || c === '\\') {
2514
- escaping = !escaping;
2515
- acc += c;
2516
- continue;
2517
- }
2518
- if (inBrace) {
2519
- if (i === braceStart + 1) {
2520
- if (c === '^' || c === '!') {
2521
- braceNeg = true;
2522
- }
2523
- }
2524
- else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
2525
- inBrace = false;
2526
- }
2527
- acc += c;
2528
- continue;
2529
- }
2530
- else if (c === '[') {
2531
- inBrace = true;
2532
- braceStart = i;
2533
- braceNeg = false;
2534
- acc += c;
2535
- continue;
2536
- }
2537
- if (isExtglobType(c) && str.charAt(i) === '(') {
2538
- part.push(acc);
2539
- acc = '';
2540
- const ext = new AST(c, part);
2541
- part.push(ext);
2542
- i = AST.#parseAST(str, ext, i, opt);
2543
- continue;
2544
- }
2545
- if (c === '|') {
2546
- part.push(acc);
2547
- acc = '';
2548
- parts.push(part);
2549
- part = new AST(null, ast);
2550
- continue;
2551
- }
2552
- if (c === ')') {
2553
- if (acc === '' && ast.#parts.length === 0) {
2554
- ast.#emptyExt = true;
2555
- }
2556
- part.push(acc);
2557
- acc = '';
2558
- ast.push(...parts, part);
2559
- return i;
2560
- }
2561
- acc += c;
2562
- }
2563
- // unfinished extglob
2564
- // if we got here, it was a malformed extglob! not an extglob, but
2565
- // maybe something else in there.
2566
- ast.type = null;
2567
- ast.#hasMagic = undefined;
2568
- ast.#parts = [str.substring(pos - 1)];
2569
- return i;
2570
- }
2571
- static fromGlob(pattern, options = {}) {
2572
- const ast = new AST(null, undefined, options);
2573
- AST.#parseAST(pattern, ast, 0, options);
2574
- return ast;
2575
- }
2576
- // returns the regular expression if there's magic, or the unescaped
2577
- // string if not.
2578
- toMMPattern() {
2579
- // should only be called on root
2580
- /* c8 ignore start */
2581
- if (this !== this.#root)
2582
- return this.#root.toMMPattern();
2583
- /* c8 ignore stop */
2584
- const glob = this.toString();
2585
- const [re, body, hasMagic, uflag] = this.toRegExpSource();
2586
- // if we're in nocase mode, and not nocaseMagicOnly, then we do
2587
- // still need a regular expression if we have to case-insensitively
2588
- // match capital/lowercase characters.
2589
- const anyMagic = hasMagic ||
2590
- this.#hasMagic ||
2591
- (this.#options.nocase &&
2592
- !this.#options.nocaseMagicOnly &&
2593
- glob.toUpperCase() !== glob.toLowerCase());
2594
- if (!anyMagic) {
2595
- return body;
2596
- }
2597
- const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
2598
- return Object.assign(new RegExp(`^${re}$`, flags), {
2599
- _src: re,
2600
- _glob: glob,
2601
- });
2602
- }
2603
- // returns the string match, the regexp source, whether there's magic
2604
- // in the regexp (so a regular expression is required) and whether or
2605
- // not the uflag is needed for the regular expression (for posix classes)
2606
- // TODO: instead of injecting the start/end at this point, just return
2607
- // the BODY of the regexp, along with the start/end portions suitable
2608
- // for binding the start/end in either a joined full-path makeRe context
2609
- // (where we bind to (^|/), or a standalone matchPart context (where
2610
- // we bind to ^, and not /). Otherwise slashes get duped!
2611
- //
2612
- // In part-matching mode, the start is:
2613
- // - if not isStart: nothing
2614
- // - if traversal possible, but not allowed: ^(?!\.\.?$)
2615
- // - if dots allowed or not possible: ^
2616
- // - if dots possible and not allowed: ^(?!\.)
2617
- // end is:
2618
- // - if not isEnd(): nothing
2619
- // - else: $
2620
- //
2621
- // In full-path matching mode, we put the slash at the START of the
2622
- // pattern, so start is:
2623
- // - if first pattern: same as part-matching mode
2624
- // - if not isStart(): nothing
2625
- // - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
2626
- // - if dots allowed or not possible: /
2627
- // - if dots possible and not allowed: /(?!\.)
2628
- // end is:
2629
- // - if last pattern, same as part-matching mode
2630
- // - else nothing
2631
- //
2632
- // Always put the (?:$|/) on negated tails, though, because that has to be
2633
- // there to bind the end of the negated pattern portion, and it's easier to
2634
- // just stick it in now rather than try to inject it later in the middle of
2635
- // the pattern.
2636
- //
2637
- // We can just always return the same end, and leave it up to the caller
2638
- // to know whether it's going to be used joined or in parts.
2639
- // And, if the start is adjusted slightly, can do the same there:
2640
- // - if not isStart: nothing
2641
- // - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
2642
- // - if dots allowed or not possible: (?:/|^)
2643
- // - if dots possible and not allowed: (?:/|^)(?!\.)
2644
- //
2645
- // But it's better to have a simpler binding without a conditional, for
2646
- // performance, so probably better to return both start options.
2647
- //
2648
- // Then the caller just ignores the end if it's not the first pattern,
2649
- // and the start always gets applied.
2650
- //
2651
- // But that's always going to be $ if it's the ending pattern, or nothing,
2652
- // so the caller can just attach $ at the end of the pattern when building.
2653
- //
2654
- // So the todo is:
2655
- // - better detect what kind of start is needed
2656
- // - return both flavors of starting pattern
2657
- // - attach $ at the end of the pattern when creating the actual RegExp
2658
- //
2659
- // Ah, but wait, no, that all only applies to the root when the first pattern
2660
- // is not an extglob. If the first pattern IS an extglob, then we need all
2661
- // that dot prevention biz to live in the extglob portions, because eg
2662
- // +(*|.x*) can match .xy but not .yx.
2663
- //
2664
- // So, return the two flavors if it's #root and the first child is not an
2665
- // AST, otherwise leave it to the child AST to handle it, and there,
2666
- // use the (?:^|/) style of start binding.
2667
- //
2668
- // Even simplified further:
2669
- // - Since the start for a join is eg /(?!\.) and the start for a part
2670
- // is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
2671
- // or start or whatever) and prepend ^ or / at the Regexp construction.
2672
- toRegExpSource(allowDot) {
2673
- const dot = allowDot ?? !!this.#options.dot;
2674
- if (this.#root === this)
2675
- this.#fillNegs();
2676
- if (!this.type) {
2677
- const noEmpty = this.isStart() && this.isEnd();
2678
- const src = this.#parts
2679
- .map(p => {
2680
- const [re, _, hasMagic, uflag] = typeof p === 'string'
2681
- ? AST.#parseGlob(p, this.#hasMagic, noEmpty)
2682
- : p.toRegExpSource(allowDot);
2683
- this.#hasMagic = this.#hasMagic || hasMagic;
2684
- this.#uflag = this.#uflag || uflag;
2685
- return re;
2686
- })
2687
- .join('');
2688
- let start = '';
2689
- if (this.isStart()) {
2690
- if (typeof this.#parts[0] === 'string') {
2691
- // this is the string that will match the start of the pattern,
2692
- // so we need to protect against dots and such.
2693
- // '.' and '..' cannot match unless the pattern is that exactly,
2694
- // even if it starts with . or dot:true is set.
2695
- const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
2696
- if (!dotTravAllowed) {
2697
- const aps = addPatternStart;
2698
- // check if we have a possibility of matching . or ..,
2699
- // and prevent that.
2700
- const needNoTrav =
2701
- // dots are allowed, and the pattern starts with [ or .
2702
- (dot && aps.has(src.charAt(0))) ||
2703
- // the pattern starts with \., and then [ or .
2704
- (src.startsWith('\\.') && aps.has(src.charAt(2))) ||
2705
- // the pattern starts with \.\., and then [ or .
2706
- (src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
2707
- // no need to prevent dots if it can't match a dot, or if a
2708
- // sub-pattern will be preventing it anyway.
2709
- const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
2710
- start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
2711
- }
2712
- }
2713
- }
2714
- // append the "end of path portion" pattern to negation tails
2715
- let end = '';
2716
- if (this.isEnd() &&
2717
- this.#root.#filledNegs &&
2718
- this.#parent?.type === '!') {
2719
- end = '(?:$|\\/)';
2720
- }
2721
- const final = start + src + end;
2722
- return [
2723
- final,
2724
- unescape(src),
2725
- (this.#hasMagic = !!this.#hasMagic),
2726
- this.#uflag,
2727
- ];
2728
- }
2729
- // We need to calculate the body *twice* if it's a repeat pattern
2730
- // at the start, once in nodot mode, then again in dot mode, so a
2731
- // pattern like *(?) can match 'x.y'
2732
- const repeated = this.type === '*' || this.type === '+';
2733
- // some kind of extglob
2734
- const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
2735
- let body = this.#partsToRegExp(dot);
2736
- if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
2737
- // invalid extglob, has to at least be *something* present, if it's
2738
- // the entire path portion.
2739
- const s = this.toString();
2740
- this.#parts = [s];
2741
- this.type = null;
2742
- this.#hasMagic = undefined;
2743
- return [s, unescape(this.toString()), false, false];
2744
- }
2745
- // XXX abstract out this map method
2746
- let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
2747
- ? ''
2748
- : this.#partsToRegExp(true);
2749
- if (bodyDotAllowed === body) {
2750
- bodyDotAllowed = '';
2751
- }
2752
- if (bodyDotAllowed) {
2753
- body = `(?:${body})(?:${bodyDotAllowed})*?`;
2754
- }
2755
- // an empty !() is exactly equivalent to a starNoEmpty
2756
- let final = '';
2757
- if (this.type === '!' && this.#emptyExt) {
2758
- final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
2759
- }
2760
- else {
2761
- const close = this.type === '!'
2762
- ? // !() must match something,but !(x) can match ''
2763
- '))' +
2764
- (this.isStart() && !dot && !allowDot ? startNoDot : '') +
2765
- star$1 +
2766
- ')'
2767
- : this.type === '@'
2768
- ? ')'
2769
- : this.type === '?'
2770
- ? ')?'
2771
- : this.type === '+' && bodyDotAllowed
2772
- ? ')'
2773
- : this.type === '*' && bodyDotAllowed
2774
- ? `)?`
2775
- : `)${this.type}`;
2776
- final = start + body + close;
2777
- }
2778
- return [
2779
- final,
2780
- unescape(body),
2781
- (this.#hasMagic = !!this.#hasMagic),
2782
- this.#uflag,
2783
- ];
2784
- }
2785
- #partsToRegExp(dot) {
2786
- return this.#parts
2787
- .map(p => {
2788
- // extglob ASTs should only contain parent ASTs
2789
- /* c8 ignore start */
2790
- if (typeof p === 'string') {
2791
- throw new Error('string type in extglob ast??');
2792
- }
2793
- /* c8 ignore stop */
2794
- // can ignore hasMagic, because extglobs are already always magic
2795
- const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
2796
- this.#uflag = this.#uflag || uflag;
2797
- return re;
2798
- })
2799
- .filter(p => !(this.isStart() && this.isEnd()) || !!p)
2800
- .join('|');
2801
- }
2802
- static #parseGlob(glob, hasMagic, noEmpty = false) {
2803
- let escaping = false;
2804
- let re = '';
2805
- let uflag = false;
2806
- for (let i = 0; i < glob.length; i++) {
2807
- const c = glob.charAt(i);
2808
- if (escaping) {
2809
- escaping = false;
2810
- re += (reSpecials.has(c) ? '\\' : '') + c;
2811
- continue;
2812
- }
2813
- if (c === '\\') {
2814
- if (i === glob.length - 1) {
2815
- re += '\\\\';
2816
- }
2817
- else {
2818
- escaping = true;
2819
- }
2820
- continue;
2821
- }
2822
- if (c === '[') {
2823
- const [src, needUflag, consumed, magic] = parseClass(glob, i);
2824
- if (consumed) {
2825
- re += src;
2826
- uflag = uflag || needUflag;
2827
- i += consumed - 1;
2828
- hasMagic = hasMagic || magic;
2829
- continue;
2830
- }
2831
- }
2832
- if (c === '*') {
2833
- if (noEmpty && glob === '*')
2834
- re += starNoEmpty;
2835
- else
2836
- re += star$1;
2837
- hasMagic = true;
2838
- continue;
2839
- }
2840
- if (c === '?') {
2841
- re += qmark$1;
2842
- hasMagic = true;
2843
- continue;
2844
- }
2845
- re += regExpEscape$1(c);
2846
- }
2847
- return [re, unescape(glob), !!hasMagic, uflag];
2848
- }
2849
- }
2850
-
2851
- /**
2852
- * Escape all magic characters in a glob pattern.
2853
- *
2854
- * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
2855
- * option is used, then characters are escaped by wrapping in `[]`, because
2856
- * a magic character wrapped in a character class can only be satisfied by
2857
- * that exact character. In this mode, `\` is _not_ escaped, because it is
2858
- * not interpreted as a magic character, but instead as a path separator.
2859
- */
2860
- const escape = (s, { windowsPathsNoEscape = false, } = {}) => {
2861
- // don't need to escape +@! because we escape the parens
2862
- // that make those magic, and escaping ! as [!] isn't valid,
2863
- // because [!]] is a valid glob class meaning not ']'.
2864
- return windowsPathsNoEscape
2865
- ? s.replace(/[?*()[\]]/g, '[$&]')
2866
- : s.replace(/[?*()[\]\\]/g, '\\$&');
733
+ //#endregion
734
+ //#region src/index.ts
735
+ const defaultDelimiters = ["{{", "}}"];
736
+ var ProstoRewrite = class {
737
+ options;
738
+ _mixedRewriter;
739
+ _textRewriter;
740
+ _htmlRewriter;
741
+ constructor(options) {
742
+ this.options = {
743
+ defaultMode: options?.defaultMode || "auto",
744
+ debug: options?.debug || false,
745
+ htmlPattern: __NODE_JS__ ? (options?.htmlPattern || ["*.{html,xhtml,xml,svg}"]).map((p) => new Minimatch(p, { matchBase: true })) : [],
746
+ textPattern: __NODE_JS__ ? (options?.textPattern || [
747
+ "*.{js,jsx,ts,tsx,txt,json,yml,yaml,md,ini}",
748
+ "Dockerfile",
749
+ "*config",
750
+ ".gitignore"
751
+ ]).map((p) => new Minimatch(p, { matchBase: true })) : [],
752
+ html: {
753
+ exprDelimiters: defaultDelimiters,
754
+ attrExpression: ":",
755
+ blockOperation: "v-",
756
+ directive: "!@",
757
+ voidTags: options?.html?.voidTags || htmlVoidTags,
758
+ textTags: options?.html?.textTags || htmlTextTags,
759
+ ...options?.html
760
+ },
761
+ text: {
762
+ exprDelimiters: defaultDelimiters,
763
+ blockOperation: "=",
764
+ revealLine: ":",
765
+ directive: "!@",
766
+ ...options?.text
767
+ }
768
+ };
769
+ }
770
+ get mixedRewriter() {
771
+ if (!this._mixedRewriter) {
772
+ const textNodes = getTextParser(this.options.text, true);
773
+ const htmlNodes = getHtmlParser(this.options.html, true);
774
+ textNodes.htmlDirectiveNode.recognize(...htmlNodes.rootNode.recognizes);
775
+ htmlNodes.textDirectiveNode.recognize(...textNodes.rootNode.recognizes);
776
+ this._mixedRewriter = {
777
+ text: getRewriter(textNodes.rootNode, this.options.debug),
778
+ html: getRewriter(htmlNodes.rootNode, this.options.debug)
779
+ };
780
+ }
781
+ return this._mixedRewriter;
782
+ }
783
+ get textRewriter() {
784
+ if (!this._textRewriter) this._textRewriter = getTextRewriter(this.options.text, this.options.debug);
785
+ return this._textRewriter;
786
+ }
787
+ get htmlRewriter() {
788
+ if (!this._htmlRewriter) this._htmlRewriter = getHtmlRewriter(this.options.html, this.options.debug);
789
+ return this._htmlRewriter;
790
+ }
791
+ async rewriteFile(opts, context) {
792
+ const file = await readFile(opts.input);
793
+ const mode = this.determineMode(opts.mode || this.options.defaultMode, opts.input, file);
794
+ let output = file;
795
+ if (mode) {
796
+ this.debug("Parsing file in " + mode + " mode. " + __DYE_UNDERSCORE__ + __DYE_BOLD_OFF__ + opts.input);
797
+ output = this.mixedRewriter[mode].rewrite(file, context);
798
+ } else this.debug("File isn't recognized as text nor as html. " + __DYE_UNDERSCORE__ + __DYE_BOLD_OFF__ + opts.input);
799
+ if (opts.output) if (mode) {
800
+ await writeFile(opts.output, output);
801
+ this.debug("File has been rewritten in " + mode + " mode. " + __DYE_UNDERSCORE__ + __DYE_BOLD_OFF__ + opts.output);
802
+ } else {
803
+ await copyFile(opts.input, opts.output);
804
+ this.debug("File rewriting was skipped. File copied. " + __DYE_UNDERSCORE__ + __DYE_BOLD_OFF__ + opts.output);
805
+ }
806
+ return output;
807
+ }
808
+ async rewriteDir(opts, context) {
809
+ if (__BROWSER__) return;
810
+ const files = await readDir(opts.baseDir);
811
+ const dirPath = await pathResolve(opts.baseDir);
812
+ const include = opts.include && opts.include.length ? opts.include.map((s) => new Minimatch(s, { matchBase: true })) : null;
813
+ const exclude = opts.exclude && opts.exclude.length ? opts.exclude.map((s) => new Minimatch(s, { matchBase: true })) : null;
814
+ const rename = opts.renameFile || ((f) => f);
815
+ for await (const filePath of files) {
816
+ let included = true;
817
+ let excluded = false;
818
+ if (include) included = !!include.find((m) => m.match(filePath));
819
+ if (exclude && included) excluded = !!exclude.find((m) => m.match(filePath));
820
+ if (!included || excluded) continue;
821
+ const relativeFilePath = rename(filePath.slice(dirPath.length + 1));
822
+ let targetPath;
823
+ if (opts.output) targetPath = await pathJoin(opts.output, relativeFilePath);
824
+ const output = await this.rewriteFile({
825
+ mode: opts.mode,
826
+ input: filePath,
827
+ output: targetPath
828
+ }, context);
829
+ if (opts.onFile) opts.onFile(filePath, output);
830
+ }
831
+ }
832
+ determineMode(mode, path, content) {
833
+ if (mode === "text") return "text";
834
+ if (mode === "html") return "html";
835
+ if (mode === "auto") {
836
+ const isText = !!this.options.textPattern.find((m) => m.match(path));
837
+ const isHtml = !!this.options.htmlPattern.find((m) => m.match(path));
838
+ if (isText && isHtml) {
839
+ if (/^<!DOCTYPE\s/.test(content)) return "html";
840
+ if (/^<\?xml\s/.test(content)) return "html";
841
+ return "text";
842
+ }
843
+ if (isText) return "text";
844
+ if (isHtml) return "html";
845
+ }
846
+ }
847
+ debug(message) {
848
+ if (!this.options.debug) return;
849
+ debug(message);
850
+ }
2867
851
  };
2868
-
2869
- const minimatch = (p, pattern, options = {}) => {
2870
- assertValidPattern(pattern);
2871
- // shortcut: comments match nothing.
2872
- if (!options.nocomment && pattern.charAt(0) === '#') {
2873
- return false;
2874
- }
2875
- return new Minimatch(pattern, options).match(p);
2876
- };
2877
- // Optimized checking for the most common glob patterns.
2878
- const starDotExtRE = /^\*+([^+@!?\*\[\(]*)$/;
2879
- const starDotExtTest = (ext) => (f) => !f.startsWith('.') && f.endsWith(ext);
2880
- const starDotExtTestDot = (ext) => (f) => f.endsWith(ext);
2881
- const starDotExtTestNocase = (ext) => {
2882
- ext = ext.toLowerCase();
2883
- return (f) => !f.startsWith('.') && f.toLowerCase().endsWith(ext);
2884
- };
2885
- const starDotExtTestNocaseDot = (ext) => {
2886
- ext = ext.toLowerCase();
2887
- return (f) => f.toLowerCase().endsWith(ext);
2888
- };
2889
- const starDotStarRE = /^\*+\.\*+$/;
2890
- const starDotStarTest = (f) => !f.startsWith('.') && f.includes('.');
2891
- const starDotStarTestDot = (f) => f !== '.' && f !== '..' && f.includes('.');
2892
- const dotStarRE = /^\.\*+$/;
2893
- const dotStarTest = (f) => f !== '.' && f !== '..' && f.startsWith('.');
2894
- const starRE = /^\*+$/;
2895
- const starTest = (f) => f.length !== 0 && !f.startsWith('.');
2896
- const starTestDot = (f) => f.length !== 0 && f !== '.' && f !== '..';
2897
- const qmarksRE = /^\?+([^+@!?\*\[\(]*)?$/;
2898
- const qmarksTestNocase = ([$0, ext = '']) => {
2899
- const noext = qmarksTestNoExt([$0]);
2900
- if (!ext)
2901
- return noext;
2902
- ext = ext.toLowerCase();
2903
- return (f) => noext(f) && f.toLowerCase().endsWith(ext);
2904
- };
2905
- const qmarksTestNocaseDot = ([$0, ext = '']) => {
2906
- const noext = qmarksTestNoExtDot([$0]);
2907
- if (!ext)
2908
- return noext;
2909
- ext = ext.toLowerCase();
2910
- return (f) => noext(f) && f.toLowerCase().endsWith(ext);
2911
- };
2912
- const qmarksTestDot = ([$0, ext = '']) => {
2913
- const noext = qmarksTestNoExtDot([$0]);
2914
- return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
2915
- };
2916
- const qmarksTest = ([$0, ext = '']) => {
2917
- const noext = qmarksTestNoExt([$0]);
2918
- return !ext ? noext : (f) => noext(f) && f.endsWith(ext);
2919
- };
2920
- const qmarksTestNoExt = ([$0]) => {
2921
- const len = $0.length;
2922
- return (f) => f.length === len && !f.startsWith('.');
2923
- };
2924
- const qmarksTestNoExtDot = ([$0]) => {
2925
- const len = $0.length;
2926
- return (f) => f.length === len && f !== '.' && f !== '..';
2927
- };
2928
- /* c8 ignore start */
2929
- const defaultPlatform = (typeof process === 'object' && process
2930
- ? (typeof process.env === 'object' &&
2931
- process.env &&
2932
- process.env.__MINIMATCH_TESTING_PLATFORM__) ||
2933
- process.platform
2934
- : 'posix');
2935
- const path = {
2936
- win32: { sep: '\\' },
2937
- posix: { sep: '/' },
2938
- };
2939
- /* c8 ignore stop */
2940
- const sep = defaultPlatform === 'win32' ? path.win32.sep : path.posix.sep;
2941
- minimatch.sep = sep;
2942
- const GLOBSTAR = Symbol('globstar **');
2943
- minimatch.GLOBSTAR = GLOBSTAR;
2944
- // any single thing other than /
2945
- // don't need to escape / when using new RegExp()
2946
- const qmark = '[^/]';
2947
- // * => any number of characters
2948
- const star = qmark + '*?';
2949
- // ** when dots are allowed. Anything goes, except .. and .
2950
- // not (^ or / followed by one or two dots followed by $ or /),
2951
- // followed by anything, any number of times.
2952
- const twoStarDot = '(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?';
2953
- // not a ^ or / followed by a dot,
2954
- // followed by anything, any number of times.
2955
- const twoStarNoDot = '(?:(?!(?:\\/|^)\\.).)*?';
2956
- const filter = (pattern, options = {}) => (p) => minimatch(p, pattern, options);
2957
- minimatch.filter = filter;
2958
- const ext = (a, b = {}) => Object.assign({}, a, b);
2959
- const defaults = (def) => {
2960
- if (!def || typeof def !== 'object' || !Object.keys(def).length) {
2961
- return minimatch;
2962
- }
2963
- const orig = minimatch;
2964
- const m = (p, pattern, options = {}) => orig(p, pattern, ext(def, options));
2965
- return Object.assign(m, {
2966
- Minimatch: class Minimatch extends orig.Minimatch {
2967
- constructor(pattern, options = {}) {
2968
- super(pattern, ext(def, options));
2969
- }
2970
- static defaults(options) {
2971
- return orig.defaults(ext(def, options)).Minimatch;
2972
- }
2973
- },
2974
- AST: class AST extends orig.AST {
2975
- /* c8 ignore start */
2976
- constructor(type, parent, options = {}) {
2977
- super(type, parent, ext(def, options));
2978
- }
2979
- /* c8 ignore stop */
2980
- static fromGlob(pattern, options = {}) {
2981
- return orig.AST.fromGlob(pattern, ext(def, options));
2982
- }
2983
- },
2984
- unescape: (s, options = {}) => orig.unescape(s, ext(def, options)),
2985
- escape: (s, options = {}) => orig.escape(s, ext(def, options)),
2986
- filter: (pattern, options = {}) => orig.filter(pattern, ext(def, options)),
2987
- defaults: (options) => orig.defaults(ext(def, options)),
2988
- makeRe: (pattern, options = {}) => orig.makeRe(pattern, ext(def, options)),
2989
- braceExpand: (pattern, options = {}) => orig.braceExpand(pattern, ext(def, options)),
2990
- match: (list, pattern, options = {}) => orig.match(list, pattern, ext(def, options)),
2991
- sep: orig.sep,
2992
- GLOBSTAR: GLOBSTAR,
2993
- });
2994
- };
2995
- minimatch.defaults = defaults;
2996
- // Brace expansion:
2997
- // a{b,c}d -> abd acd
2998
- // a{b,}c -> abc ac
2999
- // a{0..3}d -> a0d a1d a2d a3d
3000
- // a{b,c{d,e}f}g -> abg acdfg acefg
3001
- // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
3002
- //
3003
- // Invalid sets are not expanded.
3004
- // a{2..}b -> a{2..}b
3005
- // a{b}c -> a{b}c
3006
- const braceExpand = (pattern, options = {}) => {
3007
- assertValidPattern(pattern);
3008
- // Thanks to Yeting Li <https://github.com/yetingli> for
3009
- // improving this regexp to avoid a ReDOS vulnerability.
3010
- if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
3011
- // shortcut. no need to expand.
3012
- return [pattern];
3013
- }
3014
- return expand$1(pattern);
3015
- };
3016
- minimatch.braceExpand = braceExpand;
3017
- // parse a component of the expanded set.
3018
- // At this point, no pattern may contain "/" in it
3019
- // so we're going to return a 2d array, where each entry is the full
3020
- // pattern, split on '/', and then turned into a regular expression.
3021
- // A regexp is made at the end which joins each array with an
3022
- // escaped /, and another full one which joins each regexp with |.
3023
- //
3024
- // Following the lead of Bash 4.1, note that "**" only has special meaning
3025
- // when it is the *only* thing in a path portion. Otherwise, any series
3026
- // of * is equivalent to a single *. Globstar behavior is enabled by
3027
- // default, and can be disabled by setting options.noglobstar.
3028
- const makeRe = (pattern, options = {}) => new Minimatch(pattern, options).makeRe();
3029
- minimatch.makeRe = makeRe;
3030
- const match = (list, pattern, options = {}) => {
3031
- const mm = new Minimatch(pattern, options);
3032
- list = list.filter(f => mm.match(f));
3033
- if (mm.options.nonull && !list.length) {
3034
- list.push(pattern);
3035
- }
3036
- return list;
3037
- };
3038
- minimatch.match = match;
3039
- // replace stuff like \* with *
3040
- const globMagic = /[?*]|[+@!]\(.*?\)|\[|\]/;
3041
- const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
3042
- class Minimatch {
3043
- options;
3044
- set;
3045
- pattern;
3046
- windowsPathsNoEscape;
3047
- nonegate;
3048
- negate;
3049
- comment;
3050
- empty;
3051
- preserveMultipleSlashes;
3052
- partial;
3053
- globSet;
3054
- globParts;
3055
- nocase;
3056
- isWindows;
3057
- platform;
3058
- windowsNoMagicRoot;
3059
- regexp;
3060
- constructor(pattern, options = {}) {
3061
- assertValidPattern(pattern);
3062
- options = options || {};
3063
- this.options = options;
3064
- this.pattern = pattern;
3065
- this.platform = options.platform || defaultPlatform;
3066
- this.isWindows = this.platform === 'win32';
3067
- this.windowsPathsNoEscape =
3068
- !!options.windowsPathsNoEscape || options.allowWindowsEscape === false;
3069
- if (this.windowsPathsNoEscape) {
3070
- this.pattern = this.pattern.replace(/\\/g, '/');
3071
- }
3072
- this.preserveMultipleSlashes = !!options.preserveMultipleSlashes;
3073
- this.regexp = null;
3074
- this.negate = false;
3075
- this.nonegate = !!options.nonegate;
3076
- this.comment = false;
3077
- this.empty = false;
3078
- this.partial = !!options.partial;
3079
- this.nocase = !!this.options.nocase;
3080
- this.windowsNoMagicRoot =
3081
- options.windowsNoMagicRoot !== undefined
3082
- ? options.windowsNoMagicRoot
3083
- : !!(this.isWindows && this.nocase);
3084
- this.globSet = [];
3085
- this.globParts = [];
3086
- this.set = [];
3087
- // make the set of regexps etc.
3088
- this.make();
3089
- }
3090
- hasMagic() {
3091
- if (this.options.magicalBraces && this.set.length > 1) {
3092
- return true;
3093
- }
3094
- for (const pattern of this.set) {
3095
- for (const part of pattern) {
3096
- if (typeof part !== 'string')
3097
- return true;
3098
- }
3099
- }
3100
- return false;
3101
- }
3102
- debug(..._) { }
3103
- make() {
3104
- const pattern = this.pattern;
3105
- const options = this.options;
3106
- // empty patterns and comments match nothing.
3107
- if (!options.nocomment && pattern.charAt(0) === '#') {
3108
- this.comment = true;
3109
- return;
3110
- }
3111
- if (!pattern) {
3112
- this.empty = true;
3113
- return;
3114
- }
3115
- // step 1: figure out negation, etc.
3116
- this.parseNegate();
3117
- // step 2: expand braces
3118
- this.globSet = [...new Set(this.braceExpand())];
3119
- if (options.debug) {
3120
- this.debug = (...args) => console.error(...args);
3121
- }
3122
- this.debug(this.pattern, this.globSet);
3123
- // step 3: now we have a set, so turn each one into a series of
3124
- // path-portion matching patterns.
3125
- // These will be regexps, except in the case of "**", which is
3126
- // set to the GLOBSTAR object for globstar behavior,
3127
- // and will not contain any / characters
3128
- //
3129
- // First, we preprocess to make the glob pattern sets a bit simpler
3130
- // and deduped. There are some perf-killing patterns that can cause
3131
- // problems with a glob walk, but we can simplify them down a bit.
3132
- const rawGlobParts = this.globSet.map(s => this.slashSplit(s));
3133
- this.globParts = this.preprocess(rawGlobParts);
3134
- this.debug(this.pattern, this.globParts);
3135
- // glob --> regexps
3136
- let set = this.globParts.map((s, _, __) => {
3137
- if (this.isWindows && this.windowsNoMagicRoot) {
3138
- // check if it's a drive or unc path.
3139
- const isUNC = s[0] === '' &&
3140
- s[1] === '' &&
3141
- (s[2] === '?' || !globMagic.test(s[2])) &&
3142
- !globMagic.test(s[3]);
3143
- const isDrive = /^[a-z]:/i.test(s[0]);
3144
- if (isUNC) {
3145
- return [...s.slice(0, 4), ...s.slice(4).map(ss => this.parse(ss))];
3146
- }
3147
- else if (isDrive) {
3148
- return [s[0], ...s.slice(1).map(ss => this.parse(ss))];
3149
- }
3150
- }
3151
- return s.map(ss => this.parse(ss));
3152
- });
3153
- this.debug(this.pattern, set);
3154
- // filter out everything that didn't compile properly.
3155
- this.set = set.filter(s => s.indexOf(false) === -1);
3156
- // do not treat the ? in UNC paths as magic
3157
- if (this.isWindows) {
3158
- for (let i = 0; i < this.set.length; i++) {
3159
- const p = this.set[i];
3160
- if (p[0] === '' &&
3161
- p[1] === '' &&
3162
- this.globParts[i][2] === '?' &&
3163
- typeof p[3] === 'string' &&
3164
- /^[a-z]:$/i.test(p[3])) {
3165
- p[2] = '?';
3166
- }
3167
- }
3168
- }
3169
- this.debug(this.pattern, this.set);
3170
- }
3171
- // various transforms to equivalent pattern sets that are
3172
- // faster to process in a filesystem walk. The goal is to
3173
- // eliminate what we can, and push all ** patterns as far
3174
- // to the right as possible, even if it increases the number
3175
- // of patterns that we have to process.
3176
- preprocess(globParts) {
3177
- // if we're not in globstar mode, then turn all ** into *
3178
- if (this.options.noglobstar) {
3179
- for (let i = 0; i < globParts.length; i++) {
3180
- for (let j = 0; j < globParts[i].length; j++) {
3181
- if (globParts[i][j] === '**') {
3182
- globParts[i][j] = '*';
3183
- }
3184
- }
3185
- }
3186
- }
3187
- const { optimizationLevel = 1 } = this.options;
3188
- if (optimizationLevel >= 2) {
3189
- // aggressive optimization for the purpose of fs walking
3190
- globParts = this.firstPhasePreProcess(globParts);
3191
- globParts = this.secondPhasePreProcess(globParts);
3192
- }
3193
- else if (optimizationLevel >= 1) {
3194
- // just basic optimizations to remove some .. parts
3195
- globParts = this.levelOneOptimize(globParts);
3196
- }
3197
- else {
3198
- globParts = this.adjascentGlobstarOptimize(globParts);
3199
- }
3200
- return globParts;
3201
- }
3202
- // just get rid of adjascent ** portions
3203
- adjascentGlobstarOptimize(globParts) {
3204
- return globParts.map(parts => {
3205
- let gs = -1;
3206
- while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
3207
- let i = gs;
3208
- while (parts[i + 1] === '**') {
3209
- i++;
3210
- }
3211
- if (i !== gs) {
3212
- parts.splice(gs, i - gs);
3213
- }
3214
- }
3215
- return parts;
3216
- });
3217
- }
3218
- // get rid of adjascent ** and resolve .. portions
3219
- levelOneOptimize(globParts) {
3220
- return globParts.map(parts => {
3221
- parts = parts.reduce((set, part) => {
3222
- const prev = set[set.length - 1];
3223
- if (part === '**' && prev === '**') {
3224
- return set;
3225
- }
3226
- if (part === '..') {
3227
- if (prev && prev !== '..' && prev !== '.' && prev !== '**') {
3228
- set.pop();
3229
- return set;
3230
- }
3231
- }
3232
- set.push(part);
3233
- return set;
3234
- }, []);
3235
- return parts.length === 0 ? [''] : parts;
3236
- });
3237
- }
3238
- levelTwoFileOptimize(parts) {
3239
- if (!Array.isArray(parts)) {
3240
- parts = this.slashSplit(parts);
3241
- }
3242
- let didSomething = false;
3243
- do {
3244
- didSomething = false;
3245
- // <pre>/<e>/<rest> -> <pre>/<rest>
3246
- if (!this.preserveMultipleSlashes) {
3247
- for (let i = 1; i < parts.length - 1; i++) {
3248
- const p = parts[i];
3249
- // don't squeeze out UNC patterns
3250
- if (i === 1 && p === '' && parts[0] === '')
3251
- continue;
3252
- if (p === '.' || p === '') {
3253
- didSomething = true;
3254
- parts.splice(i, 1);
3255
- i--;
3256
- }
3257
- }
3258
- if (parts[0] === '.' &&
3259
- parts.length === 2 &&
3260
- (parts[1] === '.' || parts[1] === '')) {
3261
- didSomething = true;
3262
- parts.pop();
3263
- }
3264
- }
3265
- // <pre>/<p>/../<rest> -> <pre>/<rest>
3266
- let dd = 0;
3267
- while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
3268
- const p = parts[dd - 1];
3269
- if (p && p !== '.' && p !== '..' && p !== '**') {
3270
- didSomething = true;
3271
- parts.splice(dd - 1, 2);
3272
- dd -= 2;
3273
- }
3274
- }
3275
- } while (didSomething);
3276
- return parts.length === 0 ? [''] : parts;
3277
- }
3278
- // First phase: single-pattern processing
3279
- // <pre> is 1 or more portions
3280
- // <rest> is 1 or more portions
3281
- // <p> is any portion other than ., .., '', or **
3282
- // <e> is . or ''
3283
- //
3284
- // **/.. is *brutal* for filesystem walking performance, because
3285
- // it effectively resets the recursive walk each time it occurs,
3286
- // and ** cannot be reduced out by a .. pattern part like a regexp
3287
- // or most strings (other than .., ., and '') can be.
3288
- //
3289
- // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
3290
- // <pre>/<e>/<rest> -> <pre>/<rest>
3291
- // <pre>/<p>/../<rest> -> <pre>/<rest>
3292
- // **/**/<rest> -> **/<rest>
3293
- //
3294
- // **/*/<rest> -> */**/<rest> <== not valid because ** doesn't follow
3295
- // this WOULD be allowed if ** did follow symlinks, or * didn't
3296
- firstPhasePreProcess(globParts) {
3297
- let didSomething = false;
3298
- do {
3299
- didSomething = false;
3300
- // <pre>/**/../<p>/<p>/<rest> -> {<pre>/../<p>/<p>/<rest>,<pre>/**/<p>/<p>/<rest>}
3301
- for (let parts of globParts) {
3302
- let gs = -1;
3303
- while (-1 !== (gs = parts.indexOf('**', gs + 1))) {
3304
- let gss = gs;
3305
- while (parts[gss + 1] === '**') {
3306
- // <pre>/**/**/<rest> -> <pre>/**/<rest>
3307
- gss++;
3308
- }
3309
- // eg, if gs is 2 and gss is 4, that means we have 3 **
3310
- // parts, and can remove 2 of them.
3311
- if (gss > gs) {
3312
- parts.splice(gs + 1, gss - gs);
3313
- }
3314
- let next = parts[gs + 1];
3315
- const p = parts[gs + 2];
3316
- const p2 = parts[gs + 3];
3317
- if (next !== '..')
3318
- continue;
3319
- if (!p ||
3320
- p === '.' ||
3321
- p === '..' ||
3322
- !p2 ||
3323
- p2 === '.' ||
3324
- p2 === '..') {
3325
- continue;
3326
- }
3327
- didSomething = true;
3328
- // edit parts in place, and push the new one
3329
- parts.splice(gs, 1);
3330
- const other = parts.slice(0);
3331
- other[gs] = '**';
3332
- globParts.push(other);
3333
- gs--;
3334
- }
3335
- // <pre>/<e>/<rest> -> <pre>/<rest>
3336
- if (!this.preserveMultipleSlashes) {
3337
- for (let i = 1; i < parts.length - 1; i++) {
3338
- const p = parts[i];
3339
- // don't squeeze out UNC patterns
3340
- if (i === 1 && p === '' && parts[0] === '')
3341
- continue;
3342
- if (p === '.' || p === '') {
3343
- didSomething = true;
3344
- parts.splice(i, 1);
3345
- i--;
3346
- }
3347
- }
3348
- if (parts[0] === '.' &&
3349
- parts.length === 2 &&
3350
- (parts[1] === '.' || parts[1] === '')) {
3351
- didSomething = true;
3352
- parts.pop();
3353
- }
3354
- }
3355
- // <pre>/<p>/../<rest> -> <pre>/<rest>
3356
- let dd = 0;
3357
- while (-1 !== (dd = parts.indexOf('..', dd + 1))) {
3358
- const p = parts[dd - 1];
3359
- if (p && p !== '.' && p !== '..' && p !== '**') {
3360
- didSomething = true;
3361
- const needDot = dd === 1 && parts[dd + 1] === '**';
3362
- const splin = needDot ? ['.'] : [];
3363
- parts.splice(dd - 1, 2, ...splin);
3364
- if (parts.length === 0)
3365
- parts.push('');
3366
- dd -= 2;
3367
- }
3368
- }
3369
- }
3370
- } while (didSomething);
3371
- return globParts;
3372
- }
3373
- // second phase: multi-pattern dedupes
3374
- // {<pre>/*/<rest>,<pre>/<p>/<rest>} -> <pre>/*/<rest>
3375
- // {<pre>/<rest>,<pre>/<rest>} -> <pre>/<rest>
3376
- // {<pre>/**/<rest>,<pre>/<rest>} -> <pre>/**/<rest>
3377
- //
3378
- // {<pre>/**/<rest>,<pre>/**/<p>/<rest>} -> <pre>/**/<rest>
3379
- // ^-- not valid because ** doens't follow symlinks
3380
- secondPhasePreProcess(globParts) {
3381
- for (let i = 0; i < globParts.length - 1; i++) {
3382
- for (let j = i + 1; j < globParts.length; j++) {
3383
- const matched = this.partsMatch(globParts[i], globParts[j], !this.preserveMultipleSlashes);
3384
- if (!matched)
3385
- continue;
3386
- globParts[i] = matched;
3387
- globParts[j] = [];
3388
- }
3389
- }
3390
- return globParts.filter(gs => gs.length);
3391
- }
3392
- partsMatch(a, b, emptyGSMatch = false) {
3393
- let ai = 0;
3394
- let bi = 0;
3395
- let result = [];
3396
- let which = '';
3397
- while (ai < a.length && bi < b.length) {
3398
- if (a[ai] === b[bi]) {
3399
- result.push(which === 'b' ? b[bi] : a[ai]);
3400
- ai++;
3401
- bi++;
3402
- }
3403
- else if (emptyGSMatch && a[ai] === '**' && b[bi] === a[ai + 1]) {
3404
- result.push(a[ai]);
3405
- ai++;
3406
- }
3407
- else if (emptyGSMatch && b[bi] === '**' && a[ai] === b[bi + 1]) {
3408
- result.push(b[bi]);
3409
- bi++;
3410
- }
3411
- else if (a[ai] === '*' &&
3412
- b[bi] &&
3413
- (this.options.dot || !b[bi].startsWith('.')) &&
3414
- b[bi] !== '**') {
3415
- if (which === 'b')
3416
- return false;
3417
- which = 'a';
3418
- result.push(a[ai]);
3419
- ai++;
3420
- bi++;
3421
- }
3422
- else if (b[bi] === '*' &&
3423
- a[ai] &&
3424
- (this.options.dot || !a[ai].startsWith('.')) &&
3425
- a[ai] !== '**') {
3426
- if (which === 'a')
3427
- return false;
3428
- which = 'b';
3429
- result.push(b[bi]);
3430
- ai++;
3431
- bi++;
3432
- }
3433
- else {
3434
- return false;
3435
- }
3436
- }
3437
- // if we fall out of the loop, it means they two are identical
3438
- // as long as their lengths match
3439
- return a.length === b.length && result;
3440
- }
3441
- parseNegate() {
3442
- if (this.nonegate)
3443
- return;
3444
- const pattern = this.pattern;
3445
- let negate = false;
3446
- let negateOffset = 0;
3447
- for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
3448
- negate = !negate;
3449
- negateOffset++;
3450
- }
3451
- if (negateOffset)
3452
- this.pattern = pattern.slice(negateOffset);
3453
- this.negate = negate;
3454
- }
3455
- // set partial to true to test if, for example,
3456
- // "/a/b" matches the start of "/*/b/*/d"
3457
- // Partial means, if you run out of file before you run
3458
- // out of pattern, then that's fine, as long as all
3459
- // the parts match.
3460
- matchOne(file, pattern, partial = false) {
3461
- const options = this.options;
3462
- // UNC paths like //?/X:/... can match X:/... and vice versa
3463
- // Drive letters in absolute drive or unc paths are always compared
3464
- // case-insensitively.
3465
- if (this.isWindows) {
3466
- const fileDrive = typeof file[0] === 'string' && /^[a-z]:$/i.test(file[0]);
3467
- const fileUNC = !fileDrive &&
3468
- file[0] === '' &&
3469
- file[1] === '' &&
3470
- file[2] === '?' &&
3471
- /^[a-z]:$/i.test(file[3]);
3472
- const patternDrive = typeof pattern[0] === 'string' && /^[a-z]:$/i.test(pattern[0]);
3473
- const patternUNC = !patternDrive &&
3474
- pattern[0] === '' &&
3475
- pattern[1] === '' &&
3476
- pattern[2] === '?' &&
3477
- typeof pattern[3] === 'string' &&
3478
- /^[a-z]:$/i.test(pattern[3]);
3479
- const fdi = fileUNC ? 3 : fileDrive ? 0 : undefined;
3480
- const pdi = patternUNC ? 3 : patternDrive ? 0 : undefined;
3481
- if (typeof fdi === 'number' && typeof pdi === 'number') {
3482
- const [fd, pd] = [file[fdi], pattern[pdi]];
3483
- if (fd.toLowerCase() === pd.toLowerCase()) {
3484
- pattern[pdi] = fd;
3485
- if (pdi > fdi) {
3486
- pattern = pattern.slice(pdi);
3487
- }
3488
- else if (fdi > pdi) {
3489
- file = file.slice(fdi);
3490
- }
3491
- }
3492
- }
3493
- }
3494
- // resolve and reduce . and .. portions in the file as well.
3495
- // dont' need to do the second phase, because it's only one string[]
3496
- const { optimizationLevel = 1 } = this.options;
3497
- if (optimizationLevel >= 2) {
3498
- file = this.levelTwoFileOptimize(file);
3499
- }
3500
- this.debug('matchOne', this, { file, pattern });
3501
- this.debug('matchOne', file.length, pattern.length);
3502
- for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) {
3503
- this.debug('matchOne loop');
3504
- var p = pattern[pi];
3505
- var f = file[fi];
3506
- this.debug(pattern, p, f);
3507
- // should be impossible.
3508
- // some invalid regexp stuff in the set.
3509
- /* c8 ignore start */
3510
- if (p === false) {
3511
- return false;
3512
- }
3513
- /* c8 ignore stop */
3514
- if (p === GLOBSTAR) {
3515
- this.debug('GLOBSTAR', [pattern, p, f]);
3516
- // "**"
3517
- // a/**/b/**/c would match the following:
3518
- // a/b/x/y/z/c
3519
- // a/x/y/z/b/c
3520
- // a/b/x/b/x/c
3521
- // a/b/c
3522
- // To do this, take the rest of the pattern after
3523
- // the **, and see if it would match the file remainder.
3524
- // If so, return success.
3525
- // If not, the ** "swallows" a segment, and try again.
3526
- // This is recursively awful.
3527
- //
3528
- // a/**/b/**/c matching a/b/x/y/z/c
3529
- // - a matches a
3530
- // - doublestar
3531
- // - matchOne(b/x/y/z/c, b/**/c)
3532
- // - b matches b
3533
- // - doublestar
3534
- // - matchOne(x/y/z/c, c) -> no
3535
- // - matchOne(y/z/c, c) -> no
3536
- // - matchOne(z/c, c) -> no
3537
- // - matchOne(c, c) yes, hit
3538
- var fr = fi;
3539
- var pr = pi + 1;
3540
- if (pr === pl) {
3541
- this.debug('** at the end');
3542
- // a ** at the end will just swallow the rest.
3543
- // We have found a match.
3544
- // however, it will not swallow /.x, unless
3545
- // options.dot is set.
3546
- // . and .. are *never* matched by **, for explosively
3547
- // exponential reasons.
3548
- for (; fi < fl; fi++) {
3549
- if (file[fi] === '.' ||
3550
- file[fi] === '..' ||
3551
- (!options.dot && file[fi].charAt(0) === '.'))
3552
- return false;
3553
- }
3554
- return true;
3555
- }
3556
- // ok, let's see if we can swallow whatever we can.
3557
- while (fr < fl) {
3558
- var swallowee = file[fr];
3559
- this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
3560
- // XXX remove this slice. Just pass the start index.
3561
- if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
3562
- this.debug('globstar found match!', fr, fl, swallowee);
3563
- // found a match.
3564
- return true;
3565
- }
3566
- else {
3567
- // can't swallow "." or ".." ever.
3568
- // can only swallow ".foo" when explicitly asked.
3569
- if (swallowee === '.' ||
3570
- swallowee === '..' ||
3571
- (!options.dot && swallowee.charAt(0) === '.')) {
3572
- this.debug('dot detected!', file, fr, pattern, pr);
3573
- break;
3574
- }
3575
- // ** swallows a segment, and continue.
3576
- this.debug('globstar swallow a segment, and continue');
3577
- fr++;
3578
- }
3579
- }
3580
- // no match was found.
3581
- // However, in partial mode, we can't say this is necessarily over.
3582
- /* c8 ignore start */
3583
- if (partial) {
3584
- // ran out of file
3585
- this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
3586
- if (fr === fl) {
3587
- return true;
3588
- }
3589
- }
3590
- /* c8 ignore stop */
3591
- return false;
3592
- }
3593
- // something other than **
3594
- // non-magic patterns just have to match exactly
3595
- // patterns with magic have been turned into regexps.
3596
- let hit;
3597
- if (typeof p === 'string') {
3598
- hit = f === p;
3599
- this.debug('string match', p, f, hit);
3600
- }
3601
- else {
3602
- hit = p.test(f);
3603
- this.debug('pattern match', p, f, hit);
3604
- }
3605
- if (!hit)
3606
- return false;
3607
- }
3608
- // Note: ending in / means that we'll get a final ""
3609
- // at the end of the pattern. This can only match a
3610
- // corresponding "" at the end of the file.
3611
- // If the file ends in /, then it can only match a
3612
- // a pattern that ends in /, unless the pattern just
3613
- // doesn't have any more for it. But, a/b/ should *not*
3614
- // match "a/b/*", even though "" matches against the
3615
- // [^/]*? pattern, except in partial mode, where it might
3616
- // simply not be reached yet.
3617
- // However, a/b/ should still satisfy a/*
3618
- // now either we fell off the end of the pattern, or we're done.
3619
- if (fi === fl && pi === pl) {
3620
- // ran out of pattern and filename at the same time.
3621
- // an exact hit!
3622
- return true;
3623
- }
3624
- else if (fi === fl) {
3625
- // ran out of file, but still had pattern left.
3626
- // this is ok if we're doing the match as part of
3627
- // a glob fs traversal.
3628
- return partial;
3629
- }
3630
- else if (pi === pl) {
3631
- // ran out of pattern, still have file left.
3632
- // this is only acceptable if we're on the very last
3633
- // empty segment of a file with a trailing slash.
3634
- // a/* should match a/b/
3635
- return fi === fl - 1 && file[fi] === '';
3636
- /* c8 ignore start */
3637
- }
3638
- else {
3639
- // should be unreachable.
3640
- throw new Error('wtf?');
3641
- }
3642
- /* c8 ignore stop */
3643
- }
3644
- braceExpand() {
3645
- return braceExpand(this.pattern, this.options);
3646
- }
3647
- parse(pattern) {
3648
- assertValidPattern(pattern);
3649
- const options = this.options;
3650
- // shortcuts
3651
- if (pattern === '**')
3652
- return GLOBSTAR;
3653
- if (pattern === '')
3654
- return '';
3655
- // far and away, the most common glob pattern parts are
3656
- // *, *.*, and *.<ext> Add a fast check method for those.
3657
- let m;
3658
- let fastTest = null;
3659
- if ((m = pattern.match(starRE))) {
3660
- fastTest = options.dot ? starTestDot : starTest;
3661
- }
3662
- else if ((m = pattern.match(starDotExtRE))) {
3663
- fastTest = (options.nocase
3664
- ? options.dot
3665
- ? starDotExtTestNocaseDot
3666
- : starDotExtTestNocase
3667
- : options.dot
3668
- ? starDotExtTestDot
3669
- : starDotExtTest)(m[1]);
3670
- }
3671
- else if ((m = pattern.match(qmarksRE))) {
3672
- fastTest = (options.nocase
3673
- ? options.dot
3674
- ? qmarksTestNocaseDot
3675
- : qmarksTestNocase
3676
- : options.dot
3677
- ? qmarksTestDot
3678
- : qmarksTest)(m);
3679
- }
3680
- else if ((m = pattern.match(starDotStarRE))) {
3681
- fastTest = options.dot ? starDotStarTestDot : starDotStarTest;
3682
- }
3683
- else if ((m = pattern.match(dotStarRE))) {
3684
- fastTest = dotStarTest;
3685
- }
3686
- const re = AST.fromGlob(pattern, this.options).toMMPattern();
3687
- return fastTest ? Object.assign(re, { test: fastTest }) : re;
3688
- }
3689
- makeRe() {
3690
- if (this.regexp || this.regexp === false)
3691
- return this.regexp;
3692
- // at this point, this.set is a 2d array of partial
3693
- // pattern strings, or "**".
3694
- //
3695
- // It's better to use .match(). This function shouldn't
3696
- // be used, really, but it's pretty convenient sometimes,
3697
- // when you just want to work with a regex.
3698
- const set = this.set;
3699
- if (!set.length) {
3700
- this.regexp = false;
3701
- return this.regexp;
3702
- }
3703
- const options = this.options;
3704
- const twoStar = options.noglobstar
3705
- ? star
3706
- : options.dot
3707
- ? twoStarDot
3708
- : twoStarNoDot;
3709
- const flags = new Set(options.nocase ? ['i'] : []);
3710
- // regexpify non-globstar patterns
3711
- // if ** is only item, then we just do one twoStar
3712
- // if ** is first, and there are more, prepend (\/|twoStar\/)? to next
3713
- // if ** is last, append (\/twoStar|) to previous
3714
- // if ** is in the middle, append (\/|\/twoStar\/) to previous
3715
- // then filter out GLOBSTAR symbols
3716
- let re = set
3717
- .map(pattern => {
3718
- const pp = pattern.map(p => {
3719
- if (p instanceof RegExp) {
3720
- for (const f of p.flags.split(''))
3721
- flags.add(f);
3722
- }
3723
- return typeof p === 'string'
3724
- ? regExpEscape(p)
3725
- : p === GLOBSTAR
3726
- ? GLOBSTAR
3727
- : p._src;
3728
- });
3729
- pp.forEach((p, i) => {
3730
- const next = pp[i + 1];
3731
- const prev = pp[i - 1];
3732
- if (p !== GLOBSTAR || prev === GLOBSTAR) {
3733
- return;
3734
- }
3735
- if (prev === undefined) {
3736
- if (next !== undefined && next !== GLOBSTAR) {
3737
- pp[i + 1] = '(?:\\/|' + twoStar + '\\/)?' + next;
3738
- }
3739
- else {
3740
- pp[i] = twoStar;
3741
- }
3742
- }
3743
- else if (next === undefined) {
3744
- pp[i - 1] = prev + '(?:\\/|' + twoStar + ')?';
3745
- }
3746
- else if (next !== GLOBSTAR) {
3747
- pp[i - 1] = prev + '(?:\\/|\\/' + twoStar + '\\/)' + next;
3748
- pp[i + 1] = GLOBSTAR;
3749
- }
3750
- });
3751
- return pp.filter(p => p !== GLOBSTAR).join('/');
3752
- })
3753
- .join('|');
3754
- // need to wrap in parens if we had more than one thing with |,
3755
- // otherwise only the first will be anchored to ^ and the last to $
3756
- const [open, close] = set.length > 1 ? ['(?:', ')'] : ['', ''];
3757
- // must match entire pattern
3758
- // ending in a * or ** will make it less strict.
3759
- re = '^' + open + re + close + '$';
3760
- // can match anything, as long as it's not this.
3761
- if (this.negate)
3762
- re = '^(?!' + re + ').+$';
3763
- try {
3764
- this.regexp = new RegExp(re, [...flags].join(''));
3765
- /* c8 ignore start */
3766
- }
3767
- catch (ex) {
3768
- // should be impossible
3769
- this.regexp = false;
3770
- }
3771
- /* c8 ignore stop */
3772
- return this.regexp;
3773
- }
3774
- slashSplit(p) {
3775
- // if p starts with // on windows, we preserve that
3776
- // so that UNC paths aren't broken. Otherwise, any number of
3777
- // / characters are coalesced into one, unless
3778
- // preserveMultipleSlashes is set to true.
3779
- if (this.preserveMultipleSlashes) {
3780
- return p.split('/');
3781
- }
3782
- else if (this.isWindows && /^\/\/[^\/]+/.test(p)) {
3783
- // add an extra '' for the one we lose
3784
- return ['', ...p.split(/\/+/)];
3785
- }
3786
- else {
3787
- return p.split(/\/+/);
3788
- }
3789
- }
3790
- match(f, partial = this.partial) {
3791
- this.debug('match', f, this.pattern);
3792
- // short-circuit in the case of busted things.
3793
- // comments, etc.
3794
- if (this.comment) {
3795
- return false;
3796
- }
3797
- if (this.empty) {
3798
- return f === '';
3799
- }
3800
- if (f === '/' && partial) {
3801
- return true;
3802
- }
3803
- const options = this.options;
3804
- // windows: need to use /, not \
3805
- if (this.isWindows) {
3806
- f = f.split('\\').join('/');
3807
- }
3808
- // treat the test path as a set of pathparts.
3809
- const ff = this.slashSplit(f);
3810
- this.debug(this.pattern, 'split', ff);
3811
- // just ONE of the pattern sets in this.set needs to match
3812
- // in order for it to be valid. If negating, then just one
3813
- // match means that we have failed.
3814
- // Either way, return on the first hit.
3815
- const set = this.set;
3816
- this.debug(this.pattern, 'set', set);
3817
- // Find the basename of the path by looking for the last non-empty segment
3818
- let filename = ff[ff.length - 1];
3819
- if (!filename) {
3820
- for (let i = ff.length - 2; !filename && i >= 0; i--) {
3821
- filename = ff[i];
3822
- }
3823
- }
3824
- for (let i = 0; i < set.length; i++) {
3825
- const pattern = set[i];
3826
- let file = ff;
3827
- if (options.matchBase && pattern.length === 1) {
3828
- file = [filename];
3829
- }
3830
- const hit = this.matchOne(file, pattern, partial);
3831
- if (hit) {
3832
- if (options.flipNegate) {
3833
- return true;
3834
- }
3835
- return !this.negate;
3836
- }
3837
- }
3838
- // didn't get any hits. this is success if it's a negative
3839
- // pattern, failure otherwise.
3840
- if (options.flipNegate) {
3841
- return false;
3842
- }
3843
- return this.negate;
3844
- }
3845
- static defaults(def) {
3846
- return minimatch.defaults(def).Minimatch;
3847
- }
3848
- }
3849
- /* c8 ignore stop */
3850
- minimatch.AST = AST;
3851
- minimatch.Minimatch = Minimatch;
3852
- minimatch.escape = escape;
3853
- minimatch.unescape = unescape;
3854
-
3855
- const defaultDelimeters = ['{{', '}}'];
3856
- class ProstoRewrite {
3857
- constructor(options) {
3858
- var _a, _b;
3859
- this.options = {
3860
- defaultMode: (options === null || options === void 0 ? void 0 : options.defaultMode) || 'auto',
3861
- debug: (options === null || options === void 0 ? void 0 : options.debug) || false,
3862
- htmlPattern: __NODE_JS__ ? ((options === null || options === void 0 ? void 0 : options.htmlPattern) || ['*.{html,xhtml,xml,svg}']).map(p => new Minimatch(p, { matchBase: true })) : [],
3863
- textPattern: __NODE_JS__ ? ((options === null || options === void 0 ? void 0 : options.textPattern) || [
3864
- '*.{js,jsx,ts,tsx,txt,json,yml,yaml,md,ini}',
3865
- 'Dockerfile',
3866
- '*config',
3867
- '.gitignore',
3868
- ]).map(p => new Minimatch(p, { matchBase: true })) : [],
3869
- html: {
3870
- exprDelimeters: defaultDelimeters,
3871
- attrExpression: ':',
3872
- blockOperation: 'v-',
3873
- directive: '!@',
3874
- voidTags: ((_a = options === null || options === void 0 ? void 0 : options.html) === null || _a === void 0 ? void 0 : _a.voidTags) || htmlVoidTags,
3875
- textTags: ((_b = options === null || options === void 0 ? void 0 : options.html) === null || _b === void 0 ? void 0 : _b.textTags) || htmlTextTags,
3876
- ...options === null || options === void 0 ? void 0 : options.html,
3877
- },
3878
- text: {
3879
- exprDelimeters: defaultDelimeters,
3880
- blockOperation: '=',
3881
- revealLine: ':',
3882
- directive: '!@',
3883
- ...options === null || options === void 0 ? void 0 : options.text,
3884
- },
3885
- };
3886
- }
3887
- get mixedRewriter() {
3888
- const textNodes = getTextParser(this.options.text, true);
3889
- const htmlNodes = getHtmlParser(this.options.html, true);
3890
- textNodes.htmlDirectiveNode.addRecognizes(...htmlNodes.rootNode.recognizes);
3891
- htmlNodes.textDirectiveNode.addRecognizes(...textNodes.rootNode.recognizes);
3892
- return {
3893
- text: getRewriter(textNodes.rootNode, this.options.debug),
3894
- html: getRewriter(htmlNodes.rootNode, this.options.debug),
3895
- };
3896
- }
3897
- get textRewriter() {
3898
- return getTextRewriter(this.options.text, this.options.debug);
3899
- }
3900
- get htmlRewriter() {
3901
- return getHtmlRewriter(this.options.html, this.options.debug);
3902
- }
3903
- async rewriteFile(opts, context) {
3904
- const file = await readFile(opts.input);
3905
- const mode = this.determineMode(opts.mode || this.options.defaultMode, opts.input, file);
3906
- let output = file;
3907
- const modes = this.mixedRewriter;
3908
- if (mode) {
3909
- this.debug('Parsing file in ' + mode + ' mode. ' + '' + '' + opts.input);
3910
- output = modes[mode].rewrite(file, context);
3911
- }
3912
- else {
3913
- this.debug('File isn\'t recognized as text nor as html. ' + '' + '' + opts.input);
3914
- }
3915
- if (opts.output) {
3916
- if (mode) {
3917
- await writeFile(opts.output, output);
3918
- this.debug('File has been rewritten in ' + mode + ' mode. ' + '' + '' + opts.output);
3919
- }
3920
- else {
3921
- await copyFile(opts.input, opts.output);
3922
- this.debug('File rewriting was skipped. File copied. ' + '' + '' + opts.output);
3923
- }
3924
- }
3925
- return output;
3926
- }
3927
- async rewriteDir(opts, context) {
3928
- if (__BROWSER__)
3929
- return;
3930
- const files = await readDir(opts.baseDir);
3931
- const dirPath = await pathResolve(opts.baseDir);
3932
- const include = opts.include && opts.include.length ? opts.include.map(s => new Minimatch(s, { matchBase: true })) : null;
3933
- const exclude = opts.exclude && opts.exclude.length ? opts.exclude.map(s => new Minimatch(s, { matchBase: true })) : null;
3934
- const rename = opts.renameFile || (f => f);
3935
- for await (const filePath of files) {
3936
- let included = true;
3937
- let excluded = false;
3938
- if (include)
3939
- included = !!include.find(m => m.match(filePath));
3940
- if (exclude && included)
3941
- excluded = !!exclude.find(m => m.match(filePath));
3942
- if (!included || excluded)
3943
- continue;
3944
- const relativeFilePath = rename(filePath.slice(dirPath.length + 1));
3945
- let targetPath;
3946
- if (opts.output) {
3947
- targetPath = await pathJoin(opts.output, relativeFilePath);
3948
- }
3949
- const output = await this.rewriteFile({
3950
- mode: opts.mode,
3951
- input: filePath,
3952
- output: targetPath,
3953
- }, context);
3954
- if (opts.onFile) {
3955
- opts.onFile(filePath, output);
3956
- }
3957
- }
3958
- }
3959
- determineMode(mode, path, content) {
3960
- if (mode === 'text')
3961
- return 'text';
3962
- if (mode === 'html')
3963
- return 'html';
3964
- if (mode === 'auto') {
3965
- const isText = !!this.options.textPattern.find(m => m.match(path));
3966
- const isHtml = !!this.options.htmlPattern.find(m => m.match(path));
3967
- if (isText && isHtml) {
3968
- if (/^<!DOCTYPE\s/.test(content))
3969
- return 'html';
3970
- if (/^<\?xml\s/.test(content))
3971
- return 'html';
3972
- return 'text';
3973
- }
3974
- if (isText)
3975
- return 'text';
3976
- if (isHtml)
3977
- return 'html';
3978
- }
3979
- }
3980
- debug(message) {
3981
- if (!this.options.debug)
3982
- return;
3983
- debug(message);
3984
- }
3985
- }
3986
-
3987
- export { ProstoRewrite, genSafeFunc, getRewriter, getStringExpressionRewriter, pushString, renderCode };
852
+ //#endregion
853
+ export { ProstoRewrite, genFunc, genSafeFunc, getRewriter, getStringExpressionRewriter, pushString, renderCode };