@e-mc/document 0.3.3 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,1294 +1,1294 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const path = require("path");
4
- const fs = require("fs");
5
- const pm = require("picomatch");
6
- const yaml = require("js-yaml");
7
- const chalk = require("chalk");
8
- const types_1 = require("../types");
9
- const core_1 = require("../core");
10
- const db_1 = require("../db");
11
- const util_1 = require("./util");
12
- const transform_1 = require("./transform");
13
- const parse_1 = require("./parse");
14
- const EMC2_PLUGINS = Object.freeze({
15
- "@babel/core": "@e-mc2/babel",
16
- "clean-css": "@e-mc2/clean-css",
17
- "csso": "@e-mc2/csso",
18
- "eslint": "@e-mc2/eslint",
19
- "html-minifier": "@e-mc2/html-minifier",
20
- "html-minifier-terser": "@e-mc2/html-minifier-terser",
21
- "html-validate": "@e-mc2/html-validate",
22
- "postcss": "@e-mc2/postcss",
23
- "posthtml": "@e-mc2/posthtml",
24
- "prettier": "@e-mc2/prettier",
25
- "rollup": "@e-mc2/rollup",
26
- "sass": "@e-mc2/sass",
27
- "stylelint": "@e-mc2/stylelint",
28
- "svgo": "@e-mc2/svgo",
29
- "terser": "@e-mc2/terser",
30
- "uglify-js": "@e-mc2/uglify-js"
31
- });
32
- const CACHE_PACKAGE = {};
33
- const CACHE_REQUIRE = {};
34
- const CACHE_ETAG = {};
35
- const CACHE_CODE = {};
36
- const CACHE_HASH = {};
37
- const CACHE_TEMPLATE = {};
38
- const CACHE_EXTERNAL = {};
39
- const CACHE_PICOMATCH = new Map();
40
- let CACHE_TOTAL = 0;
41
- function renewTransform(map, key, expires) {
42
- if (expires > 0) {
43
- return setTimeout(() => deleteTransform(map, key), expires);
44
- }
45
- return null;
46
- }
47
- function deleteTransform(map, key, timeout) {
48
- if (timeout) {
49
- clearTimeout(timeout);
50
- }
51
- delete map[key];
52
- --CACHE_TOTAL;
53
- }
54
- function getSourceMappingURL(value, css) {
55
- if (value.indexOf(' ') !== -1) {
56
- value = encodeURIComponent(value);
57
- }
58
- return css ? `\n/*# sourceMappingURL=${value} */\n` : `\n//# sourceMappingURL=${value}\n`;
59
- }
60
- const joinString = (...values) => values.reduce((a, b) => b ? a + (a ? ' -> ' : '') + b : a, '');
61
- const spliceSource = (source, startIndex, endIndex, content) => source.substring(0, startIndex) + content + source.substring(endIndex);
62
- const isFunction = (value) => typeof value === 'function';
63
- class Document extends core_1.Client {
64
- static async purgeMemory(percent = 1, limit = 0, parent) {
65
- if (limit > 0 && CACHE_TOTAL < limit) {
66
- return 0;
67
- }
68
- let result = 0;
69
- if (percent >= 1) {
70
- for (const cache of [CACHE_ETAG, CACHE_CODE, CACHE_HASH]) {
71
- for (const name in cache) {
72
- const map = cache[name];
73
- for (const key in map) {
74
- deleteTransform(map, key, map[key].timeout);
75
- ++result;
76
- }
77
- delete cache[name];
78
- }
79
- }
80
- for (const cache of [CACHE_PACKAGE, CACHE_REQUIRE, CACHE_EXTERNAL, CACHE_TEMPLATE]) {
81
- for (const name in cache) {
82
- delete cache[name];
83
- }
84
- }
85
- CACHE_PICOMATCH.clear();
86
- CACHE_TOTAL = 0;
87
- }
88
- else if (percent > 0) {
89
- const stored = [];
90
- for (const cache of [CACHE_ETAG, CACHE_CODE, CACHE_HASH]) {
91
- for (const name in cache) {
92
- const map = cache[name];
93
- for (const key in map) {
94
- stored.push([map, key]);
95
- }
96
- }
97
- }
98
- stored.sort(([a1, a2], [b1, b2]) => a1[a2].lastAccessed - b1[b2].lastAccessed);
99
- result = Math.floor(stored.length * percent);
100
- for (let i = 0; i < result; ++i) {
101
- const [map, key] = stored[i];
102
- deleteTransform(map, key, map[key].timeout);
103
- }
104
- CACHE_TOTAL = stored.length - result;
105
- }
106
- return result + (parent && result > 0 ? await super.purgeMemory(percent, limit, true) : 0);
107
- }
108
- static async finalize(instance) {
109
- for (const ext of instance.extensions) {
110
- if (instance.aborted) {
111
- return Promise.reject((0, types_1.createAbortError)());
112
- }
113
- try {
114
- const args = [instance];
115
- // @ts-ignore
116
- if (ext["__cjs__" /* INTERNAL.CJS */]) {
117
- args.push(__dirname);
118
- }
119
- else if (core_1.Client.enabled("node.require.inline" /* KEY_NAME.NODE_REQUIRE_INLINE */)) {
120
- args.push(require);
121
- }
122
- await ext.apply(this, args);
123
- }
124
- catch (err) {
125
- instance.writeFail(["Unknown" /* ERR_MESSAGE.UNKNOWN */, this.moduleName], err);
126
- }
127
- }
128
- }
129
- static writeSourceMap(uri, data, options) {
130
- const map = data.map;
131
- if (!map) {
132
- return;
133
- }
134
- let file, sourceRoot, sourceMappingURL, hash, inlineMap, emptySources, mimeType;
135
- if (options) {
136
- ({ file, sourceRoot, sourceMappingURL, hash, inlineMap, emptySources, mimeType } = options);
137
- }
138
- file || (file = path.basename(uri));
139
- map.file = file;
140
- if (sourceRoot) {
141
- map.sourceRoot = sourceRoot;
142
- }
143
- if (emptySources) {
144
- map.sources = [""];
145
- }
146
- try {
147
- let css = mimeType === 'text/css', flags = 0 /* SOURCEMAP.NONE */;
148
- const output = JSON.stringify(map);
149
- const toBase64 = () => 'data:application/json;base64,' + Buffer.from(output).toString('base64');
150
- if (!inlineMap) {
151
- if (!sourceMappingURL) {
152
- sourceMappingURL = data.sourceMappingURL || file;
153
- }
154
- if (!sourceMappingURL.endsWith('.map')) {
155
- sourceMappingURL += '.map';
156
- }
157
- if (hash) {
158
- const [algorithm, length] = (0, util_1.getHashData)(hash);
159
- if (algorithm) {
160
- const value = this.asHash(output, algorithm);
161
- if (value) {
162
- sourceMappingURL = (0, util_1.appendSuffix)(sourceMappingURL, length ? value.substring(0, length) : value);
163
- }
164
- }
165
- }
166
- }
167
- let code = data.code.replace(transform_1.SourceMap.RE_SOURCE_MAPPING_URL, (...capture) => {
168
- flags |= 1 /* SOURCEMAP.FOUND */;
169
- if (capture[2] && capture[5]) {
170
- css = true;
171
- }
172
- if (inlineMap || capture[3]) {
173
- flags |= 2 /* SOURCEMAP.INLINE */;
174
- return getSourceMappingURL(toBase64(), css);
175
- }
176
- return capture[1] || css ? getSourceMappingURL(sourceMappingURL, css) : capture[0];
177
- });
178
- if (inlineMap || flags & 2 /* SOURCEMAP.INLINE */) {
179
- if (flags === 0 /* SOURCEMAP.NONE */) {
180
- code += getSourceMappingURL(toBase64(), css);
181
- }
182
- data.code = code;
183
- }
184
- else {
185
- if (flags === 0 /* SOURCEMAP.NONE */) {
186
- code += getSourceMappingURL(sourceMappingURL, css);
187
- }
188
- const result = path.join(path.dirname(uri), sourceMappingURL);
189
- fs.writeFileSync(result, output);
190
- data.code = code;
191
- return result;
192
- }
193
- }
194
- catch {
195
- }
196
- }
197
- static createSourceMap(code, uri, remove) {
198
- return new transform_1.SourceMap(code, uri, remove);
199
- }
200
- static updateGradle(source, namespaces, value, options) {
201
- const local = /^(\w+)\s*(=)?\s*(".+"|'.+'|\([\S\s]+\)||\[[\S\s]+\]|\S+)$/.exec(value = value.trim());
202
- if (!local) {
203
- return source;
204
- }
205
- let upgrade, multiple, addendum, updateOnly;
206
- if (typeof options === 'boolean') {
207
- upgrade = options;
208
- }
209
- else if (options) {
210
- ({ upgrade, multiple, addendum, updateOnly } = options);
211
- }
212
- if (addendum) {
213
- value += ' ' + addendum;
214
- }
215
- const length = namespaces.length;
216
- let ident, lastIndex = 0, i = 0;
217
- while (i < length) {
218
- const pattern = new RegExp(`([\\t ]*)${(0, types_1.escapePattern)(namespaces[i])}\\s*\\{` + parse_1.XmlWriter.PATTERN_TRAILINGSPACE);
219
- pattern.lastIndex = lastIndex;
220
- const match = pattern.exec(source);
221
- if (!match) {
222
- break;
223
- }
224
- if (i > 0 && !ident && match[1]) {
225
- ident = match[1];
226
- }
227
- lastIndex = match.index + match[0].length;
228
- ++i;
229
- }
230
- const newline = (0, util_1.getNewline)(source);
231
- ident || (ident = (0, util_1.getIndent)(source));
232
- if (i === length) {
233
- const sanitizeValue = (segment) => segment.replace(/["'()]/g, '').trim();
234
- const pattern = new RegExp(`\\b${(0, types_1.escapePattern)(local[1])}\\b` + (local[2] ? '\\s*=\\s*' : '\\s*') + `("[^"]+"|'[^']+'|\\([^)]+\\)|[^\\s]+)?` + (addendum ? '[^\\r\\n]*' : '[^\\w\\r\\n]*'), 'g');
235
- pattern.lastIndex = lastIndex;
236
- let match;
237
- while (match = pattern.exec(source)) {
238
- const preceding = source.substring(lastIndex, match.index);
239
- let opening = 0, closing = namespaces.length - 1;
240
- for (let j = 0, q = preceding.length; j < q; ++j) {
241
- switch (preceding[j]) {
242
- case '{':
243
- ++opening;
244
- break;
245
- case '}':
246
- ++closing;
247
- break;
248
- }
249
- }
250
- if (opening === closing && (!multiple || match[1] && sanitizeValue(match[1]) === sanitizeValue(local[3]))) {
251
- return upgrade ? parse_1.XmlWriter.replaceMatch(match, source, value, pattern) : source;
252
- }
253
- }
254
- return spliceSource(source, lastIndex, lastIndex, ident.repeat(length) + value + newline);
255
- }
256
- if (updateOnly) {
257
- return source;
258
- }
259
- const j = i;
260
- let leading = '', trailing = '';
261
- while (i < length) {
262
- leading += ident.repeat(i) + namespaces[i] + ' {' + newline;
263
- ++i;
264
- }
265
- for (i = length - 1; i >= j; --i) {
266
- trailing += ident.repeat(i) + '}' + newline;
267
- }
268
- const content = leading + ident.repeat(length) + value + newline + trailing;
269
- return lastIndex > 0 ? spliceSource(source, lastIndex, lastIndex, content) : source + newline + content;
270
- }
271
- static generateLintTable(messages, options) {
272
- const { leadingText, trailingText, pathname, filename, ruleWidth = 30, messageWidth = 60 } = options;
273
- const result = [];
274
- const truncate = (value, width) => value.length > width ? value.substring(0, width - 3) + '...' : value.padStart(width);
275
- const currentTime = Date.now();
276
- let timeStamp = options.timeStamp, maxWidth = 0, maxLine = 0, maxColumn = 0, errorCount = 0, warningCount = 0, fatalErrorCount = 0;
277
- messages.sort((a, b) => {
278
- const offset = a.line - b.line;
279
- return offset === 0 ? a.column - b.column : offset;
280
- });
281
- if (!timeStamp) {
282
- timeStamp = currentTime;
283
- }
284
- else if (timeStamp instanceof Date) {
285
- timeStamp = timeStamp.getTime();
286
- }
287
- for (const { line, column } of messages) {
288
- maxLine = Math.max(line, maxLine);
289
- maxColumn = Math.max(column, maxColumn);
290
- }
291
- maxLine = maxLine.toString().length + 1;
292
- maxColumn = maxColumn.toString().length + 1;
293
- for (const { severity, line, column, ruleId, message, fatal } of messages) {
294
- let error;
295
- if (severity) {
296
- if (error = severity === 2 /* LINT_SEVERITY.ERROR */ || severity === "error" /* LINT_SEVERITY.ERROR_TEXT */) {
297
- ++errorCount;
298
- }
299
- else {
300
- ++warningCount;
301
- }
302
- }
303
- if (fatal) {
304
- ++fatalErrorCount;
305
- }
306
- const [type, errorColor] = typeof error === 'boolean' ? error ? [types_1.STATUS_TYPE.ERROR, 'red'] : [types_1.STATUS_TYPE.WARN, 'yellow'] : [types_1.STATUS_TYPE.INFO, 'white'];
307
- maxWidth = Math.max(1 + 0 + 1 + 0 + 1 + 2 + Math.min(Math.max(ruleId.length, ruleWidth), ruleWidth) + 2 + Math.min(Math.max(message.length, messageWidth), messageWidth), maxWidth);
308
- result.push({
309
- type,
310
- value: chalk[errorColor]('[') + chalk.bold(line.toString().padStart(maxLine)) + chalk.grey(':' + column.toString().padEnd(maxColumn)) + chalk[errorColor](']') + ' ' + chalk.bold(chalk.white(truncate(ruleId, ruleWidth))) + ' ' + chalk.grey(truncate(message, messageWidth)),
311
- timeStamp
312
- });
313
- }
314
- maxWidth += maxLine + maxColumn;
315
- const title = (leadingText || '') + (pathname || filename ? (leadingText ? ': ' : '') + (pathname && filename ? path.join(pathname, filename) : pathname || filename) : '');
316
- const divider = { type: types_1.STATUS_TYPE.INFO, value: '-'.repeat(maxWidth), timeStamp };
317
- errorCount = (options.errorCount ?? errorCount).toString();
318
- warningCount = (options.warningCount ?? warningCount).toString();
319
- fatalErrorCount = (options.fatalErrorCount ?? fatalErrorCount).toString();
320
- const hasFatal = fatalErrorCount !== '0';
321
- result.unshift(divider, { type: types_1.STATUS_TYPE.INFO, value: title + ' '.repeat(maxWidth - title.length - (hasFatal ? fatalErrorCount.length + 9 : 0)) + (hasFatal ? `fatal(${chalk.bold.bgRed.white(` ${fatalErrorCount} `)})` : ''), timeStamp, duration: currentTime - timeStamp }, divider);
322
- result.push(divider);
323
- if (trailingText) {
324
- const wrapCount = (value) => chalk.grey('(') + value + chalk.grey(')');
325
- result.push({ type: types_1.STATUS_TYPE.INFO, value: chalk.bold.red('error') + wrapCount(errorCount) + ' / ' + chalk.bold.yellow('warning') + wrapCount(warningCount) + ' '.repeat(maxWidth - trailingText.length - (7 + errorCount.length + 3 + warningCount.length + 9)) + trailingText, timeStamp });
326
- }
327
- return result;
328
- }
329
- constructor(data) {
330
- super(data);
331
- this.Db = null;
332
- this.config = {};
333
- this._assets = null;
334
- this._dataSource = null;
335
- this._transformConfig = null;
336
- this._mimeMap = null;
337
- const transform = this.settingsOf('transform', 'cache');
338
- if (transform !== undefined) {
339
- this.customize({ transform });
340
- }
341
- }
342
- restart() { }
343
- init(assets, config) {
344
- var _a;
345
- let ignoreModules;
346
- if (config) {
347
- const { baseUrl, ignoreExtensions } = config;
348
- if (ignoreExtensions === true) {
349
- this._extensions = [];
350
- }
351
- else if (typeof ignoreExtensions === 'string') {
352
- this._extensions = ignoreExtensions === this.moduleName ? [] : this._extensions.filter(value => value !== ignoreExtensions);
353
- }
354
- else if (Array.isArray(ignoreExtensions)) {
355
- this._extensions = ignoreExtensions.includes(this.moduleName) ? [] : this._extensions.filter(value => !ignoreExtensions.includes(value));
356
- }
357
- if (baseUrl) {
358
- const username = this.host?.username;
359
- let pages = this.settings.pages;
360
- if (username) {
361
- const users = this.settings.users?.[username]?.pages;
362
- if ((0, types_1.isPlainObject)(users)) {
363
- pages = (0, types_1.isPlainObject)(pages) ? { ...pages, ...users } : users;
364
- }
365
- }
366
- if ((0, types_1.isPlainObject)(pages)) {
367
- let mimeMap;
368
- if (!(0, types_1.isPlainObject)(mimeMap = pages[baseUrl])) {
369
- const items = [];
370
- for (const pattern in pages) {
371
- const item = pages[pattern];
372
- if ((0, types_1.isPlainObject)(item)) {
373
- let isMatch;
374
- if (!(isMatch = CACHE_PICOMATCH.get(pattern)) && (0, types_1.hasGlob)(pattern)) {
375
- isMatch = pm(pattern, { matchBase: true });
376
- CACHE_PICOMATCH.set(pattern, isMatch);
377
- }
378
- else {
379
- continue;
380
- }
381
- if (isMatch(baseUrl)) {
382
- items.push(item);
383
- }
384
- }
385
- else {
386
- delete pages[pattern];
387
- }
388
- }
389
- if (items.length > 1) {
390
- items.sort((a, b) => typeof a.ordinal === 'number' && typeof b.ordinal === 'number' ? a.ordinal - b.ordinal : 0);
391
- mimeMap = items.reduce((a, b) => Object.assign(a, b), {});
392
- }
393
- else {
394
- mimeMap = items[0];
395
- }
396
- }
397
- if (mimeMap) {
398
- let merge;
399
- for (const item of assets) {
400
- const mimeType = item.mimeType;
401
- if (mimeType && (0, types_1.isPlainObject)(merge = mimeMap[mimeType])) {
402
- Object.assign(item, merge);
403
- }
404
- }
405
- this._mimeMap = mimeMap;
406
- }
407
- }
408
- }
409
- ignoreModules = config.ignoreModules;
410
- }
411
- if (this.dataSource.length && !ignoreModules?.includes('db')) {
412
- const db = (_a = this.module).db || (_a.db = {});
413
- const handler = db.handler;
414
- const database = this.dataSource.filter(this.forDb.bind(this));
415
- let instance;
416
- if ((0, types_1.isString)(handler) && handler !== "@e-mc/db" /* PACKAGE_NAME.DB */) {
417
- try {
418
- const Handler = require(handler);
419
- if (isFunction(Handler) && Handler.prototype instanceof db_1.default) {
420
- instance = new Handler(db, database);
421
- }
422
- else {
423
- throw (0, types_1.errorMessage)(this.moduleName, "Not a Db constructor" /* ERR_DB.CONSTRUCTOR */, handler);
424
- }
425
- }
426
- catch (err) {
427
- this.checkPackage(err, handler, ["Unable to load handler" /* ERR_MESSAGE.LOAD_HANDLER */, this.moduleName], 65536 /* LOG_TYPE.DB */);
428
- }
429
- }
430
- else {
431
- instance = new db_1.default(db, database);
432
- }
433
- if (instance) {
434
- const host = this.host;
435
- if (host) {
436
- instance.host = host;
437
- instance.init(host.config);
438
- }
439
- else {
440
- instance.init();
441
- }
442
- this.Db = instance;
443
- }
444
- }
445
- this.assets = assets;
446
- return super.init();
447
- }
448
- abort(name) {
449
- if (this.aborted || name && this.settingsOf(name, 'abort') !== true) {
450
- return;
451
- }
452
- super.abort();
453
- }
454
- customize(options) {
455
- const transform = options.transform;
456
- if (transform) {
457
- const config = this._transformConfig || (this._transformConfig = { algorithm: undefined, etag: false, expires: 0, renew: false, limit: Infinity, exclude: {}, include: {} });
458
- let enabled, algorithm, etag, expires, renew, limit, exclude, include;
459
- if (transform === true || transform === 'etag') {
460
- etag = true;
461
- enabled = true;
462
- }
463
- else if (typeof transform === 'string') {
464
- algorithm = transform;
465
- enabled = true;
466
- }
467
- else if ((0, types_1.isPlainObject)(transform)) {
468
- ({ enabled = true, algorithm, etag, expires, renew, limit, exclude, include } = transform);
469
- }
470
- if (!enabled) {
471
- this._transformConfig = null;
472
- return;
473
- }
474
- switch (algorithm = algorithm?.toLowerCase()) {
475
- case 'md5':
476
- case 'sha1':
477
- case 'sha224':
478
- case 'sha256':
479
- case 'sha384':
480
- case 'sha512':
481
- config.algorithm = algorithm;
482
- break;
483
- default:
484
- config.algorithm = undefined;
485
- break;
486
- }
487
- if (typeof etag === 'boolean') {
488
- config.etag = etag;
489
- }
490
- if (expires && (expires = (0, types_1.parseExpires)(expires)) >= 0) {
491
- config.expires = Math.min(expires, core_1.Client.MAX_TIMEOUT);
492
- }
493
- if (renew) {
494
- config.renew = true;
495
- }
496
- if ((0, types_1.isPlainObject)(exclude)) {
497
- for (const type in exclude) {
498
- const item = exclude[type];
499
- if (item === '*') {
500
- config.exclude[type] = true;
501
- }
502
- else if ((0, types_1.isArray)(item)) {
503
- config.exclude[type] = item;
504
- }
505
- }
506
- }
507
- if ((0, types_1.isPlainObject)(include)) {
508
- for (const type in include) {
509
- const item = include[type];
510
- if (item === '*') {
511
- config.include[type] = true;
512
- }
513
- else if ((0, types_1.isArray)(item)) {
514
- config.include[type] = item;
515
- }
516
- }
517
- }
518
- if (limit !== undefined) {
519
- let value;
520
- if (typeof limit === 'string') {
521
- if (parseFloat(limit) === 0) {
522
- value = 0;
523
- }
524
- else if ((value = (0, types_1.formatSize)(limit)) === 0) {
525
- return;
526
- }
527
- }
528
- else {
529
- value = limit;
530
- }
531
- if (value >= 0) {
532
- config.limit = value;
533
- }
534
- }
535
- }
536
- else if (transform === false || transform === null) {
537
- this._transformConfig = null;
538
- }
539
- }
540
- findConfig(data, name, type) {
541
- for (const plugin in data) {
542
- const settings = data[plugin];
543
- for (const attr in settings) {
544
- if (attr === name) {
545
- const options = this.loadConfig(settings, attr);
546
- const output = this.loadConfig(settings, attr + '-output');
547
- if (options || output) {
548
- return [plugin, options, output, true];
549
- }
550
- }
551
- }
552
- }
553
- return [];
554
- }
555
- loadConfig(data, name) {
556
- const value = data[name];
557
- const getObject = (target, cache) => {
558
- if (this.settingsOf('transform', 'coerce') === true) {
559
- (0, types_1.coerceObject)(target, cache);
560
- }
561
- return (0, types_1.cloneObject)(data[name] = target, true);
562
- };
563
- switch (typeof value) {
564
- case 'function':
565
- return value;
566
- case 'object':
567
- if (value) {
568
- return getObject(value, true);
569
- }
570
- break;
571
- case 'string': {
572
- const warning = (message) => this.addLog(types_1.STATUS_TYPE.ERROR, joinString(this.moduleName, 'transform@' + name, message));
573
- const result = this.asSourceFile(value);
574
- if (typeof result === 'function') {
575
- if (!name.endsWith('-output')) {
576
- return data[name] = result;
577
- }
578
- warning('"output" can only be a plain object');
579
- }
580
- else if ((0, types_1.isPlainObject)(result)) {
581
- return getObject(result, false);
582
- }
583
- else {
584
- warning(path.isAbsolute(value) ? "Unsupported access" /* ERR_MESSAGE.UNSUPPORTED_ACCESS */ + ` (${value})` : "Unknown" /* ERR_MESSAGE.UNKNOWN */);
585
- }
586
- break;
587
- }
588
- }
589
- delete data[name];
590
- }
591
- resolveDir(name, ...paths) {
592
- let baseDir = this.settings.directory?.[name];
593
- if (baseDir) {
594
- try {
595
- baseDir = path.resolve(baseDir);
596
- const username = this.host?.username;
597
- let result;
598
- if (username) {
599
- const leading = path.join(baseDir, 'users', username);
600
- if (fs.existsSync(result = path.join(leading, ...paths)) && result.startsWith(leading)) {
601
- return result;
602
- }
603
- }
604
- if (fs.existsSync(result = path.join(baseDir, ...paths)) && result.startsWith(baseDir)) {
605
- return result;
606
- }
607
- }
608
- catch {
609
- }
610
- }
611
- }
612
- asSourceFile(value, options) {
613
- let encoding, persist, cache;
614
- if (typeof options === 'boolean') {
615
- cache = options;
616
- }
617
- else if ((0, types_1.isObject)(options)) {
618
- ({ encoding, persist, cache } = options);
619
- }
620
- let result;
621
- if ((value = value.trim()).startsWith('npm:')) {
622
- const pkgName = value.substring(4);
623
- if (persist) {
624
- result = CACHE_REQUIRE[pkgName];
625
- }
626
- if (!result) {
627
- if (!core_1.Client.enabled("node.require.npm" /* KEY_NAME.NODE_REQUIRE_NPM */)) {
628
- return null;
629
- }
630
- try {
631
- if (!persist) {
632
- delete require.cache[pkgName];
633
- }
634
- result = require(pkgName);
635
- if (persist && result) {
636
- CACHE_REQUIRE[pkgName] = result;
637
- }
638
- if (typeof result === 'function') {
639
- return Object.defineProperty(result, "__cjs__" /* INTERNAL.CJS */, { value: true });
640
- }
641
- }
642
- catch (err) {
643
- this.checkPackage(err, pkgName, "Unknown" /* ERR_MESSAGE.UNKNOWN */);
644
- }
645
- if (!result) {
646
- return null;
647
- }
648
- }
649
- }
650
- try {
651
- const source = result || this.readFile(value, { ownPermissionOnly: true, absolutePath: this.hasEval('absolute'), requireExt: true, encoding, cache }) || value;
652
- if (typeof source !== 'string') {
653
- result = source;
654
- }
655
- else if (!(result = (0, types_1.asFunction)(source))) {
656
- try {
657
- result = this.tryParse(source, path.extname(value).substring(1));
658
- }
659
- catch {
660
- }
661
- }
662
- // @ts-ignore
663
- if ((0, types_1.isObject)(result) || typeof result === 'function' && (result["__cjs__" /* INTERNAL.CJS */] || this.hasEval('function'))) {
664
- return result;
665
- }
666
- }
667
- catch (err) {
668
- this.writeFail(["Unable to read file" /* ERR_MESSAGE.READ_FILE */, path.basename(value)], err, 8192 /* LOG_TYPE.PERMISSION */);
669
- }
670
- return null;
671
- }
672
- findVersion(name, fallback = '') {
673
- let result;
674
- const versions = this.module.versions;
675
- if (versions) {
676
- if (Array.isArray(name)) {
677
- for (const value of name) {
678
- if (result = versions[value]) {
679
- break;
680
- }
681
- }
682
- }
683
- else {
684
- result = this.module.versions?.[name];
685
- }
686
- }
687
- return result || fallback;
688
- }
689
- findSourceRoot(uri, imports = this.imports) {
690
- if (imports) {
691
- const normalizeDir = (value) => value + (value[value.length - 1] !== '/' ? '/' : '');
692
- for (const url in imports) {
693
- if (uri === url || normalizeDir(uri) === normalizeDir(url)) {
694
- return imports[url];
695
- }
696
- }
697
- const found = [];
698
- for (const hostname in imports) {
699
- if (uri.startsWith(normalizeDir(hostname)) && (0, types_1.isString)(imports[hostname])) {
700
- found.push(hostname);
701
- }
702
- }
703
- if (found.length) {
704
- const hostname = found.sort((a, b) => b.length - a.length)[0];
705
- return core_1.Client.toPosix(path.resolve(imports[hostname], uri.substring(normalizeDir(hostname).length).split('?')[0]));
706
- }
707
- }
708
- }
709
- locateSourceFiles(file, code, bundleContent) {
710
- return (imports = this.imports) => {
711
- const href = file.uri;
712
- const sourceFile = [];
713
- let mainFile, invalid;
714
- if (Document.isFile(href, 'unc') || path.isAbsolute(href)) {
715
- sourceFile.push([href]);
716
- }
717
- else if (imports && Object.keys(imports).length) {
718
- const bundleId = file.bundleId;
719
- const assets = !(0, types_1.isEmpty)(bundleId) ? this.assets.filter(item => item.bundleId === bundleId).sort((a, b) => a.bundleIndex - b.bundleIndex) : [file];
720
- if (!Array.isArray(bundleContent) || bundleContent.length !== assets.length - 1) {
721
- bundleContent = undefined;
722
- }
723
- for (const item of assets) {
724
- const localFile = !item.exported && item.uri ? this.findSourceRoot(item.uri, imports) : undefined;
725
- if (localFile && core_1.Client.isPath(localFile) && !item.trailingContent) {
726
- sourceFile.push([localFile]);
727
- }
728
- else {
729
- let source;
730
- if (item.bundleIndex === 0) {
731
- const localUri = item.localUri;
732
- try {
733
- source = fs.readFileSync(localUri, file.encoding || (file.encoding = 'utf-8'));
734
- if (this.resolveUri && (0, types_1.isArray)(file.trailingContent)) {
735
- let trailing;
736
- [source, trailing] = this.resolveUri(file, source, (0, util_1.concatString)(file.trailingContent));
737
- if ((0, types_1.isString)(trailing)) {
738
- source += trailing;
739
- }
740
- }
741
- }
742
- catch (err) {
743
- this.writeFail(["Unable to read file" /* ERR_MESSAGE.READ_FILE */, localUri && path.basename(localUri)], 32 /* LOG_TYPE.FILE */);
744
- }
745
- }
746
- else if (bundleContent) {
747
- source = bundleContent[item.bundleIndex - 1];
748
- }
749
- if (!source) {
750
- invalid = true;
751
- break;
752
- }
753
- sourceFile.push(['', this.resolveImports?.(item, source, localFile) || source, localFile]);
754
- }
755
- }
756
- }
757
- if (sourceFile.length && (sourceFile[0] && (mainFile = sourceFile[0][0]) || !invalid) && (!this.hasOwnPermission() || !sourceFile.some(item => item[0] && !this.canRead(item[0])))) {
758
- return { code, sourceFile: !invalid ? sourceFile : undefined, sourcesRelativeTo: mainFile && path.dirname(mainFile) };
759
- }
760
- };
761
- }
762
- resolveSourceFile(file) {
763
- return (code, imports = this.imports) => {
764
- const uri = file.uri;
765
- let source, sourceFile;
766
- if (code && imports && Object.keys(imports).length) {
767
- const output = this.resolveImports?.(file, code, uri && this.findSourceRoot(uri, imports));
768
- if (output) {
769
- source = output;
770
- }
771
- }
772
- if (uri) {
773
- sourceFile = Document.isFile(uri, 'unc') || path.isAbsolute(uri) ? uri : this.findSourceRoot(uri, imports);
774
- }
775
- if (source || sourceFile) {
776
- return { code: source || code, sourceFile, sourcesRelativeTo: sourceFile && path.dirname(sourceFile) };
777
- }
778
- };
779
- }
780
- tryParse(source, format, options) {
781
- try {
782
- switch (format.toLowerCase()) {
783
- case 'yml':
784
- case 'yaml':
785
- return yaml.load(source, options);
786
- case 'json5':
787
- return require('json5').parse(source);
788
- case 'xml':
789
- return new (require('fast-xml-parser').XMLParser)(options).parse(source);
790
- case 'toml':
791
- return require('toml').parse(source);
792
- default:
793
- return JSON.parse(source);
794
- }
795
- }
796
- catch (err) {
797
- const name = (0, util_1.getModuleName)(err);
798
- if (name) {
799
- this.checkPackage(err, (0, util_1.getModuleName)(err), "Unknown" /* ERR_MESSAGE.UNKNOWN */);
800
- }
801
- throw err;
802
- }
803
- }
804
- forDb(item) {
805
- return item.source !== 'cloud';
806
- }
807
- hasEval(name) {
808
- return !!this.module.eval?.[name];
809
- }
810
- settingsOf(name, option) {
811
- const options = this.settings.options?.[name];
812
- if ((0, types_1.isObject)(options)) {
813
- return options[option];
814
- }
815
- }
816
- async parseTemplate(viewEngine, template, data) {
817
- let target, stored;
818
- if (typeof viewEngine === 'string') {
819
- target = this.settings.view_engine?.[viewEngine];
820
- const username = this.host?.username;
821
- const userConfig = username && this.settings.users?.[username]?.view_engine?.[viewEngine];
822
- if ((0, types_1.isPlainObject)(userConfig)) {
823
- if ((0, types_1.isPlainObject)(target)) {
824
- (0, types_1.cloneObject)(userConfig, { target, deep: true, preserve: true });
825
- }
826
- else {
827
- target = userConfig;
828
- }
829
- }
830
- stored = true;
831
- }
832
- else {
833
- target = viewEngine;
834
- }
835
- if (!((0, types_1.isPlainObject)(target) && target.name)) {
836
- this.abort('view_engine');
837
- const from = typeof viewEngine === 'string' ? viewEngine : this.moduleName;
838
- this.writeFail(["Unable to load configuration" /* ERR_MESSAGE.LOAD_CONFIG */, from], (0, types_1.errorMessage)('view-engine', from, "Unknown" /* ERR_MESSAGE.UNKNOWN */));
839
- return null;
840
- }
841
- const length = data.length;
842
- if (length === 0 && !target.outputEmpty) {
843
- return '';
844
- }
845
- let name;
846
- try {
847
- const context = require(name = target.name);
848
- const { singleRow, options = {} } = target;
849
- let { compile, output } = options;
850
- if (!(0, types_1.isPlainObject)(output)) {
851
- output = undefined;
852
- }
853
- if (this.settingsOf('view_engine', 'coerce') === true) {
854
- if (compile) {
855
- (0, types_1.coerceObject)(compile, stored);
856
- }
857
- if (output) {
858
- (0, types_1.coerceObject)(output, stored);
859
- }
860
- }
861
- const username = this.host?.username || '';
862
- const cache = CACHE_TEMPLATE[name] || (CACHE_TEMPLATE[name] = {});
863
- const cacheKey = username + core_1.Client.asHash(template + (compile ? core_1.Client.asString(compile) : ''));
864
- let result = '', render, valid;
865
- if (!(render = cache[cacheKey])) {
866
- render = await context.compile(template, compile); // eslint-disable-line @typescript-eslint/await-thenable
867
- cache[cacheKey] = render;
868
- if (!core_1.Client.enabled("memory.settings.users" /* KEY_NAME.MEMORY_SETTINGS_USERS */, username)) {
869
- setTimeout(() => delete cache[cacheKey], 60000 /* VALUES.TEMPLATE_EXPIRES */);
870
- }
871
- }
872
- for (let i = 0, j = 0, row; i < length; ++i) {
873
- if ((0, types_1.isPlainObject)(row = data[i])) {
874
- row['__index__'] ?? (row['__index__'] = ++j);
875
- if (output) {
876
- row = { ...output, ...row };
877
- }
878
- }
879
- else if (!(0, types_1.isObject)(row)) {
880
- this.addLog(types_1.STATUS_TYPE.WARN, joinString(`view engine[${name}]`, `row #${i + 1}`, core_1.Client.asString(row) || "Unknown" /* ERR_MESSAGE.UNKNOWN */));
881
- continue;
882
- }
883
- if (!singleRow) {
884
- const content = await render.call(context, row); // eslint-disable-line @typescript-eslint/await-thenable
885
- if (content !== undefined && content !== null) {
886
- result += content;
887
- valid = true;
888
- }
889
- }
890
- }
891
- return singleRow ? render.call(context, data) ?? null : valid ? result : null;
892
- }
893
- catch (err) {
894
- this.abort('view_engine');
895
- this.checkPackage(err, name, "Unknown" /* ERR_MESSAGE.UNKNOWN */, 4 /* LOG_TYPE.PROCESS */);
896
- }
897
- return null;
898
- }
899
- async transform(type, code, format, options = {}) {
900
- var _a;
901
- let transform = this.settings.transform;
902
- const data = transform?.[type];
903
- if (!(0, types_1.isObject)(data)) {
904
- return;
905
- }
906
- format = typeof format === 'string' ? format.trim().split(/\s*\+\s*/) : format.map(item => typeof item === 'string' ? item.trim() : '');
907
- const moduleName = this.moduleName;
908
- const username = this.host?.username || '';
909
- const config = this._transformConfig;
910
- const cacheData = config && options.cacheData;
911
- const cacheType = username && core_1.Client.enabled("memory.settings.users" /* KEY_NAME.MEMORY_SETTINGS_USERS */, username) ? true : this.cacheDir || core_1.Client.enabled("memory.settings.users" /* KEY_NAME.MEMORY_SETTINGS_USERS */);
912
- let formatKey, hashKey, excludeKey;
913
- if (cacheData && cacheType && !CACHE_EXTERNAL[excludeKey = moduleName + '_' + type + '_' + format] && (!config.exclude[type] || Array.isArray(config.exclude[type]) && !format.some(value => config.exclude[type].includes(value)) || Array.isArray(config.include[type]) && format.every(value => config.include[type].includes(value)))) {
914
- const { uri, etag } = cacheData;
915
- const encoding = (0, types_1.getEncoding)(cacheData.encoding);
916
- const algorithm = config.algorithm;
917
- let result, cacheName;
918
- formatKey = type + '_' + format + '_' + encoding + (username ? '_' + username : '') + core_1.Client.asString(options.external) + core_1.Client.asString(options.metadata);
919
- const resetTimeout = (map, key, stored) => {
920
- if (config.renew) {
921
- if (stored.timeout) {
922
- clearTimeout(stored.timeout);
923
- }
924
- stored.timeout = renewTransform(map, key, config.expires);
925
- }
926
- stored.lastAccessed = Date.now();
927
- };
928
- const getData = (stored) => {
929
- const location = stored.format[formatKey];
930
- if (typeof location === 'string') {
931
- try {
932
- return JSON.parse(fs.readFileSync(location, encoding));
933
- }
934
- catch {
935
- fs.unlink(location, () => { });
936
- return;
937
- }
938
- }
939
- return location;
940
- };
941
- if (config.etag && etag && uri) {
942
- const etagMap = CACHE_ETAG[moduleName] || (CACHE_ETAG[moduleName] = {});
943
- const stored = etagMap[uri];
944
- if (stored) {
945
- if (stored.etag !== etag) {
946
- deleteTransform(etagMap, uri, stored.timeout);
947
- }
948
- else if (result = getData(stored)) {
949
- resetTimeout(etagMap, uri, stored);
950
- cacheName = 'etag';
951
- }
952
- }
953
- }
954
- if (!result) {
955
- if (algorithm) {
956
- const limit = config.limit;
957
- if ((limit === Infinity || limit > 0 && Buffer.byteLength(code, encoding) <= limit) && (hashKey = core_1.Client.asHash(code, { algorithm, encoding }))) {
958
- const hashMap = CACHE_HASH[moduleName] || (CACHE_HASH[moduleName] = {});
959
- const stored = hashMap[hashKey];
960
- if (stored && (result = getData(stored))) {
961
- resetTimeout(hashMap, hashKey, stored);
962
- cacheName = algorithm;
963
- }
964
- }
965
- else {
966
- formatKey = '';
967
- }
968
- }
969
- else if (uri) {
970
- const codeMap = CACHE_CODE[moduleName] || (CACHE_CODE[moduleName] = {});
971
- const stored = codeMap[uri];
972
- if (stored) {
973
- if (stored.code !== code) {
974
- deleteTransform(codeMap, uri, stored.timeout);
975
- }
976
- else if (result = getData(stored)) {
977
- resetTimeout(codeMap, uri, stored);
978
- }
979
- }
980
- }
981
- else {
982
- formatKey = '';
983
- }
984
- }
985
- if (result) {
986
- result.storedLog?.forEach(log => this.addLog(log));
987
- this.formatMessage(4 /* LOG_TYPE.PROCESS */, type, [joinString(cacheName, format.filter(value => value).join(' | '), options.filename), 'cache'], uri, { ...core_1.Client.LOG_STYLE_NOTICE, hintBold: true });
988
- return result;
989
- }
990
- }
991
- if (cacheData) {
992
- delete options.cacheData;
993
- }
994
- const imports = (_a = transform).imports || (_a.imports = {});
995
- const series = new transform_1.TransformSeries(type, code, options);
996
- series.init(this, __dirname);
997
- let valid, excluded, userData, userImports, ignoreCache, storedLog, sourceFiles;
998
- if (username && (transform = this.settings.users?.[username]?.transform)) {
999
- userData = transform[type];
1000
- userImports = transform.imports;
1001
- }
1002
- const abort = () => {
1003
- ignoreCache = true;
1004
- this.abort('transform');
1005
- };
1006
- const includes = (name) => {
1007
- const include = config?.include[type];
1008
- if (include === true || include?.includes(name)) {
1009
- const exclude = config.exclude[type];
1010
- return !exclude || exclude === true && include !== true || Array.isArray(exclude) && !exclude.includes(name);
1011
- }
1012
- return cacheData?.override === true;
1013
- };
1014
- for (let i = 0, length = format.length, name; i < length; ++i) {
1015
- if (this.aborted) {
1016
- break;
1017
- }
1018
- if (!(name = format[i])) {
1019
- continue;
1020
- }
1021
- let [plugin, baseConfig, outputConfig, baseSettings] = this.findConfig(data, name, type);
1022
- if ((0, types_1.isObject)(userData)) {
1023
- const [a, b, c, d] = this.findConfig(userData, name, type);
1024
- if (!plugin || a === plugin) {
1025
- if (b) {
1026
- if (baseConfig) {
1027
- (0, types_1.cloneObject)(b, { target: baseConfig, deep: true, preserve: true });
1028
- }
1029
- else {
1030
- baseConfig = b;
1031
- }
1032
- }
1033
- if (c) {
1034
- if (outputConfig) {
1035
- (0, types_1.cloneObject)(c, { target: outputConfig, deep: true, preserve: true });
1036
- }
1037
- else {
1038
- outputConfig = c;
1039
- }
1040
- }
1041
- if (!d) {
1042
- baseSettings = false;
1043
- }
1044
- }
1045
- }
1046
- if (!baseSettings) {
1047
- excluded = !includes(name);
1048
- }
1049
- outputConfig || (outputConfig = {});
1050
- if (plugin && baseConfig) {
1051
- series.outputConfig = outputConfig;
1052
- const source = series.code;
1053
- const startTime = process.hrtime();
1054
- const hint = plugin + '@' + name;
1055
- const next = (value) => {
1056
- if (this.aborted) {
1057
- valid = false;
1058
- return;
1059
- }
1060
- const out = series.out;
1061
- let bypassLog, failed;
1062
- if (typeof value !== 'string' || (0, types_1.isArray)(out.sourceFiles) && this.hasOwnPermission() && out.sourceFiles.some(item => !this.canRead(item, { ownPermissionOnly: true }))) {
1063
- failed = true;
1064
- ignoreCache = true;
1065
- this.writeFail(["Unable to transform document" /* ERR_MESSAGE.TRANSFORM_DOCUMENT */, plugin], (0, types_1.errorMessage)(plugin, name, typeof value === 'string' ? "Unsupported access" /* ERR_MESSAGE.UNSUPPORTED_ACCESS */ : 'Empty'), { type: 4 /* LOG_TYPE.PROCESS */, startTime });
1066
- }
1067
- else if (source !== value) {
1068
- series.code = value;
1069
- valid = true;
1070
- if (out.ignoreCache && !includes(name)) {
1071
- ignoreCache = true;
1072
- }
1073
- if ((0, types_1.isArray)(out.sourceFiles)) {
1074
- if (!sourceFiles) {
1075
- sourceFiles = out.sourceFiles.slice(0);
1076
- }
1077
- else {
1078
- out.sourceFiles.forEach(item => !sourceFiles.includes(item) && sourceFiles.push(item));
1079
- }
1080
- }
1081
- }
1082
- if ((0, types_1.isArray)(out.logAppend)) {
1083
- out.logAppend.forEach(log => this.addLog(log));
1084
- (storedLog || (storedLog = [])).push(...out.logAppend);
1085
- bypassLog = true;
1086
- }
1087
- if ((0, types_1.isArray)(out.logQueued)) {
1088
- out.logQueued.forEach(log => this.writeLog(log, true));
1089
- (storedLog || (storedLog = [])).push(...out.logQueued);
1090
- bypassLog = true;
1091
- }
1092
- if (i < length - 1) {
1093
- series.reset();
1094
- }
1095
- this.writeTimeProcess(failed ? 'CHECK' : type, joinString(hint, options.filename) + (series.out.messageAppend || ''), startTime, { failed, bypassLog });
1096
- };
1097
- this.formatMessage(4 /* LOG_TYPE.PROCESS */, type, ['Transforming source...', hint], options.filename, { hintColor: 'cyan' });
1098
- try {
1099
- let context = require(plugin);
1100
- series.packageName = plugin;
1101
- if (typeof baseConfig === 'function') {
1102
- series.baseConfig = outputConfig;
1103
- // @ts-ignore
1104
- if (baseConfig["__cjs__" /* INTERNAL.CJS */]) {
1105
- next(await baseConfig(context, source, series));
1106
- }
1107
- else {
1108
- const thisArg = core_1.Client.enabled("node.process.inline" /* KEY_NAME.NODE_PROCESS_INLINE */) ? process : null;
1109
- const inline = core_1.Client.enabled("node.require.inline" /* KEY_NAME.NODE_REQUIRE_INLINE */);
1110
- const args = [context, source, series];
1111
- if (baseConfig.toString().startsWith('async')) {
1112
- if (inline) {
1113
- args.push(require);
1114
- }
1115
- next(await baseConfig.apply(thisArg, args));
1116
- }
1117
- else {
1118
- next(await new Promise(resolve => {
1119
- args.push(resolve);
1120
- if (inline) {
1121
- args.push(require);
1122
- }
1123
- baseConfig.apply(thisArg, args);
1124
- }));
1125
- }
1126
- }
1127
- }
1128
- else {
1129
- let transformer = CACHE_PACKAGE[plugin + username];
1130
- if (!transformer) {
1131
- try {
1132
- let pkg = this.resolveDir('package', plugin + '.js') || userImports?.[plugin] || imports[plugin] || EMC2_PLUGINS[plugin];
1133
- if ((0, types_1.isString)(pkg)) {
1134
- const match = /^(@?\S+)@(\d+(?:\.\d+(?:\.\S+)?)?|[a-z]+)$/.exec(pkg);
1135
- if (match) {
1136
- pkg = match[1];
1137
- series.version = match[2];
1138
- }
1139
- transformer = require(pkg);
1140
- }
1141
- else {
1142
- transformer = context;
1143
- context = this;
1144
- pkg = undefined;
1145
- }
1146
- if (typeof transformer !== 'function' && typeof (transformer = transformer?.['default']) !== 'function') {
1147
- throw (0, types_1.errorMessage)(plugin, pkg || name, 'Invalid function');
1148
- }
1149
- if (pkg) {
1150
- CACHE_PACKAGE[plugin + username] = transformer;
1151
- }
1152
- }
1153
- catch (err) {
1154
- abort();
1155
- this.writeFail(["Unknown" /* ERR_MESSAGE.UNKNOWN */, username ? plugin + ':' + username : hint], err, { type: 4 /* LOG_TYPE.PROCESS */, startTime });
1156
- continue;
1157
- }
1158
- }
1159
- series.baseConfig = baseConfig;
1160
- next(await transformer(context, source, series));
1161
- }
1162
- }
1163
- catch (err) {
1164
- abort();
1165
- this.checkPackage(err, (0, util_1.getModuleName)(err), ["Unable to transform document" /* ERR_MESSAGE.TRANSFORM_DOCUMENT */, hint], { type: 4 /* LOG_TYPE.PROCESS */, startTime });
1166
- if (i < length - 1) {
1167
- series.reset();
1168
- }
1169
- }
1170
- }
1171
- else {
1172
- abort();
1173
- if (plugin) {
1174
- this.writeFail("Unable to load configuration" /* ERR_MESSAGE.LOAD_CONFIG */, (0, types_1.errorMessage)(plugin, name, 'Invalid config'), 4 /* LOG_TYPE.PROCESS */);
1175
- }
1176
- else {
1177
- this.writeFail('Format method was not found', (0, types_1.errorValue)(name, "Unknown" /* ERR_MESSAGE.UNKNOWN */), 4 /* LOG_TYPE.PROCESS */);
1178
- }
1179
- }
1180
- }
1181
- if (this.aborted) {
1182
- series.detach();
1183
- return;
1184
- }
1185
- series.close(this);
1186
- if (excluded && excludeKey) {
1187
- CACHE_EXTERNAL[excludeKey] = true;
1188
- }
1189
- if (!valid) {
1190
- return;
1191
- }
1192
- const output = { type, code: series.code };
1193
- const sourceMap = series.sourceMap;
1194
- if (sourceMap.map && sourceMap.code === output.code) {
1195
- output.map = sourceMap.map;
1196
- }
1197
- if ((0, types_1.isArray)(series.supplementChunks)) {
1198
- output.chunks = series.supplementChunks.map(item => ({ code: item.code, map: output.map && item.sourceMap?.map, entryPoint: item.entryPoint, filename: item.filename }));
1199
- }
1200
- if (sourceFiles) {
1201
- output.sourceFiles = sourceFiles;
1202
- }
1203
- if (formatKey && !excluded && !ignoreCache) {
1204
- const { uri, etag } = cacheData;
1205
- const formatData = { ...output, storedLog };
1206
- const lastAccessed = Date.now();
1207
- const setData = () => {
1208
- let pathname;
1209
- if (typeof cacheType === 'string' && core_1.Client.createDir(pathname = path.join(cacheType, 'transform', type))) {
1210
- try {
1211
- fs.writeFileSync(pathname = path.join(pathname, (0, types_1.generateUUID)()), JSON.stringify(formatData));
1212
- return pathname;
1213
- }
1214
- catch {
1215
- }
1216
- }
1217
- return formatData;
1218
- };
1219
- if (config.etag && etag && uri) {
1220
- const etagMap = CACHE_ETAG[moduleName];
1221
- const stored = etagMap[uri];
1222
- if (stored) {
1223
- if (stored.etag === etag) {
1224
- stored.format[formatKey] = setData();
1225
- stored.lastAccessed = lastAccessed;
1226
- return output;
1227
- }
1228
- deleteTransform(etagMap, uri, stored.timeout);
1229
- }
1230
- etagMap[uri] = { lastAccessed, etag, timeout: renewTransform(etagMap, uri, config.expires), format: { [formatKey]: setData() } };
1231
- ++CACHE_TOTAL;
1232
- }
1233
- else if (hashKey) {
1234
- const hashMap = CACHE_HASH[moduleName];
1235
- const stored = hashMap[hashKey];
1236
- if (stored) {
1237
- stored.format[formatKey] = setData();
1238
- stored.lastAccessed = lastAccessed;
1239
- return output;
1240
- }
1241
- hashMap[hashKey] = { lastAccessed, timeout: renewTransform(hashMap, hashKey, config.expires), format: { [formatKey]: setData() } };
1242
- ++CACHE_TOTAL;
1243
- }
1244
- else if (uri) {
1245
- const codeMap = CACHE_CODE[moduleName];
1246
- const stored = codeMap[uri];
1247
- if (stored) {
1248
- if (stored.code === code) {
1249
- stored.format[formatKey] = setData();
1250
- stored.lastAccessed = lastAccessed;
1251
- return output;
1252
- }
1253
- deleteTransform(codeMap, uri, stored.timeout);
1254
- }
1255
- codeMap[uri] = { lastAccessed, code, timeout: renewTransform(codeMap, uri, config.expires), format: { [formatKey]: setData() } };
1256
- ++CACHE_TOTAL;
1257
- }
1258
- }
1259
- return output;
1260
- }
1261
- set assets(value) {
1262
- this._assets = value;
1263
- }
1264
- get assets() {
1265
- if (this.host) {
1266
- try {
1267
- return this._assets || (this._assets = this.host.getDocumentAssets(this));
1268
- }
1269
- catch {
1270
- }
1271
- }
1272
- return this._assets || [];
1273
- }
1274
- set dataSource(value) {
1275
- this._dataSource = value;
1276
- }
1277
- get dataSource() {
1278
- if (this.host) {
1279
- try {
1280
- return this._dataSource || (this._dataSource = this.host.getDataSourceItems(this));
1281
- }
1282
- catch {
1283
- }
1284
- }
1285
- return this._dataSource || [];
1286
- }
1287
- get watching() {
1288
- return this.assets.some(item => item.watch);
1289
- }
1290
- }
1291
- exports.default = Document;
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const path = require("path");
4
+ const fs = require("fs");
5
+ const pm = require("picomatch");
6
+ const yaml = require("js-yaml");
7
+ const chalk = require("chalk");
8
+ const types_1 = require("../types");
9
+ const core_1 = require("../core");
10
+ const db_1 = require("../db");
11
+ const util_1 = require("./util");
12
+ const transform_1 = require("./transform");
13
+ const parse_1 = require("./parse");
14
+ const PIR_PLUGINS = Object.freeze({
15
+ "@babel/core": "@pi-r/babel",
16
+ "clean-css": "@pi-r/clean-css",
17
+ "csso": "@pi-r/csso",
18
+ "eslint": "@pi-r/eslint",
19
+ "html-minifier": "@pi-r/html-minifier",
20
+ "html-minifier-terser": "@pi-r/html-minifier-terser",
21
+ "html-validate": "@pi-r/html-validate",
22
+ "postcss": "@pi-r/postcss",
23
+ "posthtml": "@pi-r/posthtml",
24
+ "prettier": "@pi-r/prettier",
25
+ "rollup": "@pi-r/rollup",
26
+ "sass": "@pi-r/sass",
27
+ "stylelint": "@pi-r/stylelint",
28
+ "svgo": "@pi-r/svgo",
29
+ "terser": "@pi-r/terser",
30
+ "uglify-js": "@pi-r/uglify-js"
31
+ });
32
+ const CACHE_PACKAGE = {};
33
+ const CACHE_REQUIRE = {};
34
+ const CACHE_ETAG = {};
35
+ const CACHE_CODE = {};
36
+ const CACHE_HASH = {};
37
+ const CACHE_TEMPLATE = {};
38
+ const CACHE_EXTERNAL = {};
39
+ const CACHE_PICOMATCH = new Map();
40
+ let CACHE_TOTAL = 0;
41
+ function renewTransform(map, key, expires) {
42
+ if (expires > 0) {
43
+ return setTimeout(() => deleteTransform(map, key), expires);
44
+ }
45
+ return null;
46
+ }
47
+ function deleteTransform(map, key, timeout) {
48
+ if (timeout) {
49
+ clearTimeout(timeout);
50
+ }
51
+ delete map[key];
52
+ --CACHE_TOTAL;
53
+ }
54
+ function getSourceMappingURL(value, css) {
55
+ if (value.indexOf(' ') !== -1) {
56
+ value = encodeURIComponent(value);
57
+ }
58
+ return css ? `\n/*# sourceMappingURL=${value} */\n` : `\n//# sourceMappingURL=${value}\n`;
59
+ }
60
+ const joinString = (...values) => values.reduce((a, b) => b ? a + (a ? ' -> ' : '') + b : a, '');
61
+ const spliceSource = (source, startIndex, endIndex, content) => source.substring(0, startIndex) + content + source.substring(endIndex);
62
+ const isFunction = (value) => typeof value === 'function';
63
+ class Document extends core_1.Client {
64
+ static async purgeMemory(percent = 1, limit = 0, parent) {
65
+ if (limit > 0 && CACHE_TOTAL < limit) {
66
+ return 0;
67
+ }
68
+ let result = 0;
69
+ if (percent >= 1) {
70
+ for (const cache of [CACHE_ETAG, CACHE_CODE, CACHE_HASH]) {
71
+ for (const name in cache) {
72
+ const map = cache[name];
73
+ for (const key in map) {
74
+ deleteTransform(map, key, map[key].timeout);
75
+ ++result;
76
+ }
77
+ delete cache[name];
78
+ }
79
+ }
80
+ for (const cache of [CACHE_PACKAGE, CACHE_REQUIRE, CACHE_EXTERNAL, CACHE_TEMPLATE]) {
81
+ for (const name in cache) {
82
+ delete cache[name];
83
+ }
84
+ }
85
+ CACHE_PICOMATCH.clear();
86
+ CACHE_TOTAL = 0;
87
+ }
88
+ else if (percent > 0) {
89
+ const stored = [];
90
+ for (const cache of [CACHE_ETAG, CACHE_CODE, CACHE_HASH]) {
91
+ for (const name in cache) {
92
+ const map = cache[name];
93
+ for (const key in map) {
94
+ stored.push([map, key]);
95
+ }
96
+ }
97
+ }
98
+ stored.sort(([a1, a2], [b1, b2]) => a1[a2].lastAccessed - b1[b2].lastAccessed);
99
+ result = Math.floor(stored.length * percent);
100
+ for (let i = 0; i < result; ++i) {
101
+ const [map, key] = stored[i];
102
+ deleteTransform(map, key, map[key].timeout);
103
+ }
104
+ CACHE_TOTAL = stored.length - result;
105
+ }
106
+ return result + (parent && result > 0 ? await super.purgeMemory(percent, limit, true) : 0);
107
+ }
108
+ static async finalize(instance) {
109
+ for (const ext of instance.extensions) {
110
+ if (instance.aborted) {
111
+ return Promise.reject((0, types_1.createAbortError)());
112
+ }
113
+ try {
114
+ const args = [instance];
115
+ // @ts-ignore
116
+ if (ext["__cjs__" /* INTERNAL.CJS */]) {
117
+ args.push(__dirname);
118
+ }
119
+ else if (core_1.Client.enabled("node.require.inline" /* KEY_NAME.NODE_REQUIRE_INLINE */)) {
120
+ args.push(require);
121
+ }
122
+ await ext.apply(this, args);
123
+ }
124
+ catch (err) {
125
+ instance.writeFail(["Unknown" /* ERR_MESSAGE.UNKNOWN */, this.moduleName], err);
126
+ }
127
+ }
128
+ }
129
+ static writeSourceMap(uri, data, options) {
130
+ const map = data.map;
131
+ if (!map) {
132
+ return;
133
+ }
134
+ let file, sourceRoot, sourceMappingURL, hash, inlineMap, emptySources, mimeType;
135
+ if (options) {
136
+ ({ file, sourceRoot, sourceMappingURL, hash, inlineMap, emptySources, mimeType } = options);
137
+ }
138
+ file || (file = path.basename(uri));
139
+ map.file = file;
140
+ if (sourceRoot) {
141
+ map.sourceRoot = sourceRoot;
142
+ }
143
+ if (emptySources) {
144
+ map.sources = [""];
145
+ }
146
+ try {
147
+ let css = mimeType === 'text/css', flags = 0 /* SOURCEMAP.NONE */;
148
+ const output = JSON.stringify(map);
149
+ const toBase64 = () => 'data:application/json;base64,' + Buffer.from(output).toString('base64');
150
+ if (!inlineMap) {
151
+ if (!sourceMappingURL) {
152
+ sourceMappingURL = data.sourceMappingURL || file;
153
+ }
154
+ if (!sourceMappingURL.endsWith('.map')) {
155
+ sourceMappingURL += '.map';
156
+ }
157
+ if (hash) {
158
+ const [algorithm, length] = (0, util_1.getHashData)(hash);
159
+ if (algorithm) {
160
+ const value = this.asHash(output, algorithm);
161
+ if (value) {
162
+ sourceMappingURL = (0, util_1.appendSuffix)(sourceMappingURL, length ? value.substring(0, length) : value);
163
+ }
164
+ }
165
+ }
166
+ }
167
+ let code = data.code.replace(transform_1.SourceMap.RE_SOURCE_MAPPING_URL, (...capture) => {
168
+ flags |= 1 /* SOURCEMAP.FOUND */;
169
+ if (capture[2] && capture[5]) {
170
+ css = true;
171
+ }
172
+ if (inlineMap || capture[3]) {
173
+ flags |= 2 /* SOURCEMAP.INLINE */;
174
+ return getSourceMappingURL(toBase64(), css);
175
+ }
176
+ return capture[1] || css ? getSourceMappingURL(sourceMappingURL, css) : capture[0];
177
+ });
178
+ if (inlineMap || flags & 2 /* SOURCEMAP.INLINE */) {
179
+ if (flags === 0 /* SOURCEMAP.NONE */) {
180
+ code += getSourceMappingURL(toBase64(), css);
181
+ }
182
+ data.code = code;
183
+ }
184
+ else {
185
+ if (flags === 0 /* SOURCEMAP.NONE */) {
186
+ code += getSourceMappingURL(sourceMappingURL, css);
187
+ }
188
+ const result = path.join(path.dirname(uri), sourceMappingURL);
189
+ fs.writeFileSync(result, output);
190
+ data.code = code;
191
+ return result;
192
+ }
193
+ }
194
+ catch {
195
+ }
196
+ }
197
+ static createSourceMap(code, uri, remove) {
198
+ return new transform_1.SourceMap(code, uri, remove);
199
+ }
200
+ static updateGradle(source, namespaces, value, options) {
201
+ const local = /^(\w+)\s*(=)?\s*(".+"|'.+'|\([\S\s]+\)||\[[\S\s]+\]|\S+)$/.exec(value = value.trim());
202
+ if (!local) {
203
+ return source;
204
+ }
205
+ let upgrade, multiple, addendum, updateOnly;
206
+ if (typeof options === 'boolean') {
207
+ upgrade = options;
208
+ }
209
+ else if (options) {
210
+ ({ upgrade, multiple, addendum, updateOnly } = options);
211
+ }
212
+ if (addendum) {
213
+ value += ' ' + addendum;
214
+ }
215
+ const length = namespaces.length;
216
+ let ident, lastIndex = 0, i = 0;
217
+ while (i < length) {
218
+ const pattern = new RegExp(`([\\t ]*)${(0, types_1.escapePattern)(namespaces[i])}\\s*\\{` + parse_1.XmlWriter.PATTERN_TRAILINGSPACE);
219
+ pattern.lastIndex = lastIndex;
220
+ const match = pattern.exec(source);
221
+ if (!match) {
222
+ break;
223
+ }
224
+ if (i > 0 && !ident && match[1]) {
225
+ ident = match[1];
226
+ }
227
+ lastIndex = match.index + match[0].length;
228
+ ++i;
229
+ }
230
+ const newline = (0, util_1.getNewline)(source);
231
+ ident || (ident = (0, util_1.getIndent)(source));
232
+ if (i === length) {
233
+ const sanitizeValue = (segment) => segment.replace(/["'()]/g, '').trim();
234
+ const pattern = new RegExp(`\\b${(0, types_1.escapePattern)(local[1])}\\b` + (local[2] ? '\\s*=\\s*' : '\\s*') + `("[^"]+"|'[^']+'|\\([^)]+\\)|[^\\s]+)?` + (addendum ? '[^\\r\\n]*' : '[^\\w\\r\\n]*'), 'g');
235
+ pattern.lastIndex = lastIndex;
236
+ let match;
237
+ while (match = pattern.exec(source)) {
238
+ const preceding = source.substring(lastIndex, match.index);
239
+ let opening = 0, closing = namespaces.length - 1;
240
+ for (let j = 0, q = preceding.length; j < q; ++j) {
241
+ switch (preceding[j]) {
242
+ case '{':
243
+ ++opening;
244
+ break;
245
+ case '}':
246
+ ++closing;
247
+ break;
248
+ }
249
+ }
250
+ if (opening === closing && (!multiple || match[1] && sanitizeValue(match[1]) === sanitizeValue(local[3]))) {
251
+ return upgrade ? parse_1.XmlWriter.replaceMatch(match, source, value, pattern) : source;
252
+ }
253
+ }
254
+ return spliceSource(source, lastIndex, lastIndex, ident.repeat(length) + value + newline);
255
+ }
256
+ if (updateOnly) {
257
+ return source;
258
+ }
259
+ const j = i;
260
+ let leading = '', trailing = '';
261
+ while (i < length) {
262
+ leading += ident.repeat(i) + namespaces[i] + ' {' + newline;
263
+ ++i;
264
+ }
265
+ for (i = length - 1; i >= j; --i) {
266
+ trailing += ident.repeat(i) + '}' + newline;
267
+ }
268
+ const content = leading + ident.repeat(length) + value + newline + trailing;
269
+ return lastIndex > 0 ? spliceSource(source, lastIndex, lastIndex, content) : source + newline + content;
270
+ }
271
+ static generateLintTable(messages, options) {
272
+ const { leadingText, trailingText, pathname, filename, ruleWidth = 30, messageWidth = 60 } = options;
273
+ const result = [];
274
+ const truncate = (value, width) => value.length > width ? value.substring(0, width - 3) + '...' : value.padStart(width);
275
+ const currentTime = Date.now();
276
+ let timeStamp = options.timeStamp, maxWidth = 0, maxLine = 0, maxColumn = 0, errorCount = 0, warningCount = 0, fatalErrorCount = 0;
277
+ messages.sort((a, b) => {
278
+ const offset = a.line - b.line;
279
+ return offset === 0 ? a.column - b.column : offset;
280
+ });
281
+ if (!timeStamp) {
282
+ timeStamp = currentTime;
283
+ }
284
+ else if (timeStamp instanceof Date) {
285
+ timeStamp = timeStamp.getTime();
286
+ }
287
+ for (const { line, column } of messages) {
288
+ maxLine = Math.max(line, maxLine);
289
+ maxColumn = Math.max(column, maxColumn);
290
+ }
291
+ maxLine = maxLine.toString().length + 1;
292
+ maxColumn = maxColumn.toString().length + 1;
293
+ for (const { severity, line, column, ruleId, message, fatal } of messages) {
294
+ let error;
295
+ if (severity) {
296
+ if (error = severity === 2 /* LINT_SEVERITY.ERROR */ || severity === "error" /* LINT_SEVERITY.ERROR_TEXT */) {
297
+ ++errorCount;
298
+ }
299
+ else {
300
+ ++warningCount;
301
+ }
302
+ }
303
+ if (fatal) {
304
+ ++fatalErrorCount;
305
+ }
306
+ const [type, errorColor] = typeof error === 'boolean' ? error ? [types_1.STATUS_TYPE.ERROR, 'red'] : [types_1.STATUS_TYPE.WARN, 'yellow'] : [types_1.STATUS_TYPE.INFO, 'white'];
307
+ maxWidth = Math.max(1 + 0 + 1 + 0 + 1 + 2 + Math.min(Math.max(ruleId.length, ruleWidth), ruleWidth) + 2 + Math.min(Math.max(message.length, messageWidth), messageWidth), maxWidth);
308
+ result.push({
309
+ type,
310
+ value: chalk[errorColor]('[') + chalk.bold(line.toString().padStart(maxLine)) + chalk.grey(':' + column.toString().padEnd(maxColumn)) + chalk[errorColor](']') + ' ' + chalk.bold(chalk.white(truncate(ruleId, ruleWidth))) + ' ' + chalk.grey(truncate(message, messageWidth)),
311
+ timeStamp
312
+ });
313
+ }
314
+ maxWidth += maxLine + maxColumn;
315
+ const title = (leadingText || '') + (pathname || filename ? (leadingText ? ': ' : '') + (pathname && filename ? path.join(pathname, filename) : pathname || filename) : '');
316
+ const divider = { type: types_1.STATUS_TYPE.INFO, value: '-'.repeat(maxWidth), timeStamp };
317
+ errorCount = (options.errorCount ?? errorCount).toString();
318
+ warningCount = (options.warningCount ?? warningCount).toString();
319
+ fatalErrorCount = (options.fatalErrorCount ?? fatalErrorCount).toString();
320
+ const hasFatal = fatalErrorCount !== '0';
321
+ result.unshift(divider, { type: types_1.STATUS_TYPE.INFO, value: title + ' '.repeat(maxWidth - title.length - (hasFatal ? fatalErrorCount.length + 9 : 0)) + (hasFatal ? `fatal(${chalk.bold.bgRed.white(` ${fatalErrorCount} `)})` : ''), timeStamp, duration: currentTime - timeStamp }, divider);
322
+ result.push(divider);
323
+ if (trailingText) {
324
+ const wrapCount = (value) => chalk.grey('(') + value + chalk.grey(')');
325
+ result.push({ type: types_1.STATUS_TYPE.INFO, value: chalk.bold.red('error') + wrapCount(errorCount) + ' / ' + chalk.bold.yellow('warning') + wrapCount(warningCount) + ' '.repeat(maxWidth - trailingText.length - (7 + errorCount.length + 3 + warningCount.length + 9)) + trailingText, timeStamp });
326
+ }
327
+ return result;
328
+ }
329
+ constructor(data) {
330
+ super(data);
331
+ this.Db = null;
332
+ this.config = {};
333
+ this._assets = null;
334
+ this._dataSource = null;
335
+ this._transformConfig = null;
336
+ this._mimeMap = null;
337
+ const transform = this.settingsOf('transform', 'cache');
338
+ if (transform !== undefined) {
339
+ this.customize({ transform });
340
+ }
341
+ }
342
+ restart() { }
343
+ init(assets, config) {
344
+ var _a;
345
+ let ignoreModules;
346
+ if (config) {
347
+ const { baseUrl, ignoreExtensions } = config;
348
+ if (ignoreExtensions === true) {
349
+ this._extensions = [];
350
+ }
351
+ else if (typeof ignoreExtensions === 'string') {
352
+ this._extensions = ignoreExtensions === this.moduleName ? [] : this._extensions.filter(value => value !== ignoreExtensions);
353
+ }
354
+ else if (Array.isArray(ignoreExtensions)) {
355
+ this._extensions = ignoreExtensions.includes(this.moduleName) ? [] : this._extensions.filter(value => !ignoreExtensions.includes(value));
356
+ }
357
+ if (baseUrl) {
358
+ const username = this.host?.username;
359
+ let pages = this.settings.pages;
360
+ if (username) {
361
+ const users = this.settings.users?.[username]?.pages;
362
+ if ((0, types_1.isPlainObject)(users)) {
363
+ pages = (0, types_1.isPlainObject)(pages) ? { ...pages, ...users } : users;
364
+ }
365
+ }
366
+ if ((0, types_1.isPlainObject)(pages)) {
367
+ let mimeMap;
368
+ if (!(0, types_1.isPlainObject)(mimeMap = pages[baseUrl])) {
369
+ const items = [];
370
+ for (const pattern in pages) {
371
+ const item = pages[pattern];
372
+ if ((0, types_1.isPlainObject)(item)) {
373
+ let isMatch;
374
+ if (!(isMatch = CACHE_PICOMATCH.get(pattern)) && (0, types_1.hasGlob)(pattern)) {
375
+ isMatch = pm(pattern, { matchBase: true });
376
+ CACHE_PICOMATCH.set(pattern, isMatch);
377
+ }
378
+ else {
379
+ continue;
380
+ }
381
+ if (isMatch(baseUrl)) {
382
+ items.push(item);
383
+ }
384
+ }
385
+ else {
386
+ delete pages[pattern];
387
+ }
388
+ }
389
+ if (items.length > 1) {
390
+ items.sort((a, b) => typeof a.ordinal === 'number' && typeof b.ordinal === 'number' ? a.ordinal - b.ordinal : 0);
391
+ mimeMap = items.reduce((a, b) => Object.assign(a, b), {});
392
+ }
393
+ else {
394
+ mimeMap = items[0];
395
+ }
396
+ }
397
+ if (mimeMap) {
398
+ let merge;
399
+ for (const item of assets) {
400
+ const mimeType = item.mimeType;
401
+ if (mimeType && (0, types_1.isPlainObject)(merge = mimeMap[mimeType])) {
402
+ Object.assign(item, merge);
403
+ }
404
+ }
405
+ this._mimeMap = mimeMap;
406
+ }
407
+ }
408
+ }
409
+ ignoreModules = config.ignoreModules;
410
+ }
411
+ if (this.dataSource.length && !ignoreModules?.includes('db')) {
412
+ const db = (_a = this.module).db || (_a.db = {});
413
+ const handler = db.handler;
414
+ const database = this.dataSource.filter(this.forDb.bind(this));
415
+ let instance;
416
+ if ((0, types_1.isString)(handler) && handler !== "@e-mc/db" /* PACKAGE_NAME.DB */) {
417
+ try {
418
+ const Handler = require(handler);
419
+ if (isFunction(Handler) && Handler.prototype instanceof db_1.default) {
420
+ instance = new Handler(db, database);
421
+ }
422
+ else {
423
+ throw (0, types_1.errorMessage)(this.moduleName, "Not a Db constructor" /* ERR_DB.CONSTRUCTOR */, handler);
424
+ }
425
+ }
426
+ catch (err) {
427
+ this.checkPackage(err, handler, ["Unable to load handler" /* ERR_MESSAGE.LOAD_HANDLER */, this.moduleName], 65536 /* LOG_TYPE.DB */);
428
+ }
429
+ }
430
+ else {
431
+ instance = new db_1.default(db, database);
432
+ }
433
+ if (instance) {
434
+ const host = this.host;
435
+ if (host) {
436
+ instance.host = host;
437
+ instance.init(host.config);
438
+ }
439
+ else {
440
+ instance.init();
441
+ }
442
+ this.Db = instance;
443
+ }
444
+ }
445
+ this.assets = assets;
446
+ return super.init();
447
+ }
448
+ abort(name) {
449
+ if (this.aborted || name && this.settingsOf(name, 'abort') !== true) {
450
+ return;
451
+ }
452
+ super.abort();
453
+ }
454
+ customize(options) {
455
+ const transform = options.transform;
456
+ if (transform) {
457
+ const config = this._transformConfig || (this._transformConfig = { algorithm: undefined, etag: false, expires: 0, renew: false, limit: Infinity, exclude: {}, include: {} });
458
+ let enabled, algorithm, etag, expires, renew, limit, exclude, include;
459
+ if (transform === true || transform === 'etag') {
460
+ etag = true;
461
+ enabled = true;
462
+ }
463
+ else if (typeof transform === 'string') {
464
+ algorithm = transform;
465
+ enabled = true;
466
+ }
467
+ else if ((0, types_1.isPlainObject)(transform)) {
468
+ ({ enabled = true, algorithm, etag, expires, renew, limit, exclude, include } = transform);
469
+ }
470
+ if (!enabled) {
471
+ this._transformConfig = null;
472
+ return;
473
+ }
474
+ switch (algorithm = algorithm?.toLowerCase()) {
475
+ case 'md5':
476
+ case 'sha1':
477
+ case 'sha224':
478
+ case 'sha256':
479
+ case 'sha384':
480
+ case 'sha512':
481
+ config.algorithm = algorithm;
482
+ break;
483
+ default:
484
+ config.algorithm = undefined;
485
+ break;
486
+ }
487
+ if (typeof etag === 'boolean') {
488
+ config.etag = etag;
489
+ }
490
+ if (expires && (expires = (0, types_1.parseExpires)(expires)) >= 0) {
491
+ config.expires = Math.min(expires, core_1.Client.MAX_TIMEOUT);
492
+ }
493
+ if (renew) {
494
+ config.renew = true;
495
+ }
496
+ if ((0, types_1.isPlainObject)(exclude)) {
497
+ for (const type in exclude) {
498
+ const item = exclude[type];
499
+ if (item === '*') {
500
+ config.exclude[type] = true;
501
+ }
502
+ else if ((0, types_1.isArray)(item)) {
503
+ config.exclude[type] = item;
504
+ }
505
+ }
506
+ }
507
+ if ((0, types_1.isPlainObject)(include)) {
508
+ for (const type in include) {
509
+ const item = include[type];
510
+ if (item === '*') {
511
+ config.include[type] = true;
512
+ }
513
+ else if ((0, types_1.isArray)(item)) {
514
+ config.include[type] = item;
515
+ }
516
+ }
517
+ }
518
+ if (limit !== undefined) {
519
+ let value;
520
+ if (typeof limit === 'string') {
521
+ if (parseFloat(limit) === 0) {
522
+ value = 0;
523
+ }
524
+ else if ((value = (0, types_1.formatSize)(limit)) === 0) {
525
+ return;
526
+ }
527
+ }
528
+ else {
529
+ value = limit;
530
+ }
531
+ if (value >= 0) {
532
+ config.limit = value;
533
+ }
534
+ }
535
+ }
536
+ else if (transform === false || transform === null) {
537
+ this._transformConfig = null;
538
+ }
539
+ }
540
+ findConfig(data, name, type) {
541
+ for (const plugin in data) {
542
+ const settings = data[plugin];
543
+ for (const attr in settings) {
544
+ if (attr === name) {
545
+ const options = this.loadConfig(settings, attr);
546
+ const output = this.loadConfig(settings, attr + '-output');
547
+ if (options || output) {
548
+ return [plugin, options, output, true];
549
+ }
550
+ }
551
+ }
552
+ }
553
+ return [];
554
+ }
555
+ loadConfig(data, name) {
556
+ const value = data[name];
557
+ const getObject = (target, cache) => {
558
+ if (this.settingsOf('transform', 'coerce') === true) {
559
+ (0, types_1.coerceObject)(target, cache);
560
+ }
561
+ return (0, types_1.cloneObject)(data[name] = target, true);
562
+ };
563
+ switch (typeof value) {
564
+ case 'function':
565
+ return value;
566
+ case 'object':
567
+ if (value) {
568
+ return getObject(value, true);
569
+ }
570
+ break;
571
+ case 'string': {
572
+ const warning = (message) => this.addLog(types_1.STATUS_TYPE.ERROR, joinString(this.moduleName, 'transform@' + name, message));
573
+ const result = this.asSourceFile(value);
574
+ if (typeof result === 'function') {
575
+ if (!name.endsWith('-output')) {
576
+ return data[name] = result;
577
+ }
578
+ warning('"output" can only be a plain object');
579
+ }
580
+ else if ((0, types_1.isPlainObject)(result)) {
581
+ return getObject(result, false);
582
+ }
583
+ else {
584
+ warning(path.isAbsolute(value) ? "Unsupported access" /* ERR_MESSAGE.UNSUPPORTED_ACCESS */ + ` (${value})` : "Unknown" /* ERR_MESSAGE.UNKNOWN */);
585
+ }
586
+ break;
587
+ }
588
+ }
589
+ delete data[name];
590
+ }
591
+ resolveDir(name, ...paths) {
592
+ let baseDir = this.settings.directory?.[name];
593
+ if (baseDir) {
594
+ try {
595
+ baseDir = path.resolve(baseDir);
596
+ const username = this.host?.username;
597
+ let result;
598
+ if (username) {
599
+ const leading = path.join(baseDir, 'users', username);
600
+ if (fs.existsSync(result = path.join(leading, ...paths)) && result.startsWith(leading)) {
601
+ return result;
602
+ }
603
+ }
604
+ if (fs.existsSync(result = path.join(baseDir, ...paths)) && result.startsWith(baseDir)) {
605
+ return result;
606
+ }
607
+ }
608
+ catch {
609
+ }
610
+ }
611
+ }
612
+ asSourceFile(value, options) {
613
+ let encoding, persist, cache;
614
+ if (typeof options === 'boolean') {
615
+ cache = options;
616
+ }
617
+ else if ((0, types_1.isObject)(options)) {
618
+ ({ encoding, persist, cache } = options);
619
+ }
620
+ let result;
621
+ if ((value = value.trim()).startsWith('npm:')) {
622
+ const pkgName = value.substring(4);
623
+ if (persist) {
624
+ result = CACHE_REQUIRE[pkgName];
625
+ }
626
+ if (!result) {
627
+ if (!core_1.Client.enabled("node.require.npm" /* KEY_NAME.NODE_REQUIRE_NPM */)) {
628
+ return null;
629
+ }
630
+ try {
631
+ if (!persist) {
632
+ delete require.cache[pkgName];
633
+ }
634
+ result = require(pkgName);
635
+ if (persist && result) {
636
+ CACHE_REQUIRE[pkgName] = result;
637
+ }
638
+ if (typeof result === 'function') {
639
+ return Object.defineProperty(result, "__cjs__" /* INTERNAL.CJS */, { value: true });
640
+ }
641
+ }
642
+ catch (err) {
643
+ this.checkPackage(err, pkgName, "Unknown" /* ERR_MESSAGE.UNKNOWN */);
644
+ }
645
+ if (!result) {
646
+ return null;
647
+ }
648
+ }
649
+ }
650
+ try {
651
+ const source = result || this.readFile(value, { ownPermissionOnly: true, absolutePath: this.hasEval('absolute'), requireExt: true, encoding, cache }) || value;
652
+ if (typeof source !== 'string') {
653
+ result = source;
654
+ }
655
+ else if (!(result = (0, types_1.asFunction)(source))) {
656
+ try {
657
+ result = this.tryParse(source, path.extname(value).substring(1));
658
+ }
659
+ catch {
660
+ }
661
+ }
662
+ // @ts-ignore
663
+ if ((0, types_1.isObject)(result) || typeof result === 'function' && (result["__cjs__" /* INTERNAL.CJS */] || this.hasEval('function'))) {
664
+ return result;
665
+ }
666
+ }
667
+ catch (err) {
668
+ this.writeFail(["Unable to read file" /* ERR_MESSAGE.READ_FILE */, path.basename(value)], err, 8192 /* LOG_TYPE.PERMISSION */);
669
+ }
670
+ return null;
671
+ }
672
+ findVersion(name, fallback = '') {
673
+ let result;
674
+ const versions = this.module.versions;
675
+ if (versions) {
676
+ if (Array.isArray(name)) {
677
+ for (const value of name) {
678
+ if (result = versions[value]) {
679
+ break;
680
+ }
681
+ }
682
+ }
683
+ else {
684
+ result = this.module.versions?.[name];
685
+ }
686
+ }
687
+ return result || fallback;
688
+ }
689
+ findSourceRoot(uri, imports = this.imports) {
690
+ if (imports) {
691
+ const normalizeDir = (value) => value + (value[value.length - 1] !== '/' ? '/' : '');
692
+ for (const url in imports) {
693
+ if (uri === url || normalizeDir(uri) === normalizeDir(url)) {
694
+ return imports[url];
695
+ }
696
+ }
697
+ const found = [];
698
+ for (const hostname in imports) {
699
+ if (uri.startsWith(normalizeDir(hostname)) && (0, types_1.isString)(imports[hostname])) {
700
+ found.push(hostname);
701
+ }
702
+ }
703
+ if (found.length) {
704
+ const hostname = found.sort((a, b) => b.length - a.length)[0];
705
+ return core_1.Client.toPosix(path.resolve(imports[hostname], uri.substring(normalizeDir(hostname).length).split('?')[0]));
706
+ }
707
+ }
708
+ }
709
+ locateSourceFiles(file, code, bundleContent) {
710
+ return (imports = this.imports) => {
711
+ const href = file.uri;
712
+ const sourceFile = [];
713
+ let mainFile, invalid;
714
+ if (Document.isFile(href, 'unc') || path.isAbsolute(href)) {
715
+ sourceFile.push([href]);
716
+ }
717
+ else if (imports && Object.keys(imports).length) {
718
+ const bundleId = file.bundleId;
719
+ const assets = !(0, types_1.isEmpty)(bundleId) ? this.assets.filter(item => item.bundleId === bundleId).sort((a, b) => a.bundleIndex - b.bundleIndex) : [file];
720
+ if (!Array.isArray(bundleContent) || bundleContent.length !== assets.length - 1) {
721
+ bundleContent = undefined;
722
+ }
723
+ for (const item of assets) {
724
+ const localFile = !item.exported && item.uri ? this.findSourceRoot(item.uri, imports) : undefined;
725
+ if (localFile && core_1.Client.isPath(localFile) && !item.trailingContent) {
726
+ sourceFile.push([localFile]);
727
+ }
728
+ else {
729
+ let source;
730
+ if (item.bundleIndex === 0) {
731
+ const localUri = item.localUri;
732
+ try {
733
+ source = fs.readFileSync(localUri, file.encoding || (file.encoding = 'utf-8'));
734
+ if (this.resolveUri && (0, types_1.isArray)(file.trailingContent)) {
735
+ let trailing;
736
+ [source, trailing] = this.resolveUri(file, source, (0, util_1.concatString)(file.trailingContent));
737
+ if ((0, types_1.isString)(trailing)) {
738
+ source += trailing;
739
+ }
740
+ }
741
+ }
742
+ catch (err) {
743
+ this.writeFail(["Unable to read file" /* ERR_MESSAGE.READ_FILE */, localUri && path.basename(localUri)], 32 /* LOG_TYPE.FILE */);
744
+ }
745
+ }
746
+ else if (bundleContent) {
747
+ source = bundleContent[item.bundleIndex - 1];
748
+ }
749
+ if (!source) {
750
+ invalid = true;
751
+ break;
752
+ }
753
+ sourceFile.push(['', this.resolveImports?.(item, source, localFile) || source, localFile]);
754
+ }
755
+ }
756
+ }
757
+ if (sourceFile.length && (sourceFile[0] && (mainFile = sourceFile[0][0]) || !invalid) && (!this.hasOwnPermission() || !sourceFile.some(item => item[0] && !this.canRead(item[0])))) {
758
+ return { code, sourceFile: !invalid ? sourceFile : undefined, sourcesRelativeTo: mainFile && path.dirname(mainFile) };
759
+ }
760
+ };
761
+ }
762
+ resolveSourceFile(file) {
763
+ return (code, imports = this.imports) => {
764
+ const uri = file.uri;
765
+ let source, sourceFile;
766
+ if (code && imports && Object.keys(imports).length) {
767
+ const output = this.resolveImports?.(file, code, uri && this.findSourceRoot(uri, imports));
768
+ if (output) {
769
+ source = output;
770
+ }
771
+ }
772
+ if (uri) {
773
+ sourceFile = Document.isFile(uri, 'unc') || path.isAbsolute(uri) ? uri : this.findSourceRoot(uri, imports);
774
+ }
775
+ if (source || sourceFile) {
776
+ return { code: source || code, sourceFile, sourcesRelativeTo: sourceFile && path.dirname(sourceFile) };
777
+ }
778
+ };
779
+ }
780
+ tryParse(source, format, options) {
781
+ try {
782
+ switch (format.toLowerCase()) {
783
+ case 'yml':
784
+ case 'yaml':
785
+ return yaml.load(source, options);
786
+ case 'json5':
787
+ return require('json5').parse(source);
788
+ case 'xml':
789
+ return new (require('fast-xml-parser').XMLParser)(options).parse(source);
790
+ case 'toml':
791
+ return require('toml').parse(source);
792
+ default:
793
+ return JSON.parse(source);
794
+ }
795
+ }
796
+ catch (err) {
797
+ const name = (0, util_1.getModuleName)(err);
798
+ if (name) {
799
+ this.checkPackage(err, (0, util_1.getModuleName)(err), "Unknown" /* ERR_MESSAGE.UNKNOWN */);
800
+ }
801
+ throw err;
802
+ }
803
+ }
804
+ forDb(item) {
805
+ return item.source !== 'cloud';
806
+ }
807
+ hasEval(name) {
808
+ return !!this.module.eval?.[name];
809
+ }
810
+ settingsOf(name, option) {
811
+ const options = this.settings.options?.[name];
812
+ if ((0, types_1.isObject)(options)) {
813
+ return options[option];
814
+ }
815
+ }
816
+ async parseTemplate(viewEngine, template, data) {
817
+ let target, stored;
818
+ if (typeof viewEngine === 'string') {
819
+ target = this.settings.view_engine?.[viewEngine];
820
+ const username = this.host?.username;
821
+ const userConfig = username && this.settings.users?.[username]?.view_engine?.[viewEngine];
822
+ if ((0, types_1.isPlainObject)(userConfig)) {
823
+ if ((0, types_1.isPlainObject)(target)) {
824
+ (0, types_1.cloneObject)(userConfig, { target, deep: true, preserve: true });
825
+ }
826
+ else {
827
+ target = userConfig;
828
+ }
829
+ }
830
+ stored = true;
831
+ }
832
+ else {
833
+ target = viewEngine;
834
+ }
835
+ if (!((0, types_1.isPlainObject)(target) && target.name)) {
836
+ this.abort('view_engine');
837
+ const from = typeof viewEngine === 'string' ? viewEngine : this.moduleName;
838
+ this.writeFail(["Unable to load configuration" /* ERR_MESSAGE.LOAD_CONFIG */, from], (0, types_1.errorMessage)('view-engine', from, "Unknown" /* ERR_MESSAGE.UNKNOWN */));
839
+ return null;
840
+ }
841
+ const length = data.length;
842
+ if (length === 0 && !target.outputEmpty) {
843
+ return '';
844
+ }
845
+ let name;
846
+ try {
847
+ const context = require(name = target.name);
848
+ const { singleRow, options = {} } = target;
849
+ let { compile, output } = options;
850
+ if (!(0, types_1.isPlainObject)(output)) {
851
+ output = undefined;
852
+ }
853
+ if (this.settingsOf('view_engine', 'coerce') === true) {
854
+ if (compile) {
855
+ (0, types_1.coerceObject)(compile, stored);
856
+ }
857
+ if (output) {
858
+ (0, types_1.coerceObject)(output, stored);
859
+ }
860
+ }
861
+ const username = this.host?.username || '';
862
+ const cache = CACHE_TEMPLATE[name] || (CACHE_TEMPLATE[name] = {});
863
+ const cacheKey = username + core_1.Client.asHash(template + (compile ? core_1.Client.asString(compile) : ''));
864
+ let result = '', render, valid;
865
+ if (!(render = cache[cacheKey])) {
866
+ render = await context.compile(template, compile); // eslint-disable-line @typescript-eslint/await-thenable
867
+ cache[cacheKey] = render;
868
+ if (!core_1.Client.enabled("memory.settings.users" /* KEY_NAME.MEMORY_SETTINGS_USERS */, username)) {
869
+ setTimeout(() => delete cache[cacheKey], 60000 /* VALUES.TEMPLATE_EXPIRES */);
870
+ }
871
+ }
872
+ for (let i = 0, j = 0, row; i < length; ++i) {
873
+ if ((0, types_1.isPlainObject)(row = data[i])) {
874
+ row['__index__'] ?? (row['__index__'] = ++j);
875
+ if (output) {
876
+ row = { ...output, ...row };
877
+ }
878
+ }
879
+ else if (!(0, types_1.isObject)(row)) {
880
+ this.addLog(types_1.STATUS_TYPE.WARN, joinString(`view engine[${name}]`, `row #${i + 1}`, core_1.Client.asString(row) || "Unknown" /* ERR_MESSAGE.UNKNOWN */));
881
+ continue;
882
+ }
883
+ if (!singleRow) {
884
+ const content = await render.call(context, row); // eslint-disable-line @typescript-eslint/await-thenable
885
+ if (content !== undefined && content !== null) {
886
+ result += content;
887
+ valid = true;
888
+ }
889
+ }
890
+ }
891
+ return singleRow ? render.call(context, data) ?? null : valid ? result : null;
892
+ }
893
+ catch (err) {
894
+ this.abort('view_engine');
895
+ this.checkPackage(err, name, "Unknown" /* ERR_MESSAGE.UNKNOWN */, 4 /* LOG_TYPE.PROCESS */);
896
+ }
897
+ return null;
898
+ }
899
+ async transform(type, code, format, options = {}) {
900
+ var _a;
901
+ let transform = this.settings.transform;
902
+ const data = transform?.[type];
903
+ if (!(0, types_1.isObject)(data)) {
904
+ return;
905
+ }
906
+ format = typeof format === 'string' ? format.trim().split(/\s*\+\s*/) : format.map(item => typeof item === 'string' ? item.trim() : '');
907
+ const moduleName = this.moduleName;
908
+ const username = this.host?.username || '';
909
+ const config = this._transformConfig;
910
+ const cacheData = config && options.cacheData;
911
+ const cacheType = username && core_1.Client.enabled("memory.settings.users" /* KEY_NAME.MEMORY_SETTINGS_USERS */, username) ? true : this.cacheDir || core_1.Client.enabled("memory.settings.users" /* KEY_NAME.MEMORY_SETTINGS_USERS */);
912
+ let formatKey, hashKey, excludeKey;
913
+ if (cacheData && cacheType && !CACHE_EXTERNAL[excludeKey = moduleName + '_' + type + '_' + format] && (!config.exclude[type] || Array.isArray(config.exclude[type]) && !format.some(value => config.exclude[type].includes(value)) || Array.isArray(config.include[type]) && format.every(value => config.include[type].includes(value)))) {
914
+ const { uri, etag } = cacheData;
915
+ const encoding = (0, types_1.getEncoding)(cacheData.encoding);
916
+ const algorithm = config.algorithm;
917
+ let result, cacheName;
918
+ formatKey = type + '_' + format + '_' + encoding + (username ? '_' + username : '') + core_1.Client.asString(options.external) + core_1.Client.asString(options.metadata);
919
+ const resetTimeout = (map, key, stored) => {
920
+ if (config.renew) {
921
+ if (stored.timeout) {
922
+ clearTimeout(stored.timeout);
923
+ }
924
+ stored.timeout = renewTransform(map, key, config.expires);
925
+ }
926
+ stored.lastAccessed = Date.now();
927
+ };
928
+ const getData = (stored) => {
929
+ const location = stored.format[formatKey];
930
+ if (typeof location === 'string') {
931
+ try {
932
+ return JSON.parse(fs.readFileSync(location, encoding));
933
+ }
934
+ catch {
935
+ fs.unlink(location, () => { });
936
+ return;
937
+ }
938
+ }
939
+ return location;
940
+ };
941
+ if (config.etag && etag && uri) {
942
+ const etagMap = CACHE_ETAG[moduleName] || (CACHE_ETAG[moduleName] = {});
943
+ const stored = etagMap[uri];
944
+ if (stored) {
945
+ if (stored.etag !== etag) {
946
+ deleteTransform(etagMap, uri, stored.timeout);
947
+ }
948
+ else if (result = getData(stored)) {
949
+ resetTimeout(etagMap, uri, stored);
950
+ cacheName = 'etag';
951
+ }
952
+ }
953
+ }
954
+ if (!result) {
955
+ if (algorithm) {
956
+ const limit = config.limit;
957
+ if ((limit === Infinity || limit > 0 && Buffer.byteLength(code, encoding) <= limit) && (hashKey = core_1.Client.asHash(code, { algorithm, encoding }))) {
958
+ const hashMap = CACHE_HASH[moduleName] || (CACHE_HASH[moduleName] = {});
959
+ const stored = hashMap[hashKey];
960
+ if (stored && (result = getData(stored))) {
961
+ resetTimeout(hashMap, hashKey, stored);
962
+ cacheName = algorithm;
963
+ }
964
+ }
965
+ else {
966
+ formatKey = '';
967
+ }
968
+ }
969
+ else if (uri) {
970
+ const codeMap = CACHE_CODE[moduleName] || (CACHE_CODE[moduleName] = {});
971
+ const stored = codeMap[uri];
972
+ if (stored) {
973
+ if (stored.code !== code) {
974
+ deleteTransform(codeMap, uri, stored.timeout);
975
+ }
976
+ else if (result = getData(stored)) {
977
+ resetTimeout(codeMap, uri, stored);
978
+ }
979
+ }
980
+ }
981
+ else {
982
+ formatKey = '';
983
+ }
984
+ }
985
+ if (result) {
986
+ result.storedLog?.forEach(log => this.addLog(log));
987
+ this.formatMessage(4 /* LOG_TYPE.PROCESS */, type, [joinString(cacheName, format.filter(value => value).join(' | '), options.filename), 'cache'], uri, { ...core_1.Client.LOG_STYLE_NOTICE, hintBold: true });
988
+ return result;
989
+ }
990
+ }
991
+ if (cacheData) {
992
+ delete options.cacheData;
993
+ }
994
+ const imports = (_a = transform).imports || (_a.imports = {});
995
+ const series = new transform_1.TransformSeries(type, code, options);
996
+ series.init(this, __dirname);
997
+ let valid, excluded, userData, userImports, ignoreCache, storedLog, sourceFiles;
998
+ if (username && (transform = this.settings.users?.[username]?.transform)) {
999
+ userData = transform[type];
1000
+ userImports = transform.imports;
1001
+ }
1002
+ const abort = () => {
1003
+ ignoreCache = true;
1004
+ this.abort('transform');
1005
+ };
1006
+ const includes = (name) => {
1007
+ const include = config?.include[type];
1008
+ if (include === true || include?.includes(name)) {
1009
+ const exclude = config.exclude[type];
1010
+ return !exclude || exclude === true && include !== true || Array.isArray(exclude) && !exclude.includes(name);
1011
+ }
1012
+ return cacheData?.override === true;
1013
+ };
1014
+ for (let i = 0, length = format.length, name; i < length; ++i) {
1015
+ if (this.aborted) {
1016
+ break;
1017
+ }
1018
+ if (!(name = format[i])) {
1019
+ continue;
1020
+ }
1021
+ let [plugin, baseConfig, outputConfig, baseSettings] = this.findConfig(data, name, type);
1022
+ if ((0, types_1.isObject)(userData)) {
1023
+ const [a, b, c, d] = this.findConfig(userData, name, type);
1024
+ if (!plugin || a === plugin) {
1025
+ if (b) {
1026
+ if (baseConfig) {
1027
+ (0, types_1.cloneObject)(b, { target: baseConfig, deep: true, preserve: true });
1028
+ }
1029
+ else {
1030
+ baseConfig = b;
1031
+ }
1032
+ }
1033
+ if (c) {
1034
+ if (outputConfig) {
1035
+ (0, types_1.cloneObject)(c, { target: outputConfig, deep: true, preserve: true });
1036
+ }
1037
+ else {
1038
+ outputConfig = c;
1039
+ }
1040
+ }
1041
+ if (!d) {
1042
+ baseSettings = false;
1043
+ }
1044
+ }
1045
+ }
1046
+ if (!baseSettings) {
1047
+ excluded = !includes(name);
1048
+ }
1049
+ outputConfig || (outputConfig = {});
1050
+ if (plugin && baseConfig) {
1051
+ series.outputConfig = outputConfig;
1052
+ const source = series.code;
1053
+ const startTime = process.hrtime();
1054
+ const hint = plugin + '@' + name;
1055
+ const next = (value) => {
1056
+ if (this.aborted) {
1057
+ valid = false;
1058
+ return;
1059
+ }
1060
+ const out = series.out;
1061
+ let bypassLog, failed;
1062
+ if (typeof value !== 'string' || (0, types_1.isArray)(out.sourceFiles) && this.hasOwnPermission() && out.sourceFiles.some(item => !this.canRead(item, { ownPermissionOnly: true }))) {
1063
+ failed = true;
1064
+ ignoreCache = true;
1065
+ this.writeFail(["Unable to transform document" /* ERR_MESSAGE.TRANSFORM_DOCUMENT */, plugin], (0, types_1.errorMessage)(plugin, name, typeof value === 'string' ? "Unsupported access" /* ERR_MESSAGE.UNSUPPORTED_ACCESS */ : 'Empty'), { type: 4 /* LOG_TYPE.PROCESS */, startTime });
1066
+ }
1067
+ else if (source !== value) {
1068
+ series.code = value;
1069
+ valid = true;
1070
+ if (out.ignoreCache && !includes(name)) {
1071
+ ignoreCache = true;
1072
+ }
1073
+ if ((0, types_1.isArray)(out.sourceFiles)) {
1074
+ if (!sourceFiles) {
1075
+ sourceFiles = out.sourceFiles.slice(0);
1076
+ }
1077
+ else {
1078
+ out.sourceFiles.forEach(item => !sourceFiles.includes(item) && sourceFiles.push(item));
1079
+ }
1080
+ }
1081
+ }
1082
+ if ((0, types_1.isArray)(out.logAppend)) {
1083
+ out.logAppend.forEach(log => this.addLog(log));
1084
+ (storedLog || (storedLog = [])).push(...out.logAppend);
1085
+ bypassLog = true;
1086
+ }
1087
+ if ((0, types_1.isArray)(out.logQueued)) {
1088
+ out.logQueued.forEach(log => this.writeLog(log, true));
1089
+ (storedLog || (storedLog = [])).push(...out.logQueued);
1090
+ bypassLog = true;
1091
+ }
1092
+ if (i < length - 1) {
1093
+ series.reset();
1094
+ }
1095
+ this.writeTimeProcess(failed ? 'CHECK' : type, joinString(hint, options.filename) + (series.out.messageAppend || ''), startTime, { failed, bypassLog });
1096
+ };
1097
+ this.formatMessage(4 /* LOG_TYPE.PROCESS */, type, ['Transforming source...', hint], options.filename, { hintColor: 'cyan' });
1098
+ try {
1099
+ let context = require(plugin);
1100
+ series.packageName = plugin;
1101
+ if (typeof baseConfig === 'function') {
1102
+ series.baseConfig = outputConfig;
1103
+ // @ts-ignore
1104
+ if (baseConfig["__cjs__" /* INTERNAL.CJS */]) {
1105
+ next(await baseConfig(context, source, series));
1106
+ }
1107
+ else {
1108
+ const thisArg = core_1.Client.enabled("node.process.inline" /* KEY_NAME.NODE_PROCESS_INLINE */) ? process : null;
1109
+ const inline = core_1.Client.enabled("node.require.inline" /* KEY_NAME.NODE_REQUIRE_INLINE */);
1110
+ const args = [context, source, series];
1111
+ if (baseConfig.toString().startsWith('async')) {
1112
+ if (inline) {
1113
+ args.push(require);
1114
+ }
1115
+ next(await baseConfig.apply(thisArg, args));
1116
+ }
1117
+ else {
1118
+ next(await new Promise(resolve => {
1119
+ args.push(resolve);
1120
+ if (inline) {
1121
+ args.push(require);
1122
+ }
1123
+ baseConfig.apply(thisArg, args);
1124
+ }));
1125
+ }
1126
+ }
1127
+ }
1128
+ else {
1129
+ let transformer = CACHE_PACKAGE[plugin + username];
1130
+ if (!transformer) {
1131
+ try {
1132
+ let pkg = this.resolveDir('package', plugin + '.js') || userImports?.[plugin] || imports[plugin] || PIR_PLUGINS[plugin];
1133
+ if ((0, types_1.isString)(pkg)) {
1134
+ const match = /^(@?\S+)@(\d+(?:\.\d+(?:\.\S+)?)?|[a-z]+)$/.exec(pkg);
1135
+ if (match) {
1136
+ pkg = match[1];
1137
+ series.version = match[2];
1138
+ }
1139
+ transformer = require(pkg);
1140
+ }
1141
+ else {
1142
+ transformer = context;
1143
+ context = this;
1144
+ pkg = undefined;
1145
+ }
1146
+ if (typeof transformer !== 'function' && typeof (transformer = transformer?.['default']) !== 'function') {
1147
+ throw (0, types_1.errorMessage)(plugin, pkg || name, 'Invalid function');
1148
+ }
1149
+ if (pkg) {
1150
+ CACHE_PACKAGE[plugin + username] = transformer;
1151
+ }
1152
+ }
1153
+ catch (err) {
1154
+ abort();
1155
+ this.writeFail(["Unknown" /* ERR_MESSAGE.UNKNOWN */, username ? plugin + ':' + username : hint], err, { type: 4 /* LOG_TYPE.PROCESS */, startTime });
1156
+ continue;
1157
+ }
1158
+ }
1159
+ series.baseConfig = baseConfig;
1160
+ next(await transformer(context, source, series));
1161
+ }
1162
+ }
1163
+ catch (err) {
1164
+ abort();
1165
+ this.checkPackage(err, (0, util_1.getModuleName)(err), ["Unable to transform document" /* ERR_MESSAGE.TRANSFORM_DOCUMENT */, hint], { type: 4 /* LOG_TYPE.PROCESS */, startTime });
1166
+ if (i < length - 1) {
1167
+ series.reset();
1168
+ }
1169
+ }
1170
+ }
1171
+ else {
1172
+ abort();
1173
+ if (plugin) {
1174
+ this.writeFail("Unable to load configuration" /* ERR_MESSAGE.LOAD_CONFIG */, (0, types_1.errorMessage)(plugin, name, 'Invalid config'), 4 /* LOG_TYPE.PROCESS */);
1175
+ }
1176
+ else {
1177
+ this.writeFail('Format method was not found', (0, types_1.errorValue)(name, "Unknown" /* ERR_MESSAGE.UNKNOWN */), 4 /* LOG_TYPE.PROCESS */);
1178
+ }
1179
+ }
1180
+ }
1181
+ if (this.aborted) {
1182
+ series.detach();
1183
+ return;
1184
+ }
1185
+ series.close(this);
1186
+ if (excluded && excludeKey) {
1187
+ CACHE_EXTERNAL[excludeKey] = true;
1188
+ }
1189
+ if (!valid) {
1190
+ return;
1191
+ }
1192
+ const output = { type, code: series.code };
1193
+ const sourceMap = series.sourceMap;
1194
+ if (sourceMap.map && sourceMap.code === output.code) {
1195
+ output.map = sourceMap.map;
1196
+ }
1197
+ if ((0, types_1.isArray)(series.supplementChunks)) {
1198
+ output.chunks = series.supplementChunks.map(item => ({ code: item.code, map: output.map && item.sourceMap?.map, entryPoint: item.entryPoint, filename: item.filename }));
1199
+ }
1200
+ if (sourceFiles) {
1201
+ output.sourceFiles = sourceFiles;
1202
+ }
1203
+ if (formatKey && !excluded && !ignoreCache) {
1204
+ const { uri, etag } = cacheData;
1205
+ const formatData = { ...output, storedLog };
1206
+ const lastAccessed = Date.now();
1207
+ const setData = () => {
1208
+ let pathname;
1209
+ if (typeof cacheType === 'string' && core_1.Client.createDir(pathname = path.join(cacheType, 'transform', type))) {
1210
+ try {
1211
+ fs.writeFileSync(pathname = path.join(pathname, (0, types_1.generateUUID)()), JSON.stringify(formatData));
1212
+ return pathname;
1213
+ }
1214
+ catch {
1215
+ }
1216
+ }
1217
+ return formatData;
1218
+ };
1219
+ if (config.etag && etag && uri) {
1220
+ const etagMap = CACHE_ETAG[moduleName];
1221
+ const stored = etagMap[uri];
1222
+ if (stored) {
1223
+ if (stored.etag === etag) {
1224
+ stored.format[formatKey] = setData();
1225
+ stored.lastAccessed = lastAccessed;
1226
+ return output;
1227
+ }
1228
+ deleteTransform(etagMap, uri, stored.timeout);
1229
+ }
1230
+ etagMap[uri] = { lastAccessed, etag, timeout: renewTransform(etagMap, uri, config.expires), format: { [formatKey]: setData() } };
1231
+ ++CACHE_TOTAL;
1232
+ }
1233
+ else if (hashKey) {
1234
+ const hashMap = CACHE_HASH[moduleName];
1235
+ const stored = hashMap[hashKey];
1236
+ if (stored) {
1237
+ stored.format[formatKey] = setData();
1238
+ stored.lastAccessed = lastAccessed;
1239
+ return output;
1240
+ }
1241
+ hashMap[hashKey] = { lastAccessed, timeout: renewTransform(hashMap, hashKey, config.expires), format: { [formatKey]: setData() } };
1242
+ ++CACHE_TOTAL;
1243
+ }
1244
+ else if (uri) {
1245
+ const codeMap = CACHE_CODE[moduleName];
1246
+ const stored = codeMap[uri];
1247
+ if (stored) {
1248
+ if (stored.code === code) {
1249
+ stored.format[formatKey] = setData();
1250
+ stored.lastAccessed = lastAccessed;
1251
+ return output;
1252
+ }
1253
+ deleteTransform(codeMap, uri, stored.timeout);
1254
+ }
1255
+ codeMap[uri] = { lastAccessed, code, timeout: renewTransform(codeMap, uri, config.expires), format: { [formatKey]: setData() } };
1256
+ ++CACHE_TOTAL;
1257
+ }
1258
+ }
1259
+ return output;
1260
+ }
1261
+ set assets(value) {
1262
+ this._assets = value;
1263
+ }
1264
+ get assets() {
1265
+ if (this.host) {
1266
+ try {
1267
+ return this._assets || (this._assets = this.host.getDocumentAssets(this));
1268
+ }
1269
+ catch {
1270
+ }
1271
+ }
1272
+ return this._assets || [];
1273
+ }
1274
+ set dataSource(value) {
1275
+ this._dataSource = value;
1276
+ }
1277
+ get dataSource() {
1278
+ if (this.host) {
1279
+ try {
1280
+ return this._dataSource || (this._dataSource = this.host.getDataSourceItems(this));
1281
+ }
1282
+ catch {
1283
+ }
1284
+ }
1285
+ return this._dataSource || [];
1286
+ }
1287
+ get watching() {
1288
+ return this.assets.some(item => item.watch);
1289
+ }
1290
+ }
1291
+ exports.default = Document;
1292
1292
 
1293
1293
  if (exports.default) {
1294
1294
  module.exports = exports.default;