@pi-r/chrome 0.6.7 → 0.7.1

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
@@ -58,13 +58,13 @@ const REGEXP_IMAGESET = /\b(?:-webkit-)?image-set\(/gi;
58
58
  const REGEXP_IMAGESET_URL = /(?:^|[^(])\s*("(\s*[^)][^"]*)"|'(\s*[^)][^"]*)')\s*(?:,|$|[^)][^,]*,?)/g;
59
59
  function removeNamespace(name, source, newline, comments) {
60
60
  if (source.includes('-' + name)) {
61
- const [a, b, c, d, e] = CACHE_DATASET[name] || (CACHE_DATASET[name] = [
61
+ const [a, b, c, d, e] = CACHE_DATASET[name] ||= [
62
62
  new RegExp(`(\\s*)<(script|style)(${dom_1.DomWriter.PATTERN_TAGOPEN}+)>[\\S\\s]*?<\\/\\2\\s*>` + dom_1.DomWriter.PATTERN_TRAILINGSPACE, 'gi'),
63
63
  new RegExp(`(\\s*)<link(${dom_1.DomWriter.PATTERN_TAGOPEN}+)>` + dom_1.DomWriter.PATTERN_TRAILINGSPACE, 'gi'),
64
64
  new RegExp(`\\s+data-${name}-[a-z-]+\\s*` + dom_1.DomWriter.PATTERN_ATTRVALUE, 'g'),
65
65
  new RegExp(`data-${name}-file\\s*=\\s*(["'])?exclude\\1`),
66
66
  new RegExp(`data-${name}-template\\s*` + dom_1.DomWriter.PATTERN_ATTRVALUE)
67
- ]);
67
+ ];
68
68
  source = source
69
69
  .replace(a, (...capture) => d.test(capture[3]) || e.test(capture[3]) ? getNewlineString(capture[1], capture[7], newline) : capture[0])
70
70
  .replace(b, (...capture) => d.test(capture[2]) ? getNewlineString(capture[1], capture[6], newline) : capture[0])
@@ -180,9 +180,7 @@ function spliceSource(source, startIndex, endIndex, pattern, leading = '', trail
180
180
  if (leading || trailing) {
181
181
  content += getNewlineString(leading, trailing);
182
182
  }
183
- if (pattern && content) {
184
- pattern.lastIndex = startIndex + content.length;
185
- }
183
+ pattern.lastIndex = startIndex + content.length;
186
184
  return spliceString(source, startIndex, endIndex, content);
187
185
  }
188
186
  function hasCondition(data, condition) {
@@ -297,7 +295,7 @@ function hasSameOrigin(value, ...other) {
297
295
  return false;
298
296
  }
299
297
  function restoreSearchParams(value, prefix = '__sqd') {
300
- if (value === null || value === void 0 ? void 0 : value.includes(prefix)) {
298
+ if (value?.includes(prefix)) {
301
299
  const params = new URLSearchParams(value);
302
300
  params.forEach((_, key) => key.startsWith(prefix) && params.delete(key));
303
301
  if (value = params.toString()) {
@@ -385,7 +383,6 @@ function getSrcURL(parent, file) {
385
383
  return [found ? joinPath('../'.repeat(prefix.length), suffix.join('/'), file.filename) : '../'.repeat(prefix.length) + relativeUrl];
386
384
  }
387
385
  function transformURL(host, parent, type, source, importFile) {
388
- var _a;
389
386
  const related = [];
390
387
  const baseHref = getBaseURLs(importFile || parent, this.baseUrl);
391
388
  const isHtml = type === 'html';
@@ -472,20 +469,19 @@ function transformURL(host, parent, type, source, importFile) {
472
469
  }
473
470
  }
474
471
  const setOutputURL = (value, asset) => {
475
- var _a;
476
472
  if (!value) {
477
473
  return;
478
474
  }
479
475
  if (asset) {
480
476
  if (!asset.inlineBase64) {
481
- if ((_a = host.Cloud) === null || _a === void 0 ? void 0 : _a.getStorage('upload', asset.cloudStorage)) {
482
- const inlineUrlCloud = asset.inlineUrlCloud || (asset.inlineUrlCloud = (0, types_1.generateUUID)());
483
- (parent.inlineUrlCloudMap || (parent.inlineUrlCloudMap = {}))[inlineUrlCloud] = value;
477
+ if (host.Cloud?.getStorage('upload', asset.cloudStorage)) {
478
+ const inlineUrlCloud = asset.inlineUrlCloud ||= (0, types_1.generateUUID)();
479
+ (parent.inlineUrlCloudMap ||= {})[inlineUrlCloud] = value;
484
480
  value = inlineUrlCloud;
485
481
  }
486
482
  else if (asset.hash && this.productionRelease) {
487
- const inlineUrl = asset.inlineUrl || (asset.inlineUrl = (0, types_1.generateUUID)());
488
- (parent.inlineUrlMap || (parent.inlineUrlMap = {}))[inlineUrl] = value;
483
+ const inlineUrl = asset.inlineUrl ||= (0, types_1.generateUUID)();
484
+ (parent.inlineUrlMap ||= {})[inlineUrl] = value;
489
485
  value = inlineUrl;
490
486
  }
491
487
  }
@@ -559,7 +555,7 @@ function transformURL(host, parent, type, source, importFile) {
559
555
  url = trimQuote(content);
560
556
  }
561
557
  if (url.startsWith('data:')) {
562
- const base64 = (_a = url.split(',')[1]) === null || _a === void 0 ? void 0 : _a.trim();
558
+ const base64 = url.split(',')[1]?.trim();
563
559
  if (base64) {
564
560
  for (const item of this.assets) {
565
561
  if (item.base64 === base64) {
@@ -631,7 +627,7 @@ function transformURL(host, parent, type, source, importFile) {
631
627
  }
632
628
  }
633
629
  else if (!asset.invalid) {
634
- fullUrl = asset.inlineBase64 || (asset.inlineBase64 = (0, types_1.generateUUID)());
630
+ fullUrl = asset.inlineBase64 ||= (0, types_1.generateUUID)();
635
631
  }
636
632
  if (url !== fullUrl) {
637
633
  setOutputURL(fullUrl, asset);
@@ -668,7 +664,7 @@ function setLocationUUID(data, file, ext) {
668
664
  const assignUUID = ChromeDocument.INTERNAL_ASSIGNUUID;
669
665
  let index, modified;
670
666
  if (filename) {
671
- ext || (ext = path.extname(filename).substring(1));
667
+ ext ||= path.extname(filename).substring(1);
672
668
  if ((index = filename.indexOf(assignUUID)) !== -1) {
673
669
  data.filename = spliceString(filename, index, index + assignUUID.length, getFormatUUID.call(this, 'filename', ext));
674
670
  if (file) {
@@ -740,7 +736,7 @@ function transformJs(host, file, output) {
740
736
  for (const item of elements) {
741
737
  const append = item.append;
742
738
  if (append && !append.prepend && dom_1.DomWriter.isEqual(item, element, host.moduleName, true)) {
743
- (appending || (appending = [])).push(append);
739
+ (appending ||= []).push(append);
744
740
  }
745
741
  }
746
742
  }
@@ -761,7 +757,7 @@ function transformJs(host, file, output) {
761
757
  if (element) {
762
758
  const attributes = { ...file.attributes, src: joinPath(relativeDir, chunkName) };
763
759
  if (file.imports && file.imported !== false) {
764
- attributes.type || (attributes.type = 'module');
760
+ attributes.type ||= 'module';
765
761
  }
766
762
  elements.push({
767
763
  ...element,
@@ -778,7 +774,7 @@ function transformJs(host, file, output) {
778
774
  this.writeFail(["Unable to write file", path.basename(chunkUri)], err, 32);
779
775
  }
780
776
  }
781
- appending === null || appending === void 0 ? void 0 : appending.forEach(item => item.order += order);
777
+ appending?.forEach(item => item.order += order);
782
778
  }
783
779
  if ((0, types_1.isArray)(sourceFiles)) {
784
780
  file.sourceFiles = sourceFiles;
@@ -831,7 +827,7 @@ function loadLocalFile(item, pathname, cacheData, encoding, out) {
831
827
  if (ext === 'cjs') {
832
828
  return require(pathname);
833
829
  }
834
- content || (content = fs.readFileSync(pathname, encoding));
830
+ content ||= fs.readFileSync(pathname, encoding);
835
831
  const result = this.tryParse(content, ext);
836
832
  if (result !== undefined && result !== null) {
837
833
  setCacheData.call(this, item, result, pathname, cacheData, true);
@@ -888,7 +884,7 @@ const asString = Document.asString.bind(Document);
888
884
  const resolvePath = Document.resolvePath.bind(Document);
889
885
  const toPosix = Document.toPosix.bind(Document);
890
886
  const isDir = Document.isDir.bind(Document);
891
- const getBuffer = (item, localUri) => item.sourceUTF8 || item.buffer || ((localUri || (localUri = item.localUri)) && isPath(localUri) ? fs.readFileSync(localUri, item.encoding) : null);
887
+ const getBuffer = (item, localUri) => item.sourceUTF8 || item.buffer || ((localUri ||= item.localUri) && isPath(localUri) ? fs.readFileSync(localUri, item.encoding) : null);
892
888
  const hasSourceMap = (metadata, value) => (0, types_1.isObject)(metadata) && metadata.__sourcemap__ === value;
893
889
  const isBundled = (value, main) => typeof value === 'number' && (value > 0 || main && value === 0);
894
890
  const isFont = (value) => value === 'truetype' || value === 'opentype' || value === 'woff' || value === 'woff2';
@@ -899,50 +895,12 @@ const isIgnored = (item, exists) => item.invalid || (0, types_1.ignoreFlag)(item
899
895
  const findFont = (value) => value && (Array.isArray(value) ? value : [value]).find(format => isFont(format));
900
896
  const spliceString = (source, startIndex, endIndex, content) => source.substring(0, startIndex) + content + source.substring(endIndex);
901
897
  const getEndIndex = (match) => match.index + match[0].length;
902
- const getRelativeURL = (file) => { var _a; return joinPath(file.moveTo, file.pathname, file.inlineFilename || file.filename) + (!file.static ? restoreSearchParams((_a = file.url) === null || _a === void 0 ? void 0 : _a.search) : ''); };
898
+ const getRelativeURL = (file) => joinPath(file.moveTo, file.pathname, file.inlineFilename || file.filename) + (!file.static ? restoreSearchParams(file.url?.search) : '');
903
899
  const errorHtml = ({ tagName, tagIndex = -1 }) => (0, types_1.errorMessage)('html', 'Location did not resolve', tagName.toLowerCase() + (tagIndex >= 0 ? ': ' + tagIndex : ''));
904
900
  const errorDataSource = (value, hint) => (0, types_1.errorMessage)('data-source', value, hint);
905
901
  class ChromeDocument extends Document {
906
- constructor() {
907
- super(...arguments);
908
- this.config = {
909
- usedVariables: undefined,
910
- usedFontFace: undefined,
911
- usedKeyframes: undefined,
912
- unusedStyles: undefined,
913
- unusedMedia: undefined,
914
- unusedContainer: undefined,
915
- unusedSupports: undefined,
916
- unusedAtRules: undefined,
917
- useOriginalHtmlPage: undefined,
918
- useUnsafeHtmlReplace: undefined,
919
- useUnsafeCssReplace: undefined,
920
- useSessionCache: undefined,
921
- stripCommentsAndCDATA: undefined,
922
- normalizeHtmlOutput: undefined,
923
- escapeReservedCharacters: undefined,
924
- ignoreServerCodeBlocks: undefined
925
- };
926
- this.htmlFile = null;
927
- this.cssFiles = [];
928
- this.jsFiles = [];
929
- this.svgFiles = [];
930
- this.baseDirectory = '';
931
- this.baseUrl = '';
932
- this.productionRelease = false;
933
- this.productionIncremental = false;
934
- this.templateMap = {};
935
- this.userAgentData = {};
936
- this.related = new Map();
937
- this.replaced = [];
938
- this._moduleName = 'chrome';
939
- this._threadable = true;
940
- this._elements = null;
941
- this._idMap = Object.create(null);
942
- this._editing = [];
943
- this._queryMap = new Map();
944
- this._selectorMap = new Map();
945
- }
902
+ static INTERNAL_ASSIGNUUID = "__assign__";
903
+ static INTERNAL_SERVERROOT = "__serverroot__";
946
904
  static async purgeMemory(percent = 1, limit = 0, parent) {
947
905
  if (typeof limit === 'boolean') {
948
906
  parent = limit;
@@ -977,7 +935,6 @@ class ChromeDocument extends Document {
977
935
  return result + (parent && result > 0 ? await super.purgeMemory(typeof parent === 'number' && parent > 0 ? parent : percent, limit, true) : 0);
978
936
  }
979
937
  static async finalize(instance) {
980
- var _a;
981
938
  if (instance.aborted) {
982
939
  return Promise.reject((0, types_1.createAbortError)());
983
940
  }
@@ -989,7 +946,7 @@ class ChromeDocument extends Document {
989
946
  db.writeTimeElapsed('DB', ["Transactions were committed", db.moduleName], processing.startTime, { ...Document.LOG_STYLE_SUCCESS, type: 65536 });
990
947
  }
991
948
  if (instance.dataSource.length === 0 && outHtml) {
992
- const incremental = (_a = htmlFile.incremental) !== null && _a !== void 0 ? _a : this.incremental;
949
+ const incremental = htmlFile.incremental ?? this.incremental;
993
950
  if (incremental === 'etag' || incremental === 'exists') {
994
951
  const fetched = this.fetchedAssets;
995
952
  const isHtmlOnly = () => !fetched.find(item => item !== htmlFile && assets.includes(item));
@@ -1084,35 +1041,34 @@ class ChromeDocument extends Document {
1084
1041
  }
1085
1042
  }
1086
1043
  let productionRelease = instance.productionRelease;
1087
- if (!(0, types_1.isString)(productionRelease)) {
1088
- return;
1089
- }
1090
- if (path.isAbsolute(productionRelease = path.normalize(productionRelease)) && isDir(productionRelease)) {
1091
- if (this.canWrite(productionRelease)) {
1092
- const serverRoot = ChromeDocument.INTERNAL_SERVERROOT;
1093
- const srcDir = path.join(this.baseDirectory, serverRoot);
1094
- if (isDir(srcDir)) {
1095
- const result = await Document.copyDir(srcDir, productionRelease, this.incremental !== 'staging');
1096
- const failed = result.failed.map(value => this.removeCwd(value));
1097
- for (const value of this.files) {
1098
- if (value.startsWith(serverRoot)) {
1099
- if (!failed.includes(value)) {
1100
- this.delete(value);
1101
- }
1102
- else {
1103
- instance.writeFail(["Unable to move file", instance.moduleName], (0, types_1.errorMessage)('production', path.join(this.baseDirectory, value)), { fatal: true });
1044
+ if ((0, types_1.isString)(productionRelease)) {
1045
+ if (path.isAbsolute(productionRelease = path.normalize(productionRelease)) && isDir(productionRelease)) {
1046
+ if (this.canWrite(productionRelease)) {
1047
+ const serverRoot = ChromeDocument.INTERNAL_SERVERROOT;
1048
+ const srcDir = path.join(this.baseDirectory, serverRoot);
1049
+ if (isDir(srcDir)) {
1050
+ const result = await Document.copyDir(srcDir, productionRelease, this.incremental !== 'staging');
1051
+ const failed = result.failed.map(value => this.removeCwd(value));
1052
+ for (const value of this.files) {
1053
+ if (value.startsWith(serverRoot)) {
1054
+ if (!failed.includes(value)) {
1055
+ this.delete(value);
1056
+ }
1057
+ else {
1058
+ instance.writeFail(["Unable to move file", instance.moduleName], (0, types_1.errorMessage)('production', path.join(this.baseDirectory, value)), { fatal: true });
1059
+ }
1104
1060
  }
1105
1061
  }
1106
1062
  }
1107
1063
  }
1064
+ else {
1065
+ instance.writeFail(["Unable to write directory", instance.moduleName], (0, types_1.errorMessage)('production', "Unsupported access", productionRelease));
1066
+ }
1108
1067
  }
1109
1068
  else {
1110
- instance.writeFail(["Unable to write directory", instance.moduleName], (0, types_1.errorMessage)('production', 'Access denied', productionRelease));
1069
+ instance.writeFail(["Unable to read directory", instance.moduleName], (0, types_1.errorMessage)('production', 'Invalid directory', productionRelease), 32);
1111
1070
  }
1112
1071
  }
1113
- else {
1114
- instance.writeFail(["Unable to read directory", instance.moduleName], (0, types_1.errorMessage)('production', 'Invalid directory', productionRelease), 32);
1115
- }
1116
1072
  }
1117
1073
  static sanitizeAssets(assets, exclusions = []) {
1118
1074
  assets.forEach(item => {
@@ -1137,6 +1093,50 @@ class ChromeDocument extends Document {
1137
1093
  }
1138
1094
  });
1139
1095
  }
1096
+ config = {
1097
+ usedVariables: undefined,
1098
+ usedFontFace: undefined,
1099
+ usedKeyframes: undefined,
1100
+ unusedStyles: undefined,
1101
+ unusedMedia: undefined,
1102
+ unusedSupports: undefined,
1103
+ unusedContainer: undefined,
1104
+ unusedScope: undefined,
1105
+ unusedAtRules: undefined,
1106
+ useOriginalHtmlPage: undefined,
1107
+ useUnsafeHtmlReplace: undefined,
1108
+ useUnsafeCssReplace: undefined,
1109
+ useSessionCache: undefined,
1110
+ stripCommentsAndCDATA: undefined,
1111
+ normalizeHtmlOutput: undefined,
1112
+ escapeReservedCharacters: undefined,
1113
+ ignoreServerCodeBlocks: undefined
1114
+ };
1115
+ htmlFile = null;
1116
+ cssFiles = [];
1117
+ jsFiles = [];
1118
+ svgFiles = [];
1119
+ baseDirectory = '';
1120
+ baseUrl = '';
1121
+ productionRelease = false;
1122
+ productionIncremental = false;
1123
+ templateMap = {};
1124
+ userAgentData = {};
1125
+ related = new Map();
1126
+ replaced = [];
1127
+ formatMap;
1128
+ _moduleName = 'chrome';
1129
+ _threadable = true;
1130
+ _dataSource;
1131
+ _mimeMap;
1132
+ _elements = null;
1133
+ _cloudUrlMap;
1134
+ _cloudUploaded;
1135
+ _cloudEndpoint;
1136
+ _idMap = Object.create(null);
1137
+ _editing = [];
1138
+ _queryMap = new Map();
1139
+ _selectorMap = new Map();
1140
1140
  init(assets, config) {
1141
1141
  assets.sort((a, b) => {
1142
1142
  if (!(0, types_1.isEmpty)(a.bundleId) && a.bundleId === b.bundleId) {
@@ -1166,19 +1166,15 @@ class ChromeDocument extends Document {
1166
1166
  else {
1167
1167
  item.editing = false;
1168
1168
  }
1169
- item.mimeType = 'text/html';
1170
1169
  break;
1171
1170
  case 'text/css':
1172
1171
  this.cssFiles.push(item);
1173
1172
  this._editing.push(item);
1174
- item.editing = true;
1175
- item.mimeType = 'text/css';
1176
1173
  break;
1177
1174
  case 'text/javascript':
1178
1175
  case 'application/javascript':
1179
1176
  this.jsFiles.push(item);
1180
1177
  this._editing.push(item);
1181
- item.editing = true;
1182
1178
  item.mimeType = 'application/javascript';
1183
1179
  break;
1184
1180
  }
@@ -1429,27 +1425,30 @@ class ChromeDocument extends Document {
1429
1425
  const instance = host.loadModule('compress');
1430
1426
  const buffer = host.getBuffer(file);
1431
1427
  if (instance && buffer) {
1432
- await instance.tryFile(buffer, { format: to, filename: file.filename, etag: file.etag }, (err, result, ext) => {
1433
- if (err) {
1434
- setFormat();
1435
- this.writeFail("Unable to compress file", err, 8);
1436
- }
1437
- else if (result) {
1428
+ const options = { format: to, filename: file.filename, etag: file.etag };
1429
+ await instance.tryFile(buffer, options)
1430
+ .then(result => {
1431
+ if (result) {
1432
+ let ext = options.outExt;
1438
1433
  if (ext) {
1439
1434
  setFormat(ext.startsWith('woff') ? ext : ext === 'otf' ? 'opentype' : 'truetype');
1440
1435
  }
1441
- const output = (0, types_1.renameExt)(localUri, ext || (ext = to));
1436
+ const output = (0, types_1.renameExt)(localUri, ext ||= to);
1442
1437
  file.mimeType = 'font/' + ext;
1443
- fs.writeFile(output, result, error => {
1444
- if (!error) {
1445
- file.buffer = result;
1438
+ fs.writeFile(output, result, err => {
1439
+ if (!err) {
1440
+ file.buffer = Buffer.from(result);
1446
1441
  host.replace(file, output);
1447
1442
  }
1448
1443
  else {
1449
- this.writeFail("Unable to write file", error, 32);
1444
+ this.writeFail("Unable to write file", err, 32);
1450
1445
  }
1451
1446
  });
1452
1447
  }
1448
+ })
1449
+ .catch((err) => {
1450
+ setFormat();
1451
+ this.writeFail("Unable to compress file", err, 8);
1453
1452
  });
1454
1453
  }
1455
1454
  break;
@@ -1584,8 +1583,6 @@ class ChromeDocument extends Document {
1584
1583
  return (trailing !== undefined ? [source, trailing] : source);
1585
1584
  }
1586
1585
  resolveImports(file, code, baseFile) {
1587
- var _a;
1588
- var _b;
1589
1586
  if (!Array.isArray(file.imports)) {
1590
1587
  return;
1591
1588
  }
@@ -1601,7 +1598,7 @@ class ChromeDocument extends Document {
1601
1598
  }
1602
1599
  const importMap = {};
1603
1600
  for (const item of file.imports) {
1604
- (importMap[_b = item.placeholder] || (importMap[_b] = [])).push(item);
1601
+ (importMap[item.placeholder] ||= []).push(item);
1605
1602
  }
1606
1603
  for (const placeholder in importMap) {
1607
1604
  const items = importMap[placeholder];
@@ -1613,7 +1610,7 @@ class ChromeDocument extends Document {
1613
1610
  const hosted = type === 'css';
1614
1611
  let value;
1615
1612
  if (hosted) {
1616
- const asset = (_a = this.host) === null || _a === void 0 ? void 0 : _a.findAsset(uri);
1613
+ const asset = this.host?.findAsset(uri);
1617
1614
  if (asset) {
1618
1615
  const [relativeUrl, sameDir] = getSrcURL.call(this, bundleMain || file, asset);
1619
1616
  if (relativeUrl) {
@@ -1626,7 +1623,7 @@ class ChromeDocument extends Document {
1626
1623
  }
1627
1624
  if (!value || !hosted && !Document.isPath(value)) {
1628
1625
  if (i < length - 1) {
1629
- found || (found = value);
1626
+ found ||= value;
1630
1627
  continue;
1631
1628
  }
1632
1629
  value = found || original;
@@ -1642,13 +1639,12 @@ class ChromeDocument extends Document {
1642
1639
  }
1643
1640
  }
1644
1641
  replaceContent(source, statement, mimeType) {
1645
- var _a;
1646
1642
  switch (mimeType) {
1647
1643
  case 'text/css': {
1648
1644
  const match = REGEXP_REPLACECSS.exec((typeof statement === 'string' ? statement : statement[0]).trim());
1649
1645
  if (match) {
1650
1646
  const layer = match[1];
1651
- const supports = (_a = match[3]) === null || _a === void 0 ? void 0 : _a.trim();
1647
+ const supports = match[3]?.trim();
1652
1648
  const query = match[4].trim();
1653
1649
  if (layer || supports || query) {
1654
1650
  const newline = (0, util_1.getNewline)(source);
@@ -1685,12 +1681,11 @@ class ChromeDocument extends Document {
1685
1681
  }
1686
1682
  }
1687
1683
  writeImage(data) {
1688
- var _a;
1689
1684
  const { file, output, command } = data;
1690
- if (output && command && ((_a = file.element) === null || _a === void 0 ? void 0 : _a.outerXml)) {
1685
+ if (output && command && file.element?.outerXml) {
1691
1686
  const match = REGEXP_SRCSETSIZE.exec(command);
1692
1687
  if (match) {
1693
- (file.srcSet || (file.srcSet = [])).push(toPosix(data.baseDirectory ? output.substring(data.baseDirectory.length + 1) : output), match[1] + match[2].toLowerCase());
1688
+ (file.srcSet ||= []).push(toPosix(data.baseDirectory ? output.substring(data.baseDirectory.length + 1) : output), match[1] + match[2].toLowerCase());
1694
1689
  file.modified = true;
1695
1690
  return true;
1696
1691
  }
@@ -1698,13 +1693,12 @@ class ChromeDocument extends Document {
1698
1693
  return false;
1699
1694
  }
1700
1695
  cloudInit({ instance }) {
1701
- var _a, _b;
1702
1696
  this._cloudUrlMap = Object.create(null);
1703
1697
  this._cloudUploaded = new Set();
1704
1698
  this._cloudEndpoint = null;
1705
1699
  const htmlFile = this.htmlFile;
1706
1700
  if (htmlFile) {
1707
- const endpoint = (_b = (_a = instance.getStorage('upload', htmlFile.cloudStorage)) === null || _a === void 0 ? void 0 : _a.upload) === null || _b === void 0 ? void 0 : _b.endpoint;
1701
+ const endpoint = instance.getStorage('upload', htmlFile.cloudStorage)?.upload?.endpoint;
1708
1702
  if (endpoint) {
1709
1703
  this._cloudEndpoint = new RegExp((0, types_1.escapePattern)(toPosix(endpoint)) + '/', 'g');
1710
1704
  }
@@ -1717,7 +1711,6 @@ class ChromeDocument extends Document {
1717
1711
  return this.editing.includes(file);
1718
1712
  }
1719
1713
  async cloudUpload({ host }, file, url, active) {
1720
- var _a;
1721
1714
  if (active) {
1722
1715
  const endpoint = this._cloudEndpoint;
1723
1716
  const inlineUrlCloud = file.inlineUrlCloud;
@@ -1726,7 +1719,7 @@ class ChromeDocument extends Document {
1726
1719
  if (inlineUrlCloud) {
1727
1720
  const pattern = new RegExp((0, types_1.escapePattern)(inlineUrlCloud), 'g');
1728
1721
  for (const item of this.editing) {
1729
- if ((_a = item.inlineUrlCloudMap) === null || _a === void 0 ? void 0 : _a[inlineUrlCloud]) {
1722
+ if (item.inlineUrlCloudMap?.[inlineUrlCloud]) {
1730
1723
  const source = host.getUTF8String(item);
1731
1724
  const output = source.replace(pattern, endpoint && item.imported && cloudUrl.includes('/') ? url : cloudUrl);
1732
1725
  if (source !== output) {
@@ -1741,12 +1734,12 @@ class ChromeDocument extends Document {
1741
1734
  return false;
1742
1735
  }
1743
1736
  async cloudFinalize(state) {
1744
- var _a;
1745
1737
  if (this.aborted) {
1746
1738
  return Promise.reject((0, types_1.createAbortError)());
1747
1739
  }
1748
1740
  const { host, instance, localStorage } = state;
1749
1741
  const htmlFile = this.htmlFile;
1742
+ const preferBuffer = process.env.EMC_CLOUD_UPLOAD_BUFFER === 'true';
1750
1743
  const checkDocument = (item) => {
1751
1744
  if (item.inlineUrlCloudMap) {
1752
1745
  const source = host.getUTF8String(item);
@@ -1760,7 +1753,7 @@ class ChromeDocument extends Document {
1760
1753
  }
1761
1754
  if (output && output !== source) {
1762
1755
  try {
1763
- fs.writeFileSync(item.localUri, output, item.encoding || (item.encoding = 'utf-8'));
1756
+ fs.writeFileSync(item.localUri, output, item.encoding ||= 'utf-8');
1764
1757
  item.sourceUTF8 = output;
1765
1758
  }
1766
1759
  catch (err) {
@@ -1776,7 +1769,7 @@ class ChromeDocument extends Document {
1776
1769
  if (item.compress) {
1777
1770
  await host.compressFile(item);
1778
1771
  }
1779
- await Promise.all(Cloud.uploadAsset(state, item, item.mimeType));
1772
+ await Promise.all(Cloud.uploadAsset(state, item, { preferBuffer }));
1780
1773
  }
1781
1774
  }
1782
1775
  if (this.aborted) {
@@ -1789,8 +1782,8 @@ class ChromeDocument extends Document {
1789
1782
  if ((0, types_1.isArray)(cloudStorage)) {
1790
1783
  for (const storage of cloudStorage) {
1791
1784
  if (instance.hasCredential('storage', storage)) {
1792
- const { service, admin, bucket, upload } = storage;
1793
- const website = (_a = admin === null || admin === void 0 ? void 0 : admin.configBucket) === null || _a === void 0 ? void 0 : _a.website;
1785
+ const { admin, bucket, upload } = storage;
1786
+ const website = admin?.configBucket?.website;
1794
1787
  if ((0, types_1.isPlainObject)(website) && bucket && upload) {
1795
1788
  let filename = joinPath(upload.pathname, upload.filename || path.basename(htmlFile.localUri));
1796
1789
  if (website.indexPage === true) {
@@ -1808,14 +1801,14 @@ class ChromeDocument extends Document {
1808
1801
  if (website.errorPath === true) {
1809
1802
  website.errorPath = filename;
1810
1803
  }
1811
- instance.setBucketWebsite(service, instance.getCredential(storage), bucket, website);
1804
+ instance.setBucketWebsite(storage.service, instance.getCredential(storage), bucket, website);
1812
1805
  }
1813
1806
  }
1814
1807
  }
1815
1808
  if (htmlFile.compress) {
1816
1809
  await host.compressFile(htmlFile);
1817
1810
  }
1818
- return Promise.all(Cloud.uploadAsset(state, htmlFile, 'text/html', true));
1811
+ return Promise.all(Cloud.uploadAsset(state, htmlFile, { preferBuffer, contentType: 'text/html', ignoreProcess: true }));
1819
1812
  }
1820
1813
  }
1821
1814
  return [];
@@ -1826,7 +1819,7 @@ class ChromeDocument extends Document {
1826
1819
  }
1827
1820
  const main = watch.main;
1828
1821
  let result;
1829
- if ((main === null || main === void 0 ? void 0 : main.editing) && main.mimeType === 'text/html') {
1822
+ if (main?.editing && main.mimeType === 'text/html') {
1830
1823
  const inlineUrlCloudMap = main.inlineUrlCloudMap || {};
1831
1824
  const using = [];
1832
1825
  let found;
@@ -1863,7 +1856,6 @@ class ChromeDocument extends Document {
1863
1856
  }
1864
1857
  watchModified(watch, assets) {
1865
1858
  return (files, errors, status) => {
1866
- var _a;
1867
1859
  if (!watch.server || watch.captured || watch.aborted) {
1868
1860
  return;
1869
1861
  }
@@ -1883,8 +1875,8 @@ class ChromeDocument extends Document {
1883
1875
  search = next.url.search;
1884
1876
  }
1885
1877
  }
1886
- search !== null && search !== void 0 ? search : (search = restoreSearchParams((_a = asset.url) === null || _a === void 0 ? void 0 : _a.search));
1887
- status && (status = status.filter(item => item.type >= types_1.STATUS_TYPE.FATAL && item.type <= types_1.STATUS_TYPE.WARN));
1878
+ search ??= restoreSearchParams(asset.url?.search);
1879
+ status &&= status.filter(item => item.type >= types_1.STATUS_TYPE.FATAL && item.type <= types_1.STATUS_TYPE.WARN);
1888
1880
  watch.send(types_1.WATCH_EVENT.MODIFIED, {
1889
1881
  action: pathname && watch.hot && !watch.main ? 'hot' : '',
1890
1882
  type: asset.mimeType,
@@ -1955,13 +1947,11 @@ class ChromeDocument extends Document {
1955
1947
  }
1956
1948
  }
1957
1949
  findDataValue(name) {
1958
- var _a;
1959
1950
  if (this.hasEval('template')) {
1960
- return (_a = this.templateMap.data) === null || _a === void 0 ? void 0 : _a[name];
1951
+ return this.templateMap.data?.[name];
1961
1952
  }
1962
1953
  }
1963
1954
  setInlinedAttributes({ host, startTime, hashed, contentMap, bufferMap, productionRelease }) {
1964
- var _a, _b;
1965
1955
  const readBase64 = (item, uuid) => {
1966
1956
  if (!contentMap[uuid]) {
1967
1957
  try {
@@ -1991,7 +1981,7 @@ class ChromeDocument extends Document {
1991
1981
  const filename = hash && createHash(host, item, hash, bufferMap);
1992
1982
  if (filename) {
1993
1983
  for (const asset of this.assets) {
1994
- const url = inlineUrl ? (_a = asset.inlineUrlMap) === null || _a === void 0 ? void 0 : _a[inlineUrl] : (_b = asset.inlineUrlCloudMap) === null || _b === void 0 ? void 0 : _b[inlineUrlCloud];
1984
+ const url = inlineUrl ? asset.inlineUrlMap?.[inlineUrl] : asset.inlineUrlCloudMap?.[inlineUrlCloud];
1995
1985
  if (url) {
1996
1986
  const search = url.indexOf('?');
1997
1987
  const index = (search !== -1 ? url.substring(0, search) : url).lastIndexOf('/');
@@ -2039,10 +2029,10 @@ class ChromeDocument extends Document {
2039
2029
  const sortNested = (a, b) => {
2040
2030
  const { inlineUrlCloud: urlA, inlineUrlCloudMap: mapA } = a;
2041
2031
  const { inlineUrlCloud: urlB, inlineUrlCloudMap: mapB } = b;
2042
- if (urlA && (mapB === null || mapB === void 0 ? void 0 : mapB[urlA])) {
2032
+ if (urlA && mapB?.[urlA]) {
2043
2033
  return -1;
2044
2034
  }
2045
- if (urlB && (mapA === null || mapA === void 0 ? void 0 : mapA[urlB])) {
2035
+ if (urlB && mapA?.[urlB]) {
2046
2036
  return 1;
2047
2037
  }
2048
2038
  return 0;
@@ -2236,7 +2226,6 @@ class ChromeDocument extends Document {
2236
2226
  htmlFile.sourceUTF8 = source;
2237
2227
  }
2238
2228
  async setElementAttributes({ host, startTime, productionRelease }, domBase) {
2239
- var _a;
2240
2229
  const { moduleName, htmlFile } = this;
2241
2230
  const cloud = host.Cloud;
2242
2231
  const removeWatchReload = (item) => (0, types_1.isObject)(item.watch) && delete item.watch.reload;
@@ -2272,9 +2261,9 @@ class ChromeDocument extends Document {
2272
2261
  }
2273
2262
  }
2274
2263
  if (uri && !(0, util_1.hasValue)(item.format, 'crossorigin') && item !== htmlFile) {
2275
- if (cloud === null || cloud === void 0 ? void 0 : cloud.getStorage('upload', item.cloudStorage)) {
2276
- const inlineUrlCloud = item.inlineUrlCloud || (item.inlineUrlCloud = (0, types_1.generateUUID)());
2277
- ((_a = htmlFile).inlineUrlCloudMap || (_a.inlineUrlCloudMap = {}))[inlineUrlCloud] = productionRelease ? this.removeServerRoot(uri) : uri;
2264
+ if (cloud?.getStorage('upload', item.cloudStorage)) {
2265
+ const inlineUrlCloud = item.inlineUrlCloud ||= (0, types_1.generateUUID)();
2266
+ (htmlFile.inlineUrlCloudMap ||= {})[inlineUrlCloud] = productionRelease ? this.removeServerRoot(uri) : uri;
2278
2267
  uri = inlineUrlCloud;
2279
2268
  }
2280
2269
  if (!(0, util_1.hasValue)(item.format, 'webbundle')) {
@@ -2365,12 +2354,13 @@ class ChromeDocument extends Document {
2365
2354
  const cloud = host.Cloud;
2366
2355
  const sessionKey = (0, types_1.generateUUID)();
2367
2356
  const cacheData = Object.create(null);
2357
+ const coerceMap = {};
2368
2358
  const dataItems = [];
2369
2359
  const displayItems = [];
2370
2360
  this.dataSource.forEach(item => item.type === 'display' ? displayItems.push(item) : dataItems.push(item));
2371
2361
  const removeElement = (item, element) => {
2372
2362
  if (item.removeEmpty || item.type === 'display') {
2373
- (element || (element = new dom_1.HtmlElement(moduleName, item.element))).remove = true;
2363
+ (element ||= new dom_1.HtmlElement(moduleName, item.element)).remove = true;
2374
2364
  if (!domBase.write(element)) {
2375
2365
  this.writeFail('Unable to remove element', errorHtml(item.element), { type: 4, startTime });
2376
2366
  }
@@ -2383,7 +2373,7 @@ class ChromeDocument extends Document {
2383
2373
  this.writeFail(["Invalid credentials", item.source], err);
2384
2374
  }
2385
2375
  };
2386
- const checkObject = (item, data) => {
2376
+ const checkObject = (item, data, type) => {
2387
2377
  const { query, cascade } = item;
2388
2378
  if ((0, types_1.isString)(cascade)) {
2389
2379
  const result = data && (0, types_1.cascadeObject)(data, cascade, data);
@@ -2413,6 +2403,9 @@ class ChromeDocument extends Document {
2413
2403
  this.checkPackage(err, pkg, ["Unable to filter results", item.source]);
2414
2404
  }
2415
2405
  }
2406
+ if (type && !item.ignoreCoerce && (coerceMap[type] ??= this.settingsOf(type, 'coerce') === true)) {
2407
+ (0, types_1.coerceObject)(data);
2408
+ }
2416
2409
  }
2417
2410
  return Array.isArray(data) ? data : (0, types_1.isObject)(data) ? [data] : null;
2418
2411
  };
@@ -2430,7 +2423,7 @@ class ChromeDocument extends Document {
2430
2423
  const { service, credential } = item;
2431
2424
  if (cloud) {
2432
2425
  const key = service + '_' + (service === 'atlas' && item.uri || '') + '_' + asString(credential, true);
2433
- (batchMap[key] || (batchMap[key] = [])).push(item);
2426
+ (batchMap[key] ||= []).push(item);
2434
2427
  }
2435
2428
  else {
2436
2429
  errorCredential(item, (0, types_1.errorValue)("Cloud module not installed", service));
@@ -2444,7 +2437,7 @@ class ChromeDocument extends Document {
2444
2437
  batchGroup.push([item]);
2445
2438
  break;
2446
2439
  default:
2447
- if (db === null || db === void 0 ? void 0 : db.hasSource(type)) {
2440
+ if (db?.hasSource(type)) {
2448
2441
  try {
2449
2442
  await db.setCredential(item);
2450
2443
  const credential = item.credential;
@@ -2460,7 +2453,7 @@ class ChromeDocument extends Document {
2460
2453
  key = core_1.ClientDb.keyOfResult(type, credential);
2461
2454
  break;
2462
2455
  }
2463
- (batchMap[key] || (batchMap[key] = [])).push(item);
2456
+ (batchMap[key] ||= []).push(item);
2464
2457
  }
2465
2458
  catch (err) {
2466
2459
  errorCredential(item, err);
@@ -2477,7 +2470,6 @@ class ChromeDocument extends Document {
2477
2470
  }
2478
2471
  return this.allSettled(batchGroup.map(async (batch) => {
2479
2472
  return new Promise(async (resolve, reject) => {
2480
- var _a, _b, _c;
2481
2473
  const errorRemove = (item, reason) => {
2482
2474
  removeElement(item);
2483
2475
  reject(reason);
@@ -2495,7 +2487,7 @@ class ChromeDocument extends Document {
2495
2487
  let result = new Array(length), errors;
2496
2488
  switch (type) {
2497
2489
  case 'cloud':
2498
- result = await cloud.getDatabaseBatchRows(batch, true, sessionKey).catch(err => {
2490
+ result = await cloud.getDatabaseBatchRows(batch, true, sessionKey).catch((err) => {
2499
2491
  this.abort(type);
2500
2492
  if (err instanceof Error) {
2501
2493
  cloud.addLog(this.aborted ? types_1.STATUS_TYPE.ERROR : types_1.STATUS_TYPE.WARN, errors = err);
@@ -2504,49 +2496,43 @@ class ChromeDocument extends Document {
2504
2496
  });
2505
2497
  break;
2506
2498
  case 'json':
2507
- if ((result[0] = checkObject(current, current.items)) === null) {
2499
+ if ((result[0] = checkObject(current, current.items, type)) === null) {
2508
2500
  this.abort(type);
2509
2501
  errorRemove(current, errorDataSource("Invalid parameters" + ' (items)', type));
2510
2502
  return;
2511
2503
  }
2512
- if (this.settingsOf(type, 'coerce') === true) {
2513
- (0, types_1.coerceObject)(result[0]);
2514
- }
2515
2504
  break;
2516
2505
  case 'uri':
2517
2506
  case 'local': {
2518
- const { ignoreCache, encoding = 'utf-8', options } = current;
2507
+ const encoding = current.encoding || 'utf-8';
2519
2508
  let content, target, data, cacheKey;
2520
2509
  if (type === 'local') {
2521
2510
  let location;
2522
- ({ pathname: target } = current);
2523
- if (target && ((location = this.resolveDir('data', target)) || host.canRead(location = path.resolve(target), { ownPermissionOnly: true }))) {
2524
- if (!ignoreCache && CACHE_DBRESULT.has(location)) {
2525
- data = getCacheItem(CACHE_DBRESULT, location);
2511
+ if (!(0, types_1.isString)(target = current.pathname) || !((location = this.resolveDir('data', target)) || host.canRead(location = path.resolve(target), { ownPermissionOnly: true }))) {
2512
+ this.abort(type);
2513
+ errorRemove(current, target ? errorDataSource('Not found', target) : errorDataSource('Not defined - ' + (this.settings.directory?.data ? 'file' : 'directory'), type));
2514
+ return;
2515
+ }
2516
+ if (!current.ignoreCache && CACHE_DBRESULT.has(location)) {
2517
+ data = getCacheItem(CACHE_DBRESULT, location);
2518
+ }
2519
+ else {
2520
+ if (current.ignoreCache === 1) {
2521
+ CACHE_DBRESULT.delete(location);
2526
2522
  }
2527
- else {
2528
- if (ignoreCache === 1) {
2529
- CACHE_DBRESULT.delete(location);
2523
+ if (!(data = cacheData[location])) {
2524
+ try {
2525
+ content = fs.readFileSync(location, encoding);
2526
+ cacheKey = location;
2530
2527
  }
2531
- if (!(data = cacheData[location])) {
2532
- try {
2533
- content = fs.readFileSync(location, encoding);
2534
- cacheKey = location;
2535
- }
2536
- catch (err) {
2537
- this.abort(type);
2538
- this.writeFail(["Unable to read file", path.basename(location)], err, { type: 32, startTime });
2539
- errorRemove(current);
2540
- return;
2541
- }
2528
+ catch (err) {
2529
+ this.abort(type);
2530
+ this.writeFail(["Unable to read file", path.basename(location)], err, { type: 32, startTime });
2531
+ errorRemove(current);
2532
+ return;
2542
2533
  }
2543
2534
  }
2544
2535
  }
2545
- else {
2546
- this.abort(type);
2547
- errorRemove(current, target ? errorDataSource('Not found', target) : errorDataSource('Not defined - ' + (((_a = this.settings.directory) === null || _a === void 0 ? void 0 : _a.data) ? 'file' : 'directory'), type));
2548
- return;
2549
- }
2550
2536
  }
2551
2537
  else if (!(0, types_1.isString)(target = current.uri)) {
2552
2538
  this.abort(type);
@@ -2569,11 +2555,11 @@ class ChromeDocument extends Document {
2569
2555
  return;
2570
2556
  }
2571
2557
  }
2572
- else if (!ignoreCache && CACHE_DBRESULT.has(target)) {
2558
+ else if (!current.ignoreCache && CACHE_DBRESULT.has(target)) {
2573
2559
  data = getCacheItem(CACHE_DBRESULT, target);
2574
2560
  }
2575
2561
  else {
2576
- if (ignoreCache === 1) {
2562
+ if (current.ignoreCache === 1) {
2577
2563
  CACHE_DBRESULT.delete(target);
2578
2564
  }
2579
2565
  if (!(data = cacheData[target])) {
@@ -2592,17 +2578,17 @@ class ChromeDocument extends Document {
2592
2578
  }
2593
2579
  else {
2594
2580
  const pathname = Document.resolveFile(target);
2595
- if (!ignoreCache && CACHE_DBRESULT.has(pathname)) {
2581
+ if (!current.ignoreCache && CACHE_DBRESULT.has(pathname)) {
2596
2582
  data = getCacheItem(CACHE_DBRESULT, pathname);
2597
2583
  }
2598
2584
  else {
2599
- if (ignoreCache === 1) {
2585
+ if (current.ignoreCache === 1) {
2600
2586
  CACHE_DBRESULT.delete(pathname);
2601
2587
  }
2602
2588
  if (!(data = cacheData[pathname])) {
2603
2589
  if (!host.canRead(pathname, { ownPermissionOnly: true })) {
2604
2590
  this.abort(type);
2605
- errorRemove(current, errorDataSource('Access denied', pathname));
2591
+ errorRemove(current, errorDataSource("Unsupported access", pathname));
2606
2592
  return;
2607
2593
  }
2608
2594
  try {
@@ -2624,11 +2610,11 @@ class ChromeDocument extends Document {
2624
2610
  if ((0, types_1.isString)(content)) {
2625
2611
  const { format = path.extname(target).substring(1) } = current;
2626
2612
  try {
2627
- data = this.tryParse(content, format, options);
2613
+ data = this.tryParse(content, format, current.options);
2628
2614
  }
2629
2615
  catch (err) {
2630
2616
  this.abort(type);
2631
- this.writeFail(['Unable to parse data source', format], err, { type: 4, startTime });
2617
+ this.writeFail(["Unable to parse inline object", format], err, { type: 4, startTime });
2632
2618
  errorRemove(current);
2633
2619
  return;
2634
2620
  }
@@ -2639,37 +2625,34 @@ class ChromeDocument extends Document {
2639
2625
  }
2640
2626
  if (!data) {
2641
2627
  this.abort(type);
2642
- errorRemove(current, errorDataSource(content !== null ? 'Invalid response' : 'Empty response', target));
2628
+ errorRemove(current, errorDataSource(content !== null ? "Invalid response" : "Unknown", target));
2643
2629
  return;
2644
2630
  }
2645
2631
  if (cacheKey) {
2646
2632
  setCacheData.call(this, current, data, cacheKey, cacheData);
2647
2633
  }
2648
- if ((result[0] = checkObject(current, data)) === null) {
2634
+ if ((result[0] = checkObject(current, data, type)) === null) {
2649
2635
  this.abort(type);
2650
2636
  errorRemove(current, errorDataSource('Invalid ' + (current.query ? 'query' : 'URI'), target));
2651
2637
  return;
2652
2638
  }
2653
- if (this.settingsOf(type, 'coerce') === true) {
2654
- (0, types_1.coerceObject)(result[0]);
2655
- }
2656
2639
  break;
2657
2640
  }
2658
2641
  case 'export': {
2659
- const ignoreCache = current.ignoreCache;
2660
2642
  const cacheKey = asString(current, true);
2661
- if (!ignoreCache && CACHE_DBRESULT.has(cacheKey)) {
2643
+ if (!current.ignoreCache && CACHE_DBRESULT.has(cacheKey)) {
2662
2644
  result[0] = getCacheItem(CACHE_DBRESULT, cacheKey);
2663
2645
  }
2664
2646
  else {
2665
- if (ignoreCache === 1) {
2647
+ if (current.ignoreCache === 1) {
2666
2648
  CACHE_DBRESULT.delete(cacheKey);
2667
2649
  }
2668
2650
  if (cacheKey in cacheData) {
2669
2651
  result[0] = cacheData[cacheKey];
2670
2652
  }
2671
2653
  else {
2672
- let { pathname, execute, params } = current, data, target, getData, hint;
2654
+ const { pathname, execute, params } = current;
2655
+ let data, target, getData, hint;
2673
2656
  if (typeof execute === 'function') {
2674
2657
  target = execute;
2675
2658
  }
@@ -2677,7 +2660,7 @@ class ChromeDocument extends Document {
2677
2660
  target = pathname;
2678
2661
  }
2679
2662
  else if ((0, types_1.isString)(pathname)) {
2680
- if ((pathname = pathname.trim()).startsWith('npm:')) {
2663
+ if (pathname.startsWith('npm:')) {
2681
2664
  target = pathname;
2682
2665
  hint = pathname;
2683
2666
  }
@@ -2690,7 +2673,7 @@ class ChromeDocument extends Document {
2690
2673
  }
2691
2674
  if (!getData) {
2692
2675
  const { settings, encoding, persist = true } = current;
2693
- target || (target = settings && ((_b = this.settings.export) === null || _b === void 0 ? void 0 : _b[settings]) || pathname);
2676
+ target ||= settings && this.settings.export?.[settings] || pathname;
2694
2677
  if (typeof target === 'function') {
2695
2678
  getData = target;
2696
2679
  hint = target.name;
@@ -2705,7 +2688,7 @@ class ChromeDocument extends Document {
2705
2688
  return;
2706
2689
  }
2707
2690
  try {
2708
- if (params && this.settingsOf(type, 'coerce') === true) {
2691
+ if (params && !current.ignoreCoerce && this.settingsOf(type, 'coerce') === true) {
2709
2692
  (0, types_1.coerceObject)(params);
2710
2693
  }
2711
2694
  if (getData["__cjs__"]) {
@@ -2749,136 +2732,129 @@ class ChromeDocument extends Document {
2749
2732
  break;
2750
2733
  }
2751
2734
  default:
2752
- if (db === null || db === void 0 ? void 0 : db.hasSource(type)) {
2753
- switch (type) {
2754
- case 'mongodb':
2755
- for (let j = 0; j < length; ++j) {
2756
- const cmd = batch[j];
2757
- cmd.cacheObjectKey = typeof cmd.cascade === 'string' ? cmd.cascade : '';
2758
- }
2759
- break;
2760
- case 'redis':
2761
- for (let j = 0; j < length; ++j) {
2762
- const cmd = batch[j];
2763
- const { search, key, query, cascade } = cmd;
2764
- if ((0, types_1.isObject)(search) && typeof search.schema === 'string') {
2765
- const pathname = this.resolveDir('schema', search.schema);
2766
- if (pathname) {
2767
- const ignoreCache = cmd.ignoreCache;
2768
- if (!ignoreCache && CACHE_LOCALFILE.has(pathname)) {
2769
- search.schema = getCacheItem(CACHE_LOCALFILE, pathname);
2735
+ if (!db?.hasSource(type)) {
2736
+ errorRemove(current, errorDataSource('Not found', type || "Unknown"));
2737
+ return;
2738
+ }
2739
+ switch (type) {
2740
+ case 'mongodb':
2741
+ for (let j = 0; j < length; ++j) {
2742
+ const cmd = batch[j];
2743
+ cmd.cacheObjectKey = typeof cmd.cascade === 'string' ? cmd.cascade : '';
2744
+ }
2745
+ break;
2746
+ case 'redis':
2747
+ for (let j = 0; j < length; ++j) {
2748
+ const cmd = batch[j];
2749
+ const { search, key, query, cascade } = cmd;
2750
+ if ((0, types_1.isObject)(search) && typeof search.schema === 'string') {
2751
+ const pathname = this.resolveDir('schema', search.schema);
2752
+ if (pathname) {
2753
+ if (!cmd.ignoreCache && CACHE_LOCALFILE.has(pathname)) {
2754
+ search.schema = getCacheItem(CACHE_LOCALFILE, pathname);
2755
+ }
2756
+ else {
2757
+ if (cmd.ignoreCache === 1) {
2758
+ CACHE_LOCALFILE.delete(pathname);
2770
2759
  }
2771
- else {
2772
- if (ignoreCache === 1) {
2773
- CACHE_LOCALFILE.delete(pathname);
2760
+ if (!(search.schema = cacheData[pathname])) {
2761
+ try {
2762
+ search.schema = loadLocalFile.call(this, current, pathname, cacheData, cmd.encoding);
2774
2763
  }
2775
- if (!(search.schema = cacheData[pathname])) {
2776
- try {
2777
- search.schema = loadLocalFile.call(this, current, pathname, cacheData, cmd.encoding);
2778
- }
2779
- catch (err) {
2780
- this.writeFail(['Unable to parse document', path.basename(pathname)], err instanceof Error ? errors = err : err, { startTime });
2781
- search.schema = undefined;
2782
- }
2764
+ catch (err) {
2765
+ this.writeFail(['Unable to parse document', path.basename(pathname)], err instanceof Error ? errors = err : err, { startTime });
2766
+ search.schema = undefined;
2783
2767
  }
2784
2768
  }
2785
2769
  }
2786
- else {
2787
- search.schema = undefined;
2788
- }
2789
2770
  }
2790
- if (key) {
2791
- cmd.cacheObjectKey = ((0, types_1.isString)(cascade) ? cascade : '') + '_' + ((0, types_1.isString)(query) ? query : '');
2771
+ else {
2772
+ search.schema = undefined;
2792
2773
  }
2793
2774
  }
2794
- break;
2795
- default:
2796
- if (db.hasSource(type, db.sourceType.SQL)) {
2797
- for (let j = 0; j < length; ++j) {
2798
- const cmd = batch[j];
2799
- const query = cmd.query;
2800
- if (typeof query === 'string' && query.endsWith('.sql')) {
2801
- const pathname = this.resolveDir('sql', query);
2802
- try {
2803
- if (pathname) {
2804
- const ignoreCache = cmd.ignoreCache;
2805
- if (!ignoreCache && CACHE_LOCALFILE.has(pathname)) {
2806
- cmd.query = getCacheItem(CACHE_LOCALFILE, pathname);
2775
+ if (key) {
2776
+ cmd.cacheObjectKey = ((0, types_1.isString)(cascade) ? cascade : '') + '_' + ((0, types_1.isString)(query) ? query : '');
2777
+ }
2778
+ }
2779
+ break;
2780
+ default:
2781
+ if (db.hasSource(type, db.sourceType.SQL)) {
2782
+ for (let j = 0; j < length; ++j) {
2783
+ const cmd = batch[j];
2784
+ const query = cmd.query;
2785
+ if (typeof query === 'string' && query.endsWith('.sql')) {
2786
+ const pathname = this.resolveDir('sql', query);
2787
+ try {
2788
+ if (pathname) {
2789
+ if (!cmd.ignoreCache && CACHE_LOCALFILE.has(pathname)) {
2790
+ cmd.query = getCacheItem(CACHE_LOCALFILE, pathname);
2791
+ }
2792
+ else {
2793
+ if (cmd.ignoreCache === 1) {
2794
+ CACHE_LOCALFILE.delete(pathname);
2807
2795
  }
2808
- else {
2809
- if (ignoreCache === 1) {
2810
- CACHE_LOCALFILE.delete(pathname);
2796
+ if (!(cmd.query = cacheData[pathname])) {
2797
+ const out = { content: '' };
2798
+ try {
2799
+ cmd.query = loadLocalFile.call(this, current, pathname, cacheData, cmd.encoding, out);
2811
2800
  }
2812
- if (!(cmd.query = cacheData[pathname])) {
2813
- const out = { content: '' };
2814
- try {
2815
- cmd.query = loadLocalFile.call(this, current, pathname, cacheData, cmd.encoding, out);
2816
- }
2817
- catch {
2818
- setCacheData.call(this, current, cmd.query = out.content, pathname, cacheData, true);
2819
- }
2801
+ catch {
2802
+ setCacheData.call(this, current, cmd.query = out.content, pathname, cacheData, true);
2820
2803
  }
2821
2804
  }
2822
2805
  }
2823
- else {
2824
- throw (0, types_1.errorMessage)(type, "File not found", query);
2825
- }
2826
2806
  }
2827
- catch (err) {
2828
- this.abort(type);
2829
- this.writeFail(["Unable to read file", pathname ? path.basename(pathname) : query], err, { startTime });
2830
- errorRemove(current);
2831
- return;
2807
+ else {
2808
+ throw (0, types_1.errorMessage)(type, "File not found", query);
2832
2809
  }
2833
2810
  }
2811
+ catch (err) {
2812
+ this.abort(type);
2813
+ this.writeFail(["Unable to read file", pathname ? path.basename(pathname) : query], err, { startTime });
2814
+ errorRemove(current);
2815
+ return;
2816
+ }
2834
2817
  }
2835
2818
  }
2836
- break;
2837
- }
2838
- try {
2839
- let coerce, cache;
2840
- if (type === 'mongodb' || type === 'redis') {
2841
- coerce = this.settingsOf(type, 'coerce');
2842
- cache = this.settingsOf(type, 'cache');
2843
2819
  }
2844
- const errorQuery = (err, data, commandType) => {
2845
- let message, aborting = true;
2846
- if (db.hasSource(type, db.sourceType.DOCUMENT)) {
2847
- message = (data.name ? data.name + ': ' : '') + (data.table || '');
2848
- }
2849
- else if (db.hasSource(type, db.sourceType.KEYVALUE)) {
2850
- aborting = commandType !== db.commandType.UPDATE;
2851
- message = asString(data.search || data.key);
2852
- }
2853
- else {
2854
- const credential = data.credential;
2855
- if ((0, types_1.isPlainObject)(credential)) {
2856
- message = credential.database;
2857
- }
2858
- }
2859
- if (data.willAbort) {
2860
- this.abort(undefined, err);
2861
- }
2862
- else if (aborting) {
2863
- this.abort(type, err);
2864
- }
2865
- if (err) {
2866
- this.writeFail(["Unable to execute query", message || "Unknown"], err instanceof Error ? errors = err : err, { type: 65536, startTime });
2820
+ break;
2821
+ }
2822
+ try {
2823
+ const errorQuery = (err, data, commandType) => {
2824
+ let message, aborting = true;
2825
+ if (db.hasSource(type, db.sourceType.DOCUMENT)) {
2826
+ message = (data.name ? data.name + ': ' : '') + (data.table || '');
2827
+ }
2828
+ else if (db.hasSource(type, db.sourceType.KEYVALUE)) {
2829
+ aborting = commandType !== db.commandType.UPDATE;
2830
+ message = asString(data.search || data.key);
2831
+ }
2832
+ else {
2833
+ const credential = data.credential;
2834
+ if ((0, types_1.isPlainObject)(credential)) {
2835
+ message = credential.database;
2867
2836
  }
2868
- return this.aborted;
2869
- };
2870
- const options = { coerce, cache, checkObject, sessionKey, connectOnce: length > 1, outCacheMiss: cacheMiss, errorQuery };
2871
- result = await db.executeBatchQuery(batch, options, result);
2872
- }
2873
- catch (err) {
2874
- this.abort(type);
2875
- const pkg = getPackageName(err);
2876
- errorClient(current, pkg && this.checkPackage(err, pkg) ? null : err);
2877
- }
2878
- break;
2837
+ }
2838
+ if (data.willAbort) {
2839
+ this.abort(undefined, err);
2840
+ }
2841
+ else if (aborting) {
2842
+ this.abort(type, err);
2843
+ }
2844
+ if (err) {
2845
+ this.writeFail(["Unable to execute query", message || "Unknown"], err instanceof Error ? errors = err : err, { type: 65536, startTime });
2846
+ }
2847
+ return this.aborted;
2848
+ };
2849
+ const options = { checkObject, sessionKey, connectOnce: length > 1, outCacheMiss: cacheMiss, errorQuery };
2850
+ result = await db.executeBatchQuery(batch, options, result);
2851
+ }
2852
+ catch (err) {
2853
+ this.abort(type);
2854
+ const pkg = getPackageName(err);
2855
+ errorClient(current, pkg && this.checkPackage(err, pkg) ? null : err);
2879
2856
  }
2880
- errorRemove(current, errorDataSource('Not found', type || "Unknown"));
2881
- return;
2857
+ break;
2882
2858
  }
2883
2859
  if (this.aborted) {
2884
2860
  resolve();
@@ -2886,9 +2862,9 @@ class ChromeDocument extends Document {
2886
2862
  }
2887
2863
  for (let i = 0, items; i < length; ++i) {
2888
2864
  const item = batch[i];
2889
- const { index, limit, ignoreEmpty, postQuery, whenEmpty } = item;
2865
+ const { index, limit, postQuery, whenEmpty } = item;
2890
2866
  const empty = (items = result[i]) === null;
2891
- if ((items || (items = [])).length === 0) {
2867
+ if ((items ||= []).length === 0) {
2892
2868
  if (whenEmpty) {
2893
2869
  const data = await checkData.call(this, item, whenEmpty, items, row => Array.isArray(row));
2894
2870
  if (data) {
@@ -2896,7 +2872,7 @@ class ChromeDocument extends Document {
2896
2872
  item.transactionFail = false;
2897
2873
  }
2898
2874
  }
2899
- if (ignoreEmpty && items.length === 0) {
2875
+ if (item.ignoreEmpty && items.length === 0) {
2900
2876
  continue;
2901
2877
  }
2902
2878
  }
@@ -2927,12 +2903,11 @@ class ChromeDocument extends Document {
2927
2903
  if (item.template) {
2928
2904
  const pathname = this.resolveDir('template', item.template);
2929
2905
  if (pathname) {
2930
- const ignoreCache = item.ignoreCache;
2931
- if (!ignoreCache && CACHE_LOCALFILE.has(pathname)) {
2906
+ if (!item.ignoreCache && CACHE_LOCALFILE.has(pathname)) {
2932
2907
  item.value = getCacheItem(CACHE_LOCALFILE, pathname);
2933
2908
  }
2934
2909
  else {
2935
- if (ignoreCache === 1) {
2910
+ if (item.ignoreCache === 1) {
2936
2911
  CACHE_LOCALFILE.delete(pathname);
2937
2912
  }
2938
2913
  if (!(item.value = cacheData[pathname])) {
@@ -2973,7 +2948,7 @@ class ChromeDocument extends Document {
2973
2948
  for (let j = 0, match; j < items.length; ++j) {
2974
2949
  const row = items[j];
2975
2950
  if ((0, types_1.isPlainObject)(row)) {
2976
- (_c = row.__index__) !== null && _c !== void 0 ? _c : (row.__index__ = j + 1);
2951
+ row.__index__ ??= j + 1;
2977
2952
  }
2978
2953
  let segment = template;
2979
2954
  while (match = REGEXP_TEMPLATECONDITIONAL.exec(segment)) {
@@ -3192,7 +3167,7 @@ class ChromeDocument extends Document {
3192
3167
  }
3193
3168
  }
3194
3169
  if (errors && item.removeEmpty) {
3195
- domElement.remove || (domElement.remove = true);
3170
+ domElement.remove ||= true;
3196
3171
  }
3197
3172
  }
3198
3173
  if (!domElement.remove) {
@@ -3220,7 +3195,7 @@ class ChromeDocument extends Document {
3220
3195
  else {
3221
3196
  if (!empty && item.type !== 'display' || item.transactionFail) {
3222
3197
  const emptyResponse = (value, service = item.source) => {
3223
- value || (value = "Unknown");
3198
+ value ||= "Unknown";
3224
3199
  return errors instanceof Error ? (0, types_1.errorMessage)(service, value, errors.message) : errorDataSource(service + ' -> Empty', value);
3225
3200
  };
3226
3201
  switch (item.source) {
@@ -3266,7 +3241,6 @@ class ChromeDocument extends Document {
3266
3241
  }
3267
3242
  }
3268
3243
  setProductionAttributes({ host, hashed, bufferMap, startTime }) {
3269
- var _a;
3270
3244
  for (const item of this.assets) {
3271
3245
  if (isIgnored(item, true)) {
3272
3246
  continue;
@@ -3274,7 +3248,7 @@ class ChromeDocument extends Document {
3274
3248
  if (item.hash && !hashed.has(item)) {
3275
3249
  createHash(host, item, item.hash, bufferMap);
3276
3250
  }
3277
- switch ((_a = item.element) === null || _a === void 0 ? void 0 : _a.tagName.toLowerCase()) {
3251
+ switch (item.element?.tagName.toLowerCase()) {
3278
3252
  case 'style':
3279
3253
  if (!item.content) {
3280
3254
  break;
@@ -3293,7 +3267,7 @@ class ChromeDocument extends Document {
3293
3267
  let value;
3294
3268
  if (data && (value = Document.asHash(data, { algorithm, encoding: item.encoding, digest: 'base64' }))) {
3295
3269
  attributes.integrity = algorithm + '-' + value;
3296
- attributes.crossorigin || (attributes.crossorigin = 'anonymous');
3270
+ attributes.crossorigin ||= 'anonymous';
3297
3271
  break;
3298
3272
  }
3299
3273
  throw (0, types_1.errorMessage)('hash', 'Source not found', item.filename);
@@ -3313,9 +3287,8 @@ class ChromeDocument extends Document {
3313
3287
  }
3314
3288
  }
3315
3289
  }
3316
- removeUnusedStyles(source, { useUnsafeCssReplace, usedVariables, usedFontFace, usedKeyframes, unusedStyles, unusedMedia, unusedContainer, unusedSupports, useSessionCache } = this.config) {
3317
- var _a;
3318
- if (!usedVariables && !usedFontFace && !usedKeyframes && !unusedStyles && !unusedMedia && !unusedContainer && !unusedSupports) {
3290
+ removeUnusedStyles(source, { useUnsafeCssReplace, usedVariables, usedFontFace, usedKeyframes, unusedStyles, unusedMedia, unusedSupports, unusedContainer, unusedScope, useSessionCache } = this.config) {
3291
+ if (!usedVariables && !usedFontFace && !usedKeyframes && !unusedStyles && !unusedMedia && !unusedContainer && !unusedSupports && !unusedScope) {
3319
3292
  return;
3320
3293
  }
3321
3294
  const queryMap = useSessionCache ? CACHE_QUERY : this._queryMap;
@@ -3421,15 +3394,17 @@ class ChromeDocument extends Document {
3421
3394
  }
3422
3395
  return selector.replace(/ +/g, getStringMany()) + getStringSome();
3423
3396
  };
3424
- const replaceUnunsed = (name, items, nesting) => {
3425
- for (let value of items) {
3426
- const key = name + '_' + (value = value.trim()) + (useUnsafeCssReplace ? '_1' : '');
3397
+ const replaceUnunsed = (name, items, nesting, increment = 1) => {
3398
+ for (let i = 0; i < items.length; i += increment) {
3399
+ const value = items[i].trim();
3400
+ let valueTo;
3401
+ const key = name + '_' + value + (increment === 2 && (valueTo = items[i + 1].trim()) ? '_' + valueTo : '') + (useUnsafeCssReplace ? '_1' : '');
3427
3402
  let pattern = queryMap.get(key), rule;
3428
3403
  if (!pattern) {
3429
3404
  let flags = 'gi', selector = '', revised;
3430
3405
  if (name === 'container') {
3431
- for (let i = 0, length = value.length, casing = true; i < length; i++) {
3432
- let ch = value[i];
3406
+ for (let j = 0, length = value.length, casing = true; j < length; j++) {
3407
+ let ch = value[j];
3433
3408
  if (!casing) {
3434
3409
  ch = ch.toLowerCase();
3435
3410
  }
@@ -3437,7 +3412,7 @@ class ChromeDocument extends Document {
3437
3412
  casing = false;
3438
3413
  }
3439
3414
  if (casing || ch < 'a' || ch > 'z') {
3440
- selector += value[i];
3415
+ selector += value[j];
3441
3416
  if (selector.endsWith(' not ')) {
3442
3417
  selector = selector.replace(/ not $/, ' `nN``oO``tT` ');
3443
3418
  }
@@ -3448,6 +3423,14 @@ class ChromeDocument extends Document {
3448
3423
  }
3449
3424
  flags = 'g';
3450
3425
  }
3426
+ else if (name === 'scope') {
3427
+ selector = `\\(${getStringSome() + parseSelector(value)}\\)`;
3428
+ if (valueTo) {
3429
+ selector += `${getStringMany()}[tT][oO]${getStringMany()}\\(${getStringSome() + parseSelector(valueTo)}\\)`;
3430
+ }
3431
+ flags = 'g';
3432
+ revised = true;
3433
+ }
3451
3434
  else if (name === 'supports' && /^selector\(/i.test(value)) {
3452
3435
  const startIndex = value.indexOf('(');
3453
3436
  const endIndex = value.lastIndexOf(')');
@@ -3474,25 +3457,18 @@ class ChromeDocument extends Document {
3474
3457
  pattern.lastIndex = 0;
3475
3458
  }
3476
3459
  while (rule = pattern.exec(current)) {
3477
- invalid: {
3478
- if (!nesting) {
3479
- for (let i = rule.index - 1; i > 0; --i) {
3480
- const ch = current[i];
3481
- if (ch === '}') {
3482
- break;
3483
- }
3484
- if (ch === '{') {
3485
- break invalid;
3486
- }
3487
- }
3488
- }
3489
- const [endIndex, trailing] = findClosingIndex(current, getEndIndex(rule), '{');
3490
- if (endIndex !== -1) {
3491
- current = spliceSource(current, rule.index, endIndex, pattern, rule[1], trailing);
3492
- (checkEmpty || (checkEmpty = {}))[name] = true;
3493
- modified = true;
3460
+ if (!nesting) {
3461
+ const block = Array.from(current.substring(0, rule.index).matchAll(/{|}/g));
3462
+ if (block.filter(open => open[0] === '{').length !== block.filter(close => close[0] === '}').length) {
3463
+ continue;
3494
3464
  }
3495
3465
  }
3466
+ const [endIndex, trailing] = findClosingIndex(current, getEndIndex(rule), '{');
3467
+ if (endIndex !== -1) {
3468
+ current = spliceSource(current, rule.index, endIndex, pattern, rule[1], trailing);
3469
+ (checkEmpty ||= {})[name] = true;
3470
+ modified = true;
3471
+ }
3496
3472
  }
3497
3473
  }
3498
3474
  };
@@ -3531,6 +3507,9 @@ class ChromeDocument extends Document {
3531
3507
  if (unusedContainer) {
3532
3508
  replaceUnunsed('container', unusedContainer, false);
3533
3509
  }
3510
+ if (unusedScope) {
3511
+ replaceUnunsed('scope', unusedScope.map(item => [item.start || '', item.end || '']).flat(), false, 2);
3512
+ }
3534
3513
  if (unusedStyles) {
3535
3514
  current = (function recurse(target, child) {
3536
3515
  let output = '', index = 0, pendingStart = 0, pendingEnd = 0, found = -1;
@@ -3682,7 +3661,7 @@ class ChromeDocument extends Document {
3682
3661
  }
3683
3662
  if (modified) {
3684
3663
  for (const name in checkEmpty) {
3685
- const pattern = CACHE_ATRULES[_a = name + (useUnsafeCssReplace ? '_1' : '')] || (CACHE_ATRULES[_a] = new RegExp(`(\\s*)@${name}[^{]*{${getStringSome()}}` + dom_1.DomWriter.PATTERN_TRAILINGSPACE, 'gi'));
3664
+ const pattern = CACHE_ATRULES[name + (useUnsafeCssReplace ? '_1' : '')] ||= new RegExp(`(\\s*)@${name}[^{]*{${getStringSome()}}` + dom_1.DomWriter.PATTERN_TRAILINGSPACE, 'gi');
3686
3665
  while (match = pattern.exec(current)) {
3687
3666
  current = spliceSource(current, match.index, getEndIndex(match), pattern, match[1], match[2]);
3688
3667
  }
@@ -3747,10 +3726,7 @@ class ChromeDocument extends Document {
3747
3726
  return [];
3748
3727
  }
3749
3728
  get settings() {
3750
- var _a;
3751
- return (_a = this.module).settings || (_a.settings = {});
3729
+ return this.module.settings ||= {};
3752
3730
  }
3753
3731
  }
3754
- ChromeDocument.INTERNAL_ASSIGNUUID = "__assign__";
3755
- ChromeDocument.INTERNAL_SERVERROOT = "__serverroot__";
3756
3732
  module.exports = ChromeDocument;