@pi-r/chrome 0.9.3 → 0.10.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/index.js CHANGED
@@ -2,6 +2,7 @@
2
2
  const path = require("node:path");
3
3
  const fs = require("node:fs");
4
4
  const node_crypto_1 = require("node:crypto");
5
+ const image_size_1 = require("image-size");
5
6
  const Cloud = require("@e-mc/cloud");
6
7
  const core_1 = require("@e-mc/core");
7
8
  const dom_1 = require("@e-mc/document/parse/dom");
@@ -10,6 +11,7 @@ const asset_1 = require("@e-mc/document/asset");
10
11
  const util_1 = require("@e-mc/document/util");
11
12
  const transform_1 = require("@e-mc/document/transform");
12
13
  const Document = require('@e-mc/document');
14
+ const kChrome = Symbol.for('chrome:constructor');
13
15
  const CACHE_DBRESULT = new Map();
14
16
  const CACHE_LOCALFILE = new Map();
15
17
  const CACHE_QUERY = new Map();
@@ -32,9 +34,10 @@ const [REGEXP_NTHCHILD, REGEXP_NTHCHILD_UNSAFE, REGEXP_REPLACECSS] = (function (
32
34
  ];
33
35
  })();
34
36
  const REGEXP_SRCSETSIZE = /~\s*([\d.]+)\s*([wx])/i;
