@e-mc/document 0.0.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.
@@ -0,0 +1,3546 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const path = require("path");
4
+ const fs = require("fs");
5
+ const jimp = require("jimp");
6
+ const asset_1 = require("../asset");
7
+ const util_1 = require("../util");
8
+ const types_1 = require("../../types");
9
+ const core_1 = require("../../core");
10
+ const index_1 = require("../index");
11
+ const cloud_1 = require("../../cloud");
12
+ const dom_1 = require("../parse/dom");
13
+ const transform_1 = require("../transform");
14
+ const CACHE_DBRESULT = new Map();
15
+ const CACHE_LOCALFILE = new Map();
16
+ const CACHE_DATASET = {};
17
+ const CACHE_ATRULES = {};
18
+ let CACHE_TOTAL = 0;
19
+ const REGEXP_SRCSETSIZE = /~\s*([\d.]+)\s*([wx])/i;
20
+ const REGEXP_TEMPLATECONDITIONAL = /(\n\s+)?\{\{if\s+((?:[^}]|}(?!}))+?)\}\}(\s*)([\S\s]*?)(?:\s*\{\{else(?:\s+if\s+((?:[^}]|}(?!}))+?))?\}\}(\s*)([\S\s]*?)\s*)?\s*\{\{end\}\}/g;
21
+ const REGEXP_TEMPLATECOMPARISON = /\s*\(\s*(?:(eq|ne|lt|le|gt|ge)\s+)?("[^"]+"|'[^']+'|[^\s)]+)(?:\s+("[^"]+"|'[^']+'|[^\s)]+))?\s*\)/g;
22
+ const REGEXP_TEMPLATEMATCH = new RegExp(`^(?:(and|or|not)\\s+)?((?:${REGEXP_TEMPLATECOMPARISON.source})+)|(!|not\\s+)?([^\\s][\\S\\s]*)$`);
23
+ const REGEXP_IMPORTMODULE = /(?:(?:^|[\n;]+)\s*import\s+(?:("(?:[^"]|(?<=\\)")+"|'(?:[^']|(?<=\\)')+')|.+?from\s+("(?:[^"]|(?<=\\)")+"|'(?:[^']|(?<=\\)')+')(?:[ \t]+assert[ \t]+\{((?:"(?:[^"]|(?<=\\)")+"|'(?:[^']|(?<=\\)')+'|`(?:[^`]|(?<=\\)`)+`|{[^{]+{|{[^}]+}|}[^}]+}|(?![{}])[^"'`])+)\})?)|\bimport\(\s*("(?:[^"]|(?<=\\)")+"|'(?:[^']|(?<=\\)')+')\s*(?:,\s*\{((?:"(?:[^"]|(?<=\\)")+"|'(?:[^']|(?<=\\)')+'|`(?:[^`]|(?<=\\)`)+`|{[^{]+{|{[^}]+}|}[^}]+}|(?![{}])[^"'`])+)\}\s*)?\))/g;
24
+ const REGEXP_BLOCKEXCLUDE = new RegExp(`(\\s*)<!--\\s*exclude\\s*:\\s*(?:start|end)\\s*-->` + dom_1.DomWriter.PATTERN_TRAILINGSPACE, 'gi');
25
+ const [PATTERN_STRING_SOME, PATTERN_STRING_MANY] = (function () {
26
+ const pattern = '(?:\\s|' + dom_1.DomWriter.PATTERN_COMMENT + '|`[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}`)';
27
+ return [pattern + '*', pattern + '+'];
28
+ })();
29
+ const REGEXP_COMMENT = new RegExp(dom_1.DomWriter.PATTERN_COMMENT, 'g');
30
+ const REGEXP_CONTENT = new RegExp(`\\bcontent${PATTERN_STRING_SOME}:${PATTERN_STRING_SOME}(?:"[^"]*"|'[^']*')`, 'gi');
31
+ const REGEXP_STYLE = new RegExp(`(<style${dom_1.DomWriter.PATTERN_TAGOPEN}*>)([\\S\\s]*?)(<\\/style\\s*>)`, 'gi');
32
+ const REGEXP_VARIABLES = new RegExp(`(\\s*)(--[^\\s:]*)${PATTERN_STRING_SOME}:[^;}]*([;}])` + dom_1.DomWriter.PATTERN_TRAILINGSPACE, 'g');
33
+ const REGEXP_FONTFACE = new RegExp(`(\\s*)@font-face${PATTERN_STRING_SOME}{([^}]+)}` + dom_1.DomWriter.PATTERN_TRAILINGSPACE, 'gi');
34
+ const REGEXP_FONTFAMILY = new RegExp(`font-family${PATTERN_STRING_SOME}:([^;}]+)`, 'i');
35
+ const REGEXP_KEYFRAMES = new RegExp(`(\\s*)@keyframes${PATTERN_STRING_MANY}([^{]+){`, 'gi');
36
+ const REGEXP_NTHCHILD = new RegExp(`\\(${PATTERN_STRING_SOME}([+-])?(?:(\\d*)[nN]|(0))${PATTERN_STRING_SOME}([+-])?${PATTERN_STRING_SOME}(\\d*)${PATTERN_STRING_SOME}\\)`, 'g');
37
+ const REGEXP_VARIABLES_UNSAFE = new RegExp(`(\\s*)(--[^\\s:]*)\\s*:[^;}]*([;}])` + dom_1.DomWriter.PATTERN_TRAILINGSPACE, 'g');
38
+ const REGEXP_FONTFACE_UNSAFE = new RegExp(`(\\s*)@font-face\\s*{([^}]+)}` + dom_1.DomWriter.PATTERN_TRAILINGSPACE, 'gi');
39
+ const REGEXP_FONTFAMILY_UNSAFE = /font-family\s*:([^;}]+)/i;
40
+ const REGEXP_KEYFRAMES_UNSAFE = /(\s*)@keyframes\s+([^{]+){/gi;
41
+ const REGEXP_NTHCHILD_UNSAFE = /\(\s*([+-])?(?:(\d*)[nN]|(0))\s*([+-])?\s*(\d*)\s*\)/g;
42
+ function removeNamespace(name, source, newline, comments) {
43
+ if (source.indexOf('-' + name) !== -1) {
44
+ const dataset = CACHE_DATASET[name] || (CACHE_DATASET[name] = [
45
+ new RegExp(`(\\s*)<(script|style)(${dom_1.DomWriter.PATTERN_TAGOPEN}+)>[\\S\\s]*?<\\/\\2\\s*>` + dom_1.DomWriter.PATTERN_TRAILINGSPACE, 'gi'),
46
+ new RegExp(`(\\s*)<link(${dom_1.DomWriter.PATTERN_TAGOPEN}+)>` + dom_1.DomWriter.PATTERN_TRAILINGSPACE, 'gi'),
47
+ new RegExp(`\\s+data-${name}-[a-z-]+\\s*` + dom_1.DomWriter.PATTERN_ATTRVALUE, 'g'),
48
+ new RegExp(`data-${name}-file\\s*=\\s*(["'])?exclude\\1`),
49
+ new RegExp(`data-${name}-template\\s*` + dom_1.DomWriter.PATTERN_ATTRVALUE)
50
+ ]);
51
+ source = source
52
+ .replace(dataset[0], (...capture) => dataset[3].test(capture[3]) || dataset[4].test(capture[3]) ? getNewlineString(capture[1], capture[7], newline) : capture[0])
53
+ .replace(dataset[1], (...capture) => dataset[3].test(capture[2]) ? getNewlineString(capture[1], capture[6], newline) : capture[0])
54
+ .replace(dataset[2], '');
55
+ }
56
+ return (0, types_1.isArray)(comments) ? source.replace(REGEXP_BLOCKEXCLUDE, (...capture) => getNewlineString(capture[1], capture[2], newline)) : source;
57
+ }
58
+ function getObjectValue(value, key) {
59
+ const pattern = /([^[.\s]+)((?:\s*\[[^\]]+\]\s*)+)?\s*\.?\s*/g;
60
+ let found, match;
61
+ while (match = pattern.exec(key)) {
62
+ if ((0, types_1.isObject)(value)) {
63
+ value = value[match[1]];
64
+ if (match[2]) {
65
+ const subscript = /\[\s*(["'])?(.+?)\1\s*\]/g;
66
+ let index;
67
+ while (index = subscript.exec(match[2])) {
68
+ const attr = index[1] ? index[2] : index[2].trim();
69
+ if (index[1] && (0, types_1.isObject)(value) || /^\d+$/.test(attr) && (typeof value === 'string' || (0, types_1.isObject)(value))) {
70
+ value = value[attr];
71
+ }
72
+ else {
73
+ return null;
74
+ }
75
+ }
76
+ }
77
+ if (value !== undefined && value !== null) {
78
+ found = true;
79
+ continue;
80
+ }
81
+ }
82
+ return null;
83
+ }
84
+ return found ? value : null;
85
+ }
86
+ function trimTemplate(value) {
87
+ const leading = /\s*\{\{- \s*((?:[^}]|}(?!}))+?)\}\}/g;
88
+ let match;
89
+ while (match = leading.exec(value)) {
90
+ value = replaceMatch(match, value, 1, leading);
91
+ }
92
+ const trailing = /\{\{((?:[^}]|}(?!}))+?)\s*? -\}\}\s*/g;
93
+ while (match = trailing.exec(value)) {
94
+ value = replaceMatch(match, value, 1, trailing);
95
+ }
96
+ return value;
97
+ }
98
+ function trimQuote(value) {
99
+ value = value.trim();
100
+ const first = value[0];
101
+ const last = value[value.length - 1];
102
+ return first === last && (first === '"' || first === "'") ? value.substring(1, value.length - 1).trim() : value;
103
+ }
104
+ function findClosingIndex(source, lastIndex) {
105
+ const pattern = /[{}]/g;
106
+ pattern.lastIndex = lastIndex;
107
+ let opened = 1, closed = 0, endIndex = -1, trailing = '', match;
108
+ while (match = pattern.exec(source)) {
109
+ if (match[0] === '{') {
110
+ ++opened;
111
+ }
112
+ else if (++closed === opened) {
113
+ endIndex = match.index + 1;
114
+ let ch;
115
+ while (isSpace(ch = source[endIndex])) {
116
+ trailing += ch;
117
+ ++endIndex;
118
+ if (ch === '\n') {
119
+ break;
120
+ }
121
+ }
122
+ break;
123
+ }
124
+ }
125
+ return [endIndex, trailing];
126
+ }
127
+ function getPackageName(err, value) {
128
+ if (err instanceof Error && err.code === types_1.ERR_CODE.MODULE_NOT_FOUND) {
129
+ switch (value) {
130
+ case 'mongodb':
131
+ case 'redis':
132
+ return value;
133
+ case 'mysql':
134
+ return 'mysql2';
135
+ case 'postgres':
136
+ return 'pg';
137
+ case 'oracle':
138
+ return 'oracledb';
139
+ case 'mssql':
140
+ return 'tedious';
141
+ default:
142
+ return (0, util_1.getModuleName)(err);
143
+ }
144
+ }
145
+ }
146
+ function getCacheItem(map, key) {
147
+ const result = map.get(key);
148
+ if (result) {
149
+ result[0] = Date.now();
150
+ return result[1];
151
+ }
152
+ }
153
+ function addCacheItem(map, key, data, timeout) {
154
+ if (!map.has(key)) {
155
+ ++CACHE_TOTAL;
156
+ }
157
+ map.set(key, [
158
+ Date.now(),
159
+ data,
160
+ setTimeout(() => deleteCacheItem(map, key), timeout * 1000 /* TIME.S */)
161
+ ]);
162
+ }
163
+ function deleteCacheItem(map, key) {
164
+ const item = map.get(key);
165
+ if (item) {
166
+ clearTimeout(item[2]);
167
+ map.delete(key);
168
+ --CACHE_TOTAL;
169
+ }
170
+ }
171
+ function spliceSource(source, startIndex, endIndex, pattern, leading = '', trailing = '', content = '') {
172
+ if (leading || trailing) {
173
+ content += getNewlineString(leading, trailing);
174
+ }
175
+ if (pattern && content) {
176
+ pattern.lastIndex = startIndex + content.length;
177
+ }
178
+ return spliceString(source, startIndex, endIndex, content);
179
+ }
180
+ function hasCondition(data, condition) {
181
+ if (!condition) {
182
+ return true;
183
+ }
184
+ let match = REGEXP_TEMPLATEMATCH.exec(condition.trim());
185
+ if (match) {
186
+ if (match[2]) {
187
+ const join = match[1];
188
+ const comparison = match[2];
189
+ const items = [];
190
+ while (match = REGEXP_TEMPLATECOMPARISON.exec(comparison)) {
191
+ if (items.length && !isSpace(match[0][0])) {
192
+ return false;
193
+ }
194
+ items.push([match[1], match[2], match[3]]);
195
+ }
196
+ REGEXP_TEMPLATECOMPARISON.lastIndex = 0;
197
+ const length = items.length;
198
+ if (length > 1 && !join) {
199
+ return false;
200
+ }
201
+ const parseArg = (value) => {
202
+ if (!isNaN(+value)) {
203
+ return +value;
204
+ }
205
+ if (match = /^(["'])([\S\s]*)\1$/.exec(value)) {
206
+ return match[2];
207
+ }
208
+ return getObjectValue(data, value);
209
+ };
210
+ for (let i = 0; i < length; ++i) {
211
+ const item = items[i];
212
+ const arg1 = item[1];
213
+ const arg2 = item[2];
214
+ let valid;
215
+ if (arg2) {
216
+ switch (item[0]) {
217
+ case 'eq':
218
+ valid = parseArg(arg1) == parseArg(arg2); // eslint-disable-line eqeqeq
219
+ break;
220
+ case 'ne':
221
+ valid = parseArg(arg1) != parseArg(arg2); // eslint-disable-line eqeqeq
222
+ break;
223
+ case 'lt':
224
+ valid = parseArg(arg1) < parseArg(arg2);
225
+ break;
226
+ case 'le':
227
+ valid = parseArg(arg1) <= parseArg(arg2);
228
+ break;
229
+ case 'gt':
230
+ valid = parseArg(arg1) > parseArg(arg2);
231
+ break;
232
+ case 'ge':
233
+ valid = parseArg(arg1) >= parseArg(arg2);
234
+ break;
235
+ default:
236
+ return false;
237
+ }
238
+ }
239
+ else if (item[0]) {
240
+ return false;
241
+ }
242
+ else {
243
+ valid = isTruthy(data, arg1, false);
244
+ }
245
+ if (join === 'or') {
246
+ if (valid) {
247
+ return true;
248
+ }
249
+ }
250
+ else {
251
+ if (join === 'not') {
252
+ valid = !valid;
253
+ }
254
+ if (!valid) {
255
+ return false;
256
+ }
257
+ }
258
+ }
259
+ return join === 'or' ? false : true;
260
+ }
261
+ if (match[7]) {
262
+ return isTruthy(data, match[7].trim(), match[6]);
263
+ }
264
+ }
265
+ return false;
266
+ }
267
+ function isTruthy(data, attr, falsey) {
268
+ const value = getObjectValue(data, attr);
269
+ return falsey ? !value : !!value;
270
+ }
271
+ function hasSameOrigin(value, ...other) {
272
+ for (let url of other) {
273
+ if (!url) {
274
+ continue;
275
+ }
276
+ try {
277
+ if (typeof value === 'string') {
278
+ value = new URL(value);
279
+ }
280
+ if (typeof url === 'string') {
281
+ url = new URL(url);
282
+ }
283
+ if (value.origin === url.origin) {
284
+ return true;
285
+ }
286
+ }
287
+ catch {
288
+ }
289
+ }
290
+ return false;
291
+ }
292
+ function restoreSearchParams(value, prefix = '__sqd') {
293
+ if (value) {
294
+ if (value.indexOf(prefix) !== -1) {
295
+ const params = new URLSearchParams(value);
296
+ params.forEach((_, key) => key.startsWith(prefix) && params.delete(key));
297
+ if (value = params.toString()) {
298
+ return '?' + value;
299
+ }
300
+ }
301
+ return value;
302
+ }
303
+ return '';
304
+ }
305
+ function getBaseURLs(asset, baseUrl) {
306
+ const result = [];
307
+ let parentUrl = asset ? asset.url || asset.uri : undefined;
308
+ try {
309
+ if (parentUrl) {
310
+ if (typeof parentUrl === 'string') {
311
+ parentUrl = new URL(parentUrl);
312
+ asset.url = parentUrl;
313
+ }
314
+ result.push(parentUrl);
315
+ }
316
+ }
317
+ catch {
318
+ parentUrl = undefined;
319
+ }
320
+ if (baseUrl) {
321
+ const url = new URL(baseUrl);
322
+ if (!parentUrl) {
323
+ result.push(parentUrl = url);
324
+ }
325
+ else if (parentUrl.origin !== url.origin) {
326
+ result.push(new URL(parentUrl.href.replace(parentUrl.origin, url.origin)), url);
327
+ }
328
+ }
329
+ return result;
330
+ }
331
+ function createHash(host, file, bufferMap) {
332
+ const hash = file.hash;
333
+ if (hash) {
334
+ try {
335
+ const localUri = file.localUri;
336
+ const buffer = localUri && bufferMap[localUri] || getBuffer(file);
337
+ if (buffer) {
338
+ const [algorithm, length] = (0, util_1.getHashData)(hash);
339
+ let value;
340
+ if (algorithm && (value = index_1.default.asHash(buffer, { algorithm, encoding: file.encoding }))) {
341
+ if (localUri) {
342
+ bufferMap[localUri] = buffer;
343
+ }
344
+ host.rename(file, (0, util_1.appendSuffix)(file.filename, length ? value.substring(0, length) : value));
345
+ return file.filename;
346
+ }
347
+ }
348
+ throw (0, types_1.errorMessage)('hash', 'Source not found', file.filename);
349
+ }
350
+ catch (err) {
351
+ host.writeFail(["Unable to read file" /* ERR_MESSAGE.READ_FILE */, file.filename], err, 32 /* LOG_TYPE.FILE */);
352
+ }
353
+ }
354
+ }
355
+ function getSrcURL(parent, file) {
356
+ const relativeUrl = file.relativeUrl || this.host.removeCwd(file.localUri) && getRelativeURL(file);
357
+ if (!relativeUrl) {
358
+ return [''];
359
+ }
360
+ if (parent.inlineContent) {
361
+ return [relativeUrl];
362
+ }
363
+ let parentDir = parent.pathname, assetDir = file.pathname;
364
+ if (!this.productionRelease) {
365
+ if (parent.moveTo) {
366
+ parentDir = joinPath(parent.moveTo, parentDir);
367
+ }
368
+ if (file.moveTo) {
369
+ assetDir = joinPath(file.moveTo, assetDir);
370
+ }
371
+ }
372
+ if (parentDir === assetDir) {
373
+ return [file.filename, true];
374
+ }
375
+ const splitPath = (value) => value.split(/[\\/]/).filter(segment => segment.trim());
376
+ const prefix = splitPath(parentDir);
377
+ const suffix = splitPath(assetDir);
378
+ let found;
379
+ while (prefix.length && suffix.length && prefix[0] === suffix[0]) {
380
+ prefix.shift();
381
+ suffix.shift();
382
+ found = true;
383
+ }
384
+ return [found ? joinPath('../'.repeat(prefix.length), suffix.join('/'), file.filename) : '../'.repeat(prefix.length) + relativeUrl];
385
+ }
386
+ function transformURL(host, parent, type, source, importFile) {
387
+ const related = [];
388
+ const baseHref = getBaseURLs(importFile || parent, this.baseUrl);
389
+ const isHtml = type === 'html';
390
+ const isJs = type === 'js';
391
+ const pattern = isJs ? /\bimport\(/g : type === 'svg' ? /(?:\b[Uu][Rr][Ll]\(|@import\s+(["'])|\b([Hh][Rr][Ee][Ff])\s*=)/g : /\b[Uu][Rr][Ll]\(|@import\s+(["'])/g;
392
+ let length = source.length, modified, match;
393
+ while (match = pattern.exec(source)) {
394
+ const isText = !!match[1];
395
+ const isHref = !!match[2];
396
+ const isUrl = !isText && !isHref;
397
+ const startIndex = match.index;
398
+ let quote = match[1], content = '', trailing = '', closed = -1, i = startIndex + match[0].length;
399
+ for (let j = -1; i < length; ++i) {
400
+ const ch = source[i];
401
+ if (quote && ch === quote) {
402
+ if (!isText) {
403
+ content += ch;
404
+ }
405
+ if (isHref) {
406
+ break;
407
+ }
408
+ if (source[i - 1] !== '\\') {
409
+ if (isText) {
410
+ break;
411
+ }
412
+ if (closed === -1) {
413
+ closed = i + 1;
414
+ }
415
+ }
416
+ j = i + 1;
417
+ continue;
418
+ }
419
+ if (!quote && (ch === '"' || ch === "'" || ch === '`' && isJs) && (isHref || !content.trim())) {
420
+ quote = ch;
421
+ }
422
+ else if (isHref && !quote && isSpace(ch) && content.trim()) {
423
+ break;
424
+ }
425
+ else if (ch === ')') {
426
+ if (isUrl) {
427
+ if (quote && closed !== -1 || !quote && (isJs || source[i - 1] !== '\\')) {
428
+ break;
429
+ }
430
+ j = i;
431
+ }
432
+ }
433
+ else if (j !== -1 && (ch === '\n' ||
434
+ isText && (ch === ';' || ch === '{') ||
435
+ isHref && (ch === '=' || ch === '>') ||
436
+ isUrl && (ch === ';' ||
437
+ !isJs && (!isHtml && (ch === ':' && !isJs || ch === '}') ||
438
+ isHtml && (ch === '"' || ch === "'" || ch === ':' || ch === '>'))))) {
439
+ if (closed !== -1) {
440
+ i = closed;
441
+ }
442
+ else {
443
+ content = content.substring(0, i = j);
444
+ }
445
+ break;
446
+ }
447
+ if (closed === -1) {
448
+ content += ch;
449
+ }
450
+ }
451
+ const setOutputURL = (value, asset) => {
452
+ if (!value) {
453
+ return;
454
+ }
455
+ if (asset) {
456
+ if (!asset.inlineBase64) {
457
+ if (host.Cloud?.getStorage('upload', asset.cloudStorage)) {
458
+ const inlineUrlCloud = asset.inlineUrlCloud || (asset.inlineUrlCloud = (0, types_1.generateUUID)());
459
+ (parent.inlineUrlCloudMap || (parent.inlineUrlCloudMap = {}))[inlineUrlCloud] = value;
460
+ value = inlineUrlCloud;
461
+ }
462
+ else if (asset.hash && this.productionRelease) {
463
+ const inlineUrl = asset.inlineUrl || (asset.inlineUrl = (0, types_1.generateUUID)());
464
+ (parent.inlineUrlMap || (parent.inlineUrlMap = {}))[inlineUrl] = value;
465
+ value = inlineUrl;
466
+ }
467
+ }
468
+ const font = findFont(asset.format);
469
+ if (font) {
470
+ found: {
471
+ for (let k = i + 1; k < length; ++k) {
472
+ switch (source[k]) {
473
+ case ')': {
474
+ const component = source.substring(i + 1, k + 1);
475
+ const format = /\s+format\([^)]+\)$/i.exec(component);
476
+ if (format) {
477
+ trailing = component.replace(format[0], ` format("${font}")`);
478
+ i = k;
479
+ break found;
480
+ }
481
+ break;
482
+ }
483
+ case ',':
484
+ case ';':
485
+ case ':':
486
+ case '}':
487
+ break found;
488
+ }
489
+ }
490
+ }
491
+ }
492
+ if (asset.initialValue && !asset.initialValue.cacheable) {
493
+ parent.flags |= 16 /* ASSET_FLAG.MODIFIED */;
494
+ }
495
+ related.push(asset);
496
+ }
497
+ if (!quote && !isHtml && !isJs) {
498
+ if (value.indexOf('"') === -1) {
499
+ quote = '"';
500
+ }
501
+ else if (value.indexOf("'") === -1) {
502
+ quote = "'";
503
+ }
504
+ }
505
+ if (isUrl) {
506
+ const index = value.indexOf('#');
507
+ if (index !== -1) {
508
+ value = value.substring(0, index);
509
+ }
510
+ }
511
+ if (quote) {
512
+ value = quote + value + quote;
513
+ }
514
+ const revised = isJs ? 'import(' + value + trailing + ')' : isHref ? 'href=' + value : (isText ? '@import ' + value : `url(${value})`) + trailing;
515
+ source = spliceString(source, startIndex, i + 1, revised);
516
+ length = source.length;
517
+ pattern.lastIndex = startIndex + revised.length;
518
+ modified = true;
519
+ };
520
+ let url;
521
+ if (isJs) {
522
+ if (!quote) {
523
+ continue;
524
+ }
525
+ const file = new RegExp('^\\s*(' + quote + '((?:[^' + quote + ']|(?<=\\\\)' + quote + ')+)' + quote + ')\\s*(,.+)$').exec(content);
526
+ if (file) {
527
+ url = file[1].trim();
528
+ trailing = file[2].trim();
529
+ }
530
+ else {
531
+ url = trimQuote(content);
532
+ }
533
+ }
534
+ else {
535
+ url = trimQuote(content);
536
+ }
537
+ if (url.startsWith('data:')) {
538
+ const base64 = url.split(',')[1]?.trim();
539
+ if (base64) {
540
+ for (const item of this.assets) {
541
+ if (item.base64 === base64) {
542
+ setOutputURL(getSrcURL.call(this, parent, item)[0], item);
543
+ break;
544
+ }
545
+ }
546
+ }
547
+ }
548
+ else if (baseHref.length) {
549
+ let fullUrl, asset;
550
+ for (const parentUrl of baseHref) {
551
+ if (asset = host.findAsset(fullUrl = resolvePath(url, parentUrl), { replaced: true }) || (this.related.has(parent) ? host.findAsset(fullUrl, { assets: Array.from(this.related.get(parent)), replaced: true }) : undefined)) {
552
+ break;
553
+ }
554
+ }
555
+ if (asset && asset !== importFile) {
556
+ if (!(0, util_1.hasValue)(asset.format, 'base64')) {
557
+ if (asset.bundleReplace) {
558
+ let k, valid;
559
+ if (!isText) {
560
+ let j = startIndex;
561
+ while (isSpace(source[--j])) { }
562
+ valid = source.substring(k = j - 6, j + 1) === '@import';
563
+ }
564
+ else {
565
+ k = startIndex;
566
+ valid = true;
567
+ }
568
+ if (valid) {
569
+ let l = i, revised = transform_1.SourceMap.removeSourceMappingURL(host.getUTF8String(asset))[0];
570
+ for (let ch; l < length; ++l) {
571
+ if ((ch = source[l]) === ';' || ch === '\n') {
572
+ break;
573
+ }
574
+ }
575
+ const layer = this.replaceContent(revised, source.substring(k, l + 1), 'text/css');
576
+ if (layer) {
577
+ revised = layer;
578
+ }
579
+ source = spliceString(source, k, l + 1, revised = transformURL.call(this, host, parent, type, this.removeServerRoot(revised), asset) || revised);
580
+ length = source.length;
581
+ pattern.lastIndex = k + revised.length;
582
+ if (!parent.watch) {
583
+ host.deleteFile(asset.localUri, { ignorePermission: true, emptyDir: true, all: true, id: asset.id });
584
+ asset.invalid = true;
585
+ }
586
+ else {
587
+ related.push(asset);
588
+ if (!(0, types_1.existsFlag)(asset.flags)) {
589
+ asset.flags |= 8 /* ASSET_FLAG.WATCH */;
590
+ }
591
+ }
592
+ modified = true;
593
+ continue;
594
+ }
595
+ }
596
+ if (hasSameOrigin(asset.url || fullUrl, ...baseHref)) {
597
+ let sameDir;
598
+ [fullUrl, sameDir] = getSrcURL.call(this, parent, asset);
599
+ if (sameDir && isJs) {
600
+ fullUrl = './' + fullUrl;
601
+ }
602
+ }
603
+ else {
604
+ const pathname = parent.pathname;
605
+ const count = pathname && pathname !== '/' && pathname !== '\\' ? pathname.split(/[\\/]/).length : 0;
606
+ fullUrl = (count ? '../'.repeat(count) : '') + asset.relativeUrl;
607
+ }
608
+ }
609
+ else if (!asset.invalid) {
610
+ fullUrl = asset.inlineBase64 || (asset.inlineBase64 = (0, types_1.generateUUID)());
611
+ }
612
+ if (url !== fullUrl) {
613
+ setOutputURL(fullUrl, asset);
614
+ }
615
+ }
616
+ else if (importFile && url !== fullUrl) {
617
+ setOutputURL(fullUrl);
618
+ }
619
+ }
620
+ }
621
+ if (modified) {
622
+ if (related.length) {
623
+ const previous = this.related.get(parent);
624
+ if (previous) {
625
+ related.forEach(item => previous.add(item));
626
+ }
627
+ else {
628
+ this.related.set(parent, new Set(related));
629
+ }
630
+ }
631
+ return source;
632
+ }
633
+ }
634
+ function getFormatUUID(attr, ext) {
635
+ const format = 'formatMap' in this ? this.formatMap : this.module.format;
636
+ let pattern;
637
+ if ((0, types_1.isObject)(format) && (0, types_1.isObject)(pattern = ext && ext in format ? format[ext] : format.uuid) && pattern[attr]) {
638
+ return (0, types_1.randomString)(pattern[attr], pattern.dictionary);
639
+ }
640
+ return (0, types_1.generateUUID)();
641
+ }
642
+ function setLocationUUID(data, file, ext) {
643
+ const { pathname, filename } = data;
644
+ const assignUUID = ChromeDocument.INTERNAL_ASSIGNUUID;
645
+ let index, modified;
646
+ if (filename) {
647
+ ext || (ext = path.extname(filename).substring(1));
648
+ if ((index = filename.indexOf(assignUUID)) !== -1) {
649
+ data.filename = spliceString(filename, index, index + assignUUID.length, getFormatUUID.call(this, 'filename', ext));
650
+ if (file) {
651
+ file.inlineFilename = data.filename;
652
+ }
653
+ modified = true;
654
+ }
655
+ }
656
+ if (pathname && (index = pathname.indexOf(assignUUID)) !== -1) {
657
+ data.pathname = spliceString(pathname, index, index + assignUUID.length, getFormatUUID.call(this, 'pathname', ext));
658
+ modified = true;
659
+ }
660
+ if (file && modified) {
661
+ (0, asset_1.setInitialValue)(file, false);
662
+ if (file.hash) {
663
+ delete file.hash;
664
+ }
665
+ }
666
+ }
667
+ function transformOptions(file, mimeType, code, bundleContent) {
668
+ const { uri, localUri, exported } = file;
669
+ let metadata;
670
+ if (mimeType === 'text/css') {
671
+ metadata = { ...this.config, ...file.metadata };
672
+ }
673
+ else if (mimeType === 'text/html') {
674
+ metadata = { '__fromhtml__': true, ...this.config, ...file.metadata };
675
+ }
676
+ else {
677
+ metadata = file.metadata;
678
+ }
679
+ const [pathname, filename] = localUri ? [path.dirname(localUri), path.basename(localUri)] : ['', file.filename];
680
+ const options = { pathname, filename, mimeType, metadata, imported: !!file.imports && file.imported !== false };
681
+ const sourceFile = !exported && uri && this.findSourceRoot(uri);
682
+ if (sourceFile) {
683
+ if (isPath(sourceFile)) {
684
+ options.sourceFile = sourceFile;
685
+ }
686
+ options.sourceName = path.basename(sourceFile);
687
+ options.sourcesRelativeTo = path.dirname(sourceFile);
688
+ options.getMainFile = this.resolveSourceFile(file);
689
+ if (code) {
690
+ options.getSourceFiles = this.locateSourceFiles(file, code, bundleContent);
691
+ }
692
+ }
693
+ if ((!this.productionRelease || this.productionIncremental) && !(0, types_1.modifiedFlag)(file.flags)) {
694
+ options.cacheData = { uri: !exported ? uri : undefined, etag: !file.modified ? file.etag : undefined, encoding: file.encoding };
695
+ }
696
+ return options;
697
+ }
698
+ function transformJs(host, file, output) {
699
+ const { sourceFiles, chunks, map } = output;
700
+ const localUri = file.localUri;
701
+ const emptySources = !!this.productionRelease;
702
+ let uri;
703
+ if (map && (uri = writeSourceMap(localUri, output, { hash: file.hash, emptySources, inlineMap: hasSourceMap(file.metadata, 'inline') }))) {
704
+ host.add(uri, file, types_1.FILE_TYPE.SOURCEMAP);
705
+ }
706
+ if (chunks) {
707
+ const elements = this.elements;
708
+ const localDir = path.dirname(localUri);
709
+ const relativeDir = joinPath(file.moveTo, file.pathname);
710
+ const element = file.element;
711
+ let order = 0, index, appending;
712
+ if (element) {
713
+ index = element.index;
714
+ for (const item of elements) {
715
+ const append = item.append;
716
+ if (append && !append.prepend && dom_1.DomWriter.isEqual(item, element, host.moduleName, true)) {
717
+ (appending || (appending = [])).push(append);
718
+ }
719
+ }
720
+ }
721
+ for (const chunk of chunks) {
722
+ let chunkName = chunk.filename;
723
+ if (!chunkName) {
724
+ chunkName = getFormatUUID.call(this, 'filename', 'js') + path.extname(localUri);
725
+ chunk.entryPoint = true;
726
+ }
727
+ const chunkUri = path.join(localDir, chunkName);
728
+ if (chunk.map && (uri = writeSourceMap(chunkUri, chunk, { emptySources, inlineMap: hasSourceMap(file.metadata, 'inline') }))) {
729
+ host.add(uri, file, types_1.FILE_TYPE.SOURCEMAP);
730
+ }
731
+ try {
732
+ fs.writeFileSync(chunkUri, chunk.code);
733
+ host.add(chunkUri, file);
734
+ if (chunk.entryPoint) {
735
+ if (element) {
736
+ const attributes = { ...file.attributes, src: joinPath(relativeDir, chunkName) };
737
+ if (file.imports && file.imported !== false) {
738
+ attributes.type || (attributes.type = 'module');
739
+ }
740
+ elements.push({
741
+ ...element,
742
+ attributes,
743
+ append: { tagName: 'script', tagCount: element.tagCount, nextSibling: dom_1.DomWriter.isIndex(index) ? index + 1 : undefined, order: ++order }
744
+ });
745
+ }
746
+ else {
747
+ this.writeFail(['Unable to create element entry point', path.basename(chunkUri)], (0, types_1.errorMessage)('js', 'Element not found', chunkUri), 4 /* LOG_TYPE.PROCESS */);
748
+ }
749
+ }
750
+ }
751
+ catch (err) {
752
+ this.writeFail(["Unable to write file" /* ERR_MESSAGE.WRITE_FILE */, path.basename(chunkUri)], err, 32 /* LOG_TYPE.FILE */);
753
+ }
754
+ }
755
+ appending?.forEach(item => item.order += order);
756
+ }
757
+ if ((0, types_1.isArray)(sourceFiles)) {
758
+ file.sourceFiles = sourceFiles;
759
+ }
760
+ file.modified = true;
761
+ return file.sourceUTF8 = output.code;
762
+ }
763
+ function replaceCss(file) {
764
+ const sanitize = (map) => {
765
+ for (const id in map) {
766
+ map[id] = this.removeServerRoot(map[id]).replace(/^\//, '');
767
+ }
768
+ };
769
+ if (file.inlineUrlMap) {
770
+ sanitize(file.inlineUrlMap);
771
+ }
772
+ if (file.inlineUrlCloudMap) {
773
+ sanitize(file.inlineUrlCloudMap);
774
+ }
775
+ }
776
+ function replaceHtml(source, { productionRelease, contentMap }, cssMap) {
777
+ for (const data of [cssMap, contentMap]) {
778
+ for (const id in data) {
779
+ source = source.replace(new RegExp((0, types_1.escapePattern)(id), 'g'), data[id]);
780
+ }
781
+ }
782
+ return productionRelease ? this.removeServerRoot(source) : source;
783
+ }
784
+ function isWatched(file) {
785
+ const { initialValue, format } = file;
786
+ if (file.imported || file.bundleReplace || file.inlineContent || file.inlineBase64 || this.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'))) {
787
+ return true;
788
+ }
789
+ return false;
790
+ }
791
+ function loadLocalFile(item, pathname, cacheData, encoding, out) {
792
+ let content;
793
+ encoding = (0, types_1.getEncoding)(encoding);
794
+ if (out) {
795
+ content = fs.readFileSync(pathname, encoding);
796
+ out.content = content;
797
+ }
798
+ const ext = path.extname(pathname).substring(1).toLowerCase();
799
+ if (ext === 'cjs') {
800
+ return require(pathname);
801
+ }
802
+ content || (content = fs.readFileSync(pathname, encoding));
803
+ const result = this.tryParse(content, ext);
804
+ if (result !== undefined && result !== null) {
805
+ setCacheData.call(this, item, result, pathname, cacheData, true);
806
+ return result;
807
+ }
808
+ }
809
+ function setCacheData(item, data, dataKey, cacheData, template) {
810
+ if ((0, types_1.isObject)(data) || template) {
811
+ const cache = this.settingsOf(item.source, template && item.source !== 'local' ? 'local_file' : 'cache');
812
+ let timeout;
813
+ if (cache && (timeout = core_1.ClientDb.getTimeout(cache)) && timeout > 0) {
814
+ addCacheItem(template ? CACHE_LOCALFILE : CACHE_DBRESULT, dataKey, data, timeout);
815
+ }
816
+ else {
817
+ cacheData[dataKey] = data;
818
+ }
819
+ }
820
+ }
821
+ async function checkData(item, name, result, validate) {
822
+ let callback;
823
+ if (typeof name === 'string') {
824
+ const template = this.findDataValue(name) || name;
825
+ callback = this.hasEval('userconfig') ? index_1.default.parseFunction(template, this.hasEval('absolute')) : (0, types_1.asFunction)(template);
826
+ }
827
+ else {
828
+ callback = name;
829
+ name = '';
830
+ }
831
+ if (typeof callback === 'function') {
832
+ try {
833
+ let output;
834
+ // @ts-ignore
835
+ if (callback["__cjs__" /* INTERNAL.CJS */]) {
836
+ output = await callback(result, item);
837
+ }
838
+ else {
839
+ output = await callback.apply(index_1.default.enabled("node.process.inline" /* KEY_NAME.NODE_PROCESS_INLINE */) ? process : null, index_1.default.enabled("node.require.inline" /* KEY_NAME.NODE_REQUIRE_INLINE */) ? [result, item, require] : [result, item]);
840
+ }
841
+ if (validate(output)) {
842
+ return output;
843
+ }
844
+ }
845
+ catch (err) {
846
+ this.writeFail(["Unable to parse inline method" /* ERR_MESSAGE.INLINE_METHOD */, name], err);
847
+ }
848
+ }
849
+ }
850
+ const getNewlineString = dom_1.DomWriter.getNewlineString.bind(dom_1.DomWriter);
851
+ const isSpace = dom_1.DomWriter.isSpace.bind(dom_1.DomWriter);
852
+ const replaceMatch = dom_1.DomWriter.replaceMatch.bind(dom_1.DomWriter);
853
+ const joinPath = index_1.default.joinPath.bind(index_1.default);
854
+ const isPath = index_1.default.isPath.bind(index_1.default);
855
+ const writeSourceMap = index_1.default.writeSourceMap.bind(index_1.default);
856
+ const asString = index_1.default.asString.bind(index_1.default);
857
+ const resolvePath = index_1.default.resolvePath.bind(index_1.default);
858
+ const toPosix = index_1.default.toPosix.bind(index_1.default);
859
+ const isDir = index_1.default.isDir.bind(index_1.default);
860
+ const hasSourceMap = (metadata, value) => (0, types_1.isObject)(metadata) && metadata['__sourcemap__'] === value;
861
+ const isBundled = (value, main) => typeof value === 'number' && (value > 0 || main && value === 0);
862
+ const isFont = (value) => value === 'truetype' || value === 'opentype' || value === 'woff' || value === 'woff2';
863
+ const isImage = (value) => typeof value === 'string' && value.startsWith('image/') && value !== 'image/svg+xml';
864
+ const getBuffer = (item) => item.sourceUTF8 || item.buffer || (item.localUri && isPath(item.localUri) ? fs.readFileSync(item.localUri, item.encoding) : null);
865
+ const isRemoved = (item) => item.exclude === true || isBundled(item.bundleIndex);
866
+ const isUnedited = (item) => !item.attributes && !item.inlineContent && !item.srcSet && !item.element.dynamic && item.element.textContent === undefined && (!item.uri && !isBundled(item.bundleIndex, true) || (0, util_1.hasValue)(item.format, 'crossorigin'));
867
+ const isIgnored = (item, exists) => item.invalid || (0, types_1.ignoreFlag)(item.flags) || !exists && (0, types_1.existsFlag)(item.flags);
868
+ const findFont = (value) => value && (Array.isArray(value) ? value : [value]).find(format => isFont(format));
869
+ const spliceString = (source, startIndex, endIndex, content) => source.substring(0, startIndex) + content + source.substring(endIndex);
870
+ const getEndIndex = (match) => match.index + match[0].length;
871
+ const getRelativeURL = (file) => joinPath(file.moveTo, file.pathname, file.inlineFilename || file.filename) + (!file.static ? restoreSearchParams(file.url?.search) : '');
872
+ const errorHtml = ({ tagName, tagIndex = -1 }) => (0, types_1.errorMessage)('html', 'Location did not resolve', tagName.toLowerCase() + (tagIndex >= 0 ? ': ' + tagIndex : ''));
873
+ const errorDataSource = (value, hint) => (0, types_1.errorMessage)('data-source', value, hint);
874
+ class ChromeDocument extends index_1.default {
875
+ constructor() {
876
+ super(...arguments);
877
+ this.config = {
878
+ usedVariables: undefined,
879
+ usedFontFace: undefined,
880
+ usedKeyframes: undefined,
881
+ unusedStyles: undefined,
882
+ unusedMedia: undefined,
883
+ unusedContainer: undefined,
884
+ unusedSupports: undefined,
885
+ unusedAtRules: undefined,
886
+ useOriginalHtmlPage: undefined,
887
+ useUnsafeHtmlReplace: undefined,
888
+ useUnsafeCssReplace: undefined,
889
+ stripCommentsAndCDATA: undefined,
890
+ normalizeHtmlOutput: undefined,
891
+ escapeReservedCharacters: undefined,
892
+ ignoreServerCodeBlocks: undefined
893
+ };
894
+ this.htmlFile = null;
895
+ this.cssFiles = [];
896
+ this.jsFiles = [];
897
+ this.svgFiles = [];
898
+ this.baseDirectory = '';
899
+ this.baseUrl = '';
900
+ this.productionRelease = false;
901
+ this.productionIncremental = false;
902
+ this.templateMap = {};
903
+ this.related = new Map();
904
+ this.replaced = [];
905
+ this._moduleName = 'chrome';
906
+ this._threadable = true;
907
+ this._elements = null;
908
+ this._idMap = Object.create(null);
909
+ this._editing = [];
910
+ this._selectorMap = {};
911
+ }
912
+ static async purgeMemory(percent = 1, limit = 0, parent) {
913
+ if (typeof limit === 'boolean') {
914
+ parent = limit;
915
+ limit = 0;
916
+ }
917
+ let result = 0;
918
+ if (limit === 0 || CACHE_TOTAL >= limit) {
919
+ if (percent >= 1) {
920
+ result += CACHE_DBRESULT.size + CACHE_LOCALFILE.size;
921
+ CACHE_DBRESULT.clear();
922
+ CACHE_LOCALFILE.clear();
923
+ CACHE_TOTAL = 0;
924
+ }
925
+ else if (percent > 0) {
926
+ const stored = [];
927
+ for (const map of [CACHE_DBRESULT, CACHE_LOCALFILE]) {
928
+ for (const [key, value] of map) {
929
+ stored.push([map, key, value[0]]);
930
+ }
931
+ }
932
+ stored.sort((a, b) => a[2] - b[2]);
933
+ result = Math.floor(stored.length * percent);
934
+ for (let i = 0; i < result; ++i) {
935
+ const [map, key] = stored[i];
936
+ deleteCacheItem(map, key);
937
+ }
938
+ CACHE_TOTAL = stored.length - result;
939
+ }
940
+ }
941
+ return result + (parent && result > 0 ? await super.purgeMemory(typeof parent === 'number' && parent > 0 ? parent : percent, limit, true) : 0);
942
+ }
943
+ static async finalize(instance) {
944
+ if (instance.aborted) {
945
+ return Promise.reject((0, types_1.createAbortError)());
946
+ }
947
+ const productionRelease = instance.productionRelease;
948
+ const processing = { host: this, startTime: process.hrtime(), hashed: new Set(), contentMap: {}, bufferMap: {}, cacheMiss: [], productionRelease: productionRelease ? true : undefined };
949
+ const { Db: db, htmlFile, assets } = instance;
950
+ const outHtml = htmlFile && !isIgnored(htmlFile, true);
951
+ if (db && await db.commit()) {
952
+ db.writeTimeElapsed('DB', ["Transactions were committed" /* VAL_MESSAGE.COMMIT_TRANSACTION */, db.moduleName], processing.startTime, { ...index_1.default.LOG_STYLE_SUCCESS, type: 65536 /* LOG_TYPE.DB */ });
953
+ }
954
+ if (instance.dataSource.length === 0 && outHtml) {
955
+ const incremental = htmlFile.incremental ?? this.incremental;
956
+ if (incremental === 'etag' || incremental === 'exists') {
957
+ const fetched = this.fetchedAssets;
958
+ const isHtmlOnly = () => !fetched.find(item => item !== htmlFile && assets.includes(item));
959
+ if (!productionRelease || instance.productionIncremental && (isHtmlOnly() || !fetched.find(item => item.hash))) {
960
+ let hint = '';
961
+ switch (incremental) {
962
+ case 'etag': {
963
+ if (outHtml) {
964
+ const { etag, initialValue } = htmlFile;
965
+ let buffer;
966
+ if (!initialValue || !(etag && initialValue.etag === etag && (buffer = initialValue.buffer)) || fetched.find(item => item.bundleReplace && (!(0, types_1.isArray)(item.from) || item.from.includes('style')))) {
967
+ break;
968
+ }
969
+ try {
970
+ const { localUri, encoding } = htmlFile;
971
+ fs.writeFileSync(localUri, buffer, (0, types_1.getEncoding)(encoding));
972
+ htmlFile.buffer = buffer;
973
+ htmlFile.sourceUTF8 = undefined;
974
+ }
975
+ catch {
976
+ break;
977
+ }
978
+ }
979
+ const { jsFiles, cssFiles, svgFiles } = instance;
980
+ const copiedAssets = this.copiedAssets;
981
+ const wasModified = (item) => fetched.includes(item) || copiedAssets.includes(item) && (!(0, types_1.isEmpty)(item.bundleId) || !(0, types_1.isEmpty)(item.trailingContent));
982
+ const js = jsFiles.filter(item => item.imports || wasModified(item));
983
+ const css = cssFiles.filter(wasModified);
984
+ const svg = svgFiles.filter(wasModified);
985
+ if (js.length || css.length || svg.length) {
986
+ instance.jsFiles = js;
987
+ instance.cssFiles = css;
988
+ instance.svgFiles = svg;
989
+ await instance.applyTransforms(processing);
990
+ }
991
+ hint = assets.filter(item => item.etag).length + ' assets';
992
+ }
993
+ case 'exists':
994
+ if (hint || isHtmlOnly()) {
995
+ this.formatMessage(4 /* LOG_TYPE.PROCESS */, 'HTML', ['No changes detected', 'incremental: ' + incremental], hint, { ...index_1.default.LOG_STYLE_NOTICE, messageBgColor: 'bgWhite', messageColor: 'black' });
996
+ return super.finalize.call(this, instance);
997
+ }
998
+ break;
999
+ }
1000
+ }
1001
+ }
1002
+ }
1003
+ instance.setInlinedAttributes(processing);
1004
+ if (instance.editing.length) {
1005
+ await instance.applyTransforms(processing);
1006
+ if (instance.aborted) {
1007
+ return Promise.reject((0, types_1.createAbortError)());
1008
+ }
1009
+ }
1010
+ if (productionRelease) {
1011
+ instance.setProductionAttributes(processing);
1012
+ }
1013
+ if (outHtml) {
1014
+ await instance.rewriteHtml(processing);
1015
+ }
1016
+ return this.aborted ? Promise.reject((0, types_1.createAbortError)()) : super.finalize.call(this, instance);
1017
+ }
1018
+ static async cleanup(instance) {
1019
+ if (instance.aborted) {
1020
+ return Promise.reject((0, types_1.createAbortError)());
1021
+ }
1022
+ if (this.Watch) {
1023
+ const related = instance.related;
1024
+ let includes;
1025
+ for (const asset of instance.assets) {
1026
+ if (asset.watch && (includes = related.get(asset))) {
1027
+ if (!(0, types_1.isPlainObject)(asset.watch)) {
1028
+ asset.watch = {};
1029
+ }
1030
+ const items = new Set((asset.watch.assets || []));
1031
+ (function recurse(children) {
1032
+ for (const item of children) {
1033
+ if (!items.has(item)) {
1034
+ if (isWatched.call(instance, item)) {
1035
+ item.flags |= 8 /* ASSET_FLAG.WATCH */;
1036
+ }
1037
+ items.add(item);
1038
+ const next = related.get(item);
1039
+ if (next) {
1040
+ recurse(next);
1041
+ }
1042
+ }
1043
+ }
1044
+ })(includes);
1045
+ asset.watch.assets = Array.from(items);
1046
+ }
1047
+ }
1048
+ }
1049
+ let productionRelease = instance.productionRelease;
1050
+ if ((0, types_1.isString)(productionRelease)) {
1051
+ if (path.isAbsolute(productionRelease = path.normalize(productionRelease)) && isDir(productionRelease)) {
1052
+ if (this.canWrite(productionRelease)) {
1053
+ const serverRoot = ChromeDocument.INTERNAL_SERVERROOT;
1054
+ const srcDir = path.join(this.baseDirectory, serverRoot);
1055
+ if (isDir(srcDir)) {
1056
+ const result = await index_1.default.copyDir(srcDir, productionRelease, !this.archiving);
1057
+ const failed = result.failed.map(value => this.removeCwd(value));
1058
+ for (const value of this.files) {
1059
+ if (value.startsWith(serverRoot)) {
1060
+ if (!failed.includes(value)) {
1061
+ this.delete(value);
1062
+ }
1063
+ else {
1064
+ instance.writeFail(["Unable to move file" /* ERR_MESSAGE.MOVE_FILE */, instance.moduleName], (0, types_1.errorMessage)('production', path.join(this.baseDirectory, value)), { fatal: true });
1065
+ }
1066
+ }
1067
+ }
1068
+ }
1069
+ }
1070
+ else {
1071
+ instance.writeFail(["Unable to write directory" /* ERR_MESSAGE.WRITE_DIRECTORY */, instance.moduleName], (0, types_1.errorMessage)('production', 'Access denied', productionRelease));
1072
+ }
1073
+ }
1074
+ else {
1075
+ instance.writeFail(["Unable to read directory" /* ERR_MESSAGE.READ_DIRECTORY */, instance.moduleName], (0, types_1.errorMessage)('production', 'Invalid directory', productionRelease), 32 /* LOG_TYPE.FILE */);
1076
+ }
1077
+ }
1078
+ }
1079
+ static sanitizeAssets(assets, exclusions = []) {
1080
+ assets.forEach(item => {
1081
+ if ((0, types_1.ignoreFlag)(item.flags)) {
1082
+ return;
1083
+ }
1084
+ for (const attr in item) {
1085
+ switch (attr) {
1086
+ case 'relativeUrl':
1087
+ case 'srcSet':
1088
+ case 'inlineUrl':
1089
+ case 'inlineUrlMap':
1090
+ case 'inlineUrlCloud':
1091
+ case 'inlineUrlCloudMap':
1092
+ case 'inlineBase64':
1093
+ case 'modified':
1094
+ if (!exclusions.includes(attr)) {
1095
+ delete item[attr];
1096
+ }
1097
+ break;
1098
+ }
1099
+ }
1100
+ });
1101
+ }
1102
+ init(assets, config) {
1103
+ assets.sort((a, b) => {
1104
+ if (!(0, types_1.isEmpty)(a.bundleId) && a.bundleId === b.bundleId) {
1105
+ return b.bundleIndex - a.bundleIndex;
1106
+ }
1107
+ return 0;
1108
+ });
1109
+ const cloud = [];
1110
+ for (const item of assets) {
1111
+ if ((0, types_1.ignoreFlag)(item.flags)) {
1112
+ continue;
1113
+ }
1114
+ if (item.trailingContent) {
1115
+ item.modified = true;
1116
+ }
1117
+ if (Array.isArray(item.cloudStorage)) {
1118
+ cloud.push(item.cloudStorage);
1119
+ }
1120
+ if (item.editing) {
1121
+ switch (item.mimeType) {
1122
+ case 'text/html':
1123
+ if (!this.htmlFile) {
1124
+ this.htmlFile = item;
1125
+ item.editing = true;
1126
+ this._editing.push(item);
1127
+ }
1128
+ else {
1129
+ item.editing = false;
1130
+ }
1131
+ item.mimeType = 'text/html';
1132
+ break;
1133
+ case 'text/css':
1134
+ this.cssFiles.push(item);
1135
+ this._editing.push(item);
1136
+ item.editing = true;
1137
+ item.mimeType = 'text/css';
1138
+ break;
1139
+ case 'text/javascript':
1140
+ case 'application/javascript':
1141
+ this.jsFiles.push(item);
1142
+ this._editing.push(item);
1143
+ item.editing = true;
1144
+ item.mimeType = 'application/javascript';
1145
+ break;
1146
+ }
1147
+ }
1148
+ }
1149
+ this.cssFiles.sort((a, b) => {
1150
+ if (a.bundleReplace) {
1151
+ return -1;
1152
+ }
1153
+ if (b.bundleReplace) {
1154
+ return 1;
1155
+ }
1156
+ return 0;
1157
+ });
1158
+ if (config) {
1159
+ const { useUnsafeReplace, baseUrl, productionRelease, productionIncremental, templateMap, imports, cache } = config;
1160
+ const target = this.config;
1161
+ for (const attr in config) {
1162
+ if (attr in target) {
1163
+ target[attr] = config[attr];
1164
+ }
1165
+ }
1166
+ switch (useUnsafeReplace) {
1167
+ case 'html':
1168
+ target.useUnsafeHtmlReplace = true;
1169
+ break;
1170
+ case 'css':
1171
+ target.useUnsafeCssReplace = true;
1172
+ break;
1173
+ default:
1174
+ if (typeof useUnsafeReplace === 'boolean') {
1175
+ target.useUnsafeHtmlReplace = useUnsafeReplace;
1176
+ target.useUnsafeCssReplace = useUnsafeReplace;
1177
+ }
1178
+ else if ((0, types_1.isArray)(useUnsafeReplace)) {
1179
+ target.useUnsafeHtmlReplace = useUnsafeReplace.includes('html');
1180
+ target.useUnsafeCssReplace = useUnsafeReplace.includes('css');
1181
+ }
1182
+ break;
1183
+ }
1184
+ if (baseUrl) {
1185
+ try {
1186
+ const { origin, pathname } = new URL(this.baseUrl = baseUrl);
1187
+ this.baseDirectory = origin + pathname.substring(0, pathname.lastIndexOf('/') + 1);
1188
+ }
1189
+ catch {
1190
+ }
1191
+ }
1192
+ if (productionRelease === true || (0, types_1.isString)(productionRelease)) {
1193
+ this.productionRelease = productionRelease;
1194
+ }
1195
+ if (productionIncremental) {
1196
+ this.productionIncremental = true;
1197
+ }
1198
+ if ((0, types_1.isObject)(templateMap)) {
1199
+ this.templateMap = templateMap;
1200
+ }
1201
+ this.imports = (0, types_1.isPlainObject)(imports) ? { ...this.module.imports, ...imports } : this.module.imports;
1202
+ if ((0, types_1.isObject)(cache) && 'transform' in cache) {
1203
+ this.customize({ transform: cache.transform });
1204
+ }
1205
+ }
1206
+ super.init(assets, config);
1207
+ const mimeMap = this._mimeMap;
1208
+ if (mimeMap && 'format' in mimeMap) {
1209
+ const format = mimeMap.format;
1210
+ if ((0, types_1.isObject)(format)) {
1211
+ this.formatMap = 'pathname' in format || 'filename' in format || 'dictionary' in format ? { uuid: format } : format;
1212
+ }
1213
+ else {
1214
+ this.formatMap = undefined;
1215
+ }
1216
+ }
1217
+ for (const storage of cloud) {
1218
+ for (const { service, upload, download } of storage) {
1219
+ if (upload) {
1220
+ setLocationUUID.call(this, upload, null, service);
1221
+ }
1222
+ if (download) {
1223
+ setLocationUUID.call(this, download, null, service);
1224
+ }
1225
+ }
1226
+ }
1227
+ return this;
1228
+ }
1229
+ findConfig(data, name, type) {
1230
+ if (type && this.hasEval('template')) {
1231
+ const settings = this.templateMap[type];
1232
+ for (const attr in settings) {
1233
+ const item = settings[attr];
1234
+ if ((0, types_1.isObject)(item) && name in item) {
1235
+ const options = this.loadConfig(item, name);
1236
+ if (options) {
1237
+ return [attr, options, this.loadConfig(item, name + '-output')];
1238
+ }
1239
+ break;
1240
+ }
1241
+ }
1242
+ }
1243
+ return super.findConfig(data, name, type);
1244
+ }
1245
+ forDb(item) {
1246
+ switch (item.source) {
1247
+ case 'cloud':
1248
+ case 'uri':
1249
+ case 'local':
1250
+ case 'export':
1251
+ return false;
1252
+ default:
1253
+ return !item.element;
1254
+ }
1255
+ }
1256
+ restart() {
1257
+ ChromeDocument.sanitizeAssets(this.assets);
1258
+ this._elements = null;
1259
+ this._dataSource = null;
1260
+ }
1261
+ async using(data) {
1262
+ if (this.aborted) {
1263
+ return Promise.reject((0, types_1.createAbortError)());
1264
+ }
1265
+ const file = data.file;
1266
+ if (file.editing) {
1267
+ return;
1268
+ }
1269
+ const host = data.host;
1270
+ const productionRelease = this.productionRelease ? true : undefined;
1271
+ const { localUri, mimeType, format } = file;
1272
+ const hash = productionRelease && file.hash;
1273
+ switch (mimeType) {
1274
+ case 'text/html':
1275
+ if (format) {
1276
+ const output = await this.transform('html', host.getUTF8String(file, localUri), format, transformOptions.call(this, file, mimeType));
1277
+ if (output) {
1278
+ file.modified = true;
1279
+ file.sourceUTF8 = output.code;
1280
+ }
1281
+ }
1282
+ break;
1283
+ case 'text/css':
1284
+ if (format) {
1285
+ const source = host.getUTF8String(file, localUri);
1286
+ const output = await this.transform('css', source, format, transformOptions.call(this, file, mimeType, source));
1287
+ if (output) {
1288
+ if (output.map) {
1289
+ const uri = writeSourceMap(localUri, output, { mimeType, hash, emptySources: productionRelease, inlineMap: hasSourceMap(file.metadata, 'inline') });
1290
+ if (uri) {
1291
+ host.add(uri, file, types_1.FILE_TYPE.SOURCEMAP);
1292
+ }
1293
+ }
1294
+ file.modified = true;
1295
+ file.sourceUTF8 = output.code;
1296
+ }
1297
+ }
1298
+ break;
1299
+ case 'text/javascript':
1300
+ case 'application/javascript': {
1301
+ let source = host.getUTF8String(file, localUri);
1302
+ if (!(file.bundleIndex >= 0)) {
1303
+ source = host.setAssetContent(file, source);
1304
+ }
1305
+ const bundle = host.getAssetContent(file);
1306
+ if (bundle) {
1307
+ source += bundle;
1308
+ file.modified = true;
1309
+ }
1310
+ if (format) {
1311
+ const output = await this.transform('js', source, format, transformOptions.call(this, file, mimeType, source, host.contentToAppend.get(localUri)));
1312
+ if (output) {
1313
+ source = transformJs.call(this, host, file, output);
1314
+ }
1315
+ }
1316
+ file.sourceUTF8 = source;
1317
+ break;
1318
+ }
1319
+ case 'image/svg+xml': {
1320
+ const source = host.getUTF8String(file, localUri);
1321
+ if (/\burl\(/i.test(source)) {
1322
+ file.editing = true;
1323
+ this.editing.push(file);
1324
+ this.svgFiles.push(file);
1325
+ }
1326
+ else if (format) {
1327
+ const output = await this.transform('html', source, format, transformOptions.call(this, file, mimeType, source));
1328
+ if (output) {
1329
+ file.modified = true;
1330
+ file.sourceUTF8 = output.code;
1331
+ }
1332
+ }
1333
+ break;
1334
+ }
1335
+ case 'font/ttf':
1336
+ case 'font/otf':
1337
+ case 'font/woff':
1338
+ case 'font/woff2': {
1339
+ const setFormat = (type) => {
1340
+ if (Array.isArray(format)) {
1341
+ file.format = format.filter(value => !isFont(value));
1342
+ if (type) {
1343
+ file.format.push(type);
1344
+ }
1345
+ }
1346
+ else {
1347
+ file.format = type;
1348
+ }
1349
+ };
1350
+ let to;
1351
+ if (mimeType.includes('woff')) {
1352
+ if ((0, util_1.hasValue)(format, 'truetype')) {
1353
+ to = 'ttf';
1354
+ }
1355
+ else if ((0, util_1.hasValue)(format, 'opentype')) {
1356
+ to = 'otf';
1357
+ }
1358
+ else {
1359
+ return;
1360
+ }
1361
+ }
1362
+ else if ((0, util_1.hasValue)(format, 'woff')) {
1363
+ to = 'woff';
1364
+ }
1365
+ else if ((0, util_1.hasValue)(format, 'woff2')) {
1366
+ to = 'woff2';
1367
+ }
1368
+ else {
1369
+ return;
1370
+ }
1371
+ const instance = host.loadModule('compress');
1372
+ const buffer = host.getBuffer(file);
1373
+ if (instance && buffer) {
1374
+ await instance.tryFile(buffer, { format: to, filename: file.filename, etag: file.etag }, (err, result, ext) => {
1375
+ if (err) {
1376
+ setFormat();
1377
+ this.writeFail("Unable to compress file" /* ERR_MESSAGE.COMPRESS_FILE */, err, 8 /* LOG_TYPE.COMPRESS */);
1378
+ }
1379
+ else if (result) {
1380
+ if (ext) {
1381
+ setFormat(ext.startsWith('woff') ? ext : ext === 'otf' ? 'opentype' : 'truetype');
1382
+ }
1383
+ const output = (0, types_1.renameExt)(localUri, ext || (ext = to));
1384
+ file.mimeType = 'font/' + ext;
1385
+ fs.writeFile(output, result, error => {
1386
+ if (!error) {
1387
+ file.buffer = result;
1388
+ host.replace(file, output);
1389
+ }
1390
+ else {
1391
+ this.writeFail("Unable to write file" /* ERR_MESSAGE.WRITE_FILE */, error, 32 /* LOG_TYPE.FILE */);
1392
+ }
1393
+ });
1394
+ }
1395
+ });
1396
+ }
1397
+ break;
1398
+ }
1399
+ }
1400
+ }
1401
+ setLocalUri(file, replace) {
1402
+ if (replace) {
1403
+ let trailing = file.inlineFilename;
1404
+ if (trailing) {
1405
+ let index = trailing.indexOf('?');
1406
+ if (index !== -1 || (index = trailing.indexOf('#')) !== -1) {
1407
+ trailing = trailing.substring(index);
1408
+ }
1409
+ else {
1410
+ trailing = '';
1411
+ }
1412
+ }
1413
+ else {
1414
+ trailing = '';
1415
+ }
1416
+ file.inlineFilename = file.filename + trailing;
1417
+ this.replaced.push(file);
1418
+ }
1419
+ else {
1420
+ setLocationUUID.call(this, file, file);
1421
+ }
1422
+ file.relativeUrl = getRelativeURL(file);
1423
+ }
1424
+ resolveUri(file, source, trailing) {
1425
+ const host = this.host;
1426
+ if (host) {
1427
+ switch (file.mimeType) {
1428
+ case 'text/javascript':
1429
+ case 'application/javascript':
1430
+ if (file.imports) {
1431
+ [[file.uri, source], [this.baseUrl, trailing]].forEach(([uri, code], index) => {
1432
+ let localFile;
1433
+ if (uri && code && (localFile = this.findSourceRoot(uri))) {
1434
+ const { exported, bundleId } = file;
1435
+ const bundleMain = !(0, types_1.isEmpty)(bundleId) && this.assets.find(item => item.bundleId === bundleId && item.bundleIndex === 0);
1436
+ let output;
1437
+ if ((index === 1 || exported) && Array.isArray(file.imports)) {
1438
+ output = this.resolveImports(file, code, bundleMain || file);
1439
+ }
1440
+ else if (index === 0 && !exported) {
1441
+ if (!isDir(localFile)) {
1442
+ localFile = path.dirname(localFile);
1443
+ }
1444
+ let mainFile, pathname, match;
1445
+ const ignorePath = bundleMain && (mainFile = this.findSourceRoot(bundleMain.uri)) && (isDir(mainFile) || (mainFile = path.dirname(mainFile))) && mainFile === localFile;
1446
+ while (match = REGEXP_IMPORTMODULE.exec(code)) {
1447
+ const value = match[1] || match[2] || match[4];
1448
+ const assert = match[3] || match[5];
1449
+ const from = trimQuote(value);
1450
+ const relative = /^\.{0,2}\//.test(from);
1451
+ if (assert && /\btype\s*:\s*(["'`])css\1/.test(assert)) {
1452
+ try {
1453
+ const asset = host.findAsset(relative ? new URL(from, uri) : from);
1454
+ if (asset) {
1455
+ const [relativeUrl, sameDir] = getSrcURL.call(this, bundleMain || file, asset);
1456
+ if (relativeUrl) {
1457
+ const quote = value[0];
1458
+ output = (output || code).replace(value, quote + (sameDir ? './' : '') + relativeUrl + quote);
1459
+ }
1460
+ }
1461
+ }
1462
+ catch {
1463
+ }
1464
+ continue;
1465
+ }
1466
+ if (relative) {
1467
+ if (ignorePath) {
1468
+ continue;
1469
+ }
1470
+ pathname = path.join(localFile, from);
1471
+ }
1472
+ else if (!(pathname = this.findSourceRoot(from)) || !isPath(pathname)) {
1473
+ const asset = host.findAsset(from);
1474
+ if (asset && !asset.invalid) {
1475
+ pathname = asset.localUri;
1476
+ }
1477
+ else {
1478
+ continue;
1479
+ }
1480
+ }
1481
+ if (pathname && isPath(pathname)) {
1482
+ const quote = value[0];
1483
+ output = (output || code).replace(value, quote + pathname + quote);
1484
+ }
1485
+ }
1486
+ REGEXP_IMPORTMODULE.lastIndex = 0;
1487
+ }
1488
+ if (output) {
1489
+ if (index === 0) {
1490
+ source = output;
1491
+ }
1492
+ else {
1493
+ trailing = output;
1494
+ }
1495
+ }
1496
+ }
1497
+ });
1498
+ }
1499
+ break;
1500
+ case 'text/css':
1501
+ if (file.editing) {
1502
+ const htmlFile = this.htmlFile;
1503
+ const bundleId = file.bundleId;
1504
+ if (!(0, types_1.isEmpty)(bundleId)) {
1505
+ for (const asset of this.assets) {
1506
+ if (asset.bundleIndex === 0 && asset.bundleId === bundleId) {
1507
+ const output = transformURL.call(this, host, file, 'css', source, asset);
1508
+ if (output) {
1509
+ source = output;
1510
+ file.modified = true;
1511
+ }
1512
+ break;
1513
+ }
1514
+ }
1515
+ }
1516
+ if (trailing && htmlFile) {
1517
+ const output = transformURL.call(this, host, file, 'css', trailing, htmlFile);
1518
+ if (output) {
1519
+ trailing = output;
1520
+ }
1521
+ }
1522
+ }
1523
+ break;
1524
+ }
1525
+ }
1526
+ return (trailing !== undefined ? [source, trailing] : source);
1527
+ }
1528
+ resolveImports(file, code, baseFile) {
1529
+ var _a;
1530
+ if (!Array.isArray(file.imports)) {
1531
+ return;
1532
+ }
1533
+ let bundleMain, modified;
1534
+ if ((0, types_1.isPlainObject)(baseFile)) {
1535
+ bundleMain = baseFile;
1536
+ }
1537
+ else {
1538
+ const bundleId = file.bundleId;
1539
+ if (!(0, types_1.isEmpty)(bundleId)) {
1540
+ bundleMain = this.assets.find(item => item.bundleId === bundleId && item.bundleIndex === 0);
1541
+ }
1542
+ }
1543
+ const importMap = {};
1544
+ for (const item of file.imports) {
1545
+ (importMap[_a = item.placeholder] || (importMap[_a] = [])).push(item);
1546
+ }
1547
+ for (const placeholder in importMap) {
1548
+ const items = importMap[placeholder];
1549
+ for (let i = 0, length = items.length; i < length; ++i) {
1550
+ const index = code.indexOf(placeholder);
1551
+ if (index !== -1) {
1552
+ const { uri, original, type, dynamic } = items[i];
1553
+ let value;
1554
+ if (type === 'css') {
1555
+ const asset = this.host?.findAsset(uri);
1556
+ if (asset) {
1557
+ const [relativeUrl, sameDir] = getSrcURL.call(this, bundleMain || file, asset);
1558
+ if (relativeUrl) {
1559
+ value = (sameDir ? './' : '') + relativeUrl;
1560
+ }
1561
+ }
1562
+ }
1563
+ else if (!(dynamic && file.imported !== false)) {
1564
+ value = this.findSourceRoot(uri);
1565
+ }
1566
+ if (!value) {
1567
+ if (i < length - 1) {
1568
+ continue;
1569
+ }
1570
+ value = original;
1571
+ }
1572
+ code = spliceString(code, index, index + placeholder.length, value);
1573
+ modified = true;
1574
+ break;
1575
+ }
1576
+ }
1577
+ }
1578
+ if (modified) {
1579
+ return code;
1580
+ }
1581
+ }
1582
+ replaceContent(source, statement, mimeType) {
1583
+ switch (mimeType) {
1584
+ case 'text/css': {
1585
+ const match = /^@import\s+(?:url\((?:[^)]|(?<=\\)\))+\)|"(?:[^"]|(?<=\\)")+"|'(?:[^']|(?<=\\)')+')(\s*layer(?:\(([^)]*)\)|\b))?(?:\s*supports\(((?:\([^(]+\(|\([^)]+\)|\)[^)]+\)|(?:(?!\))[^(])+|(?:(?!\()[^)])+)+)\))?(.*?);?$/.exec((typeof statement === 'string' ? statement : statement[0]).trim());
1586
+ if (match) {
1587
+ const layer = match[1];
1588
+ const supports = match[3]?.trim();
1589
+ const query = match[4].trim();
1590
+ if (layer || supports || query) {
1591
+ const newline = (0, util_1.getNewline)(source);
1592
+ let result = supports ? `@supports (${match[1].trim()}) {` + newline : '';
1593
+ if (query) {
1594
+ result += `@media ${query} {` + newline;
1595
+ }
1596
+ if (layer) {
1597
+ let name = match[2];
1598
+ result += '@layer ' + (name && (name = name.trim()) ? name + ' ' : '') + `{${newline + source + newline}}` + (query ? newline + '}' : '');
1599
+ }
1600
+ else if (query) {
1601
+ result += source + newline + '}';
1602
+ }
1603
+ if (supports) {
1604
+ result += newline + '}';
1605
+ }
1606
+ return result;
1607
+ }
1608
+ }
1609
+ break;
1610
+ }
1611
+ }
1612
+ }
1613
+ removeServerRoot(value) {
1614
+ return value.replace(new RegExp('(\\.\\./)*' + (0, types_1.escapePattern)(ChromeDocument.INTERNAL_SERVERROOT), 'g'), '');
1615
+ }
1616
+ addCopy(data, saveAs) {
1617
+ if (data.command && this.host) {
1618
+ const match = REGEXP_SRCSETSIZE.exec(data.command);
1619
+ if (match) {
1620
+ return (0, types_1.renameExt)(this.host.getLocalUri(data), match[1] + match[2].toLowerCase() + '.' + saveAs);
1621
+ }
1622
+ }
1623
+ }
1624
+ writeImage(data) {
1625
+ const { file, output, command } = data;
1626
+ if (output && command && file.element?.outerXml) {
1627
+ const match = REGEXP_SRCSETSIZE.exec(command);
1628
+ if (match) {
1629
+ (file.srcSet || (file.srcSet = [])).push(toPosix(data.baseDirectory ? output.substring(data.baseDirectory.length + 1) : output), match[1] + match[2].toLowerCase());
1630
+ file.modified = true;
1631
+ return true;
1632
+ }
1633
+ }
1634
+ return false;
1635
+ }
1636
+ cloudInit({ instance }) {
1637
+ this._cloudUrlMap = Object.create(null);
1638
+ this._cloudUploaded = new Set();
1639
+ this._cloudEndpoint = null;
1640
+ if (this.htmlFile) {
1641
+ const endpoint = instance.getStorage('upload', this.htmlFile.cloudStorage)?.upload?.endpoint;
1642
+ if (endpoint) {
1643
+ this._cloudEndpoint = new RegExp((0, types_1.escapePattern)(toPosix(endpoint)) + '/', 'g');
1644
+ }
1645
+ }
1646
+ }
1647
+ cloudObject(state, file) {
1648
+ if (file.inlineUrlCloud) {
1649
+ this._cloudUrlMap[file.inlineUrlCloud] = file;
1650
+ }
1651
+ return this.editing.includes(file);
1652
+ }
1653
+ cloudUpload({ host }, file, url, active) {
1654
+ if (active) {
1655
+ const endpoint = this._cloudEndpoint;
1656
+ const inlineUrlCloud = file.inlineUrlCloud;
1657
+ const cloudUrl = endpoint ? url.replace(endpoint, '') : url;
1658
+ file.cloudUrl = cloudUrl;
1659
+ if (inlineUrlCloud) {
1660
+ const htmlFile = this.htmlFile;
1661
+ const pattern = new RegExp((0, types_1.escapePattern)(inlineUrlCloud), 'g');
1662
+ for (const item of this.editing) {
1663
+ if (item.inlineUrlCloudMap?.[inlineUrlCloud]) {
1664
+ const source = host.getUTF8String(item);
1665
+ const output = source.replace(pattern, endpoint && item !== htmlFile && cloudUrl.indexOf('/') !== -1 ? url : cloudUrl);
1666
+ if (source !== output) {
1667
+ item.sourceUTF8 = output;
1668
+ item.modified = true;
1669
+ }
1670
+ }
1671
+ }
1672
+ this._cloudUploaded.add(inlineUrlCloud);
1673
+ }
1674
+ }
1675
+ return Promise.resolve(false);
1676
+ }
1677
+ async cloudFinalize(state) {
1678
+ if (this.aborted) {
1679
+ return Promise.reject((0, types_1.createAbortError)());
1680
+ }
1681
+ const { host, instance, localStorage } = state;
1682
+ const htmlFile = this.htmlFile;
1683
+ const tasks = [];
1684
+ const checkDocument = (item) => {
1685
+ if (item.inlineUrlCloudMap) {
1686
+ const source = host.getUTF8String(item);
1687
+ let output;
1688
+ for (const id in this._cloudUrlMap) {
1689
+ const inlineUrlCloud = item.inlineUrlCloudMap[id];
1690
+ if (inlineUrlCloud && !this._cloudUploaded.has(id)) {
1691
+ output = (output || source).replace(new RegExp((0, types_1.escapePattern)(id), 'g'), inlineUrlCloud);
1692
+ localStorage.delete(this._cloudUrlMap[id]);
1693
+ }
1694
+ }
1695
+ if (output && output !== source) {
1696
+ try {
1697
+ fs.writeFileSync(item.localUri, output, item.encoding || (item.encoding = 'utf-8'));
1698
+ item.sourceUTF8 = output;
1699
+ }
1700
+ catch (err) {
1701
+ host.writeFail(["Unable to write file" /* ERR_MESSAGE.WRITE_FILE */, path.basename(item.localUri)], err, 32 /* LOG_TYPE.FILE */);
1702
+ }
1703
+ }
1704
+ }
1705
+ };
1706
+ const mimeUsed = new Set();
1707
+ for (const files of [this.cssFiles, this.jsFiles, this.svgFiles]) {
1708
+ for (const item of files) {
1709
+ checkDocument(item);
1710
+ if (item.cloudStorage) {
1711
+ if (item.compress) {
1712
+ await host.compressFile(item);
1713
+ }
1714
+ const mimeType = item.mimeType;
1715
+ if (mimeType) {
1716
+ mimeUsed.add(mimeType);
1717
+ }
1718
+ tasks.push(...cloud_1.default.uploadAsset(state, item, mimeType));
1719
+ }
1720
+ }
1721
+ }
1722
+ if (tasks.length) {
1723
+ await Promise.all(tasks);
1724
+ if (this.aborted) {
1725
+ return Promise.reject((0, types_1.createAbortError)());
1726
+ }
1727
+ }
1728
+ if (htmlFile) {
1729
+ checkDocument(htmlFile);
1730
+ const cloudStorage = htmlFile.cloudStorage;
1731
+ if ((0, types_1.isArray)(cloudStorage)) {
1732
+ for (const storage of cloudStorage) {
1733
+ if (instance.hasCredential('storage', storage)) {
1734
+ const { service, admin, bucket, upload } = storage;
1735
+ const website = admin?.configBucket?.website;
1736
+ if ((0, types_1.isPlainObject)(website) && bucket && upload) {
1737
+ let filename = joinPath(upload.pathname, upload.filename || path.basename(htmlFile.localUri));
1738
+ if (website.indexPage === true) {
1739
+ website.indexPage = filename;
1740
+ filename = '';
1741
+ }
1742
+ if (website.errorPage === true) {
1743
+ website.errorPage = filename;
1744
+ filename = '';
1745
+ }
1746
+ if (website.indexPath === true) {
1747
+ website.indexPath = filename;
1748
+ filename = '';
1749
+ }
1750
+ if (website.errorPath === true) {
1751
+ website.errorPath = filename;
1752
+ }
1753
+ instance.setBucketWebsite(service, instance.getCredential(storage), bucket, website);
1754
+ }
1755
+ }
1756
+ }
1757
+ if (htmlFile.compress) {
1758
+ await host.compressFile(htmlFile);
1759
+ }
1760
+ return Promise.all(cloud_1.default.uploadAsset(state, htmlFile, 'text/html', true));
1761
+ }
1762
+ }
1763
+ return [];
1764
+ }
1765
+ watchInit(watch, assets, sanitize) {
1766
+ if (watch.captured || watch.aborted) {
1767
+ return;
1768
+ }
1769
+ const main = watch.main;
1770
+ let result;
1771
+ if (main?.editing && main.mimeType === 'text/html') {
1772
+ const inlineUrlCloudMap = main.inlineUrlCloudMap || {};
1773
+ const using = [];
1774
+ let found;
1775
+ for (let i = 0, length = assets.length, current, upload; i < length; ++i) {
1776
+ const asset = assets[i];
1777
+ if (asset.element && isUnedited(asset)) {
1778
+ continue;
1779
+ }
1780
+ if (!found && (0, asset_1.isEqual)(main, asset)) {
1781
+ found = true;
1782
+ using.push(asset);
1783
+ }
1784
+ else if (isWatched.call(this, asset) ||
1785
+ (0, types_1.watchFlag)(asset.flags) ||
1786
+ asset.base64 && watch.related.find(item => (0, asset_1.isEqual)(item, asset)) ||
1787
+ (0, types_1.isArray)(asset.cloudStorage) && asset.cloudStorage.some(item => (upload = item.upload) && upload.active)) {
1788
+ using.push(asset);
1789
+ }
1790
+ else if (current = watch.assets.find(item => (0, asset_1.isEqual)(item, asset))) {
1791
+ const { inlineUrlCloud: inlineUrlCloud, initialValue = {} } = current;
1792
+ if (inlineUrlCloud && inlineUrlCloudMap[inlineUrlCloud] || path.join(initialValue.pathname || asset.pathname, initialValue.filename || asset.filename).indexOf(ChromeDocument.INTERNAL_ASSIGNUUID) !== -1) {
1793
+ using.push(asset);
1794
+ }
1795
+ }
1796
+ }
1797
+ if (found) {
1798
+ result = { using };
1799
+ }
1800
+ }
1801
+ if (sanitize) {
1802
+ ChromeDocument.sanitizeAssets(assets);
1803
+ }
1804
+ return result;
1805
+ }
1806
+ watchModified(watch, assets) {
1807
+ return (files, errors, status) => {
1808
+ if (!watch.server || watch.captured || watch.aborted) {
1809
+ return;
1810
+ }
1811
+ const asset = watch.bundleMain || watch.assets[0];
1812
+ const pathname = (asset.cloudUrl || asset.relativeUrl || '').split('?')[0];
1813
+ let next, value, search;
1814
+ if (assets && (next = assets.find(item => (0, asset_1.isEqual)(item, asset)))) {
1815
+ if (next.cloudUrl) {
1816
+ value = next.cloudUrl;
1817
+ asset.cloudUrl = value;
1818
+ }
1819
+ else if (next.relativeUrl) {
1820
+ value = next.relativeUrl;
1821
+ asset.relativeUrl = value;
1822
+ }
1823
+ if (next.url) {
1824
+ search = next.url.search;
1825
+ }
1826
+ }
1827
+ search ?? (search = restoreSearchParams(asset.url?.search));
1828
+ if (status) {
1829
+ status = status.filter(item => item.type >= types_1.STATUS_TYPE.FATAL && item.type <= types_1.STATUS_TYPE.WARN);
1830
+ }
1831
+ watch.send(types_1.WATCH_EVENT.MODIFIED, {
1832
+ action: pathname && watch.hot && !watch.main ? 'hot' : '',
1833
+ type: asset.mimeType,
1834
+ value,
1835
+ url: { pathname, search },
1836
+ errors,
1837
+ status
1838
+ });
1839
+ };
1840
+ }
1841
+ setElementSrc(file, element, value) {
1842
+ switch (element.tagName) {
1843
+ case 'a':
1844
+ case 'area':
1845
+ case 'base':
1846
+ case 'link':
1847
+ element.setAttribute('href', value);
1848
+ break;
1849
+ case 'image':
1850
+ case 'use':
1851
+ element.setAttribute(element.hasAttribute('xlink:href') ? 'xlink:href' : 'href', value);
1852
+ break;
1853
+ case 'object':
1854
+ element.setAttribute('data', value);
1855
+ break;
1856
+ case 'video':
1857
+ element.setAttribute('poster', value);
1858
+ break;
1859
+ case 'img':
1860
+ case 'source':
1861
+ if ((0, util_1.hasValue)(file.format, 'srcset')) {
1862
+ const srcset = element.getAttribute('srcset');
1863
+ if (srcset) {
1864
+ const htmlFile = this.htmlFile;
1865
+ const uri = toPosix(file.uri);
1866
+ const items = new Set([uri]);
1867
+ const baseHref = getBaseURLs(htmlFile, this.baseUrl);
1868
+ const sameOrigin = hasSameOrigin(file.url || uri, ...baseHref);
1869
+ if (sameOrigin) {
1870
+ const src = element.getAttribute('src');
1871
+ for (const baseUri of baseHref) {
1872
+ let url;
1873
+ if (src && uri === resolvePath(url = toPosix(src), baseUri)) {
1874
+ items.add(url);
1875
+ }
1876
+ items.add(uri.startsWith(this.baseDirectory) ? uri.substring(this.baseDirectory.length) : uri.replace(baseUri.origin, ''));
1877
+ }
1878
+ }
1879
+ let current = srcset, match;
1880
+ for (const url of items) {
1881
+ const resolve = sameOrigin && !index_1.default.isURL(url);
1882
+ const pathname = url.split(/[\\/]/).map(seg => (0, types_1.escapePattern)(seg)).join('[\\\\/]');
1883
+ const pattern = new RegExp(`(,?\\s*)(${(resolve && url[0] !== '.' ? `(?:\\.\\.[\\\\/])*\\.\\.${pathname}|` : '') + pathname})(` + (url.indexOf('?') === -1 ? '(?:(?!,)(?:[^?]|$)[^,]*)|(?!\\?)[^,]*)' : '[^,]*)'), 'g');
1884
+ while (match = pattern.exec(current)) {
1885
+ const partial = match[2];
1886
+ if (!resolve || baseHref.some(baseUri => uri === resolvePath(partial, baseUri))) {
1887
+ current = replaceMatch(match, current, match[1] + value + match[3], pattern);
1888
+ }
1889
+ }
1890
+ }
1891
+ element.setAttribute('srcset', current);
1892
+ }
1893
+ break;
1894
+ }
1895
+ default:
1896
+ element.setAttribute('src', value);
1897
+ break;
1898
+ }
1899
+ }
1900
+ findDataValue(name) {
1901
+ if (this.hasEval('template')) {
1902
+ return this.templateMap.data?.[name];
1903
+ }
1904
+ }
1905
+ setInlinedAttributes({ host, startTime, hashed, contentMap, bufferMap, productionRelease }) {
1906
+ const readBase64 = (item, uuid) => {
1907
+ if (!contentMap[uuid]) {
1908
+ try {
1909
+ contentMap[uuid] = `data:${item.mimeType};base64,${(item.buffer ? item.buffer.toString('base64') : fs.readFileSync(item.localUri, 'base64')).trim()}`;
1910
+ host.removeAsset(item);
1911
+ }
1912
+ catch (err) {
1913
+ this.writeFail(["Unable to read file" /* ERR_MESSAGE.READ_FILE */, item.filename], err, { type: 32 /* LOG_TYPE.FILE */, startTime });
1914
+ return false;
1915
+ }
1916
+ }
1917
+ return true;
1918
+ };
1919
+ for (const item of this.assets) {
1920
+ if (item.inlineBase64) {
1921
+ readBase64(item, item.inlineBase64);
1922
+ }
1923
+ else if (!item.invalid && (0, util_1.hasValue)(item.format, 'base64')) {
1924
+ const uuid = (0, types_1.generateUUID)();
1925
+ if (readBase64(item, uuid)) {
1926
+ item.inlineBase64 = uuid;
1927
+ }
1928
+ }
1929
+ if (productionRelease) {
1930
+ const { imported, inlineUrl: inlineUrl, inlineUrlCloud: inlineUrlCloud } = item;
1931
+ if (inlineUrl || inlineUrlCloud) {
1932
+ const filename = createHash(host, item, bufferMap);
1933
+ if (filename) {
1934
+ for (const hash of this.assets) {
1935
+ const url = inlineUrl ? hash.inlineUrlMap?.[inlineUrl] : hash.inlineUrlCloudMap?.[inlineUrlCloud];
1936
+ if (url) {
1937
+ const search = url.indexOf('?');
1938
+ const index = (search !== -1 ? url.substring(0, search) : url).lastIndexOf('/');
1939
+ let result = '';
1940
+ if (index !== -1) {
1941
+ result = url.substring(0, index + 1);
1942
+ }
1943
+ result += filename;
1944
+ if (search !== -1) {
1945
+ result += url.substring(search);
1946
+ }
1947
+ if (inlineUrl) {
1948
+ hash.inlineUrlMap[inlineUrl] = result;
1949
+ }
1950
+ else {
1951
+ hash.inlineUrlCloudMap[inlineUrlCloud] = result;
1952
+ }
1953
+ }
1954
+ }
1955
+ }
1956
+ hashed.add(item);
1957
+ }
1958
+ else if ((!item.editing || imported) && createHash(host, item, bufferMap)) {
1959
+ hashed.add(item);
1960
+ }
1961
+ }
1962
+ }
1963
+ }
1964
+ async applyTransforms(processing) {
1965
+ const { host, hashed, bufferMap, productionRelease } = processing;
1966
+ const sanitizeSource = (item, source) => {
1967
+ if (productionRelease) {
1968
+ replaceCss.call(this, item);
1969
+ }
1970
+ const output = replaceHtml.call(this, source, processing, item.inlineUrlMap);
1971
+ if (source !== output) {
1972
+ item.modified = true;
1973
+ return output;
1974
+ }
1975
+ return source;
1976
+ };
1977
+ const transforms = [];
1978
+ const tasks = [];
1979
+ for (const item of this.svgFiles) {
1980
+ if (isIgnored(item)) {
1981
+ continue;
1982
+ }
1983
+ let source = host.getUTF8String(item);
1984
+ const output = transformURL.call(this, host, item, 'svg', source);
1985
+ if (output) {
1986
+ source = output;
1987
+ item.modified = true;
1988
+ }
1989
+ source = sanitizeSource(item, source);
1990
+ if (item.format) {
1991
+ const result = await this.transform('html', source, item.format, transformOptions.call(this, item, 'image/svg+xml'));
1992
+ if (result) {
1993
+ item.modified = true;
1994
+ source = result.code;
1995
+ }
1996
+ }
1997
+ item.sourceUTF8 = source;
1998
+ if (productionRelease && !hashed.has(item) && createHash(host, item, bufferMap)) {
1999
+ hashed.add(item);
2000
+ }
2001
+ }
2002
+ for (const item of this.cssFiles) {
2003
+ if (isIgnored(item)) {
2004
+ continue;
2005
+ }
2006
+ let source = host.getUTF8String(item), output;
2007
+ if (!(item.bundleIndex >= 0)) {
2008
+ source = host.setAssetContent(item, source);
2009
+ }
2010
+ if ((output = host.getAssetContent(item, source)) && output !== source) {
2011
+ source = output;
2012
+ item.modified = true;
2013
+ }
2014
+ if (!item.preserve && (output = this.removeUnusedStyles(source))) {
2015
+ source = output;
2016
+ item.modified = true;
2017
+ }
2018
+ if (output = transformURL.call(this, host, item, 'css', source)) {
2019
+ source = output;
2020
+ item.modified = true;
2021
+ }
2022
+ source = sanitizeSource(item, source);
2023
+ item.sourceUTF8 = source;
2024
+ if (item.format) {
2025
+ transforms.push(item);
2026
+ tasks.push(this.transform('css', source, item.format, transformOptions.call(this, item, 'text/css', source, host.contentToAppend.get(item.localUri))));
2027
+ }
2028
+ }
2029
+ for (const item of this.jsFiles) {
2030
+ if (isIgnored(item)) {
2031
+ continue;
2032
+ }
2033
+ const { bundleIndex = -1, format } = item;
2034
+ let source = host.getUTF8String(item), output;
2035
+ if (!(bundleIndex >= 0)) {
2036
+ source = host.setAssetContent(item, source);
2037
+ }
2038
+ if ((output = host.getAssetContent(item, source)) && output !== source) {
2039
+ source = output;
2040
+ item.modified = true;
2041
+ }
2042
+ if (output = transformURL.call(this, host, item, 'js', source)) {
2043
+ source = output;
2044
+ item.modified = true;
2045
+ }
2046
+ source = sanitizeSource(item, source);
2047
+ item.sourceUTF8 = source;
2048
+ if (format) {
2049
+ transforms.push(item);
2050
+ tasks.push(this.transform('js', source, format, transformOptions.call(this, item, 'application/javascript', source, host.contentToAppend.get(item.localUri))));
2051
+ }
2052
+ }
2053
+ return Promise.allSettled(tasks).then(items => {
2054
+ for (let i = 0, length = items.length, value; i < length; ++i) {
2055
+ const item = items[i];
2056
+ if (item.status === 'fulfilled' && (value = item.value)) {
2057
+ const target = transforms[i];
2058
+ if (value.type === 'css') {
2059
+ if (value.map && !target.bundleReplace) {
2060
+ const output = writeSourceMap(target.localUri, value, { mimeType: 'text/css', hash: productionRelease ? target.hash : undefined, emptySources: productionRelease, inlineMap: hasSourceMap(target.metadata, 'inline') });
2061
+ if (output) {
2062
+ host.add(output, target, types_1.FILE_TYPE.SOURCEMAP);
2063
+ }
2064
+ }
2065
+ target.modified = true;
2066
+ target.sourceUTF8 = value.code;
2067
+ }
2068
+ else {
2069
+ transformJs.call(this, host, target, value);
2070
+ }
2071
+ }
2072
+ }
2073
+ });
2074
+ }
2075
+ async rewriteHtml(processing) {
2076
+ const { host, startTime, cacheMiss, productionRelease } = processing;
2077
+ const { moduleName, config } = this;
2078
+ const htmlFile = this.htmlFile;
2079
+ const localUri = htmlFile.localUri;
2080
+ this.formatMessage(4 /* LOG_TYPE.PROCESS */, 'HTML', ['Rewriting content...', path.dirname(localUri)]);
2081
+ let source = host.getUTF8String(htmlFile, localUri), output;
2082
+ const domBase = new dom_1.DomWriter(moduleName, source, this.elements, { normalize: config.normalizeHtmlOutput, stripComments: config.stripCommentsAndCDATA, ignoreTagGroup: config.ignoreServerCodeBlocks, escapeEntities: config.escapeReservedCharacters });
2083
+ if (config.useUnsafeHtmlReplace) {
2084
+ domBase.ignoreFlag(dom_1.IGNORE_FLAG.INTERIOR);
2085
+ }
2086
+ if (this.watching) {
2087
+ domBase.ignoreFlag(dom_1.IGNORE_FLAG.LOCATOR);
2088
+ }
2089
+ if ((0, types_1.isString)(config.useOriginalHtmlPage)) {
2090
+ domBase.ignoreTag(config.useOriginalHtmlPage);
2091
+ }
2092
+ if ((0, types_1.isArray)(config.ignoreServerCodeBlocks)) {
2093
+ domBase.ignoreTag(config.ignoreServerCodeBlocks);
2094
+ }
2095
+ if (productionRelease) {
2096
+ replaceCss.call(this, htmlFile);
2097
+ }
2098
+ await this.setElementAttributes(processing, domBase);
2099
+ await this.applyDataSource(processing, domBase);
2100
+ for (const item of this.assets) {
2101
+ if (item.element && isRemoved(item) && !(0, types_1.ignoreFlag)(item.flags)) {
2102
+ const domElement = new dom_1.HtmlElement(moduleName, item.element, item.attributes);
2103
+ domElement.remove = true;
2104
+ if (!domBase.write(domElement)) {
2105
+ this.writeFail('Unable to exclude HTML element', errorHtml(item.element), 4 /* LOG_TYPE.PROCESS */);
2106
+ }
2107
+ }
2108
+ }
2109
+ source = removeNamespace(moduleName, domBase.modified ? domBase.close() : source, domBase.newline, domBase.getComments());
2110
+ if (!htmlFile.preserve) {
2111
+ let match;
2112
+ while (match = REGEXP_STYLE.exec(source)) {
2113
+ if (output = this.removeUnusedStyles(match[5])) {
2114
+ source = replaceMatch(match, source, match[1] + output + match[6], REGEXP_STYLE);
2115
+ }
2116
+ }
2117
+ REGEXP_STYLE.lastIndex = 0;
2118
+ }
2119
+ if (output = transformURL.call(this, host, htmlFile, 'html', source)) {
2120
+ source = output;
2121
+ }
2122
+ source = replaceHtml.call(this, source, processing, htmlFile.inlineUrlMap);
2123
+ if ((0, types_1.isString)(config.stripCommentsAndCDATA)) {
2124
+ source = dom_1.DomWriter.getCommentsAndCDATA(source, config.stripCommentsAndCDATA, true, true);
2125
+ }
2126
+ if (htmlFile.format) {
2127
+ const result = await this.transform('html', source, htmlFile.format, {
2128
+ pathname: path.dirname(localUri),
2129
+ filename: htmlFile.filename,
2130
+ mimeType: 'text/html',
2131
+ metadata: Object.assign({ '__fromhtml__': true, ...this.config }, htmlFile.metadata),
2132
+ cacheData: !productionRelease || this.productionIncremental ? { uri: htmlFile.uri, encoding: htmlFile.encoding } : undefined
2133
+ });
2134
+ if (result) {
2135
+ source = result.code;
2136
+ }
2137
+ }
2138
+ if (domBase.hasErrors()) {
2139
+ const timeStamp = Date.now();
2140
+ domBase.errors.forEach(err => this.addLog(types_1.STATUS_TYPE.WARN, 'dom-writer -> ' + err.message, timeStamp));
2141
+ }
2142
+ if (domBase.failCount > 0) {
2143
+ this.writeFail(['Unable to update document', moduleName], (0, types_1.errorMessage)('html', 'DOM rewrite failed', domBase.failCount + ' errors'), { type: 4 /* LOG_TYPE.PROCESS */, startTime });
2144
+ }
2145
+ else {
2146
+ this.writeTimeProcess('html', `dom-writer (${domBase.modifyCount} modified) -> ` + path.basename(localUri), startTime);
2147
+ if (cacheMiss.length) {
2148
+ const data = {};
2149
+ const message = [];
2150
+ cacheMiss.forEach(name => data[name] = (data[name] || 0) + 1);
2151
+ for (const name in data) {
2152
+ message.push(name + `(${data[name]})`);
2153
+ }
2154
+ this.formatMessage(65536 /* LOG_TYPE.DB */, 'DB', ['Cache statistics', cacheMiss.length + ' missed'], message.join(' - '), { ...index_1.default.LOG_STYLE_NOTICE, hintBold: true });
2155
+ }
2156
+ }
2157
+ htmlFile.modified = true;
2158
+ htmlFile.sourceUTF8 = source;
2159
+ }
2160
+ async setElementAttributes({ host, startTime, productionRelease }, domBase) {
2161
+ var _a;
2162
+ const { moduleName, htmlFile } = this;
2163
+ const cloud = host.Cloud;
2164
+ const removeWatchReload = (item) => (0, types_1.isObject)(item.watch) && delete item.watch.reload;
2165
+ for (const item of this.assets) {
2166
+ const element = item.element;
2167
+ if (!element || element.removed || isRemoved(item) || isUnedited(item) || (0, types_1.ignoreFlag)(item.flags) && !(0, types_1.processFlag)(item.flags)) {
2168
+ continue;
2169
+ }
2170
+ const domElement = new dom_1.HtmlElement(moduleName, element, item.attributes);
2171
+ if (item.inlineContent) {
2172
+ let [innerXml, sourceMappingURL, inlineMap] = transform_1.SourceMap.removeSourceMappingURL(host.getUTF8String(item).trim());
2173
+ if (sourceMappingURL && !inlineMap && item.localUri) {
2174
+ let mapUri = path.resolve(sourceMappingURL = decodeURIComponent(sourceMappingURL));
2175
+ if (!isPath(mapUri)) {
2176
+ mapUri = path.join(path.dirname(item.localUri), sourceMappingURL);
2177
+ }
2178
+ host.deleteFile(mapUri);
2179
+ }
2180
+ domElement.tagName = item.inlineContent;
2181
+ domElement.innerXml = innerXml;
2182
+ domElement.removeAttribute('src', 'href');
2183
+ }
2184
+ else {
2185
+ let uri = item.relativeUrl;
2186
+ if ((0, util_1.hasValue)(item.format, 'base64')) {
2187
+ if (item.invalid) {
2188
+ continue;
2189
+ }
2190
+ if (item.inlineBase64) {
2191
+ this.setElementSrc(item, domElement, item.inlineBase64);
2192
+ removeWatchReload(item);
2193
+ uri = '';
2194
+ }
2195
+ }
2196
+ if (uri && !(0, util_1.hasValue)(item.format, 'crossorigin') && item !== htmlFile) {
2197
+ if (cloud?.getStorage('upload', item.cloudStorage)) {
2198
+ const inlineUrlCloud = item.inlineUrlCloud || (item.inlineUrlCloud = (0, types_1.generateUUID)());
2199
+ ((_a = htmlFile).inlineUrlCloudMap || (_a.inlineUrlCloudMap = {}))[inlineUrlCloud] = productionRelease ? this.removeServerRoot(uri) : uri;
2200
+ uri = inlineUrlCloud;
2201
+ }
2202
+ if (!(0, util_1.hasValue)(item.format, 'webbundle')) {
2203
+ const { bundleIndex, srcSet } = item;
2204
+ if (bundleIndex === 0 || bundleIndex === -1) {
2205
+ switch (element.tagName) {
2206
+ case 'style':
2207
+ domElement.tagName = 'link';
2208
+ case 'link':
2209
+ domElement.setAttribute('rel', 'stylesheet');
2210
+ break;
2211
+ }
2212
+ domElement.innerXml = '';
2213
+ }
2214
+ this.setElementSrc(item, domElement, uri);
2215
+ if (srcSet) {
2216
+ const length = srcSet.length;
2217
+ let src = domElement.getAttribute('srcset'), i = 0;
2218
+ while (i < length) {
2219
+ src += (src ? ', ' : '') + srcSet[i++] + ' ' + srcSet[i++];
2220
+ }
2221
+ domElement.setAttribute('srcset', src);
2222
+ }
2223
+ }
2224
+ }
2225
+ const detectWidth = domElement.getAttribute('width') === 'detect';
2226
+ const detectHeight = domElement.getAttribute('height') === 'detect';
2227
+ if (detectWidth || detectHeight) {
2228
+ let width = 0, height = 0, buffer = null;
2229
+ if (isImage(item.mimeType) && (buffer = host.getBuffer(item))) {
2230
+ let dimensions;
2231
+ try {
2232
+ dimensions = require('probe-image-size').sync(buffer);
2233
+ }
2234
+ catch {
2235
+ }
2236
+ if (dimensions) {
2237
+ ({ width, height } = dimensions);
2238
+ }
2239
+ else {
2240
+ try {
2241
+ ({ width, height } = (await jimp.read(buffer)).bitmap);
2242
+ }
2243
+ catch {
2244
+ const filename = item.localUri || item.filename;
2245
+ if (filename) {
2246
+ this.addLog(types_1.STATUS_TYPE.WARN, `Could not detect image size (${path.basename(filename)})`);
2247
+ }
2248
+ }
2249
+ }
2250
+ }
2251
+ if (detectWidth) {
2252
+ if (width > 0) {
2253
+ domElement.setAttribute('width', width.toString());
2254
+ }
2255
+ else {
2256
+ domElement.removeAttribute('width');
2257
+ }
2258
+ }
2259
+ if (detectHeight) {
2260
+ if (height > 0) {
2261
+ domElement.setAttribute('height', height.toString());
2262
+ }
2263
+ else {
2264
+ domElement.removeAttribute('height');
2265
+ }
2266
+ }
2267
+ }
2268
+ }
2269
+ if (!domBase.write(domElement)) {
2270
+ this.writeFail(item.inlineContent ? 'Inline tag replacement' : 'Element attribute replacement', errorHtml(element), { type: 4 /* LOG_TYPE.PROCESS */, startTime });
2271
+ delete item.inlineUrlCloud;
2272
+ }
2273
+ else if (item.inlineContent) {
2274
+ host.removeAsset(item);
2275
+ removeWatchReload(item);
2276
+ }
2277
+ }
2278
+ }
2279
+ async applyDataSource({ host, startTime, cacheMiss }, domBase) {
2280
+ if (this.dataSource.length === 0) {
2281
+ return;
2282
+ }
2283
+ const { moduleName, Db: db } = this;
2284
+ const cloud = host.Cloud;
2285
+ const sessionKey = (0, types_1.generateUUID)();
2286
+ const cacheData = Object.create(null);
2287
+ const dataItems = [];
2288
+ const displayItems = [];
2289
+ this.dataSource.forEach(item => item.type === 'display' ? displayItems.push(item) : dataItems.push(item));
2290
+ const removeElement = (item, element) => {
2291
+ if (item.removeEmpty || item.type === 'display') {
2292
+ (element || (element = new dom_1.HtmlElement(moduleName, item.element))).remove = true;
2293
+ if (!domBase.write(element)) {
2294
+ this.writeFail('Unable to remove element', errorHtml(item.element), { type: 4 /* LOG_TYPE.PROCESS */, startTime });
2295
+ }
2296
+ }
2297
+ };
2298
+ const errorCredential = (item, err) => {
2299
+ removeElement(item);
2300
+ const pkg = getPackageName(err, item.source);
2301
+ if (!(pkg && this.checkPackage(err, pkg))) {
2302
+ this.writeFail(["Invalid credentials" /* ERR_DB.CREDENTIALS */, item.source], err);
2303
+ }
2304
+ };
2305
+ const checkObject = (item, data) => {
2306
+ const { query, cascade } = item;
2307
+ if ((0, types_1.isString)(cascade)) {
2308
+ const result = data && (0, types_1.cascadeObject)(data, cascade, data);
2309
+ if (result !== data) {
2310
+ data = result;
2311
+ }
2312
+ else if (item.fallback !== undefined) {
2313
+ data = item.fallback;
2314
+ }
2315
+ else if (!(0, types_1.isString)(query)) {
2316
+ return null;
2317
+ }
2318
+ }
2319
+ if (data) {
2320
+ if ((0, types_1.isString)(query) && item.source !== 'mongodb') {
2321
+ const pkg = query[0] === '$' ? 'jsonpath' : 'jmespath';
2322
+ try {
2323
+ if (pkg === 'jsonpath') {
2324
+ data = require(pkg).query(data, query);
2325
+ }
2326
+ else {
2327
+ data = require(pkg).search(data, query);
2328
+ }
2329
+ }
2330
+ catch (err) {
2331
+ this.abort(item.source);
2332
+ this.checkPackage(err, pkg, ["Unable to filter results" /* ERR_DB.FILTER_QUERY */, item.source]);
2333
+ }
2334
+ }
2335
+ }
2336
+ return Array.isArray(data) ? data : (0, types_1.isObject)(data) ? [data] : null;
2337
+ };
2338
+ const setElements = async (sourceSet) => {
2339
+ const batchMap = Object.create(null);
2340
+ const batchGroup = [];
2341
+ for (const item of sourceSet) {
2342
+ if (!item.element) {
2343
+ this.addLog(types_1.STATUS_TYPE.WARN, `Missing target element {${JSON.stringify(item)}}`);
2344
+ continue;
2345
+ }
2346
+ const type = item.source;
2347
+ switch (type) {
2348
+ case 'cloud': {
2349
+ const { service, credential } = item;
2350
+ if (cloud) {
2351
+ const key = service + '_' + (service === 'atlas' && item.uri || '') + '_' + asString(credential, true);
2352
+ (batchMap[key] || (batchMap[key] = [])).push(item);
2353
+ }
2354
+ else {
2355
+ errorCredential(item, (0, types_1.errorValue)("Cloud module not installed" /* ERR_CLOUD.MODULE_NOTFOUND */, service));
2356
+ }
2357
+ break;
2358
+ }
2359
+ case 'uri':
2360
+ case 'local':
2361
+ case 'export':
2362
+ batchGroup.push([item]);
2363
+ break;
2364
+ default:
2365
+ if (db?.hasSource(type)) {
2366
+ try {
2367
+ await db.setCredential(item);
2368
+ const credential = item.credential;
2369
+ let key;
2370
+ switch (type) {
2371
+ case 'mongodb':
2372
+ key = core_1.ClientDb.keyOfResult(item.uri || type, credential);
2373
+ break;
2374
+ case 'redis':
2375
+ key = credential && (key = core_1.ClientDb.keyOfResult(type, credential, true)) ? key : JSON.stringify(item.options.client);
2376
+ break;
2377
+ default:
2378
+ key = core_1.ClientDb.keyOfResult(type, credential);
2379
+ break;
2380
+ }
2381
+ (batchMap[key] || (batchMap[key] = [])).push(item);
2382
+ }
2383
+ catch (err) {
2384
+ errorCredential(item, err);
2385
+ }
2386
+ }
2387
+ else {
2388
+ errorCredential(item, (0, types_1.errorValue)(db ? "Database provider not found" /* ERR_DB.PROVIDER_NOTFOUND */ : "Db module not installed" /* ERR_DB.MODULE_NOTFOUND */, type));
2389
+ }
2390
+ break;
2391
+ }
2392
+ }
2393
+ for (const key in batchMap) {
2394
+ batchGroup.push(batchMap[key]);
2395
+ }
2396
+ return this.allSettled(batchGroup.map(batch => {
2397
+ return new Promise(async (resolve, reject) => {
2398
+ const errorRemove = (item, reason) => {
2399
+ removeElement(item);
2400
+ reject(reason);
2401
+ };
2402
+ const errorClient = (item, reason) => {
2403
+ removeElement(item);
2404
+ if (reason) {
2405
+ this.writeFail(["Unable to configure client" /* ERR_DB.CLIENT */, item.source], reason);
2406
+ }
2407
+ reject();
2408
+ };
2409
+ const length = batch.length;
2410
+ const current = batch[0];
2411
+ const type = current.source;
2412
+ let result = new Array(length);
2413
+ switch (type) {
2414
+ case 'cloud':
2415
+ result = await cloud.getDatabaseBatchRows(batch, true, sessionKey).catch(err => {
2416
+ this.abort(type);
2417
+ if (err instanceof Error) {
2418
+ cloud.addLog(this.aborted ? types_1.STATUS_TYPE.ERROR : types_1.STATUS_TYPE.WARN, err);
2419
+ }
2420
+ return [];
2421
+ });
2422
+ break;
2423
+ case 'uri':
2424
+ case 'local': {
2425
+ const { ignoreCache, encoding = 'utf-8', options } = current;
2426
+ let content, target, data, cacheKey;
2427
+ const addDownload = () => typeof content === 'string' && host.addDownload(Buffer.byteLength(content, encoding));
2428
+ if (type === 'local') {
2429
+ let location;
2430
+ ({ pathname: target } = current);
2431
+ if (target && ((location = this.resolveDir('data', target)) || host.canRead(location = path.resolve(target), { ownPermissionOnly: true }))) {
2432
+ if (!ignoreCache && CACHE_DBRESULT.has(location)) {
2433
+ data = getCacheItem(CACHE_DBRESULT, location);
2434
+ }
2435
+ else {
2436
+ if (ignoreCache === 1) {
2437
+ CACHE_DBRESULT.delete(location);
2438
+ }
2439
+ if (!(data = cacheData[location])) {
2440
+ try {
2441
+ content = fs.readFileSync(location, encoding);
2442
+ cacheKey = location;
2443
+ addDownload();
2444
+ }
2445
+ catch (err) {
2446
+ this.abort(type);
2447
+ this.writeFail(["Unable to read file" /* ERR_MESSAGE.READ_FILE */, path.basename(location)], err, { type: 32 /* LOG_TYPE.FILE */, startTime });
2448
+ errorRemove(current);
2449
+ return;
2450
+ }
2451
+ }
2452
+ }
2453
+ }
2454
+ else {
2455
+ this.abort(type);
2456
+ errorRemove(current, target ? errorDataSource('Not found', target) : errorDataSource('Not defined - ' + (this.settings.directory?.data ? 'file' : 'directory'), type));
2457
+ return;
2458
+ }
2459
+ }
2460
+ else if (!(0, types_1.isString)(target = current.uri)) {
2461
+ this.abort(type);
2462
+ errorRemove(current, errorDataSource('Not defined', type));
2463
+ return;
2464
+ }
2465
+ else if (index_1.default.isURL(target, 'file')) {
2466
+ if (!ignoreCache && CACHE_DBRESULT.has(target)) {
2467
+ data = getCacheItem(CACHE_DBRESULT, target);
2468
+ }
2469
+ else {
2470
+ if (ignoreCache === 1) {
2471
+ CACHE_DBRESULT.delete(target);
2472
+ }
2473
+ if (!(data = cacheData[target])) {
2474
+ try {
2475
+ content = await host.fetchBuffer(target, { encoding });
2476
+ if (Buffer.isBuffer(content)) {
2477
+ content = content.toString('utf-8');
2478
+ }
2479
+ cacheKey = target;
2480
+ }
2481
+ catch (err) {
2482
+ this.abort(type);
2483
+ this.writeFail(["Unable to download file" /* ERR_MESSAGE.DOWNLOAD_FILE */, target], err, { type: 1024 /* LOG_TYPE.HTTP */, startTime });
2484
+ errorRemove(current);
2485
+ return;
2486
+ }
2487
+ }
2488
+ }
2489
+ }
2490
+ else {
2491
+ const pathname = index_1.default.resolveFile(target);
2492
+ if (!ignoreCache && CACHE_DBRESULT.has(pathname)) {
2493
+ data = getCacheItem(CACHE_DBRESULT, pathname);
2494
+ }
2495
+ else {
2496
+ if (ignoreCache === 1) {
2497
+ CACHE_DBRESULT.delete(pathname);
2498
+ }
2499
+ if (!(data = cacheData[pathname])) {
2500
+ if (!host.canRead(pathname, { ownPermissionOnly: true })) {
2501
+ this.abort(type);
2502
+ errorRemove(current, errorDataSource('Access denied', pathname));
2503
+ return;
2504
+ }
2505
+ try {
2506
+ content = fs.readFileSync(pathname, encoding);
2507
+ cacheKey = pathname;
2508
+ addDownload();
2509
+ }
2510
+ catch (err) {
2511
+ this.abort(type);
2512
+ this.writeFail(["Unable to read file" /* ERR_MESSAGE.READ_FILE */, path.basename(pathname)], err, { type: 32 /* LOG_TYPE.FILE */, startTime });
2513
+ errorRemove(current);
2514
+ return;
2515
+ }
2516
+ }
2517
+ }
2518
+ }
2519
+ if ((0, types_1.isString)(content)) {
2520
+ const { format = path.extname(target).substring(1) } = current;
2521
+ try {
2522
+ data = this.tryParse(content, format, options);
2523
+ }
2524
+ catch (err) {
2525
+ this.abort(type);
2526
+ this.writeFail(['Unable to parse data source', format], err, { type: 4 /* LOG_TYPE.PROCESS */, startTime });
2527
+ errorRemove(current);
2528
+ return;
2529
+ }
2530
+ if (data && cacheKey) {
2531
+ setCacheData.call(this, current, data, cacheKey, cacheData);
2532
+ }
2533
+ }
2534
+ if (!data) {
2535
+ this.abort(type);
2536
+ errorRemove(current, errorDataSource(content !== null ? 'Invalid response' : 'Empty response', target));
2537
+ return;
2538
+ }
2539
+ if ((result[0] = checkObject(current, data)) === null) {
2540
+ this.abort(type);
2541
+ errorRemove(current, errorDataSource('Invalid ' + (current.query ? 'query' : 'URI'), target));
2542
+ return;
2543
+ }
2544
+ if (this.settingsOf(type, 'coerce') === true) {
2545
+ (0, types_1.coerceObject)(result[0]);
2546
+ }
2547
+ break;
2548
+ }
2549
+ case 'export': {
2550
+ const ignoreCache = current.ignoreCache;
2551
+ const cacheKey = asString(current, true);
2552
+ if (!current.ignoreCache && CACHE_DBRESULT.has(cacheKey)) {
2553
+ result[0] = getCacheItem(CACHE_DBRESULT, cacheKey);
2554
+ }
2555
+ else {
2556
+ if (ignoreCache === 1) {
2557
+ CACHE_DBRESULT.delete(cacheKey);
2558
+ }
2559
+ if (cacheKey in cacheData) {
2560
+ result[0] = cacheData[cacheKey];
2561
+ }
2562
+ else {
2563
+ let { pathname, execute, params } = current, data, target, getData, hint;
2564
+ if (typeof execute === 'function') {
2565
+ target = execute;
2566
+ }
2567
+ else if (typeof pathname === 'function') {
2568
+ target = pathname;
2569
+ }
2570
+ else if ((0, types_1.isString)(pathname)) {
2571
+ if ((pathname = pathname.trim()).startsWith('npm:')) {
2572
+ target = pathname;
2573
+ hint = pathname;
2574
+ }
2575
+ else if ((target = this.resolveDir(type, pathname)) && (getData = core_1.ClientDb.parseFunction(target, true))) {
2576
+ hint = pathname;
2577
+ }
2578
+ else {
2579
+ target = undefined;
2580
+ }
2581
+ }
2582
+ if (!getData) {
2583
+ const { settings, encoding, persist = true } = current;
2584
+ if (!target) {
2585
+ target = settings && this.settings.export?.[settings] || pathname;
2586
+ }
2587
+ if (typeof target === 'function') {
2588
+ getData = target;
2589
+ hint = target.name;
2590
+ }
2591
+ else if ((0, types_1.isString)(target)) {
2592
+ getData = this.asSourceFile(target, { encoding, persist });
2593
+ hint = target;
2594
+ }
2595
+ }
2596
+ if (typeof getData !== 'function') {
2597
+ errorRemove(current, target ? errorDataSource('Not a function', hint) : errorDataSource('Not defined - pathname | settings', type));
2598
+ return;
2599
+ }
2600
+ try {
2601
+ if (params && this.settingsOf(type, 'coerce') === true) {
2602
+ (0, types_1.coerceObject)(params);
2603
+ }
2604
+ // @ts-ignore
2605
+ if (getData["__cjs__" /* INTERNAL.CJS */]) {
2606
+ data = await getData(params);
2607
+ }
2608
+ else {
2609
+ const thisArg = index_1.default.enabled("node.process.inline" /* KEY_NAME.NODE_PROCESS_INLINE */) ? process : null;
2610
+ const inline = index_1.default.enabled("node.require.inline" /* KEY_NAME.NODE_REQUIRE_INLINE */);
2611
+ const args = [params];
2612
+ if (getData.toString().startsWith('async')) {
2613
+ if (inline) {
2614
+ args.push(require);
2615
+ }
2616
+ data = await getData.apply(thisArg, args);
2617
+ }
2618
+ else {
2619
+ data = await new Promise(success => {
2620
+ args.push(success);
2621
+ if (inline) {
2622
+ args.push(require);
2623
+ }
2624
+ getData.apply(thisArg, args);
2625
+ });
2626
+ }
2627
+ }
2628
+ setCacheData.call(this, current, data, cacheKey, cacheData);
2629
+ }
2630
+ catch (err) {
2631
+ this.abort(type);
2632
+ this.writeFail(['Unable to retrieve data source', hint], err, { type: 4 /* LOG_TYPE.PROCESS */, startTime });
2633
+ errorRemove(current);
2634
+ return;
2635
+ }
2636
+ if ((result[0] = checkObject(current, data)) === null) {
2637
+ this.abort(type);
2638
+ errorRemove(current, errorDataSource('Invalid ' + (current.query ? 'query' : 'params'), hint));
2639
+ return;
2640
+ }
2641
+ }
2642
+ }
2643
+ break;
2644
+ }
2645
+ default:
2646
+ if (db?.hasSource(type)) {
2647
+ switch (type) {
2648
+ case 'mongodb':
2649
+ for (let j = 0; j < length; ++j) {
2650
+ const cmd = batch[j];
2651
+ cmd.cacheObjectKey = typeof cmd.cascade === 'string' ? cmd.cascade : '';
2652
+ }
2653
+ break;
2654
+ case 'redis':
2655
+ for (let j = 0; j < length; ++j) {
2656
+ const cmd = batch[j];
2657
+ const { search, key, query, cascade } = cmd;
2658
+ if ((0, types_1.isObject)(search) && typeof search.schema === 'string') {
2659
+ const pathname = this.resolveDir('schema', search.schema);
2660
+ if (pathname) {
2661
+ const ignoreCache = cmd.ignoreCache;
2662
+ if (!ignoreCache && CACHE_LOCALFILE.has(pathname)) {
2663
+ search.schema = getCacheItem(CACHE_LOCALFILE, pathname);
2664
+ }
2665
+ else {
2666
+ if (ignoreCache === 1) {
2667
+ CACHE_LOCALFILE.delete(pathname);
2668
+ }
2669
+ if (!(search.schema = cacheData[pathname])) {
2670
+ try {
2671
+ search.schema = loadLocalFile.call(this, current, pathname, cacheData, cmd.encoding);
2672
+ }
2673
+ catch (err) {
2674
+ this.writeFail(['Unable to parse document', path.basename(pathname)], err, { startTime });
2675
+ search.schema = undefined;
2676
+ }
2677
+ }
2678
+ }
2679
+ }
2680
+ else {
2681
+ search.schema = undefined;
2682
+ }
2683
+ }
2684
+ if (key) {
2685
+ cmd.cacheObjectKey = ((0, types_1.isString)(cascade) ? cascade : '') + '_' + ((0, types_1.isString)(query) ? query : '');
2686
+ }
2687
+ }
2688
+ break;
2689
+ default:
2690
+ if (db.hasSource(type, db.sourceType.SQL)) {
2691
+ for (let j = 0; j < length; ++j) {
2692
+ const cmd = batch[j];
2693
+ const query = cmd.query;
2694
+ if (typeof query === 'string' && query.endsWith('.sql')) {
2695
+ const pathname = this.resolveDir('sql', query);
2696
+ try {
2697
+ if (pathname) {
2698
+ const ignoreCache = cmd.ignoreCache;
2699
+ if (!ignoreCache && CACHE_LOCALFILE.has(pathname)) {
2700
+ cmd.query = getCacheItem(CACHE_LOCALFILE, pathname);
2701
+ }
2702
+ else {
2703
+ if (ignoreCache === 1) {
2704
+ CACHE_LOCALFILE.delete(pathname);
2705
+ }
2706
+ if (!(cmd.query = cacheData[pathname])) {
2707
+ const out = { content: '' };
2708
+ try {
2709
+ cmd.query = loadLocalFile.call(this, current, pathname, cacheData, cmd.encoding, out);
2710
+ }
2711
+ catch {
2712
+ setCacheData.call(this, current, cmd.query = out.content, pathname, cacheData, true);
2713
+ }
2714
+ }
2715
+ }
2716
+ }
2717
+ else {
2718
+ throw (0, types_1.errorMessage)(type, "File not found" /* ERR_MESSAGE.NOTFOUND_FILE */, query);
2719
+ }
2720
+ }
2721
+ catch (err) {
2722
+ this.abort(type);
2723
+ this.writeFail(["Unable to read file" /* ERR_MESSAGE.READ_FILE */, pathname ? path.basename(pathname) : query], err, { startTime });
2724
+ errorRemove(current);
2725
+ return;
2726
+ }
2727
+ }
2728
+ }
2729
+ }
2730
+ break;
2731
+ }
2732
+ try {
2733
+ let coerce, cache;
2734
+ if (type === 'mongodb' || type === 'redis') {
2735
+ coerce = this.settingsOf(type, 'coerce');
2736
+ cache = this.settingsOf(type, 'cache');
2737
+ }
2738
+ const errorQuery = (err, data, commandType) => {
2739
+ let message, aborting = true;
2740
+ if (db.hasSource(type, db.sourceType.DOCUMENT)) {
2741
+ message = (data.name ? data.name + ': ' : '') + (data.table || '');
2742
+ }
2743
+ else if (db.hasSource(type, db.sourceType.KEYVALUE)) {
2744
+ aborting = commandType !== db.commandType.UPDATE;
2745
+ message = asString(data.search || data.key);
2746
+ }
2747
+ else {
2748
+ const credential = data.credential;
2749
+ if ((0, types_1.isPlainObject)(credential)) {
2750
+ message = credential.database;
2751
+ }
2752
+ }
2753
+ if (data.willAbort) {
2754
+ this.abort();
2755
+ }
2756
+ else if (aborting) {
2757
+ this.abort(type);
2758
+ }
2759
+ if (err) {
2760
+ this.writeFail(["Unable to execute query" /* ERR_DB.EXEC_QUERY */, message || "Unknown" /* ERR_MESSAGE.UNKNOWN */], err, { type: 65536 /* LOG_TYPE.DB */, startTime });
2761
+ }
2762
+ return this.aborted;
2763
+ };
2764
+ const options = { coerce, cache, checkObject, sessionKey, connectOnce: length > 1, outCacheMiss: cacheMiss, errorQuery };
2765
+ result = await db.executeBatchQuery(batch, options, result);
2766
+ }
2767
+ catch (err) {
2768
+ this.abort(type);
2769
+ const pkg = getPackageName(err, type);
2770
+ errorClient(current, pkg && this.checkPackage(err, pkg) ? null : err);
2771
+ }
2772
+ break;
2773
+ }
2774
+ errorRemove(current, errorDataSource('Not found', type || "Unknown" /* ERR_MESSAGE.UNKNOWN */));
2775
+ return;
2776
+ }
2777
+ if (this.aborted) {
2778
+ resolve();
2779
+ return;
2780
+ }
2781
+ for (let i = 0, items; i < length; ++i) {
2782
+ const item = batch[i];
2783
+ const { index, limit, ignoreEmpty, postQuery, whenEmpty } = item;
2784
+ const empty = (items = result[i]) === null;
2785
+ if ((items || (items = [])).length === 0) {
2786
+ if (whenEmpty) {
2787
+ const data = await checkData.call(this, item, whenEmpty, items, row => Array.isArray(row));
2788
+ if (data) {
2789
+ items = data;
2790
+ item.transactionFail = false;
2791
+ }
2792
+ }
2793
+ if (ignoreEmpty && items.length === 0) {
2794
+ continue;
2795
+ }
2796
+ }
2797
+ if (index !== undefined) {
2798
+ const data = items[index];
2799
+ items = data ? [data] : [];
2800
+ }
2801
+ else if (limit !== undefined && limit > 0 && items.length > limit) {
2802
+ items = items.slice(0, limit);
2803
+ }
2804
+ if (postQuery) {
2805
+ const data = await checkData.call(this, item, postQuery, items = items.slice(0), row => Array.isArray(row));
2806
+ if (data) {
2807
+ items = data;
2808
+ }
2809
+ }
2810
+ if (items.length && !item.transactionFail) {
2811
+ const { element, preRender } = item;
2812
+ const domElement = new dom_1.HtmlElement(moduleName, element);
2813
+ let errors, value = '';
2814
+ const checkValue = async (name) => {
2815
+ const data = await checkData.call(this, item, name, value, row => typeof row === 'string');
2816
+ if (data) {
2817
+ value = data;
2818
+ }
2819
+ };
2820
+ const valueAsString = (data, joinString) => Array.isArray(data) && !data.some(child => typeof child === 'object') ? data.join(joinString) : asString(data);
2821
+ if (item.template) {
2822
+ const pathname = this.resolveDir('template', item.template);
2823
+ if (pathname) {
2824
+ const ignoreCache = item.ignoreCache;
2825
+ if (!ignoreCache && CACHE_LOCALFILE.has(pathname)) {
2826
+ item.value = getCacheItem(CACHE_LOCALFILE, pathname);
2827
+ }
2828
+ else {
2829
+ if (ignoreCache === 1) {
2830
+ CACHE_LOCALFILE.delete(pathname);
2831
+ }
2832
+ if (!(item.value = cacheData[pathname])) {
2833
+ try {
2834
+ item.value = fs.readFileSync(pathname, item.encoding || 'utf-8');
2835
+ setCacheData.call(this, item, item.value, pathname, cacheData, true);
2836
+ }
2837
+ catch (err) {
2838
+ this.writeFail(["Unable to read file" /* ERR_MESSAGE.READ_FILE */, path.basename(pathname)], err, { type: 32 /* LOG_TYPE.FILE */, startTime });
2839
+ errors = true;
2840
+ }
2841
+ }
2842
+ }
2843
+ }
2844
+ else {
2845
+ errors = true;
2846
+ }
2847
+ }
2848
+ invalid: {
2849
+ switch (item.type) {
2850
+ case 'text': {
2851
+ const template = item.value || item.dynamic && element.innerXml || element.textContent || domElement.innerXml;
2852
+ if (typeof template === 'string' && !domElement.tagVoid) {
2853
+ if (item.viewEngine) {
2854
+ const content = await this.parseTemplate(item.viewEngine, template, items);
2855
+ if (content === null) {
2856
+ ++domBase.failCount;
2857
+ removeElement(item, domElement);
2858
+ if (length === 1) {
2859
+ resolve();
2860
+ return;
2861
+ }
2862
+ break invalid;
2863
+ }
2864
+ value = content;
2865
+ }
2866
+ else {
2867
+ for (let j = 0, match; j < items.length; ++j) {
2868
+ const row = items[j];
2869
+ if ((0, types_1.isPlainObject)(row)) {
2870
+ row['__index__'] ?? (row['__index__'] = j + 1);
2871
+ }
2872
+ let segment = template;
2873
+ while (match = REGEXP_TEMPLATECONDITIONAL.exec(segment)) {
2874
+ const col = hasCondition(row, match[2]) ? 4 : hasCondition(row, match[5]) ? 7 : -1;
2875
+ segment = replaceMatch(match, segment, match[col] ? (!match[1] || match[col - 1].indexOf('\n') !== -1 ? '' : match[1]) + match[col - 1] + match[col] : '', REGEXP_TEMPLATECONDITIONAL);
2876
+ }
2877
+ REGEXP_TEMPLATECONDITIONAL.lastIndex = 0;
2878
+ const literal = segment.trim();
2879
+ if (literal[0] === '`' && literal[literal.length - 1] === '`') {
2880
+ if (!this.hasEval('function')) {
2881
+ errors = (0, types_1.errorMessage)('eval', "Unsupported access" /* ERR_MESSAGE.UNSUPPORTED_ACCESS */, 'function');
2882
+ continue;
2883
+ }
2884
+ try {
2885
+ let content = new Function('return ' + literal + ';').call(row);
2886
+ if (segment[0] !== '`') {
2887
+ content = segment.substring(0, segment.indexOf('`')) + content;
2888
+ }
2889
+ if (segment[segment.length - 1] !== '`') {
2890
+ content += segment.substring(segment.lastIndexOf('`') + 1);
2891
+ }
2892
+ segment = content;
2893
+ }
2894
+ catch (err) {
2895
+ errors = err instanceof Error ? err : true;
2896
+ continue;
2897
+ }
2898
+ }
2899
+ else {
2900
+ const pattern = /\$\{\s*([^\s}]+)\s*\}/g;
2901
+ while (match = pattern.exec(segment)) {
2902
+ segment = replaceMatch(match, segment, match[1] === '__index__' && !(0, types_1.isObject)(row) ? (j + 1).toString() : valueAsString(getObjectValue(row, match[1]), ', '), pattern);
2903
+ }
2904
+ }
2905
+ value += trimTemplate(segment);
2906
+ }
2907
+ }
2908
+ if (preRender) {
2909
+ await checkValue(preRender);
2910
+ }
2911
+ domElement.innerXml = domBase.initOpts.normalize ? dom_1.DomWriter.normalize(value, { newline: domBase.newline, escapeEntities: domBase.initOpts.escapeEntities }) : value;
2912
+ }
2913
+ else {
2914
+ errors = true;
2915
+ }
2916
+ break;
2917
+ }
2918
+ case 'attribute': {
2919
+ const map = item.value;
2920
+ if ((0, types_1.isPlainObject)(map)) {
2921
+ for (const attr in map) {
2922
+ value = '';
2923
+ let segment = map[attr], valid;
2924
+ if (item.viewEngine) {
2925
+ if (!(0, types_1.isString)(segment)) {
2926
+ errors = true;
2927
+ continue;
2928
+ }
2929
+ const content = await this.parseTemplate(item.viewEngine, segment, items);
2930
+ if (content === null) {
2931
+ errors = true;
2932
+ continue;
2933
+ }
2934
+ value = content;
2935
+ valid = true;
2936
+ }
2937
+ else {
2938
+ if ((0, types_1.isString)(segment)) {
2939
+ segment = [segment];
2940
+ }
2941
+ else if (!(0, types_1.isArray)(segment)) {
2942
+ errors = true;
2943
+ continue;
2944
+ }
2945
+ let joinString = ' ', match;
2946
+ for (const row of items) {
2947
+ for (let seg of segment) {
2948
+ seg = seg.trim();
2949
+ if (seg[0] === ':' && (match = /^:join\(([\S\s]*)\)$/i.exec(seg))) {
2950
+ joinString = match[1];
2951
+ continue;
2952
+ }
2953
+ if (match = REGEXP_TEMPLATECONDITIONAL.exec(seg)) {
2954
+ seg = (hasCondition(row, match[2]) ? match[4] : hasCondition(row, match[5]) ? match[7] : '').trim();
2955
+ valid = true;
2956
+ }
2957
+ if (seg) {
2958
+ if (match = /^:text\(([\S\s]*)\)$/i.exec(seg)) {
2959
+ value += (value ? joinString : '') + match[1];
2960
+ valid = true;
2961
+ }
2962
+ else {
2963
+ const data = getObjectValue(row, seg);
2964
+ if (data !== null) {
2965
+ if (seg = valueAsString(data, joinString)) {
2966
+ value += (value ? joinString : '') + seg;
2967
+ }
2968
+ valid = true;
2969
+ }
2970
+ }
2971
+ }
2972
+ REGEXP_TEMPLATECONDITIONAL.lastIndex = 0;
2973
+ }
2974
+ }
2975
+ }
2976
+ if (valid) {
2977
+ if (preRender) {
2978
+ await checkValue(preRender);
2979
+ }
2980
+ domElement.setAttribute(attr, value);
2981
+ }
2982
+ else {
2983
+ errors = true;
2984
+ }
2985
+ }
2986
+ }
2987
+ else {
2988
+ errors = true;
2989
+ }
2990
+ break;
2991
+ }
2992
+ case 'display': {
2993
+ let template = item.value;
2994
+ if (template) {
2995
+ if (item.viewEngine) {
2996
+ errors = true;
2997
+ if ((0, types_1.isString)(template)) {
2998
+ const content = await this.parseTemplate(item.viewEngine, template, items);
2999
+ if (content !== null) {
3000
+ if ((0, types_1.isString)(content) && content.trim() === '') {
3001
+ domElement.remove = true;
3002
+ }
3003
+ errors = false;
3004
+ }
3005
+ }
3006
+ }
3007
+ else {
3008
+ if ((0, types_1.isString)(template)) {
3009
+ template = [template];
3010
+ }
3011
+ else if (!(0, types_1.isArray)(template)) {
3012
+ errors = true;
3013
+ continue;
3014
+ }
3015
+ let remove = true;
3016
+ complete: {
3017
+ const row = items[0];
3018
+ let condition = NaN;
3019
+ for (let seg of template) {
3020
+ switch ((seg = seg.trim()).toLowerCase()) {
3021
+ case ':is(and)':
3022
+ if (condition === 0) {
3023
+ remove = false;
3024
+ break complete;
3025
+ }
3026
+ condition = NaN;
3027
+ continue;
3028
+ case ':is(or)':
3029
+ if (isNaN(condition)) {
3030
+ condition = 0;
3031
+ }
3032
+ continue;
3033
+ default:
3034
+ if (condition > 0) {
3035
+ continue;
3036
+ }
3037
+ break;
3038
+ }
3039
+ const match = REGEXP_TEMPLATECONDITIONAL.exec(seg);
3040
+ if (match) {
3041
+ seg = (hasCondition(row, match[2]) ? match[4] : hasCondition(row, match[5]) ? match[7] : '').trim();
3042
+ }
3043
+ REGEXP_TEMPLATECONDITIONAL.lastIndex = 0;
3044
+ const sign = seg[0];
3045
+ if (sign === '+' || sign === '-') {
3046
+ seg = seg.substring(1);
3047
+ }
3048
+ const data = getObjectValue(row, seg);
3049
+ let keep = true;
3050
+ if (data === undefined || data === null) {
3051
+ if (sign !== '+') {
3052
+ keep = false;
3053
+ }
3054
+ }
3055
+ else if (sign === '+') {
3056
+ if (data) {
3057
+ keep = false;
3058
+ }
3059
+ }
3060
+ else if (sign === '-' && !data) {
3061
+ keep = false;
3062
+ }
3063
+ if (!isNaN(condition)) {
3064
+ if (!keep) {
3065
+ ++condition;
3066
+ }
3067
+ }
3068
+ else if (keep) {
3069
+ remove = false;
3070
+ break;
3071
+ }
3072
+ }
3073
+ if (condition === 0) {
3074
+ remove = false;
3075
+ }
3076
+ }
3077
+ if (remove) {
3078
+ domElement.remove = true;
3079
+ }
3080
+ }
3081
+ if (errors && item.removeEmpty) {
3082
+ domElement.remove || (domElement.remove = true);
3083
+ }
3084
+ }
3085
+ if (!domElement.remove) {
3086
+ if (length === 1) {
3087
+ resolve();
3088
+ return;
3089
+ }
3090
+ break invalid;
3091
+ }
3092
+ break;
3093
+ }
3094
+ default:
3095
+ removeElement(item, domElement);
3096
+ if (length === 1) {
3097
+ reject(errorDataSource('Invalid action', item.type || "Unknown" /* ERR_MESSAGE.UNKNOWN */));
3098
+ return;
3099
+ }
3100
+ break invalid;
3101
+ }
3102
+ if (!domBase.write(domElement) || errors) {
3103
+ 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 /* LOG_TYPE.PROCESS */, startTime });
3104
+ }
3105
+ }
3106
+ }
3107
+ else {
3108
+ if (!empty && item.type !== 'display' || item.transactionFail) {
3109
+ const emptyResponse = (value, service = item.source) => errorDataSource(service + ' -> Empty', value || "Unknown" /* ERR_MESSAGE.UNKNOWN */);
3110
+ switch (item.source) {
3111
+ case 'cloud': {
3112
+ const { service, table, id, query } = item;
3113
+ const queryString = (table ? 'table=' + table : '') + (id || query ? (table ? ';' : '') + (id ? 'id=' + id : 'query=' + asString(query)) : '');
3114
+ (cloud || this).formatFail(64 /* LOG_TYPE.CLOUD */, service, ["Unable to execute query" /* ERR_DB.EXEC_QUERY */, queryString], emptyResponse(queryString, service), { ...cloud_1.default.LOG_CLOUD_FAIL, startTime });
3115
+ break;
3116
+ }
3117
+ case 'uri': {
3118
+ const { uri, format = uri && path.extname(uri).substring(1) } = item;
3119
+ this.formatFail(4 /* LOG_TYPE.PROCESS */, format || 'URI', ['No records were found', uri], emptyResponse(uri), { startTime });
3120
+ break;
3121
+ }
3122
+ case 'local': {
3123
+ const { pathname, format = pathname && path.extname(pathname).substring(1) } = item;
3124
+ this.formatFail(4 /* LOG_TYPE.PROCESS */, format || 'LOCAL', ['No records were found', pathname], emptyResponse(pathname), { startTime });
3125
+ break;
3126
+ }
3127
+ case 'export': {
3128
+ const { pathname, settings, execute } = item;
3129
+ let target = execute || pathname || settings;
3130
+ if (typeof target === 'function') {
3131
+ target = target.name;
3132
+ }
3133
+ this.formatFail(4 /* LOG_TYPE.PROCESS */, 'EXPORT', ['No records were retrieved', target], emptyResponse(target), { startTime });
3134
+ break;
3135
+ }
3136
+ }
3137
+ }
3138
+ removeElement(item);
3139
+ }
3140
+ }
3141
+ resolve();
3142
+ });
3143
+ }), 'Element text or attribute replacement');
3144
+ };
3145
+ if (dataItems.length) {
3146
+ await setElements(dataItems);
3147
+ }
3148
+ if (displayItems.length) {
3149
+ await setElements(displayItems);
3150
+ }
3151
+ }
3152
+ setProductionAttributes({ host, hashed, bufferMap, startTime }) {
3153
+ for (const item of this.assets) {
3154
+ if (isIgnored(item, true)) {
3155
+ continue;
3156
+ }
3157
+ if (!hashed.has(item)) {
3158
+ createHash(host, item, bufferMap);
3159
+ }
3160
+ switch (item.element?.tagName.toLowerCase()) {
3161
+ case 'style':
3162
+ if (!item.content) {
3163
+ break;
3164
+ }
3165
+ case 'link':
3166
+ case 'script': {
3167
+ const attributes = item.attributes;
3168
+ if (attributes) {
3169
+ const algorithm = (0, types_1.isString)(attributes.integrity) ? attributes.integrity.trim().toLowerCase() : '';
3170
+ switch (algorithm) {
3171
+ case 'sha256':
3172
+ case 'sha384':
3173
+ case 'sha512':
3174
+ try {
3175
+ const data = getBuffer(item);
3176
+ let value;
3177
+ if (data && (value = index_1.default.asHash(data, { algorithm, encoding: item.encoding, digest: 'base64' }))) {
3178
+ attributes.integrity = algorithm + '-' + value;
3179
+ attributes.crossorigin || (attributes.crossorigin = 'anonymous');
3180
+ break;
3181
+ }
3182
+ throw (0, types_1.errorMessage)('hash', 'Source not found', item.filename);
3183
+ }
3184
+ catch (err) {
3185
+ this.writeFail(["Unable to read file" /* ERR_MESSAGE.READ_FILE */, item.filename], err, { type: 32 /* LOG_TYPE.FILE */, startTime });
3186
+ }
3187
+ default:
3188
+ if (algorithm) {
3189
+ delete attributes.integrity;
3190
+ }
3191
+ break;
3192
+ }
3193
+ }
3194
+ break;
3195
+ }
3196
+ }
3197
+ }
3198
+ }
3199
+ removeUnusedStyles(source, { useUnsafeCssReplace, usedVariables, usedFontFace, usedKeyframes, unusedStyles, unusedMedia, unusedContainer, unusedSupports } = this.config) {
3200
+ var _a;
3201
+ if (!usedVariables && !usedFontFace && !usedKeyframes && !unusedStyles && !unusedMedia && !unusedContainer && !unusedSupports) {
3202
+ return;
3203
+ }
3204
+ const selectorMap = this._selectorMap;
3205
+ const replaceMap = [];
3206
+ const getStringSome = () => useUnsafeCssReplace ? '\\s*' : PATTERN_STRING_SOME;
3207
+ const getStringMany = () => useUnsafeCssReplace ? '\\s+' : PATTERN_STRING_MANY;
3208
+ let current = source, modified, checkEmpty, match;
3209
+ const parseSelector = (value) => {
3210
+ const items = [];
3211
+ const revised = value.replace(useUnsafeCssReplace ? REGEXP_NTHCHILD_UNSAFE : REGEXP_NTHCHILD, (...capture) => {
3212
+ return '`%' + (items.push('\\(' + getStringSome() + (capture[1] === '-' ? '\\x2d' : '\\x2b?') + (capture[2] || '[01]?') + (capture[3] === '0' ? !capture[1] && !capture[2] && !capture[4] && !capture[5] ? '[+-]?0[nN]?' : '0' : '[nN]') + getStringSome() + (capture[5] ? (capture[4] === '-' ? '\\x2d' : '\\x2b') + getStringSome() + capture[5] : `(?:[+-]${getStringSome()}0)?`) + getStringSome() + '\\)') - 1) + '`';
3213
+ });
3214
+ let selector = '';
3215
+ for (let i = 0, length = revised.length, casing = false, attr = false, quote = false; i < length; i++) {
3216
+ let ch = revised[i], space = 0;
3217
+ switch (ch) {
3218
+ case '.':
3219
+ case '#':
3220
+ if (!attr) {
3221
+ casing = true;
3222
+ }
3223
+ break;
3224
+ case '[':
3225
+ if (!quote) {
3226
+ attr = true;
3227
+ casing = false;
3228
+ space = 2;
3229
+ }
3230
+ break;
3231
+ case ']':
3232
+ if (!quote || attr && revised[i - 1] === '"' && revised[i - 2] === '\\') {
3233
+ if (quote) {
3234
+ selector = selector.substring(0, selector.length - 1) + '`%%%`';
3235
+ quote = false;
3236
+ }
3237
+ attr = false;
3238
+ casing = false;
3239
+ space = 1;
3240
+ }
3241
+ break;
3242
+ case '=':
3243
+ if (attr && !quote) {
3244
+ casing = true;
3245
+ space = 3;
3246
+ }
3247
+ break;
3248
+ case '\\':
3249
+ ch = '`%%%%`';
3250
+ break;
3251
+ case '"':
3252
+ if (attr) {
3253
+ if (!quote) {
3254
+ ch = '`%%%`';
3255
+ quote = true;
3256
+ }
3257
+ else if (revised[i - 1] !== '\\') {
3258
+ ch = '`%%%`';
3259
+ quote = false;
3260
+ casing = false;
3261
+ }
3262
+ }
3263
+ break;
3264
+ case '~':
3265
+ case '^':
3266
+ case '$':
3267
+ case '*':
3268
+ case '|':
3269
+ if (attr && !quote) {
3270
+ space = 1;
3271
+ }
3272
+ break;
3273
+ case ' ':
3274
+ if (attr && !quote) {
3275
+ ch = '`%%`';
3276
+ break;
3277
+ }
3278
+ case ':':
3279
+ case ',':
3280
+ if (!attr) {
3281
+ casing = false;
3282
+ }
3283
+ break;
3284
+ }
3285
+ selector += (space & 1 ? '`%%`' : '') + (!casing && ch >= 'a' && ch <= 'z' ? '`' + ch + ch.toUpperCase() + '`' : ch) + (space & 2 ? '`%%`' : '');
3286
+ }
3287
+ selector = (0, types_1.escapePattern)(selector)
3288
+ .replace(/\s*(>|~(?!=)|\\\+|\\\*(?!=)])\s*/g, (...capture) => getStringSome() + capture[1] + getStringSome())
3289
+ .replace(/`([a-z][A-Z]|%{2,4})`/g, (...capture) => {
3290
+ switch (capture[1]) {
3291
+ case '%%':
3292
+ return getStringSome();
3293
+ case '%%%':
3294
+ return `(?:["']|${getStringSome()})`;
3295
+ case '%%%%':
3296
+ return '\\\\{0,}';
3297
+ default:
3298
+ return `[${capture[1]}]`;
3299
+ }
3300
+ });
3301
+ for (let i = 0; i < items.length; ++i) {
3302
+ selector = selector.replace('`%' + i + '`', items[i]);
3303
+ }
3304
+ return selector.replace(/[ ]+/g, getStringMany()) + getStringSome();
3305
+ };
3306
+ const replaceUnunsed = (name, items) => {
3307
+ for (let value of items) {
3308
+ const key = name + '_' + (value = value.trim()) + (useUnsafeCssReplace ? '_1' : '');
3309
+ let [pattern] = selectorMap[key] || [], selector = '', rule;
3310
+ if (!pattern) {
3311
+ let flags = 'gi', revised;
3312
+ if (name === 'container') {
3313
+ for (let i = 0, length = value.length, casing = true; i < length; i++) {
3314
+ let ch = value[i];
3315
+ if (!casing) {
3316
+ ch = ch.toLowerCase();
3317
+ }
3318
+ else if (ch === '(') {
3319
+ casing = false;
3320
+ }
3321
+ if (casing || ch < 'a' || ch > 'z') {
3322
+ selector += value[i];
3323
+ if (selector.endsWith(' not ')) {
3324
+ selector = selector.replace(/ not $/, ' `nN``oO``tT` ');
3325
+ }
3326
+ }
3327
+ else {
3328
+ selector += '`' + ch + ch.toUpperCase() + '`';
3329
+ }
3330
+ }
3331
+ flags = 'g';
3332
+ }
3333
+ else if (name === 'supports' && /^selector\(/i.test(value)) {
3334
+ const startIndex = value.indexOf('(');
3335
+ const endIndex = value.lastIndexOf(')');
3336
+ if (startIndex !== -1 && endIndex !== -1) {
3337
+ selector = '[sS][eE][lL][eE][cC][tT][oO][rR]\\(' + getStringSome() + parseSelector(value.substring(startIndex + 1, endIndex)) + '\\)';
3338
+ flags = 'g';
3339
+ revised = true;
3340
+ }
3341
+ }
3342
+ if (!revised) {
3343
+ selector = (0, types_1.escapePattern)(selector || value)
3344
+ .replace(/\s*(\\[()])\s*/g, (...capture) => getStringSome() + capture[1] + getStringSome())
3345
+ .replace(/:\s+/g, getStringSome() + ':' + getStringSome())
3346
+ .replace(/\s+([<>/]|<=|>=|\\\*)\s+/g, (...capture) => getStringSome() + capture[1] + getStringSome())
3347
+ .replace(/[ ]+/g, getStringMany());
3348
+ if (flags === 'g') {
3349
+ selector = selector.replace(/`([a-z][A-Z])`/g, (...capture) => `[${capture[1]}]`);
3350
+ }
3351
+ }
3352
+ pattern = new RegExp('(\\s*)@' + (flags === 'g' ? name.split('').map(ch => `[${ch + ch.toUpperCase()}]`).join('') : name) + getStringMany() + selector + getStringSome() + '{', flags);
3353
+ }
3354
+ else {
3355
+ pattern.lastIndex = 0;
3356
+ }
3357
+ while (rule = pattern.exec(current)) {
3358
+ const [endIndex, trailing] = findClosingIndex(current, getEndIndex(rule));
3359
+ if (endIndex !== -1) {
3360
+ current = spliceSource(current, rule.index, endIndex, pattern, rule[1], trailing);
3361
+ (checkEmpty || (checkEmpty = {}))[name] = true;
3362
+ modified = true;
3363
+ }
3364
+ }
3365
+ if (selector) {
3366
+ selectorMap[key] = [pattern];
3367
+ }
3368
+ }
3369
+ };
3370
+ if (!useUnsafeCssReplace) {
3371
+ const replaceBracket = (pattern, opening) => {
3372
+ let bracket;
3373
+ while (bracket = pattern.exec(current)) {
3374
+ const segment = bracket[0];
3375
+ if (segment.indexOf('}') !== -1 || opening && segment.indexOf('{') !== -1) {
3376
+ const placeholder = '`' + (0, types_1.generateUUID)() + '`';
3377
+ replaceMap.push([placeholder, segment]);
3378
+ current = replaceMatch(bracket, current, placeholder, pattern);
3379
+ }
3380
+ }
3381
+ pattern.lastIndex = 0;
3382
+ };
3383
+ replaceBracket(REGEXP_COMMENT, true);
3384
+ replaceBracket(REGEXP_CONTENT, false);
3385
+ const values = (0, util_1.splitEnclosing)(current, /\burl/gi);
3386
+ for (let i = 0, length = values.length; i < length; ++i) {
3387
+ const seg = values[i];
3388
+ if (seg[seg.length - 1] === ')' && seg.indexOf('}') !== -1 && /^url\(/i.test(seg)) {
3389
+ replaceMap.push([values[i] = (0, types_1.generateUUID)(), seg]);
3390
+ }
3391
+ }
3392
+ if (replaceMap.length) {
3393
+ current = values.join('');
3394
+ }
3395
+ }
3396
+ if (unusedMedia) {
3397
+ replaceUnunsed('media', unusedMedia);
3398
+ }
3399
+ if (unusedSupports) {
3400
+ replaceUnunsed('supports', unusedSupports);
3401
+ }
3402
+ if (unusedContainer) {
3403
+ replaceUnunsed('container', unusedContainer);
3404
+ }
3405
+ if (unusedStyles) {
3406
+ for (const value of unusedStyles) {
3407
+ const key = value + (useUnsafeCssReplace ? '_1' : '');
3408
+ let [single, group] = selectorMap[key] || [], selector;
3409
+ if (!single || !group) {
3410
+ single = new RegExp(`(}|^)(${getStringSome()})(?<!@[^}]*)${selector = parseSelector(value)}\\{[^}]*\\}` + dom_1.DomWriter.PATTERN_TRAILINGSPACE, 'g');
3411
+ group = new RegExp(`((?:}|^)[^{]*?)((?:,${getStringSome()}|(?<!@[^}]*))${selector})(,[^{]*)?\\{`, 'g');
3412
+ }
3413
+ else {
3414
+ single.lastIndex = 0;
3415
+ group.lastIndex = 0;
3416
+ }
3417
+ while (match = single.exec(current)) {
3418
+ current = spliceSource(current, match.index, getEndIndex(match), single, match[2], match[3], match[1] || '');
3419
+ modified = true;
3420
+ }
3421
+ while (match = group.exec(current)) {
3422
+ const middle = match[2][0] === ',';
3423
+ const leading = middle ? match[1].trimEnd() : match[1];
3424
+ const trailing = match[3];
3425
+ const segment = trailing ? (!middle ? (!isSpace(leading[leading.length - 1]) ? ' ' : '') + trailing.substring(1).trimStart() : trailing).trimEnd() : '';
3426
+ current = replaceMatch(match, current, leading + segment + ' {');
3427
+ group.lastIndex = match.index;
3428
+ modified = true;
3429
+ }
3430
+ if (selector) {
3431
+ selectorMap[key] = [single, group];
3432
+ }
3433
+ }
3434
+ }
3435
+ if (usedVariables) {
3436
+ const pattern = useUnsafeCssReplace ? REGEXP_VARIABLES_UNSAFE : REGEXP_VARIABLES;
3437
+ while (match = pattern.exec(current)) {
3438
+ if (!usedVariables.includes(match[2])) {
3439
+ current = replaceMatch(match, current, match[3] === ';' ? getNewlineString(match[1], match[4]) : '', pattern);
3440
+ modified = true;
3441
+ }
3442
+ }
3443
+ pattern.lastIndex = 0;
3444
+ }
3445
+ if (usedFontFace) {
3446
+ const fontFace = useUnsafeCssReplace ? REGEXP_FONTFACE_UNSAFE : REGEXP_FONTFACE;
3447
+ const fontFamily = useUnsafeCssReplace ? REGEXP_FONTFAMILY_UNSAFE : REGEXP_FONTFAMILY;
3448
+ while (match = fontFace.exec(current)) {
3449
+ const font = fontFamily.exec(match[0]);
3450
+ if (font && !usedFontFace.includes(font[1].trim().replace(/^(["'])([\S\s]+)\1$/, (...content) => content[2]))) {
3451
+ current = spliceSource(current, match.index, getEndIndex(match), fontFace, match[1], match[3]);
3452
+ modified = true;
3453
+ }
3454
+ }
3455
+ fontFace.lastIndex = 0;
3456
+ }
3457
+ if (usedKeyframes) {
3458
+ const pattern = useUnsafeCssReplace ? REGEXP_KEYFRAMES_UNSAFE : REGEXP_KEYFRAMES;
3459
+ while (match = pattern.exec(current)) {
3460
+ if (!usedKeyframes.includes(match[2].trim())) {
3461
+ const [endIndex, trailing] = findClosingIndex(current, getEndIndex(match));
3462
+ if (endIndex !== -1) {
3463
+ current = spliceSource(current, match.index, endIndex, pattern, match[1], trailing);
3464
+ modified = true;
3465
+ }
3466
+ }
3467
+ }
3468
+ pattern.lastIndex = 0;
3469
+ }
3470
+ if (modified) {
3471
+ for (const name in checkEmpty) {
3472
+ const pattern = CACHE_ATRULES[_a = name + (useUnsafeCssReplace ? '_1' : '')] || (CACHE_ATRULES[_a] = new RegExp(`(\\s*)@${name}[^{]*{${getStringSome()}}` + dom_1.DomWriter.PATTERN_TRAILINGSPACE, 'gi'));
3473
+ while (match = pattern.exec(current)) {
3474
+ current = spliceSource(current, match.index, getEndIndex(match), pattern, match[1], match[2]);
3475
+ }
3476
+ pattern.lastIndex = 0;
3477
+ }
3478
+ if (replaceMap.length) {
3479
+ for (const [placeholder, content] of replaceMap.reverse()) {
3480
+ current = current.replace(placeholder, content);
3481
+ }
3482
+ }
3483
+ return current;
3484
+ }
3485
+ }
3486
+ get elements() {
3487
+ const result = this._elements;
3488
+ if (result) {
3489
+ return result;
3490
+ }
3491
+ const elements = new Set();
3492
+ const host = this.host;
3493
+ const restartable = host ? host.restartable || this.watching : false;
3494
+ const idMap = this._idMap;
3495
+ this.assets.forEach(item => {
3496
+ const { element, id, flags } = item;
3497
+ if (element) {
3498
+ if (restartable && id && !(0, types_1.cloneFlag)(flags)) {
3499
+ const backup = idMap[id];
3500
+ if (backup) {
3501
+ elements.add(item.element = (0, types_1.cloneObject)(backup, true));
3502
+ return;
3503
+ }
3504
+ idMap[id] = (0, types_1.cloneObject)(element, true);
3505
+ }
3506
+ elements.add(element);
3507
+ }
3508
+ });
3509
+ this.dataSource.forEach(item => elements.add(item.element));
3510
+ return this._elements = Array.from(elements);
3511
+ }
3512
+ get editing() {
3513
+ return this._editing;
3514
+ }
3515
+ set dataSource(value) {
3516
+ this._dataSource = value;
3517
+ }
3518
+ get dataSource() {
3519
+ const result = this._dataSource;
3520
+ if (result) {
3521
+ return result;
3522
+ }
3523
+ const host = this.host;
3524
+ if (host) {
3525
+ try {
3526
+ const items = host.getDataSourceItems(this);
3527
+ return this._dataSource = host.restartable || this.watching ? items.map(item => (0, types_1.cloneObject)(item, true)) : items;
3528
+ }
3529
+ catch {
3530
+ }
3531
+ }
3532
+ return [];
3533
+ }
3534
+ get settings() {
3535
+ var _a;
3536
+ return (_a = this.module).settings || (_a.settings = {});
3537
+ }
3538
+ }
3539
+ ChromeDocument.INTERNAL_ASSIGNUUID = '__assign__';
3540
+ ChromeDocument.INTERNAL_SERVERROOT = '__serverroot__';
3541
+ exports.default = ChromeDocument;
3542
+
3543
+ if (exports.default) {
3544
+ module.exports = exports.default;
3545
+ module.exports.default = exports.default;
3546
+ }