35
- const REGEXP_TEMPLATECONDITIONAL = /(\n\s+)?\{\{if\s+((?:[^}]|}(?!}))+?)\}\}(\s*)(.*?)(?:\s*\{\{else(?:\s+if\s+((?:[^}]|}(?!}))+?))?\}\}(\s*)(.*?)\s*)?\s*\{\{end\}\}/gs;
36
- const REGEXP_TEMPLATECOMPARISON = /\s*\(\s*(?:\b(eq|ne|lt|le|gt|ge)\s+)?("[^"]+"|'[^']+'|[^\s)]+)(?:\s+("[^"]+"|'[^']+'|[^\s)]+))?\s*\)/g;
37
- const REGEXP_TEMPLATEMATCH = new RegExp(`^(?:\\b(and|or|not)\\s+)?((?:${REGEXP_TEMPLATECOMPARISON.source})+)|(!|not\\s+)?([^\\s][\\S\\s]*)$`);
37
+ const REGEXP_TEMPLATECONDITIONAL = /(\n\s+)?\{\{\s*if\s+((?:[^}]|}(?!}))+?)\}\}(\s*)(.*?)((?:\s*\{\{\s*else if\s+(?:(?:[^}]|}(?!}))+?)\}\}.*?)*)(?:\s*\{\{\s*else\s*\}\}(\s*)(.*?))?\s*\{\{\s*end\s*\}\}/gs;
38
+ const REGEXP_TEMPLATEELSEIF = /\{\{\s*else if\s+((?:[^}]|}(?!}))+?)\}\}(\s*)((?:.(?!\{\{\s*else if))*)/gs;
39
+ const REGEXP_TEMPLATECOMPARISON = /\s*\(\s*(?:(eq|ne|lt|le|gt|ge)\s+)?("[^"]+"|'[^']+'|[^\s)]+)(?:\s+("[^"]+"|'[^']+'|[^\s)]+))?\s*\)/g;
40
+ const REGEXP_TEMPLATEMATCH = new RegExp(`^(?:(and|or|not)\\s+)?((?:${REGEXP_TEMPLATECOMPARISON.source})+)|(!|not\\s+)?([^\\s][\\S\\s]*)$`);
38
41
  const REGEXP_IMPORTMODULE = /(?:(?:^|[\n;]+)\s*import\s+(?:("(?:[^"]|(?<=\\)")+"|'(?:[^']|(?<=\\)')+')|.+?from\s+("(?:[^"]|(?<=\\)")+"|'(?:[^']|(?<=\\)')+')(?:[ \t]+(?:assert|with)[ \t]+\{((?:"(?:[^"]|(?<=\\)")+"|'(?:[^']|(?<=\\)')+'|`(?:[^`]|(?<=\\)`)+`|{[^{]*{|{[^}]*}|}[^}]*}|[^"'`]+)+)\})?)|\bimport\(\s*("(?:[^"]|(?<=\\)")+"|'(?:[^']|(?<=\\)')+')\s*(?:,\s*\{((?:"(?:[^"]|(?<=\\)")+"|'(?:[^']|(?<=\\)')+'|`(?:[^`]|(?<=\\)`)+`|{[^{]*{|{[^}]*}|}[^}]*}|[^"'`]+)+)\}\s*)?\))/gd;
39
42
  const REGEXP_BLOCKEXCLUDE = new RegExp(`(\\s*)<!--\\s*exclude\\s*:\\s*(?:start|end)\\s*-->` + dom_1.DomWriter.PATTERN_TRAILINGSPACE, 'gi');
40
43
  const REGEXP_COMMENT = new RegExp(dom_1.DomWriter.PATTERN_COMMENT, 'g');
@@ -118,12 +121,6 @@ function trimTemplate(value) {
118
121
  }
119
122
  return value;
120
123
  }
121
- function trimQuote(value) {
122
- value = value.trim();
123
- const first = value[0];
124
- const last = value[value.length - 1];
125
- return first === last && (first === '"' || first === "'") ? value.substring(1, value.length - 1).trim() : value;
126
- }
127
124
  function findClosingIndex(source, lastIndex, char) {
128
125
  const pattern = char === '{' ? /[{}]/g : /[()]/g;
129
126
  pattern.lastIndex = lastIndex;
@@ -209,7 +206,7 @@ function hasCondition(data, condition) {
209
206
  if (items.length > 0 && !isSpace(match[0][0])) {
210
207
  return false;
211
208
  }
212
- items.push([match[1], trimQuote(match[2]), trimQuote(match[3])]);
209
+ items.push([match[1], (0, util_1.trimQuote)(match[2]), (0, util_1.trimQuote)(match[3])]);
213
210
  }
214
211
  REGEXP_TEMPLATECOMPARISON.lastIndex = 0;
215
212
  const length = items.length;
@@ -220,7 +217,7 @@ function hasCondition(data, condition) {
220
217
  const item = items[i];
221
218
  const arg1 = item[1];
222
219
  const arg2 = item[2];
223
- let valid;
220
+ let valid = false;
224
221
  if (arg2) {
225
222
  switch (item[0]) {
226
223
  case 'eq':
@@ -265,7 +262,7 @@ function hasCondition(data, condition) {
265
262
  }
266
263
  }
267
264
  }
268
- return join === 'or' ? false : true;
265
+ return join !== 'or';
269
266
  }
270
267
  if (match[7]) {
271
268
  return isTruthy(data, match[7].trim(), match[6]);
@@ -273,6 +270,36 @@ function hasCondition(data, condition) {
273
270
  }
274
271
  return false;
275
272
  }
273
+ function checkConditionBranch(data, value) {
274
+ REGEXP_TEMPLATEELSEIF.lastIndex = 0;
275
+ let match;
276
+ while (match = REGEXP_TEMPLATEELSEIF.exec(value)) {
277
+ if (hasCondition(data, match[1])) {
278
+ return match;
279
+ }
280
+ }
281
+ return null;
282
+ }
283
+ function getConditionalValue(data, value) {
284
+ REGEXP_TEMPLATECONDITIONAL.lastIndex = 0;
285
+ const match = REGEXP_TEMPLATECONDITIONAL.exec(value);
286
+ if (match) {
287
+ let result, branch;
288
+ if (hasCondition(data, match[2])) {
289
+ result = match[4];
290
+ }
291
+ else if (match[5] && (branch = checkConditionBranch(data, match[5]))) {
292
+ result = branch[3];
293
+ }
294
+ else if (match[7]) {
295
+ result = match[7];
296
+ }
297
+ else {
298
+ return null;
299
+ }
300
+ return result.trim();
301
+ }
302
+ }
276
303
  function isTruthy(data, attr, falsey) {
277
304
  const value = getObjectValue(data, attr);
278
305
  return falsey ? !value : !!value;
@@ -316,7 +343,7 @@ function restoreSearchParams(value, prefix = '__sqd') {
316
343
  }
317
344
  return value || '';
318
345
  }
319
- function getBaseURLs(asset, baseUrl) {
346
+ function collectBaseUrl(asset, baseUrl) {
320
347
  const result = [];
321
348
  let parentUrl = asset ? asset.url || asset.uri : null;
322
349
  try {
@@ -351,8 +378,8 @@ function createHash(host, file, hash, bufferMap) {
351
378
  const buffer = localUri && bufferMap[localUri] || getBuffer(file, localUri);
352
379
  if (buffer) {
353
380
  const [algorithm, length] = (0, util_1.getHashData)(hash);
354
- let value;
355
- if (algorithm && (value = Document.asHash(buffer, algorithm, { encoding: file.encoding }))) {
381
+ const value = algorithm ? Document.asHash(buffer, algorithm, { encoding: file.encoding }) : '';
382
+ if (value) {
356
383
  if (localUri) {
357
384
  bufferMap[localUri] = buffer;
358
385
  }
@@ -366,8 +393,8 @@ function createHash(host, file, hash, bufferMap) {
366
393
  host.writeFail(["Unable to read file", filename], err, 32);
367
394
  }
368
395
  }
369
- function getSrcURL(instance, parent, file) {
370
- const relativeUrl = file.relativeUrl || instance.host.removeCwd(file.localUri) && getRelativeURL(file);
396
+ function getSrcUrl(instance, parent, file) {
397
+ const relativeUrl = file.relativeUrl || instance.host.removeCwd(file.localUri) && getRelativeUrl(file);
371
398
  if (!relativeUrl) {
372
399
  return ['', false];
373
400
  }
@@ -386,8 +413,12 @@ function getSrcURL(instance, parent, file) {
386
413
  if (parentDir === assetDir) {
387
414
  return [file.filename, true];
388
415
  }
389
- const prefix = parentDir.split('/');
390
- const suffix = assetDir.split('/');
416
+ if (!parentDir) {
417
+ return [relativeUrl, false];
418
+ }
419
+ const splitPath = (value) => value.split(/\//).filter(seg => seg.trim());
420
+ const prefix = splitPath(parentDir);
421
+ const suffix = splitPath(assetDir);
391
422
  let found = false;
392
423
  while (prefix.length > 0 && suffix.length > 0 && prefix[0] === suffix[0]) {
393
424
  prefix.shift();
@@ -396,406 +427,6 @@ function getSrcURL(instance, parent, file) {
396
427
  }
397
428
  return [found ? Document.joinPath('../'.repeat(prefix.length), suffix.join('/'), file.filename) : '../'.repeat(prefix.length) + relativeUrl, false];
398
429
  }
399
- function transformURL(instance, host, parent, type, source, importFile) {
400
- const related = [];
401
- const baseHref = getBaseURLs(importFile || parent, instance.baseUrl);
402
- const isHtml = type === 'html';
403
- const isJs = type === 'js';
404
- const pattern = isJs ? REGEXP_URL_JS : type === 'svg' ? REGEXP_URL_SVG : REGEXP_URL;
405
- pattern.lastIndex = 0;
406
- REGEXP_IMAGESET.lastIndex = 0;
407
- let length = source.length, modified = false, match;
408
- while (match = REGEXP_IMAGESET.exec(source)) {
409
- const startIndex = match.index + match[0].length;
410
- const endIndex = findClosingIndex(source, startIndex, '(');
411
- if (endIndex === -1) {
412
- continue;
413
- }
414
- REGEXP_IMAGESET_URL.lastIndex = 0;
415
- let content = source.substring(startIndex, endIndex), url;
416
- while (url = REGEXP_IMAGESET_URL.exec(content)) {
417
- const quote = url[2] ? '"' : "'";
418
- const [a, b] = url.indices[1];
419
- content = (0, util_1.spliceString)(content, a, b, `url(${quote + (url[2] || url[3]).trim() + quote})`, REGEXP_IMAGESET_URL);
420
- modified = true;
421
- }
422
- if (modified) {
423
- source = (0, util_1.spliceString)(source, startIndex, endIndex, content, REGEXP_IMAGESET);
424
- modified = false;
425
- }
426
- }
427
- while (match = pattern.exec(source)) {
428
- const isText = !!match[1];
429
- const isHref = !!match[2];
430
- const isUrl = !isText && !isHref;
431
- const startIndex = match.index;
432
- let quote = match[1], content = '', trailing = '', closed = -1, i = startIndex + match[0].length;
433
- for (let j = -1; i < length; ++i) {
434
- const ch = source[i];
435
- if (quote && ch === quote) {
436
- if (!isText) {
437
- content += ch;
438
- }
439
- if (isHref) {
440
- break;
441
- }
442
- if (source[i - 1] !== '\\') {
443
- if (isText) {
444
- break;
445
- }
446
- if (closed === -1) {
447
- closed = i + 1;
448
- }
449
- }
450
- j = i + 1;
451
- continue;
452
- }
453
- if (!quote && (ch === '"' || ch === "'" || ch === '`' && isJs) && (isHref || !content.trim())) {
454
- quote = ch;
455
- }
456
- else if (isHref && !quote && isSpace(ch) && content.trim()) {
457
- break;
458
- }
459
- else if (ch === ')') {
460
- if (isUrl) {
461
- if (quote && closed !== -1 || !quote && (isJs || source[i - 1] !== '\\')) {
462
- break;
463
- }
464
- j = i;
465
- }
466
- }
467
- else if (j !== -1 && (ch === '\n' ||
468
- isText && (ch === ';' || ch === '{') ||
469
- isHref && (ch === '=' || ch === '>') ||
470
- isUrl && (ch === ';' ||
471
- !isJs && (!isHtml && (ch === ':' && !isJs || ch === '}') ||
472
- isHtml && (ch === '"' || ch === "'" || ch === ':' || ch === '>'))))) {
473
- if (closed !== -1) {
474
- i = closed;
475
- }
476
- else {
477
- content = content.substring(0, i = j);
478
- }
479
- break;
480
- }
481
- if (closed === -1) {
482
- content += ch;
483
- }
484
- }
485
- const setOutputURL = (value, asset) => {
486
- if (!value) {
487
- return;
488
- }
489
- if (asset) {
490
- if (!asset.inlineBase64) {
491
- if (host.Cloud?.getStorage('upload', asset.cloudStorage)) {
492
- const inlineUrlCloud = asset.inlineUrlCloud ||= (0, node_crypto_1.randomUUID)();
493
- (parent.inlineUrlCloudMap ||= {})[inlineUrlCloud] = value;
494
- value = inlineUrlCloud;
495
- }
496
- else if (asset.hash && instance.productionRelease) {
497
- const inlineUrl = asset.inlineUrl ||= (0, node_crypto_1.randomUUID)();
498
- (parent.inlineUrlMap ||= {})[inlineUrl] = value;
499
- value = inlineUrl;
500
- }
501
- }
502
- const font = findFont(asset.format);
503
- if (font) {
504
- found: {
505
- for (let k = i + 1; k < length; ++k) {
506
- switch (source[k]) {
507
- case ')': {
508
- const component = source.substring(i + 1, k + 1);
509
- const format = /\s+format\([^)]+\)$/i.exec(component);
510
- if (format) {
511
- trailing = component.replace(format[0], ` format("${font}")`);
512
- i = k;
513
- break found;
514
- }
515
- break;
516
- }
517
- case ',':
518
- case ';':
519
- case ':':
520
- case '}':
521
- break found;
522
- }
523
- }
524
- }
525
- }
526
- if (asset.initialValue && !asset.initialValue.cacheable) {
527
- parent.flags |= 16;
528
- }
529
- related.push(asset);
530
- }
531
- if (!quote && !isHtml && !isJs) {
532
- if (!value.includes('"')) {
533
- quote = '"';
534
- }
535
- else if (!value.includes("'")) {
536
- quote = "'";
537
- }
538
- }
539
- if (isUrl) {
540
- const index = value.indexOf('#');
541
- if (index !== -1) {
542
- value = value.substring(0, index);
543
- }
544
- }
545
- if (quote) {
546
- value = quote + value + quote;
547
- }
548
- const revised = isJs ? 'import(' + value + trailing + ')' : isHref ? 'href=' + value : (isText ? '@import ' + value : `url(${value})`) + trailing;
549
- source = (0, util_1.spliceString)(source, startIndex, i + 1, revised, pattern);
550
- length = source.length;
551
- modified = true;
552
- };
553
- let url;
554
- if (isJs) {
555
- if (!quote) {
556
- continue;
557
- }
558
- const file = new RegExp('^\\s*(' + quote + '((?:[^' + quote + ']|(?<=\\\\)' + quote + ')+)' + quote + ')\\s*(,.+)$').exec(content);
559
- if (file) {
560
- url = file[1].trim();
561
- trailing = file[2].trim();
562
- }
563
- else {
564
- url = trimQuote(content);
565
- }
566
- }
567
- else {
568
- url = trimQuote(content);
569
- }
570
- if (url.startsWith('data:')) {
571
- const base64 = url.split(',')[1]?.trim();
572
- if (base64) {
573
- for (const item of instance.assets) {
574
- if (item.base64 === base64) {
575
- setOutputURL(getSrcURL(instance, parent, item)[0], item);
576
- break;
577
- }
578
- }
579
- }
580
- }
581
- else if (baseHref.length > 0) {
582
- let fullUrl, asset;
583
- for (const parentUrl of baseHref) {
584
- if (asset = host.findAsset(fullUrl = Document.resolvePath(url, parentUrl), { replaced: true }) || (instance.related.has(parent) ? host.findAsset(fullUrl, { assets: Array.from(instance.related.get(parent)), replaced: true }) : undefined)) {
585
- break;
586
- }
587
- }
588
- if (asset && asset !== importFile) {
589
- if (!(0, util_1.hasValue)(asset.format, 'base64')) {
590
- if (asset.bundleReplace) {
591
- let k = 0, valid;
592
- if (!isText) {
593
- let j = startIndex;
594
- while (isSpace(source[--j])) { }
595
- valid = source.substring(k = j - 6, j + 1) === '@import';
596
- }
597
- else {
598
- k = startIndex;
599
- valid = true;
600
- }
601
- if (valid) {
602
- let l = i, revised = transform_1.SourceMap.removeSourceMappingURL(host.getUTF8String(asset))[0];
603
- for (let ch; l < length; ++l) {
604
- if ((ch = source[l]) === ';' || ch === '\n') {
605
- break;
606
- }
607
- }
608
- const layer = instance.replaceContent(revised, source.substring(k, l + 1), "text/css");
609
- if (layer) {
610
- revised = layer;
611
- }
612
- revised = transformURL(instance, host, parent, type, instance.removeServerRoot(revised), asset) || revised;
613
- source = (0, util_1.spliceString)(source, k, l + 1, revised, pattern);
614
- length = source.length;
615
- if (!parent.watch) {
616
- host.deleteFile(asset.localUri, { ignorePermission: true, emptyDir: true, all: true, id: asset.id });
617
- asset.invalid = true;
618
- }
619
- else {
620
- related.push(asset);
621
- if (!(0, types_1.existsFlag)(asset.flags)) {
622
- asset.flags |= 8;
623
- }
624
- }
625
- modified = true;
626
- continue;
627
- }
628
- }
629
- if (hasSameOrigin(asset.url || fullUrl, ...baseHref)) {
630
- let sameDir = false;
631
- [fullUrl, sameDir] = getSrcURL(instance, parent, asset);
632
- if (sameDir && isJs) {
633
- fullUrl = './' + fullUrl;
634
- }
635
- }
636
- else {
637
- const pathname = parent.pathname;
638
- const count = pathname && pathname !== '/' ? pathname.split('/').length : 0;
639
- fullUrl = (count ? '../'.repeat(count) : '') + asset.relativeUrl;
640
- }
641
- }
642
- else if (!asset.invalid) {
643
- fullUrl = asset.inlineBase64 ||= (0, node_crypto_1.randomUUID)();
644
- }
645
- if (url !== fullUrl) {
646
- setOutputURL(fullUrl, asset);
647
- }
648
- }
649
- else if (importFile && url !== fullUrl) {
650
- setOutputURL(fullUrl);
651
- }
652
- }
653
- }
654
- if (modified) {
655
- if (related.length > 0) {
656
- const previous = instance.related.get(parent);
657
- if (previous) {
658
- for (const item of related) {
659
- previous.add(item);
660
- }
661
- }
662
- else {
663
- instance.related.set(parent, new Set(related));
664
- }
665
- }
666
- return source;
667
- }
668
- }
669
- function getFormatUUID(instance, attr, ext) {
670
- const format = 'formatMap' in instance ? instance.formatMap : instance.module.format;
671
- let pattern;
672
- return (0, types_1.isObject)(format) && (0, types_1.isObject)(pattern = ext && ext in format ? format[ext] : format.uuid) && pattern[attr] ? (0, types_1.randomString)(pattern[attr], pattern.dictionary) : (0, node_crypto_1.randomUUID)();
673
- }
674
- function setLocationUUID(instance, data, file, ext) {
675
- const { pathname, filename } = data;
676
- const assignUUID = ChromeDocument.INTERNAL_ASSIGNUUID;
677
- let index = 0, modified = false;
678
- if (filename) {
679
- ext ||= path.extname(filename).substring(1);
680
- if ((index = filename.indexOf(assignUUID)) !== -1) {
681
- data.filename = (0, util_1.spliceString)(filename, index, index + assignUUID.length, getFormatUUID(instance, 'filename', ext));
682
- if (file) {
683
- file.inlineFilename = data.filename;
684
- }
685
- modified = true;
686
- }
687
- }
688
- if (pathname && (index = pathname.indexOf(assignUUID)) !== -1) {
689
- data.pathname = (0, util_1.spliceString)(pathname, index, index + assignUUID.length, getFormatUUID(instance, 'pathname', ext));
690
- modified = true;
691
- }
692
- if (file && modified) {
693
- (0, asset_1.setInitialValue)(file, false);
694
- if (file.hash) {
695
- delete file.hash;
696
- }
697
- }
698
- }
699
- function transformOptions(instance, file, mimeType, code, bundleContent) {
700
- const { uri, localUri, exported } = file;
701
- const metadata = { userAgentData: instance.userAgentData };
702
- switch (mimeType) {
703
- case "text/html":
704
- metadata.__fromhtml__ = true;
705
- case "text/css":
706
- Object.assign(metadata, instance.config);
707
- default:
708
- if ((0, types_1.isObject)(file.metadata)) {
709
- Object.assign(metadata, file.metadata);
710
- }
711
- break;
712
- }
713
- const [pathname, filename] = localUri ? [path.dirname(localUri), path.basename(localUri)] : ['', file.filename];
714
- const options = { pathname, filename, mimeType, metadata, imported: !!file.imports && file.imported !== false };
715
- const sourceFile = !exported && uri && instance.findSourceRoot(uri);
716
- if (sourceFile) {
717
- if (Document.isPath(sourceFile)) {
718
- options.sourceFile = sourceFile;
719
- }
720
- options.sourceName = path.basename(sourceFile);
721
- options.sourcesRelativeTo = path.dirname(sourceFile);
722
- options.getMainFile = instance.resolveSourceFile(file);
723
- if (code) {
724
- options.getSourceFiles = instance.locateSourceFiles(file, code, bundleContent);
725
- }
726
- }
727
- if ((!instance.productionRelease || instance.productionIncremental) && !(0, types_1.modifiedFlag)(file.flags)) {
728
- options.cacheData = { uri: !exported ? uri : undefined, etag: !file.modified ? file.etag : undefined, encoding: file.encoding };
729
- }
730
- return options;
731
- }
732
- function transformJs(instance, host, file, output) {
733
- const { sourceFiles, chunks, map } = output;
734
- const localUri = file.localUri;
735
- const emptySources = !!instance.productionRelease;
736
- let uri;
737
- if (map && (uri = Document.writeSourceMap(localUri, output, { hash: file.hash, emptySources, inlineMap: hasSourceMap(file.metadata, 'inline') }))) {
738
- host.add(uri, file, types_1.FILE_TYPE.SOURCEMAP);
739
- }
740
- if (chunks) {
741
- const elements = instance.elements;
742
- const localDir = path.dirname(localUri);
743
- const relativeDir = Document.joinPath(file.moveTo, file.pathname);
744
- const element = file.element;
745
- let order = 0, index, appending;
746
- if (element) {
747
- index = element.index;
748
- for (const item of elements) {
749
- const append = item.append;
750
- if (append && !append.prepend && dom_1.DomWriter.isEqual(item, element, host.moduleName, true)) {
751
- (appending ||= []).push(append);
752
- }
753
- }
754
- }
755
- for (const chunk of chunks) {
756
- let chunkName = chunk.filename;
757
- if (!chunkName) {
758
- chunkName = getFormatUUID(instance, 'filename', 'js') + path.extname(localUri);
759
- chunk.entryPoint = true;
760
- }
761
- const chunkUri = path.join(localDir, chunkName);
762
- if (chunk.map && (uri = Document.writeSourceMap(chunkUri, chunk, { emptySources, inlineMap: hasSourceMap(file.metadata, 'inline') }))) {
763
- host.add(uri, file, types_1.FILE_TYPE.SOURCEMAP);
764
- }
765
- try {
766
- fs.writeFileSync(chunkUri, chunk.code);
767
- host.add(chunkUri, file);
768
- if (chunk.entryPoint) {
769
- if (element) {
770
- const attributes = { ...file.attributes, src: Document.joinPath(relativeDir, chunkName) };
771
- if (file.imports && file.imported !== false) {
772
- attributes.type ||= 'module';
773
- }
774
- elements.push({
775
- ...element,
776
- attributes,
777
- append: { tagName: 'script', tagCount: element.tagCount, nextSibling: dom_1.DomWriter.isIndex(index) ? index + 1 : undefined, order: ++order }
778
- });
779
- }
780
- else {
781
- instance.writeFail(['Unable to create script entry point', path.basename(chunkUri)], (0, types_1.errorMessage)('js', 'Element not found', chunkUri), 4);
782
- }
783
- }
784
- }
785
- catch (err) {
786
- instance.writeFail(["Unable to write file", path.basename(chunkUri)], err, 32);
787
- }
788
- }
789
- appending?.forEach(item => {
790
- item.order += order;
791
- });
792
- }
793
- if ((0, types_1.isArray)(sourceFiles)) {
794
- file.sourceFiles = sourceFiles;
795
- }
796
- file.modified = true;
797
- return file.sourceUTF8 = output.code;
798
- }
799
430
  function replaceCss(instance, file) {
800
431
  if (file.inlineUrlMap) {
801
432
  sanitizeCss(instance, file.inlineUrlMap);
@@ -822,74 +453,25 @@ function finalizeHtml(value, data) {
822
453
  }
823
454
  return value;
824
455
  }
825
- function isWatched(instance, file) {
826
- const { initialValue, format } = file;
827
- if (file.imported || file.bundleReplace || file.inlineContent || file.inlineBase64 || instance.replaced.includes(file) || initialValue && (file.inlineFilename !== initialValue.inlineFilename || file.pathname !== initialValue.pathname || initialValue.cacheable === false) || format && ((0, util_1.hasValue)(format, 'base64') || (0, util_1.hasValue)(format, 'woff') || (0, util_1.hasValue)(format, 'woff2'))) {
828
- return true;
829
- }
830
- return false;
831
- }
832
- function loadLocalFile(instance, item, pathname, cacheData, encoding, out) {
456
+ function loadLocalFile(instance, pathname, encoding, out) {
833
457
  let content;
834
- encoding = (0, types_1.getEncoding)(encoding);
835
458
  if (out) {
836
- content = fs.readFileSync(pathname, encoding);
459
+ content = fs.readFileSync(pathname, (0, types_1.getEncoding)(encoding));
837
460
  out.content = content;
838
461
  }
839
462
  const ext = path.extname(pathname).substring(1).toLowerCase();
840
463
  if (ext === 'cjs') {
841
464
  return require(pathname);
842
465
  }
843
- content ||= fs.readFileSync(pathname, encoding);
844
- const result = instance.tryParse(content, ext);
466
+ const result = instance.tryParse(content || fs.readFileSync(pathname, (0, types_1.getEncoding)(encoding)), ext);
845
467
  if (result != null) {
846
- setCacheData(instance, item, result, pathname, cacheData, true);
847
468
  return result;
848
469
  }
849
470
  }
850
- function setCacheData(instance, item, data, dataKey, cacheData, template) {
851
- if ((0, types_1.isObject)(data) || template) {
852
- const cache = instance.settingsOf(item.source, template && item.source !== 'local' ? 'local_file' : 'cache');
853
- let timeout = 0;
854
- if (cache && (timeout = core_1.ClientDb.getTimeout(cache)) && timeout > 0) {
855
- addCacheItem(template ? CACHE_LOCALFILE : CACHE_DBRESULT, dataKey, data, timeout);
856
- }
857
- else {
858
- cacheData[dataKey] = data;
859
- }
860
- }
861
- }
862
- async function checkData(instance, item, name, result, validate) {
863
- let callback;
864
- if (typeof name === 'string') {
865
- const template = instance.findDataValue(name) || name;
866
- callback = instance.hasEval('userconfig') ? Document.parseFunction(template, instance.hasEval('absolute')) : (0, types_1.asFunction)(template);
867
- }
868
- else {
869
- callback = name;
870
- name = '';
871
- }
872
- if (typeof callback === 'function') {
873
- try {
874
- let output;
875
- if (callback["__cjs__"]) {
876
- output = await callback(result, item);
877
- }
878
- else {
879
- output = await callback.apply(Document.enabled("node.process.inline") ? process : null, Document.enabled("node.require.inline") ? [result, item, require] : [result, item]);
880
- }
881
- if (validate(output)) {
882
- return output;
883
- }
884
- }
885
- catch (err) {
886
- instance.writeFail(["Unable to parse inline method", name], err);
887
- }
888
- }
889
- }
890
471
  function removeElement(instance, domBase, item, element) {
891
472
  if (item.removeEmpty || item.type === 'display') {
892
- (element ||= new dom_1.HtmlElement(instance.moduleName, item.element)).remove = true;
473
+ element ||= new dom_1.HtmlElement(instance.moduleName, item.element);
474
+ element.remove = true;
893
475
  if (!domBase.write(element)) {
894
476
  instance.writeFail('Unable to remove element', errorHtml(item.element), { type: 4 });
895
477
  }
@@ -903,9 +485,10 @@ function removeWatchReload(item) {
903
485
  function errorCredential(instance, domBase, item, err) {
904
486
  removeElement(instance, domBase, item);
905
487
  const pkg = getPackageName(err);
906
- if (!(pkg && instance.checkPackage(err, pkg))) {
907
- instance.writeFail(["Invalid credentials", item.source], err);
488
+ if (pkg && instance.checkPackage(err, pkg)) {
489
+ return;
908
490
  }
491
+ instance.writeFail(["Invalid credentials", item.source], err);
909
492
  }
910
493
  const isSpace = dom_1.DomWriter.isSpace.bind(dom_1.DomWriter);
911
494
  const replaceMatch = dom_1.DomWriter.replaceMatch.bind(dom_1.DomWriter);
@@ -920,13 +503,14 @@ const isUnedited = (item) => !item.attributes && !item.inlineContent && !item.sr
920
503
  const isIgnored = (item, exists) => item.invalid || (0, types_1.ignoreFlag)(item.flags) || !exists && (0, types_1.existsFlag)(item.flags);
921
504
  const findFont = (value) => value && (Array.isArray(value) ? value : [value]).find(format => isFont(format));
922
505
  const getEndIndex = (match) => match.index + match[0].length;
923
- const getRelativeURL = (file) => Document.joinPath(file.moveTo, file.pathname, file.inlineFilename || file.filename) + (!file.static ? restoreSearchParams(file.url?.search) : '');
506
+ const getRelativeUrl = (file) => Document.joinPath(file.moveTo, file.pathname, file.inlineFilename || file.filename) + (!file.static ? restoreSearchParams(file.url?.search) : '');
924
507
  const validateDir = (value) => path.isAbsolute(value) && Document.isDir(value) ? value : '';
925
508
  const valueAsString = (value, delimiter) => Array.isArray(value) && !value.some(child => typeof child === 'object') ? value.join(delimiter) : Document.asString(value);
926
- const errorHtml = ({ tagName, tagIndex = -1 }) => (0, types_1.errorMessage)('html', 'Location did not resolve', tagName.toLowerCase() + (tagIndex >= 0 ? ': ' + tagIndex : ''));
509
+ const errorHtml = ({ tagName, tagIndex = -1 }) => (0, types_1.errorMessage)('dom-writer', 'Location did not resolve', tagName.toLowerCase() + (tagIndex >= 0 ? ': ' + tagIndex : ''));
927
510
  const errorDataSource = (value, hint) => (0, types_1.errorMessage)('data-source', value, hint);
928
511
  const isHtmlOnly = (assets, items, htmlFile) => !items.find(item => item !== htmlFile && assets.includes(item));
929
512
  class ChromeDocument extends Document {
513
+ static [kChrome] = true;
930
514
  static INTERNAL_ASSIGNUUID = "__assign__";
931
515
  static INTERNAL_SERVERROOT = "__serverroot__";
932
516
  static async purgeMemory(percent = 1, limit = 0, parent) {
@@ -1097,7 +681,7 @@ class ChromeDocument extends Document {
1097
681
  (function recurse(children) {
1098
682
  for (const item of children) {
1099
683
  if (!items.has(item)) {
1100
- if (isWatched(instance, item)) {
684
+ if (instance.isWatched(item)) {
1101
685
  item.flags |= 8;
1102
686
  }
1103
687
  items.add(item);
@@ -1165,7 +749,7 @@ class ChromeDocument extends Document {
1165
749
  }
1166
750
  const dest = path.join(destDir, subDir[subDir.length - 1]);
1167
751
  Document.renameFile(src, dest);
1168
- instance.addLog(types_1.STATUS_TYPE.INFO, `production: ${dest} (mapped)`, instance.moduleName, subDir.join(path.sep));
752
+ instance.addLog(types_1.STATUS_TYPE.INFO, `production: ${dest} (mapped)`, { source: subDir.join(path.sep) });
1169
753
  emptyDir.add(path.dirname(src));
1170
754
  if (i !== start) {
1171
755
  for (let j = 0; j < i; ++j) {
@@ -1177,11 +761,7 @@ class ChromeDocument extends Document {
1177
761
  catch (err) {
1178
762
  errorMove(err);
1179
763
  if (Document.isPath(src)) {
1180
- fs.unlink(src, error => {
1181
- if (error) {
1182
- instance.addLog(types_1.STATUS_TYPE.WARN, error);
1183
- }
1184
- });
764
+ fs.unlink(src, () => { });
1185
765
  }
1186
766
  }
1187
767
  finally {
@@ -1194,7 +774,7 @@ class ChromeDocument extends Document {
1194
774
  }
1195
775
  for (const item of mapped) {
1196
776
  if (item[2] === 0) {
1197
- instance.addLog(types_1.STATUS_TYPE.INFO, `production: ${item[1]} (mapped: 0)`, instance.moduleName, item[0]);
777
+ instance.addLog(types_1.STATUS_TYPE.INFO, `production: ${item[1]} (mapped: 0)`, { source: item[0] });
1198
778
  }
1199
779
  }
1200
780
  for (const pathname of Array.from(emptyDir).sort((a, b) => b.length - a.length)) {
@@ -1290,6 +870,8 @@ class ChromeDocument extends Document {
1290
870
  _threadable = true;
1291
871
  _dataSource;
1292
872
  _mimeMap;
873
+ _sessionKey = null;
874
+ _sessionData = Object.create(null);
1293
875
  _elements = null;
1294
876
  _cloudUrlMap;
1295
877
  _cloudUploaded;
@@ -1450,10 +1032,10 @@ class ChromeDocument extends Document {
1450
1032
  for (const storage of cloud) {
1451
1033
  for (const { service, upload, download } of storage) {
1452
1034
  if (upload) {
1453
- setLocationUUID(this, upload, null, service);
1035
+ this.processLocation(upload, service);
1454
1036
  }
1455
1037
  if (download) {
1456
- setLocationUUID(this, download, null, service);
1038
+ this.processLocation(download, service);
1457
1039
  }
1458
1040
  }
1459
1041
  }
@@ -1507,7 +1089,7 @@ class ChromeDocument extends Document {
1507
1089
  switch (mimeType) {
1508
1090
  case "text/html":
1509
1091
  if (format) {
1510
- const output = await this.transform('html', host.getUTF8String(file, localUri), format, transformOptions(this, file, mimeType));
1092
+ const output = await this.transform('html', host.getUTF8String(file, localUri), format, this.createTransformOptions(host, file, mimeType));
1511
1093
  if (output) {
1512
1094
  file.modified = true;
1513
1095
  file.sourceUTF8 = output.code;
@@ -1517,7 +1099,7 @@ class ChromeDocument extends Document {
1517
1099
  case "text/css":
1518
1100
  if (format) {
1519
1101
  const source = host.getUTF8String(file, localUri);
1520
- const output = await this.transform('css', source, format, transformOptions(this, file, mimeType, source));
1102
+ const output = await this.transform('css', source, format, this.createTransformOptions(host, file, mimeType, source));
1521
1103
  if (output) {
1522
1104
  if (output.map) {
1523
1105
  const uri = Document.writeSourceMap(localUri, output, { mimeType, hash, emptySources: productionRelease, inlineMap: hasSourceMap(file.metadata, 'inline') });
@@ -1542,9 +1124,9 @@ class ChromeDocument extends Document {
1542
1124
  file.modified = true;
1543
1125
  }
1544
1126
  if (format) {
1545
- const output = await this.transform('js', source, format, transformOptions(this, file, mimeType, source, host.contentToAppend.get(localUri)));
1127
+ const output = await this.transform('js', source, format, this.createTransformOptions(host, file, mimeType, source));
1546
1128
  if (output) {
1547
- source = transformJs(this, host, file, output);
1129
+ source = this.processJs(host, file, output);
1548
1130
  }
1549
1131
  }
1550
1132
  file.sourceUTF8 = source;
@@ -1558,7 +1140,7 @@ class ChromeDocument extends Document {
1558
1140
  this.svgFiles.push(file);
1559
1141
  }
1560
1142
  else if (format) {
1561
- const output = await this.transform('html', source, format, transformOptions(this, file, mimeType, source));
1143
+ const output = await this.transform('html', source, format, this.createTransformOptions(host, file, mimeType, source));
1562
1144
  if (output) {
1563
1145
  file.modified = true;
1564
1146
  file.sourceUTF8 = output.code;
@@ -1566,10 +1148,10 @@ class ChromeDocument extends Document {
1566
1148
  }
1567
1149
  break;
1568
1150
  }
1569
- case 'font/ttf':
1570
- case 'font/otf':
1571
- case 'font/woff':
1572
- case 'font/woff2': {
1151
+ case "font/ttf":
1152
+ case "font/otf":
1153
+ case "font/woff":
1154
+ case "font/woff2": {
1573
1155
  const setFormat = (type) => {
1574
1156
  if (Array.isArray(format)) {
1575
1157
  file.format = format.filter(value => !isFont(value));
@@ -1603,9 +1185,9 @@ class ChromeDocument extends Document {
1603
1185
  return;
1604
1186
  }
1605
1187
  const instance = host.loadModule('compress');
1606
- const buffer = host.getBuffer(file);
1188
+ const buffer = file.buffer || localUri;
1607
1189
  if (instance && buffer) {
1608
- const options = { format: to, filename: file.filename, etag: file.etag };
1190
+ const options = { format: to, filename: file.filename, etag: file.etag, worker: file.worker };
1609
1191
  await instance.tryFile(buffer, options)
1610
1192
  .then(result => {
1611
1193
  if (result) {
@@ -1654,9 +1236,18 @@ class ChromeDocument extends Document {
1654
1236
  this.replaced.push(file);
1655
1237
  }
1656
1238
  else {
1657
- setLocationUUID(this, file, file);
1239
+ const modified = this.processLocation(file, path.extname(file.filename).substring(1));
1240
+ if (modified.length > 0) {
1241
+ if (modified.includes('filename')) {
1242
+ file.inlineFilename = file.filename;
1243
+ }
1244
+ (0, asset_1.setInitialValue)(file, false);
1245
+ if (file.hash) {
1246
+ delete file.hash;
1247
+ }
1248
+ }
1658
1249
  }
1659
- file.relativeUrl = getRelativeURL(file);
1250
+ file.relativeUrl = getRelativeUrl(file);
1660
1251
  }
1661
1252
  resolveUri(file, source, trailing) {
1662
1253
  const host = this.host;
@@ -1685,14 +1276,14 @@ class ChromeDocument extends Document {
1685
1276
  const assert = match[3] || match[5];
1686
1277
  const idx = match[1] ? 1 : match[2] ? 2 : 4;
1687
1278
  const [a, b] = match.indices[idx];
1688
- const from = trimQuote(match[idx]);
1279
+ const from = (0, util_1.trimQuote)(match[idx]);
1689
1280
  const quote = output[a];
1690
1281
  const relative = /^\.{0,2}\//.test(from);
1691
1282
  if (assert && /\btype\s*:\s*(["'`])(?:css|json)\1/.test(assert)) {
1692
1283
  try {
1693
1284
  const asset = host.findAsset(relative ? new URL(from, uri) : from);
1694
1285
  if (asset) {
1695
- const [relativeUrl, sameDir] = getSrcURL(this, bundleMain || file, asset);
1286
+ const [relativeUrl, sameDir] = getSrcUrl(this, bundleMain || file, asset);
1696
1287
  if (relativeUrl) {
1697
1288
  output = (0, util_1.spliceString)(output, a, b, quote + (sameDir ? './' : '') + relativeUrl + quote, REGEXP_IMPORTMODULE);
1698
1289
  }
@@ -1739,7 +1330,7 @@ class ChromeDocument extends Document {
1739
1330
  if (!(0, types_1.isEmpty)(bundleId)) {
1740
1331
  for (const asset of this.assets) {
1741
1332
  if (asset.bundleIndex === 0 && asset.bundleId === bundleId) {
1742
- const output = transformURL(this, host, file, 'css', source, asset);
1333
+ const output = this.processUrl(host, file, source, 'css', asset);
1743
1334
  if (output) {
1744
1335
  source = output;
1745
1336
  file.modified = true;
@@ -1749,7 +1340,7 @@ class ChromeDocument extends Document {
1749
1340
  }
1750
1341
  }
1751
1342
  if (trailing && this.htmlFile) {
1752
- const output = transformURL(this, host, file, 'css', trailing, this.htmlFile);
1343
+ const output = this.processUrl(host, file, trailing, 'css', this.htmlFile);
1753
1344
  if (output) {
1754
1345
  trailing = output;
1755
1346
  }
@@ -1790,7 +1381,7 @@ class ChromeDocument extends Document {
1790
1381
  if (hosted) {
1791
1382
  const asset = this.host?.findAsset(uri);
1792
1383
  if (asset) {
1793
- const [relativeUrl, sameDir] = getSrcURL(this, bundleMain || file, asset);
1384
+ const [relativeUrl, sameDir] = getSrcUrl(this, bundleMain || file, asset);
1794
1385
  if (relativeUrl) {
1795
1386
  value = (sameDir ? './' : '') + relativeUrl;
1796
1387
  }
@@ -1930,7 +1521,7 @@ class ChromeDocument extends Document {
1930
1521
  }
1931
1522
  if (output && output !== source) {
1932
1523
  try {
1933
- fs.writeFileSync(item.localUri, output, item.encoding ||= 'utf-8');
1524
+ fs.writeFileSync(item.localUri, output, item.encoding ||= 'utf8');
1934
1525
  item.sourceUTF8 = output;
1935
1526
  }
1936
1527
  catch (err) {
@@ -2009,7 +1600,7 @@ class ChromeDocument extends Document {
2009
1600
  found = true;
2010
1601
  using.push(asset);
2011
1602
  }
2012
- else if (isWatched(this, asset) ||
1603
+ else if (this.isWatched(asset) ||
2013
1604
  (0, types_1.watchFlag)(asset.flags) ||
2014
1605
  asset.base64 && watch.related.find(item => (0, asset_1.isEqual)(item, asset)) ||
2015
1606
  (0, types_1.isArray)(asset.cloudStorage) && asset.cloudStorage.some(item => item.upload?.active)) {
@@ -2090,7 +1681,7 @@ class ChromeDocument extends Document {
2090
1681
  if (srcset) {
2091
1682
  const uri = Document.toPosix(file.uri);
2092
1683
  const items = new Set([uri]);
2093
- const baseHref = getBaseURLs(this.htmlFile, this.baseUrl);
1684
+ const baseHref = collectBaseUrl(this.htmlFile, this.baseUrl);
2094
1685
  const sameOrigin = hasSameOrigin(file.url || uri, ...baseHref);
2095
1686
  if (sameOrigin) {
2096
1687
  const src = element.getAttribute('src');
@@ -2222,7 +1813,7 @@ class ChromeDocument extends Document {
2222
1813
  continue;
2223
1814
  }
2224
1815
  let source = host.getUTF8String(item);
2225
- const output = transformURL(this, host, item, 'svg', source);
1816
+ const output = this.processUrl(host, item, source, 'svg');
2226
1817
  if (output) {
2227
1818
  source = output;
2228
1819
  item.modified = true;
@@ -2230,7 +1821,7 @@ class ChromeDocument extends Document {
2230
1821
  source = sanitizeSource(item, source);
2231
1822
  const format = item.format;
2232
1823
  if (format) {
2233
- const result = await this.transform('html', source, format, transformOptions(this, item, "image/svg+xml"));
1824
+ const result = await this.transform('html', source, format, this.createTransformOptions(host, item, "image/svg+xml"));
2234
1825
  if (result) {
2235
1826
  item.modified = true;
2236
1827
  source = result.code;
@@ -2257,7 +1848,7 @@ class ChromeDocument extends Document {
2257
1848
  source = output;
2258
1849
  item.modified = true;
2259
1850
  }
2260
- if (output = transformURL(this, host, item, 'css', source)) {
1851
+ if (output = this.processUrl(host, item, source, 'css')) {
2261
1852
  source = output;
2262
1853
  item.modified = true;
2263
1854
  }
@@ -2265,7 +1856,7 @@ class ChromeDocument extends Document {
2265
1856
  item.sourceUTF8 = source;
2266
1857
  if (item.format) {
2267
1858
  transforms.push(item);
2268
- tasks.push(this.transform('css', source, item.format, transformOptions(this, item, "text/css", source, host.contentToAppend.get(item.localUri))));
1859
+ tasks.push(this.transform('css', source, item.format, this.createTransformOptions(host, item, "text/css", source)));
2269
1860
  }
2270
1861
  }
2271
1862
  for (const item of this.jsFiles) {
@@ -2281,7 +1872,7 @@ class ChromeDocument extends Document {
2281
1872
  source = output;
2282
1873
  item.modified = true;
2283
1874
  }
2284
- if (output = transformURL(this, host, item, 'js', source)) {
1875
+ if (output = this.processUrl(host, item, source, 'js')) {
2285
1876
  source = output;
2286
1877
  item.modified = true;
2287
1878
  }
@@ -2289,7 +1880,7 @@ class ChromeDocument extends Document {
2289
1880
  item.sourceUTF8 = source;
2290
1881
  if (format) {
2291
1882
  transforms.push(item);
2292
- tasks.push(this.transform('js', source, format, transformOptions(this, item, "application/javascript", source, host.contentToAppend.get(item.localUri))));
1883
+ tasks.push(this.transform('js', source, format, this.createTransformOptions(host, item, "application/javascript", source)));
2293
1884
  }
2294
1885
  }
2295
1886
  return Promise.allSettled(tasks).then(items => {
@@ -2309,7 +1900,7 @@ class ChromeDocument extends Document {
2309
1900
  target.sourceUTF8 = value.code;
2310
1901
  }
2311
1902
  else {
2312
- transformJs(this, host, target, value);
1903
+ this.processJs(host, target, value);
2313
1904
  }
2314
1905
  }
2315
1906
  }
@@ -2365,7 +1956,7 @@ class ChromeDocument extends Document {
2365
1956
  }
2366
1957
  REGEXP_STYLE.lastIndex = 0;
2367
1958
  }
2368
- if (output = transformURL(this, host, htmlFile, 'html', source)) {
1959
+ if (output = this.processUrl(host, htmlFile, source, 'html')) {
2369
1960
  source = output;
2370
1961
  }
2371
1962
  source = replaceHtml(this, source, processing, htmlFile.inlineUrlMap);
@@ -2388,14 +1979,14 @@ class ChromeDocument extends Document {
2388
1979
  if (domBase.hasErrors()) {
2389
1980
  const timeStamp = Date.now();
2390
1981
  for (const err of domBase.errors) {
2391
- this.addLog(types_1.STATUS_TYPE.WARN, 'dom-writer: ' + err.message, timeStamp);
1982
+ this.addLog(types_1.STATUS_TYPE.WARN, err, { timeStamp, source: 'dom-writer' });
2392
1983
  }
2393
1984
  }
2394
1985
  if (domBase.failCount > 0) {
2395
- this.writeFail(['Unable to update document', moduleName], (0, types_1.errorMessage)('html', 'DOM rewrite failed', domBase.failCount + ' errors'), { type: 4, startTime });
1986
+ this.writeFail(['Unable to update document', moduleName], (0, types_1.errorMessage)('dom-writer', domBase.failCount + ' failed', domBase.modifyCount + ' modified'), { type: 4, startTime });
2396
1987
  }
2397
1988
  else {
2398
- this.writeTimeProcess('html', `dom-writer: ${domBase.modifyCount} modified > ` + path.basename(localUri), startTime);
1989
+ this.writeTimeProcess('html', `dom-writer: ${domBase.modifyCount} modified (${path.basename(localUri)})`, startTime);
2399
1990
  if (cacheMiss.length > 0) {
2400
1991
  const data = {};
2401
1992
  const message = [];
@@ -2475,30 +2066,16 @@ class ChromeDocument extends Document {
2475
2066
  const detectWidth = domElement.getAttribute('width') === 'detect';
2476
2067
  const detectHeight = domElement.getAttribute('height') === 'detect';
2477
2068
  if (detectWidth || detectHeight) {
2478
- let width = 0, height = 0, buffer = null, packageName;
2479
- const addLog = (dimension) => {
2480
- this.addLog(types_1.STATUS_TYPE.WARN, 'Could not detect image ' + dimension, packageName || this.moduleName, item.localUri ? path.basename(item.localUri) : item.filename);
2069
+ let width = 0, height = 0, buffer = null;
2070
+ const addLog = (suffix, err) => {
2071
+ this.addLog(types_1.STATUS_TYPE.WARN, err instanceof Error ? err : 'Could not detect image ' + suffix, { source: item.localUri ? path.basename(item.localUri) : item.filename });
2481
2072
  };
2482
2073
  if (isImage(item.mimeType) && (buffer = host.getBuffer(item))) {
2483
2074
  try {
2484
- ({ width, height } = require(packageName = 'image-size').imageSize(buffer));
2075
+ ({ width, height } = (0, image_size_1.imageSize)(buffer));
2485
2076
  }
2486
- catch {
2487
- try {
2488
- const dimension = require(packageName = 'probe-image-size').sync(buffer);
2489
- if (!dimension) {
2490
- throw new Error("MIME not found");
2491
- }
2492
- ({ width, height } = dimension);
2493
- }
2494
- catch {
2495
- try {
2496
- ({ width, height } = (await require('jimp').read(buffer)).bitmap);
2497
- }
2498
- catch {
2499
- }
2500
- packageName = '';
2501
- }
2077
+ catch (err) {
2078
+ addLog('from buffer', err);
2502
2079
  }
2503
2080
  }
2504
2081
  if (detectWidth) {
@@ -2535,8 +2112,6 @@ class ChromeDocument extends Document {
2535
2112
  if (this.dataSource.length === 0) {
2536
2113
  return;
2537
2114
  }
2538
- const sessionKey = (0, node_crypto_1.randomUUID)();
2539
- const cacheData = Object.create(null);
2540
2115
  const dataItems = [];
2541
2116
  const displayItems = [];
2542
2117
  for (const item of this.dataSource) {
@@ -2548,33 +2123,38 @@ class ChromeDocument extends Document {
2548
2123
  }
2549
2124
  }
2550
2125
  const checkObject = (item, data, type) => {
2551
- const { query, cascade } = item;
2552
- if ((0, types_1.isString)(cascade)) {
2553
- const result = data && (0, types_1.cascadeObject)(data, cascade, data);
2126
+ if (item.cascade) {
2127
+ const result = data && (0, types_1.cascadeObject)(data, item.cascade, data);
2554
2128
  if (result !== data) {
2555
2129
  data = result;
2556
2130
  }
2557
2131
  else if (item.fallback !== undefined) {
2558
2132
  data = item.fallback;
2559
2133
  }
2560
- else if (!(0, types_1.isString)(query)) {
2134
+ else if (!(0, types_1.isString)(item.query)) {
2561
2135
  return null;
2562
2136
  }
2563
2137
  }
2564
2138
  if (data) {
2565
- if ((0, types_1.isString)(query) && item.source !== 'mongodb') {
2566
- const pkg = query.startsWith('$') ? 'jsonpath' : 'jmespath';
2139
+ if ((0, types_1.isString)(item.query)) {
2140
+ const pkg = item.query.startsWith('$') ? Document.checkSemVer('jsonpath-plus', 5) ? null : 'jsonpath' : 'jmespath';
2567
2141
  try {
2568
- if (pkg === 'jsonpath') {
2569
- data = require(pkg).query(data, query);
2142
+ if (pkg === 'jmespath') {
2143
+ data = require(pkg).search(data, item.query);
2144
+ }
2145
+ else if (pkg === 'jsonpath') {
2146
+ data = require(pkg).query(data, item.query);
2570
2147
  }
2571
2148
  else {
2572
- data = require(pkg).search(data, query);
2149
+ const { JSONPath } = require('jsonpath-plus');
2150
+ data = JSONPath({ path: item.query, json: data });
2573
2151
  }
2574
2152
  }
2575
2153
  catch (err) {
2576
2154
  this.abort(item.source);
2577
- this.checkPackage(err, pkg, ["Unable to filter results", item.source]);
2155
+ if (pkg) {
2156
+ this.checkPackage(err, pkg, ["Unable to filter results", item.source]);
2157
+ }
2578
2158
  }
2579
2159
  }
2580
2160
  if (type && !item.ignoreCoerce && this.settingsOf(type, 'coerce') === true) {
@@ -2590,7 +2170,7 @@ class ChromeDocument extends Document {
2590
2170
  const batchGroup = [];
2591
2171
  for (const item of sourceSet) {
2592
2172
  if (!item.element) {
2593
- this.addLog(types_1.STATUS_TYPE.WARN, `dom-writer: Missing target element {${JSON.stringify(item)}}`);
2173
+ this.addLog(types_1.STATUS_TYPE.WARN, `No target element {${JSON.stringify(item)}}`, { source: 'dom-writer' });
2594
2174
  continue;
2595
2175
  }
2596
2176
  const type = item.source;
@@ -2663,10 +2243,10 @@ class ChromeDocument extends Document {
2663
2243
  let result = new Array(length), errors;
2664
2244
  switch (type) {
2665
2245
  case 'cloud':
2666
- result = await cloud.getDatabaseBatchRows(batch, true, sessionKey).catch((err) => {
2246
+ result = await cloud.getDatabaseBatchRows(batch, true, this.sessionKey).catch((err) => {
2667
2247
  this.abort(type);
2668
2248
  if (err instanceof Error) {
2669
- cloud.addLog(this.aborted ? types_1.STATUS_TYPE.ERROR : types_1.STATUS_TYPE.WARN, errors = err);
2249
+ cloud.addLog(this.aborted ? types_1.STATUS_TYPE.ERROR : types_1.STATUS_TYPE.WARN, errors = err, { source: batch[0].service });
2670
2250
  }
2671
2251
  return [];
2672
2252
  });
@@ -2680,7 +2260,7 @@ class ChromeDocument extends Document {
2680
2260
  break;
2681
2261
  case 'uri':
2682
2262
  case 'local': {
2683
- const encoding = current.encoding || 'utf-8';
2263
+ const encoding = current.encoding || 'utf8';
2684
2264
  let content, target, data, cacheKey;
2685
2265
  if (type === 'local') {
2686
2266
  let location;
@@ -2696,7 +2276,7 @@ class ChromeDocument extends Document {
2696
2276
  if (current.ignoreCache === 1) {
2697
2277
  CACHE_DBRESULT.delete(location);
2698
2278
  }
2699
- if (!(data = cacheData[location])) {
2279
+ if (!(data = this._sessionData[location])) {
2700
2280
  try {
2701
2281
  content = fs.readFileSync(location, encoding);
2702
2282
  cacheKey = location;
@@ -2738,7 +2318,7 @@ class ChromeDocument extends Document {
2738
2318
  if (current.ignoreCache === 1) {
2739
2319
  CACHE_DBRESULT.delete(target);
2740
2320
  }
2741
- if (!(data = cacheData[target])) {
2321
+ if (!(data = this._sessionData[target])) {
2742
2322
  try {
2743
2323
  content = await host.Request.get(target, { format, encoding });
2744
2324
  cacheKey = target;
@@ -2761,7 +2341,7 @@ class ChromeDocument extends Document {
2761
2341
  if (current.ignoreCache === 1) {
2762
2342
  CACHE_DBRESULT.delete(pathname);
2763
2343
  }
2764
- if (!(data = cacheData[pathname])) {
2344
+ if (!(data = this._sessionData[pathname])) {
2765
2345
  if (!host.canRead(pathname, { ownPermissionOnly: true })) {
2766
2346
  this.abort(type);
2767
2347
  errorRemove(current, errorDataSource("Unsupported access", pathname));
@@ -2781,7 +2361,7 @@ class ChromeDocument extends Document {
2781
2361
  }
2782
2362
  }
2783
2363
  if (Buffer.isBuffer(content)) {
2784
- content = content.toString('utf-8');
2364
+ content = content.toString('utf8');
2785
2365
  }
2786
2366
  if ((0, types_1.isString)(content)) {
2787
2367
  const { format = path.extname(target).substring(1) } = current;
@@ -2805,7 +2385,7 @@ class ChromeDocument extends Document {
2805
2385
  return;
2806
2386
  }
2807
2387
  if (cacheKey) {
2808
- setCacheData(this, current, data, cacheKey, cacheData);
2388
+ this.addSessionData(current, cacheKey, data);
2809
2389
  }
2810
2390
  if ((result[0] = checkObject(current, data, type)) === null) {
2811
2391
  this.abort(type);
@@ -2823,16 +2403,16 @@ class ChromeDocument extends Document {
2823
2403
  if (current.ignoreCache === 1) {
2824
2404
  CACHE_DBRESULT.delete(cacheKey);
2825
2405
  }
2826
- if (cacheKey in cacheData) {
2827
- result[0] = cacheData[cacheKey];
2406
+ if (cacheKey in this._sessionData) {
2407
+ result[0] = this._sessionData[cacheKey];
2828
2408
  }
2829
2409
  else {
2830
2410
  const { pathname, execute, params } = current;
2831
2411
  let data, target, getData, hint;
2832
- if (typeof execute === 'function') {
2412
+ if ((0, types_1.isFunction)(execute)) {
2833
2413
  target = execute;
2834
2414
  }
2835
- else if (typeof pathname === 'function') {
2415
+ else if ((0, types_1.isFunction)(pathname)) {
2836
2416
  target = pathname;
2837
2417
  }
2838
2418
  else if ((0, types_1.isString)(pathname)) {
@@ -2848,49 +2428,49 @@ class ChromeDocument extends Document {
2848
2428
  }
2849
2429
  }
2850
2430
  if (!getData) {
2851
- const { settings, encoding } = current;
2431
+ const settings = current.settings;
2852
2432
  target ||= settings && this.settings.export?.[settings] || pathname;
2853
- if (typeof target === 'function') {
2433
+ if ((0, types_1.isFunction)(target)) {
2854
2434
  getData = target;
2855
2435
  hint = target.name;
2856
2436
  }
2857
2437
  else if ((0, types_1.isString)(target)) {
2858
- getData = this.asSourceFile(target, { encoding });
2438
+ getData = this.asSourceFile(target, { encoding: current.encoding });
2859
2439
  hint = target;
2860
2440
  }
2861
2441
  }
2862
- if (typeof getData !== 'function') {
2863
- errorRemove(current, target ? errorDataSource('Not a function', hint) : errorDataSource('Not defined - pathname | settings', type));
2442
+ if (!(0, types_1.isFunction)(getData)) {
2443
+ errorRemove(current, target ? errorDataSource('Not a function', hint) : errorDataSource('Not defined - pathname', type));
2864
2444
  return;
2865
2445
  }
2866
2446
  try {
2867
2447
  if (params && !current.ignoreCoerce && this.settingsOf(type, 'coerce') === true) {
2868
2448
  (0, types_1.coerceObject)(params);
2869
2449
  }
2870
- if (getData["__cjs__"]) {
2450
+ if ((0, types_1.isFunction)(getData, true)) {
2871
2451
  data = await getData(params);
2872
2452
  }
2873
2453
  else {
2874
2454
  const thisArg = Document.enabled("node.process.inline") ? process : null;
2875
- const inline = Document.enabled("node.require.inline");
2876
2455
  const args = [params];
2877
- if (getData.toString().startsWith('async')) {
2878
- if (inline) {
2456
+ const addRequire = () => {
2457
+ if (Document.enabled("node.require.inline")) {
2879
2458
  args.push(require);
2880
2459
  }
2460
+ };
2461
+ if (getData.toString().startsWith('async')) {
2462
+ addRequire();
2881
2463
  data = await getData.apply(thisArg, args);
2882
2464
  }
2883
2465
  else {
2884
2466
  data = await new Promise(success => {
2885
2467
  args.push(success);
2886
- if (inline) {
2887
- args.push(require);
2888
- }
2468
+ addRequire();
2889
2469
  getData.apply(thisArg, args);
2890
2470
  });
2891
2471
  }
2892
2472
  }
2893
- setCacheData(this, current, data, cacheKey, cacheData);
2473
+ this.addSessionData(current, cacheKey, data);
2894
2474
  }
2895
2475
  catch (err) {
2896
2476
  this.abort(type);
@@ -2933,9 +2513,10 @@ class ChromeDocument extends Document {
2933
2513
  if (cmd.ignoreCache === 1) {
2934
2514
  CACHE_LOCALFILE.delete(pathname);
2935
2515
  }
2936
- if (!(search.schema = cacheData[pathname])) {
2516
+ if (!(search.schema = this._sessionData[pathname])) {
2937
2517
  try {
2938
- search.schema = loadLocalFile(this, current, pathname, cacheData, cmd.encoding);
2518
+ search.schema = loadLocalFile(this, pathname, cmd.encoding);
2519
+ this.addSessionData(current, pathname, search.schema, { template: true });
2939
2520
  }
2940
2521
  catch (err) {
2941
2522
  this.writeFail(['Unable to parse document', path.basename(pathname)], err instanceof Error ? errors = err : err, 32);
@@ -2969,14 +2550,15 @@ class ChromeDocument extends Document {
2969
2550
  if (cmd.ignoreCache === 1) {
2970
2551
  CACHE_LOCALFILE.delete(pathname);
2971
2552
  }
2972
- if (!(cmd.query = cacheData[pathname])) {
2553
+ if (!(cmd.query = this._sessionData[pathname])) {
2973
2554
  const out = { content: '' };
2974
2555
  try {
2975
- cmd.query = loadLocalFile(this, current, pathname, cacheData, cmd.encoding, out);
2556
+ cmd.query = loadLocalFile(this, pathname, cmd.encoding, out);
2976
2557
  }
2977
2558
  catch {
2978
- setCacheData(this, current, cmd.query = out.content, pathname, cacheData, true);
2559
+ cmd.query = out.content;
2979
2560
  }
2561
+ this.addSessionData(current, pathname, cmd.query, { template: true });
2980
2562
  }
2981
2563
  }
2982
2564
  }
@@ -3005,11 +2587,8 @@ class ChromeDocument extends Document {
3005
2587
  aborting = commandType !== db.commandType.UPDATE;
3006
2588
  message = Document.asString(data.search || data.key);
3007
2589
  }
3008
- else {
3009
- const credential = data.credential;
3010
- if ((0, types_1.isPlainObject)(credential)) {
3011
- message = credential.database;
3012
- }
2590
+ else if ((0, types_1.isObject)(data.credential)) {
2591
+ message = data.credential.database;
3013
2592
  }
3014
2593
  if (data.willAbort) {
3015
2594
  this.abort(undefined, err);
@@ -3022,7 +2601,7 @@ class ChromeDocument extends Document {
3022
2601
  }
3023
2602
  return this.aborted;
3024
2603
  };
3025
- const options = { checkObject, sessionKey, connectOnce: length > 1, outCacheMiss: cacheMiss, errorQuery };
2604
+ const options = { checkObject, sessionKey: this.sessionKey, connectOnce: length > 1, outCacheMiss: cacheMiss, errorQuery };
3026
2605
  result = await db.executeBatchQuery(batch, options, result);
3027
2606
  }
3028
2607
  catch (err) {
@@ -3042,7 +2621,7 @@ class ChromeDocument extends Document {
3042
2621
  const empty = (items = result[i]) === null;
3043
2622
  if ((items ||= []).length === 0) {
3044
2623
  if (whenEmpty) {
3045
- const data = await checkData(this, item, whenEmpty, items, row => Array.isArray(row));
2624
+ const data = await this.processData(item, items, whenEmpty, row => Array.isArray(row));
3046
2625
  if (data) {
3047
2626
  items = data;
3048
2627
  item.transactionFail = false;
@@ -3060,7 +2639,7 @@ class ChromeDocument extends Document {
3060
2639
  items = items.slice(0, limit);
3061
2640
  }
3062
2641
  if (postQuery) {
3063
- const data = await checkData(this, item, postQuery, items = items.slice(0), row => Array.isArray(row));
2642
+ const data = await this.processData(item, items = items.slice(0), postQuery, row => Array.isArray(row));
3064
2643
  if (data) {
3065
2644
  items = data;
3066
2645
  }
@@ -3070,7 +2649,7 @@ class ChromeDocument extends Document {
3070
2649
  const domElement = new dom_1.HtmlElement(this.moduleName, element);
3071
2650
  let value = '';
3072
2651
  const checkValue = async (name) => {
3073
- const data = await checkData(this, item, name, value, row => typeof row === 'string');
2652
+ const data = await this.processData(item, value, name, row => typeof row === 'string');
3074
2653
  if (data) {
3075
2654
  value = data;
3076
2655
  }
@@ -3085,10 +2664,10 @@ class ChromeDocument extends Document {
3085
2664
  if (item.ignoreCache === 1) {
3086
2665
  CACHE_LOCALFILE.delete(pathname);
3087
2666
  }
3088
- if (!(item.value = cacheData[pathname])) {
2667
+ if (!(item.value = this._sessionData[pathname])) {
3089
2668
  try {
3090
- item.value = fs.readFileSync(pathname, item.encoding || 'utf-8');
3091
- setCacheData(this, item, item.value, pathname, cacheData, true);
2669
+ item.value = fs.readFileSync(pathname, item.encoding || 'utf8');
2670
+ this.addSessionData(item, item.value, pathname, { template: true });
3092
2671
  }
3093
2672
  catch (err) {
3094
2673
  this.writeFail(["Unable to read file", path.basename(pathname)], err, 32);
@@ -3126,11 +2705,21 @@ class ChromeDocument extends Document {
3126
2705
  row.__index__ ??= j + 1;
3127
2706
  }
3128
2707
  let segment = template;
2708
+ REGEXP_TEMPLATECONDITIONAL.lastIndex = 0;
3129
2709
  while (match = REGEXP_TEMPLATECONDITIONAL.exec(segment)) {
3130
- const col = hasCondition(row, match[2]) ? 4 : hasCondition(row, match[5]) ? 7 : -1;
3131
- segment = replaceMatch(match, segment, match[col] ? (!match[1] || match[col - 1].includes('\n') ? '' : match[1]) + match[col - 1] + match[col] : '', REGEXP_TEMPLATECONDITIONAL);
2710
+ let col = -1, target = match, branch;
2711
+ if (hasCondition(row, match[2])) {
2712
+ col = 4;
2713
+ }
2714
+ else if (match[5] && (branch = checkConditionBranch(row, match[5]))) {
2715
+ target = branch;
2716
+ col = 3;
2717
+ }
2718
+ else if (match[7]) {
2719
+ col = 7;
2720
+ }
2721
+ segment = replaceMatch(match, segment, target[col] ? (!match[1] || target[col - 1].includes('\n') ? '' : match[1]) + target[col - 1] + target[col] : '', REGEXP_TEMPLATECONDITIONAL);
3132
2722
  }
3133
- REGEXP_TEMPLATECONDITIONAL.lastIndex = 0;
3134
2723
  const literal = segment.trim();
3135
2724
  if (literal.startsWith('`') && literal.endsWith('`')) {
3136
2725
  if (!this.hasEval('function')) {
@@ -3208,15 +2797,19 @@ class ChromeDocument extends Document {
3208
2797
  let joinString = ' ', match;
3209
2798
  for (const row of items) {
3210
2799
  for (let seg of segment) {
3211
- seg = seg.trim();
3212
- if (seg.startsWith(':') && (match = /^:join\((.*)\)$/is.exec(seg))) {
2800
+ if (match = /^:join\((.*)\)$/is.exec(seg = seg.trim())) {
3213
2801
  joinString = match[1];
3214
2802
  continue;
3215
2803
  }
3216
- if (match = REGEXP_TEMPLATECONDITIONAL.exec(seg)) {
3217
- seg = (hasCondition(row, match[2]) ? match[4] : hasCondition(row, match[5]) ? match[7] : '').trim();
2804
+ const content = getConditionalValue(row, seg);
2805
+ if (typeof content === 'string') {
2806
+ seg = content;
3218
2807
  valid = true;
3219
2808
  }
2809
+ else if (content === null) {
2810
+ valid = true;
2811
+ continue;
2812
+ }
3220
2813
  if (seg) {
3221
2814
  if (match = /^:text\((.*)\)$/is.exec(seg)) {
3222
2815
  value += (value ? joinString : '') + match[1];
@@ -3232,7 +2825,6 @@ class ChromeDocument extends Document {
3232
2825
  }
3233
2826
  }
3234
2827
  }
3235
- REGEXP_TEMPLATECONDITIONAL.lastIndex = 0;
3236
2828
  }
3237
2829
  }
3238
2830
  }
@@ -3300,11 +2892,15 @@ class ChromeDocument extends Document {
3300
2892
  }
3301
2893
  break;
3302
2894
  }
3303
- const match = REGEXP_TEMPLATECONDITIONAL.exec(seg);
3304
- if (match) {
3305
- seg = (hasCondition(row, match[2]) ? match[4] : hasCondition(row, match[5]) ? match[7] : '').trim();
2895
+ const content = getConditionalValue(row, seg);
2896
+ if (typeof content === 'string') {
2897
+ seg = content;
2898
+ }
2899
+ else if (content === null) {
2900
+ remove = true;
2901
+ errors = 1;
2902
+ break;
3306
2903
  }
3307
- REGEXP_TEMPLATECONDITIONAL.lastIndex = 0;
3308
2904
  const sign = seg[0];
3309
2905
  if (sign === '+' || sign === '-') {
3310
2906
  seg = seg.substring(1);
@@ -3364,7 +2960,7 @@ class ChromeDocument extends Document {
3364
2960
  break invalid;
3365
2961
  }
3366
2962
  if (!domBase.write(domElement) || errors) {
3367
- this.writeFail(item.type === 'display' ? domElement.remove ? errors ? 'Element was removed with errors' : 'Unable to remove element' : 'Unable to determine display conditional' : 'Unable to replace ' + item.type, errors instanceof Error ? errors : errorHtml(element), { type: 4, startTime });
2963
+ this.writeFail(item.type === 'display' ? domElement.remove && errors !== 1 ? errors ? 'Element was removed with errors' : 'Unable to remove element' : 'Unable to determine display conditional' : 'Unable to replace ' + item.type, errors instanceof Error ? errors : errorHtml(element), { type: 4, startTime });
3368
2964
  }
3369
2965
  }
3370
2966
  }
@@ -3372,7 +2968,7 @@ class ChromeDocument extends Document {
3372
2968
  if (!empty && item.type !== 'display' || item.transactionFail) {
3373
2969
  const emptyResponse = (value, service = item.source) => {
3374
2970
  value ||= "Unknown";
3375
- return errors instanceof Error ? (0, types_1.errorMessage)(service, value, errors.message) : errorDataSource(service + ' -> Empty', value);
2971
+ return errorDataSource(service + ': ' + (errors instanceof Error ? errors.message : 'Empty'), value);
3376
2972
  };
3377
2973
  switch (item.source) {
3378
2974
  case 'cloud': {
@@ -3433,7 +3029,7 @@ class ChromeDocument extends Document {
3433
3029
  case 'script': {
3434
3030
  const attributes = item.attributes;
3435
3031
  if (attributes) {
3436
- const algorithm = (0, types_1.isString)(attributes.integrity) ? attributes.integrity.trim().toLowerCase() : '';
3032
+ const algorithm = (0, types_1.isString)(attributes.integrity) ? attributes.integrity.toLowerCase() : '';
3437
3033
  switch (algorithm) {
3438
3034
  case 'sha256':
3439
3035
  case 'sha384':
@@ -3850,6 +3446,468 @@ class ChromeDocument extends Document {
3850
3446
  return current;
3851
3447
  }
3852
3448
  }
3449
+ isWatched(file) {
3450
+ const { initialValue, format } = file;
3451
+ return (file.imported ||
3452
+ file.bundleReplace ||
3453
+ file.inlineContent ||
3454
+ file.inlineBase64 ||
3455
+ this.replaced.includes(file) ||
3456
+ initialValue && (file.inlineFilename !== initialValue.inlineFilename || file.pathname !== initialValue.pathname || initialValue.cacheable === false) ||
3457
+ format && ((0, util_1.hasValue)(format, 'base64') || (0, util_1.hasValue)(format, 'woff') || (0, util_1.hasValue)(format, 'woff2')) ? true : false);
3458
+ }
3459
+ async processData(item, result, method, validate) {
3460
+ let callback;
3461
+ if (typeof method === 'string') {
3462
+ const template = this.findDataValue(method) || method;
3463
+ callback = this.hasEval('userconfig') ? Document.parseFunction(template, this.hasEval('absolute')) : (0, types_1.asFunction)(template);
3464
+ }
3465
+ else {
3466
+ callback = method;
3467
+ method = '';
3468
+ }
3469
+ if (typeof callback === 'function') {
3470
+ try {
3471
+ let output;
3472
+ if ((0, types_1.isFunction)(callback, true)) {
3473
+ output = await callback(result, item);
3474
+ }
3475
+ else {
3476
+ const thisArg = Document.enabled("node.process.inline") ? process : null;
3477
+ const args = [result, item];
3478
+ if (Document.enabled("node.require.inline")) {
3479
+ args.push(require);
3480
+ }
3481
+ output = await callback.apply(thisArg, args);
3482
+ }
3483
+ if (!validate || validate(output)) {
3484
+ return output;
3485
+ }
3486
+ }
3487
+ catch (err) {
3488
+ this.writeFail(["Unable to parse inline method", method], err);
3489
+ }
3490
+ }
3491
+ }
3492
+ processJs(host, file, output) {
3493
+ const writeSourceMap = (uri, data, hash) => {
3494
+ const value = Document.writeSourceMap(uri, data, { hash, emptySources: !!this.productionRelease, inlineMap: hasSourceMap(file.metadata, 'inline') });
3495
+ if (value) {
3496
+ host.add(value, file, types_1.FILE_TYPE.SOURCEMAP);
3497
+ }
3498
+ };
3499
+ if (output.map) {
3500
+ writeSourceMap(file.localUri, output, file.hash);
3501
+ }
3502
+ if (output.chunks) {
3503
+ const elements = this.elements;
3504
+ const localUri = file.localUri;
3505
+ const localDir = path.dirname(localUri);
3506
+ const relativeDir = Document.joinPath(file.moveTo, file.pathname);
3507
+ const element = file.element;
3508
+ let order = 0, appending;
3509
+ if (element) {
3510
+ for (const item of elements) {
3511
+ const append = item.append;
3512
+ if (append && !append.prepend && dom_1.DomWriter.isEqual(item, element, host.moduleName, true)) {
3513
+ (appending ||= []).push(append);
3514
+ }
3515
+ }
3516
+ }
3517
+ for (const chunk of output.chunks) {
3518
+ let chunkName = chunk.filename;
3519
+ if (!chunkName) {
3520
+ chunkName = this.formatLocation('filename', 'js') + path.extname(localUri);
3521
+ chunk.entryPoint = true;
3522
+ }
3523
+ const chunkUri = path.join(localDir, chunkName);
3524
+ if (chunk.map) {
3525
+ writeSourceMap(chunkUri, chunk);
3526
+ }
3527
+ try {
3528
+ fs.writeFileSync(chunkUri, chunk.code);
3529
+ host.add(chunkUri, file);
3530
+ if (chunk.entryPoint) {
3531
+ if (element) {
3532
+ const attributes = { ...file.attributes, src: Document.joinPath(relativeDir, chunkName) };
3533
+ if (file.imports && file.imported !== false) {
3534
+ attributes.type ||= 'module';
3535
+ }
3536
+ elements.push({
3537
+ ...element,
3538
+ attributes,
3539
+ append: { tagName: 'script', tagCount: element.tagCount, nextSibling: dom_1.DomWriter.isIndex(element.index) ? element.index + 1 : undefined, order: ++order }
3540
+ });
3541
+ }
3542
+ else {
3543
+ this.writeFail(['Unable to create entry point', path.basename(chunkUri)], (0, types_1.errorMessage)('js', 'Element not found', chunkUri), 4);
3544
+ }
3545
+ }
3546
+ }
3547
+ catch (err) {
3548
+ this.writeFail(["Unable to write file", path.basename(chunkUri)], err, 32);
3549
+ }
3550
+ }
3551
+ appending?.forEach(item => {
3552
+ item.order += order;
3553
+ });
3554
+ }
3555
+ if ((0, types_1.isArray)(output.sourceFiles)) {
3556
+ file.sourceFiles = output.sourceFiles;
3557
+ }
3558
+ file.modified = true;
3559
+ return file.sourceUTF8 = output.code;
3560
+ }
3561
+ processUrl(host, file, source, type, importFile) {
3562
+ const related = [];
3563
+ const baseHref = collectBaseUrl(importFile || file, this.baseUrl);
3564
+ const isHtml = type === 'html';
3565
+ const isJs = type === 'js';
3566
+ const pattern = isJs ? REGEXP_URL_JS : type === 'svg' ? REGEXP_URL_SVG : REGEXP_URL;
3567
+ pattern.lastIndex = 0;
3568
+ REGEXP_IMAGESET.lastIndex = 0;
3569
+ let length = source.length, modified = false, match;
3570
+ while (match = REGEXP_IMAGESET.exec(source)) {
3571
+ const startIndex = match.index + match[0].length;
3572
+ const endIndex = findClosingIndex(source, startIndex, '(');
3573
+ if (endIndex === -1) {
3574
+ continue;
3575
+ }
3576
+ REGEXP_IMAGESET_URL.lastIndex = 0;
3577
+ let content = source.substring(startIndex, endIndex), url;
3578
+ while (url = REGEXP_IMAGESET_URL.exec(content)) {
3579
+ const quote = url[2] ? '"' : "'";
3580
+ const [a, b] = url.indices[1];
3581
+ content = (0, util_1.spliceString)(content, a, b, `url(${quote + (url[2] || url[3]).trim() + quote})`, REGEXP_IMAGESET_URL);
3582
+ modified = true;
3583
+ }
3584
+ if (modified) {
3585
+ source = (0, util_1.spliceString)(source, startIndex, endIndex, content, REGEXP_IMAGESET);
3586
+ modified = false;
3587
+ }
3588
+ }
3589
+ while (match = pattern.exec(source)) {
3590
+ const isText = !!match[1];
3591
+ const isHref = !!match[2];
3592
+ const isUrl = !isText && !isHref;
3593
+ const startIndex = match.index;
3594
+ let quote = match[1], content = '', trailing = '', closed = -1, i = startIndex + match[0].length;
3595
+ for (let j = -1; i < length; ++i) {
3596
+ const ch = source[i];
3597
+ if (quote && ch === quote) {
3598
+ if (!isText) {
3599
+ content += ch;
3600
+ }
3601
+ if (isHref) {
3602
+ break;
3603
+ }
3604
+ if (source[i - 1] !== '\\') {
3605
+ if (isText) {
3606
+ break;
3607
+ }
3608
+ if (closed === -1) {
3609
+ closed = i + 1;
3610
+ }
3611
+ }
3612
+ j = i + 1;
3613
+ continue;
3614
+ }
3615
+ if (!quote && (ch === '"' || ch === "'" || ch === '`' && isJs) && (isHref || !content.trim())) {
3616
+ quote = ch;
3617
+ }
3618
+ else if (isHref && !quote && isSpace(ch) && content.trim()) {
3619
+ break;
3620
+ }
3621
+ else if (ch === ')') {
3622
+ if (isUrl) {
3623
+ if (quote && closed !== -1 || !quote && (isJs || source[i - 1] !== '\\')) {
3624
+ break;
3625
+ }
3626
+ j = i;
3627
+ }
3628
+ }
3629
+ else if (j !== -1 && (ch === '\n' ||
3630
+ isText && (ch === ';' || ch === '{') ||
3631
+ isHref && (ch === '=' || ch === '>') ||
3632
+ isUrl && (ch === ';' ||
3633
+ !isJs && (!isHtml && (ch === ':' && !isJs || ch === '}') ||
3634
+ isHtml && (ch === '"' || ch === "'" || ch === ':' || ch === '>'))))) {
3635
+ if (closed !== -1) {
3636
+ i = closed;
3637
+ }
3638
+ else {
3639
+ content = content.substring(0, i = j);
3640
+ }
3641
+ break;
3642
+ }
3643
+ if (closed === -1) {
3644
+ content += ch;
3645
+ }
3646
+ }
3647
+ const setOutputURL = (value, asset) => {
3648
+ if (!value) {
3649
+ return;
3650
+ }
3651
+ if (asset) {
3652
+ if (!asset.inlineBase64) {
3653
+ if (host.Cloud?.getStorage('upload', asset.cloudStorage)) {
3654
+ const inlineUrlCloud = asset.inlineUrlCloud ||= (0, node_crypto_1.randomUUID)();
3655
+ (file.inlineUrlCloudMap ||= {})[inlineUrlCloud] = value;
3656
+ value = inlineUrlCloud;
3657
+ }
3658
+ else if (asset.hash && this.productionRelease) {
3659
+ const inlineUrl = asset.inlineUrl ||= (0, node_crypto_1.randomUUID)();
3660
+ (file.inlineUrlMap ||= {})[inlineUrl] = value;
3661
+ value = inlineUrl;
3662
+ }
3663
+ }
3664
+ const font = findFont(asset.format);
3665
+ if (font) {
3666
+ found: {
3667
+ for (let k = i + 1; k < length; ++k) {
3668
+ switch (source[k]) {
3669
+ case ')': {
3670
+ const component = source.substring(i + 1, k + 1);
3671
+ const format = /\s+format\([^)]+\)$/i.exec(component);
3672
+ if (format) {
3673
+ trailing = component.replace(format[0], ` format("${font}")`);
3674
+ i = k;
3675
+ break found;
3676
+ }
3677
+ break;
3678
+ }
3679
+ case ',':
3680
+ case ';':
3681
+ case ':':
3682
+ case '}':
3683
+ break found;
3684
+ }
3685
+ }
3686
+ }
3687
+ }
3688
+ if (asset.initialValue && !asset.initialValue.cacheable) {
3689
+ file.flags |= 16;
3690
+ }
3691
+ related.push(asset);
3692
+ }
3693
+ if (!quote && !isHtml && !isJs) {
3694
+ if (!value.includes('"')) {
3695
+ quote = '"';
3696
+ }
3697
+ else if (!value.includes("'")) {
3698
+ quote = "'";
3699
+ }
3700
+ }
3701
+ if (isUrl) {
3702
+ const index = value.indexOf('#');
3703
+ if (index !== -1) {
3704
+ value = value.substring(0, index);
3705
+ }
3706
+ }
3707
+ if (quote) {
3708
+ value = quote + value + quote;
3709
+ }
3710
+ const revised = isJs ? 'import(' + value + trailing + ')' : isHref ? 'href=' + value : (isText ? '@import ' + value : `url(${value})`) + trailing;
3711
+ source = (0, util_1.spliceString)(source, startIndex, i + 1, revised, pattern);
3712
+ length = source.length;
3713
+ modified = true;
3714
+ };
3715
+ let url;
3716
+ if (isJs) {
3717
+ if (!quote) {
3718
+ continue;
3719
+ }
3720
+ const target = new RegExp('^\\s*(' + quote + '((?:[^' + quote + ']|(?<=\\\\)' + quote + ')+)' + quote + ')\\s*(,.+)$').exec(content);
3721
+ if (target) {
3722
+ url = target[1].trim();
3723
+ trailing = target[2].trim();
3724
+ }
3725
+ else {
3726
+ url = (0, util_1.trimQuote)(content);
3727
+ }
3728
+ }
3729
+ else {
3730
+ url = (0, util_1.trimQuote)(content);
3731
+ }
3732
+ if (url.startsWith('data:')) {
3733
+ const base64 = url.split(',')[1]?.trim();
3734
+ if (base64) {
3735
+ for (const item of this.assets) {
3736
+ if (item.base64 === base64) {
3737
+ setOutputURL(getSrcUrl(this, file, item)[0], item);
3738
+ break;
3739
+ }
3740
+ }
3741
+ }
3742
+ }
3743
+ else if (baseHref.length > 0) {
3744
+ let fullUrl, asset;
3745
+ for (const parentUrl of baseHref) {
3746
+ asset = host.findAsset(fullUrl = Document.resolvePath(url, parentUrl), { replaced: true }) || (this.related.has(file) ? host.findAsset(fullUrl, { assets: Array.from(this.related.get(file)), replaced: true }) : undefined);
3747
+ if (asset) {
3748
+ break;
3749
+ }
3750
+ }
3751
+ if (asset && asset !== importFile) {
3752
+ if (!(0, util_1.hasValue)(asset.format, 'base64')) {
3753
+ if (asset.bundleReplace) {
3754
+ let k = 0, valid = true;
3755
+ if (!isText) {
3756
+ let j = startIndex;
3757
+ while (isSpace(source[--j])) { }
3758
+ valid = source.substring(k = j - 6, j + 1) === '@import';
3759
+ }
3760
+ else {
3761
+ k = startIndex;
3762
+ }
3763
+ if (valid) {
3764
+ let l = i, revised = transform_1.SourceMap.removeSourceMappingURL(host.getUTF8String(asset))[0];
3765
+ for (let ch; l < length; ++l) {
3766
+ if ((ch = source[l]) === ';' || ch === '\n') {
3767
+ break;
3768
+ }
3769
+ }
3770
+ const layer = this.replaceContent(revised, source.substring(k, l + 1), "text/css");
3771
+ if (layer) {
3772
+ revised = layer;
3773
+ }
3774
+ revised = this.processUrl(host, file, this.removeServerRoot(revised), type, asset) || revised;
3775
+ source = (0, util_1.spliceString)(source, k, l + 1, revised, pattern);
3776
+ length = source.length;
3777
+ if (!file.watch) {
3778
+ host.deleteFile(asset.localUri, { ignorePermission: true, emptyDir: true, all: true, id: asset.id });
3779
+ asset.invalid = true;
3780
+ }
3781
+ else {
3782
+ related.push(asset);
3783
+ if (!(0, types_1.existsFlag)(asset.flags)) {
3784
+ asset.flags |= 8;
3785
+ }
3786
+ }
3787
+ modified = true;
3788
+ continue;
3789
+ }
3790
+ }
3791
+ if (hasSameOrigin(asset.url || fullUrl, ...baseHref)) {
3792
+ let sameDir = false;
3793
+ [fullUrl, sameDir] = getSrcUrl(this, file, asset);
3794
+ if (sameDir && isJs) {
3795
+ fullUrl = './' + fullUrl;
3796
+ }
3797
+ }
3798
+ else {
3799
+ const pathname = file.pathname;
3800
+ const count = pathname && pathname !== '/' ? pathname.split('/').length : 0;
3801
+ fullUrl = (count ? '../'.repeat(count) : '') + asset.relativeUrl;
3802
+ }
3803
+ }
3804
+ else if (!asset.invalid) {
3805
+ fullUrl = asset.inlineBase64 ||= (0, node_crypto_1.randomUUID)();
3806
+ }
3807
+ if (url !== fullUrl) {
3808
+ setOutputURL(fullUrl, asset);
3809
+ }
3810
+ }
3811
+ else if (importFile && url !== fullUrl) {
3812
+ setOutputURL(fullUrl);
3813
+ }
3814
+ }
3815
+ }
3816
+ if (modified) {
3817
+ if (related.length > 0) {
3818
+ const previous = this.related.get(file);
3819
+ if (previous) {
3820
+ for (const item of related) {
3821
+ previous.add(item);
3822
+ }
3823
+ }
3824
+ else {
3825
+ this.related.set(file, new Set(related));
3826
+ }
3827
+ }
3828
+ return source;
3829
+ }
3830
+ }
3831
+ processLocation(target, nameExt) {
3832
+ const modified = [];
3833
+ const checkAttribute = (attr) => {
3834
+ const value = target[attr];
3835
+ if (value) {
3836
+ const index = value.indexOf(ChromeDocument.INTERNAL_ASSIGNUUID);
3837
+ if (index !== -1) {
3838
+ target[attr] = (0, util_1.spliceString)(value, index, index + ChromeDocument.INTERNAL_ASSIGNUUID.length, this.formatLocation(attr, nameExt));
3839
+ modified.push(attr);
3840
+ return true;
3841
+ }
3842
+ }
3843
+ return false;
3844
+ };
3845
+ checkAttribute('filename');
3846
+ checkAttribute('pathname');
3847
+ return modified;
3848
+ }
3849
+ formatLocation(attr, nameExt) {
3850
+ const format = this.formatMap || this.module.format;
3851
+ if ((0, types_1.isObject)(format)) {
3852
+ const pattern = nameExt && nameExt in format ? format[nameExt] : format.uuid;
3853
+ if ((0, types_1.isObject)(pattern) && (0, types_1.isString)(pattern[attr])) {
3854
+ return (0, types_1.randomString)(pattern[attr], pattern.dictionary);
3855
+ }
3856
+ }
3857
+ return (0, node_crypto_1.randomUUID)();
3858
+ }
3859
+ createTransformOptions(host, file, mimeType, source = {}) {
3860
+ if (typeof source === 'string') {
3861
+ source = { code: source };
3862
+ }
3863
+ const metadata = { userAgentData: this.userAgentData };
3864
+ switch (mimeType) {
3865
+ case "text/html":
3866
+ metadata.__fromhtml__ = true;
3867
+ case "text/css":
3868
+ Object.assign(metadata, this.config);
3869
+ default:
3870
+ if ((0, types_1.isObject)(file.metadata)) {
3871
+ Object.assign(metadata, file.metadata);
3872
+ }
3873
+ break;
3874
+ }
3875
+ const { uri, localUri } = file;
3876
+ const [pathname, filename] = localUri ? [path.dirname(localUri), path.basename(localUri)] : ['', file.filename];
3877
+ const options = { pathname, filename, mimeType, metadata, imported: !!file.imports && file.imported !== false };
3878
+ const sourceFile = source.sourceFile || !file.exported && uri && this.findSourceRoot(uri);
3879
+ if (sourceFile) {
3880
+ if (Document.isPath(sourceFile)) {
3881
+ options.sourceFile = sourceFile;
3882
+ }
3883
+ options.sourceName = path.basename(sourceFile);
3884
+ options.sourcesRelativeTo = path.dirname(sourceFile);
3885
+ options.getMainFile = this.resolveSourceFile(file);
3886
+ if (source.code) {
3887
+ options.getSourceFiles = this.locateSourceFiles(file, source.code, source.contentFiles || (localUri ? host.contentToAppend.get(localUri) : undefined));
3888
+ }
3889
+ }
3890
+ if ((!this.productionRelease || this.productionIncremental) && !(0, types_1.modifiedFlag)(file.flags)) {
3891
+ options.cacheData = { uri: !file.exported ? uri : undefined, etag: !file.modified ? file.etag : undefined, encoding: file.encoding };
3892
+ }
3893
+ return options;
3894
+ }
3895
+ addSessionData(item, key, data, { timeout = 0, template = false } = {}) {
3896
+ if ((0, types_1.isObject)(data) || template && data != null) {
3897
+ if (timeout === 0) {
3898
+ const cache = this.settingsOf(item.source, template && item.source !== 'local' ? 'local_file' : 'cache');
3899
+ if (cache) {
3900
+ timeout = core_1.ClientDb.getTimeout(cache);
3901
+ }
3902
+ }
3903
+ if (timeout > 0) {
3904
+ addCacheItem(template ? CACHE_LOCALFILE : CACHE_DBRESULT, key, data, timeout);
3905
+ }
3906
+ else {
3907
+ this._sessionData[key] = data;
3908
+ }
3909
+ }
3910
+ }
3853
3911
  get elements() {
3854
3912
  if (this._elements) {
3855
3913
  return this._elements;
@@ -3896,6 +3954,9 @@ class ChromeDocument extends Document {
3896
3954
  }
3897
3955
  return [];
3898
3956
  }
3957
+ get sessionKey() {
3958
+ return this._sessionKey ||= (0, node_crypto_1.randomUUID)();
3959
+ }
3899
3960
  get settings() {
3900
3961
  return this.module.settings ||= {};
3901
3962
  }