@wyw-in-js/transform 0.8.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/esm/babel.js.map +1 -1
- package/esm/cache.js +15 -4
- package/esm/cache.js.map +1 -1
- package/esm/debug/fileReporter.js.map +1 -1
- package/esm/evaluators/index.js.map +1 -1
- package/esm/index.js.map +1 -1
- package/esm/module.js +174 -15
- package/esm/module.js.map +1 -1
- package/esm/options/buildOptions.js +123 -4
- package/esm/options/buildOptions.js.map +1 -1
- package/esm/options/buildOptions.test.js +41 -0
- package/esm/options/buildOptions.test.js.map +1 -0
- package/esm/options/loadBabelOptions.js.map +1 -1
- package/esm/plugins/babel-transform.js.map +1 -1
- package/esm/plugins/collector.js.map +1 -1
- package/esm/plugins/dynamic-import.js +35 -12
- package/esm/plugins/dynamic-import.js.map +1 -1
- package/esm/plugins/preeval.js +4 -0
- package/esm/plugins/preeval.js.map +1 -1
- package/esm/plugins/shaker.js +170 -23
- package/esm/plugins/shaker.js.map +1 -1
- package/esm/shaker.js +6 -3
- package/esm/shaker.js.map +1 -1
- package/esm/transform/BaseEntrypoint.js.map +1 -1
- package/esm/transform/Entrypoint.helpers.js +105 -15
- package/esm/transform/Entrypoint.helpers.js.map +1 -1
- package/esm/transform/Entrypoint.js +13 -2
- package/esm/transform/Entrypoint.js.map +1 -1
- package/esm/transform/Entrypoint.types.js.map +1 -1
- package/esm/transform/EvaluatedEntrypoint.js.map +1 -1
- package/esm/transform/actions/AbortError.js.map +1 -1
- package/esm/transform/actions/BaseAction.js +5 -0
- package/esm/transform/actions/BaseAction.js.map +1 -1
- package/esm/transform/actions/UnprocessedEntrypointError.js.map +1 -1
- package/esm/transform/actions/actionRunner.js.map +1 -1
- package/esm/transform/actions/types.js.map +1 -1
- package/esm/transform/generators/baseProcessingHandlers.js.map +1 -1
- package/esm/transform/generators/collect.js.map +1 -1
- package/esm/transform/generators/createStylisPreprocessor.js +118 -2
- package/esm/transform/generators/createStylisPreprocessor.js.map +1 -1
- package/esm/transform/generators/evalFile.js.map +1 -1
- package/esm/transform/generators/explodeReexports.js +10 -10
- package/esm/transform/generators/explodeReexports.js.map +1 -1
- package/esm/transform/generators/extract.js.map +1 -1
- package/esm/transform/generators/getExports.js.map +1 -1
- package/esm/transform/generators/index.js.map +1 -1
- package/esm/transform/generators/processEntrypoint.js +5 -8
- package/esm/transform/generators/processEntrypoint.js.map +1 -1
- package/esm/transform/generators/processImports.js.map +1 -1
- package/esm/transform/generators/resolveImports.js +41 -2
- package/esm/transform/generators/resolveImports.js.map +1 -1
- package/esm/transform/generators/transform.js +7 -3
- package/esm/transform/generators/transform.js.map +1 -1
- package/esm/transform/generators/workflow.js.map +1 -1
- package/esm/transform/helpers/loadWywOptions.js +15 -2
- package/esm/transform/helpers/loadWywOptions.js.map +1 -1
- package/esm/transform/helpers/withDefaultServices.js +2 -0
- package/esm/transform/helpers/withDefaultServices.js.map +1 -1
- package/esm/transform/isStaticallyEvaluatableModule.js +153 -0
- package/esm/transform/isStaticallyEvaluatableModule.js.map +1 -0
- package/esm/transform/rootLog.js.map +1 -1
- package/esm/transform/types.js.map +1 -1
- package/esm/transform.js +15 -6
- package/esm/transform.js.map +1 -1
- package/esm/types.js.map +1 -1
- package/esm/utils/EventEmitter.js.map +1 -1
- package/esm/utils/ShakerMetadata.js.map +1 -1
- package/esm/utils/TransformMetadata.js.map +1 -1
- package/esm/utils/addIdentifierToWywPreval.js.map +1 -1
- package/esm/utils/collectExportsAndImports.js +97 -6
- package/esm/utils/collectExportsAndImports.js.map +1 -1
- package/esm/utils/collectTemplateDependencies.js +1 -1
- package/esm/utils/collectTemplateDependencies.js.map +1 -1
- package/esm/utils/createId.js.map +1 -1
- package/esm/utils/dispose-polyfill.js.map +1 -1
- package/esm/utils/findIdentifiers.js.map +1 -1
- package/esm/utils/getConstantStringValue.js +58 -0
- package/esm/utils/getConstantStringValue.js.map +1 -0
- package/esm/utils/getFileIdx.js.map +1 -1
- package/esm/utils/getMemberExpressionPropertyName.js +11 -0
- package/esm/utils/getMemberExpressionPropertyName.js.map +1 -0
- package/esm/utils/getPluginKey.js.map +1 -1
- package/esm/utils/getScope.js.map +1 -1
- package/esm/utils/getSource.js.map +1 -1
- package/esm/utils/getTagProcessor.js +34 -6
- package/esm/utils/getTagProcessor.js.map +1 -1
- package/esm/utils/getVisitorKeys.js.map +1 -1
- package/esm/utils/hasWywPreval.js.map +1 -1
- package/esm/utils/importOverrides.js +47 -0
- package/esm/utils/importOverrides.js.map +1 -0
- package/esm/utils/isExports.js.map +1 -1
- package/esm/utils/isGlobal.js.map +1 -1
- package/esm/utils/isNode.js.map +1 -1
- package/esm/utils/isNodePath.js.map +1 -1
- package/esm/utils/isNotNull.js.map +1 -1
- package/esm/utils/isRemoved.js.map +1 -1
- package/esm/utils/isRequire.js.map +1 -1
- package/esm/utils/isSerializable.js.map +1 -1
- package/esm/utils/isTypedNode.js.map +1 -1
- package/esm/utils/isUnnecessaryReactCall.js.map +1 -1
- package/esm/utils/parseRequest.js +29 -0
- package/esm/utils/parseRequest.js.map +1 -0
- package/esm/utils/peek.js.map +1 -1
- package/esm/utils/removeDangerousCode.js +32 -2
- package/esm/utils/removeDangerousCode.js.map +1 -1
- package/esm/utils/replaceImportMetaEnv.js +44 -0
- package/esm/utils/replaceImportMetaEnv.js.map +1 -0
- package/esm/utils/scopeHelpers.js.map +1 -1
- package/esm/utils/traversalCache.js.map +1 -1
- package/esm/utils/unwrapExpression.js +18 -0
- package/esm/utils/unwrapExpression.js.map +1 -0
- package/esm/utils/unwrapSequence.js.map +1 -1
- package/esm/utils/valueToLiteral.js.map +1 -1
- package/esm/utils/visitors/JSXElementsRemover.js.map +1 -1
- package/esm/vm/createVmContext.js +44 -0
- package/esm/vm/createVmContext.js.map +1 -1
- package/esm/vm/process.js.map +1 -1
- package/lib/babel.js.map +1 -1
- package/lib/cache.js +16 -5
- package/lib/cache.js.map +1 -1
- package/lib/debug/fileReporter.js +1 -1
- package/lib/debug/fileReporter.js.map +1 -1
- package/lib/evaluators/index.js.map +1 -1
- package/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/lib/module.js +177 -16
- package/lib/module.js.map +1 -1
- package/lib/options/buildOptions.js +127 -6
- package/lib/options/buildOptions.js.map +1 -1
- package/lib/options/buildOptions.test.js +44 -0
- package/lib/options/buildOptions.test.js.map +1 -0
- package/lib/options/loadBabelOptions.js.map +1 -1
- package/lib/plugins/babel-transform.js.map +1 -1
- package/lib/plugins/collector.js.map +1 -1
- package/lib/plugins/dynamic-import.js +34 -12
- package/lib/plugins/dynamic-import.js.map +1 -1
- package/lib/plugins/preeval.js +4 -0
- package/lib/plugins/preeval.js.map +1 -1
- package/lib/plugins/shaker.js +172 -22
- package/lib/plugins/shaker.js.map +1 -1
- package/lib/shaker.js +8 -4
- package/lib/shaker.js.map +1 -1
- package/lib/transform/BaseEntrypoint.js.map +1 -1
- package/lib/transform/Entrypoint.helpers.js +106 -15
- package/lib/transform/Entrypoint.helpers.js.map +1 -1
- package/lib/transform/Entrypoint.js +13 -2
- package/lib/transform/Entrypoint.js.map +1 -1
- package/lib/transform/Entrypoint.types.js.map +1 -1
- package/lib/transform/EvaluatedEntrypoint.js.map +1 -1
- package/lib/transform/actions/AbortError.js.map +1 -1
- package/lib/transform/actions/BaseAction.js +5 -0
- package/lib/transform/actions/BaseAction.js.map +1 -1
- package/lib/transform/actions/UnprocessedEntrypointError.js.map +1 -1
- package/lib/transform/actions/actionRunner.js.map +1 -1
- package/lib/transform/actions/types.js.map +1 -1
- package/lib/transform/generators/baseProcessingHandlers.js.map +1 -1
- package/lib/transform/generators/collect.js.map +1 -1
- package/lib/transform/generators/createStylisPreprocessor.js +119 -3
- package/lib/transform/generators/createStylisPreprocessor.js.map +1 -1
- package/lib/transform/generators/evalFile.js +1 -1
- package/lib/transform/generators/evalFile.js.map +1 -1
- package/lib/transform/generators/explodeReexports.js +11 -11
- package/lib/transform/generators/explodeReexports.js.map +1 -1
- package/lib/transform/generators/extract.js.map +1 -1
- package/lib/transform/generators/getExports.js.map +1 -1
- package/lib/transform/generators/index.js.map +1 -1
- package/lib/transform/generators/processEntrypoint.js +5 -8
- package/lib/transform/generators/processEntrypoint.js.map +1 -1
- package/lib/transform/generators/processImports.js.map +1 -1
- package/lib/transform/generators/resolveImports.js +41 -2
- package/lib/transform/generators/resolveImports.js.map +1 -1
- package/lib/transform/generators/transform.js +8 -3
- package/lib/transform/generators/transform.js.map +1 -1
- package/lib/transform/generators/workflow.js.map +1 -1
- package/lib/transform/helpers/loadWywOptions.js +16 -2
- package/lib/transform/helpers/loadWywOptions.js.map +1 -1
- package/lib/transform/helpers/withDefaultServices.js +3 -2
- package/lib/transform/helpers/withDefaultServices.js.map +1 -1
- package/lib/transform/isStaticallyEvaluatableModule.js +159 -0
- package/lib/transform/isStaticallyEvaluatableModule.js.map +1 -0
- package/lib/transform/rootLog.js.map +1 -1
- package/lib/transform/types.js.map +1 -1
- package/lib/transform.js +15 -6
- package/lib/transform.js.map +1 -1
- package/lib/types.js.map +1 -1
- package/lib/utils/EventEmitter.js.map +1 -1
- package/lib/utils/ShakerMetadata.js.map +1 -1
- package/lib/utils/TransformMetadata.js.map +1 -1
- package/lib/utils/addIdentifierToWywPreval.js.map +1 -1
- package/lib/utils/collectExportsAndImports.js +97 -6
- package/lib/utils/collectExportsAndImports.js.map +1 -1
- package/lib/utils/collectTemplateDependencies.js +1 -1
- package/lib/utils/collectTemplateDependencies.js.map +1 -1
- package/lib/utils/createId.js.map +1 -1
- package/lib/utils/dispose-polyfill.js.map +1 -1
- package/lib/utils/findIdentifiers.js.map +1 -1
- package/lib/utils/getConstantStringValue.js +66 -0
- package/lib/utils/getConstantStringValue.js.map +1 -0
- package/lib/utils/getFileIdx.js.map +1 -1
- package/lib/utils/getMemberExpressionPropertyName.js +18 -0
- package/lib/utils/getMemberExpressionPropertyName.js.map +1 -0
- package/lib/utils/getPluginKey.js.map +1 -1
- package/lib/utils/getScope.js.map +1 -1
- package/lib/utils/getSource.js +1 -1
- package/lib/utils/getSource.js.map +1 -1
- package/lib/utils/getTagProcessor.js +33 -6
- package/lib/utils/getTagProcessor.js.map +1 -1
- package/lib/utils/getVisitorKeys.js.map +1 -1
- package/lib/utils/hasWywPreval.js.map +1 -1
- package/lib/utils/importOverrides.js +57 -0
- package/lib/utils/importOverrides.js.map +1 -0
- package/lib/utils/isExports.js.map +1 -1
- package/lib/utils/isGlobal.js.map +1 -1
- package/lib/utils/isNode.js.map +1 -1
- package/lib/utils/isNodePath.js.map +1 -1
- package/lib/utils/isNotNull.js.map +1 -1
- package/lib/utils/isRemoved.js.map +1 -1
- package/lib/utils/isRequire.js.map +1 -1
- package/lib/utils/isSerializable.js.map +1 -1
- package/lib/utils/isTypedNode.js.map +1 -1
- package/lib/utils/isUnnecessaryReactCall.js.map +1 -1
- package/lib/utils/parseRequest.js +37 -0
- package/lib/utils/parseRequest.js.map +1 -0
- package/lib/utils/peek.js.map +1 -1
- package/lib/utils/removeDangerousCode.js +32 -2
- package/lib/utils/removeDangerousCode.js.map +1 -1
- package/lib/utils/replaceImportMetaEnv.js +50 -0
- package/lib/utils/replaceImportMetaEnv.js.map +1 -0
- package/lib/utils/scopeHelpers.js.map +1 -1
- package/lib/utils/traversalCache.js.map +1 -1
- package/lib/utils/unwrapExpression.js +25 -0
- package/lib/utils/unwrapExpression.js.map +1 -0
- package/lib/utils/unwrapSequence.js.map +1 -1
- package/lib/utils/valueToLiteral.js.map +1 -1
- package/lib/utils/visitors/JSXElementsRemover.js.map +1 -1
- package/lib/vm/createVmContext.js +45 -2
- package/lib/vm/createVmContext.js.map +1 -1
- package/lib/vm/process.js.map +1 -1
- package/package.json +13 -15
- package/types/cache.d.ts +1 -1
- package/types/cache.js +15 -4
- package/types/evaluators/index.js +1 -1
- package/types/module.d.ts +1 -2
- package/types/module.js +189 -11
- package/types/options/buildOptions.d.ts +0 -1
- package/types/options/buildOptions.js +125 -9
- package/types/options/loadBabelOptions.js +1 -2
- package/types/plugins/babel-transform.js +1 -1
- package/types/plugins/collector.js +3 -3
- package/types/plugins/dynamic-import.js +38 -18
- package/types/plugins/preeval.js +5 -2
- package/types/plugins/shaker.d.ts +4 -1
- package/types/plugins/shaker.js +189 -24
- package/types/shaker.js +9 -3
- package/types/transform/BaseEntrypoint.d.ts +0 -1
- package/types/transform/Entrypoint.helpers.d.ts +0 -1
- package/types/transform/Entrypoint.helpers.js +122 -25
- package/types/transform/Entrypoint.js +14 -2
- package/types/transform/Entrypoint.types.d.ts +0 -1
- package/types/transform/EvaluatedEntrypoint.d.ts +0 -1
- package/types/transform/actions/BaseAction.d.ts +1 -1
- package/types/transform/actions/BaseAction.js +5 -0
- package/types/transform/actions/actionRunner.js +2 -3
- package/types/transform/generators/collect.js +1 -2
- package/types/transform/generators/createStylisPreprocessor.d.ts +0 -1
- package/types/transform/generators/createStylisPreprocessor.js +168 -13
- package/types/transform/generators/evalFile.js +1 -2
- package/types/transform/generators/explodeReexports.js +12 -15
- package/types/transform/generators/extract.js +1 -2
- package/types/transform/generators/getExports.js +2 -3
- package/types/transform/generators/processEntrypoint.js +13 -7
- package/types/transform/generators/processImports.js +1 -2
- package/types/transform/generators/resolveImports.js +41 -5
- package/types/transform/generators/transform.d.ts +1 -1
- package/types/transform/generators/transform.js +16 -6
- package/types/transform/generators/workflow.js +1 -2
- package/types/transform/helpers/loadWywOptions.js +16 -5
- package/types/transform/helpers/withDefaultServices.d.ts +1 -1
- package/types/transform/helpers/withDefaultServices.js +19 -8
- package/types/transform/isStaticallyEvaluatableModule.d.ts +2 -0
- package/types/transform/isStaticallyEvaluatableModule.js +177 -0
- package/types/transform/rootLog.d.ts +0 -1
- package/types/transform/types.d.ts +1 -1
- package/types/transform.js +17 -9
- package/types/types.d.ts +1 -1
- package/types/utils/addIdentifierToWywPreval.js +2 -3
- package/types/utils/collectExportsAndImports.js +102 -20
- package/types/utils/collectTemplateDependencies.js +3 -4
- package/types/utils/findIdentifiers.js +2 -3
- package/types/utils/getConstantStringValue.d.ts +2 -0
- package/types/utils/getConstantStringValue.js +94 -0
- package/types/utils/getFileIdx.js +1 -2
- package/types/utils/getMemberExpressionPropertyName.d.ts +2 -0
- package/types/utils/getMemberExpressionPropertyName.js +46 -0
- package/types/utils/getScope.js +1 -2
- package/types/utils/getTagProcessor.js +35 -9
- package/types/utils/getVisitorKeys.js +1 -2
- package/types/utils/hasWywPreval.js +1 -1
- package/types/utils/importOverrides.d.ts +19 -0
- package/types/utils/importOverrides.js +40 -0
- package/types/utils/isExports.js +1 -2
- package/types/utils/isNodePath.js +1 -2
- package/types/utils/isNotNull.js +1 -2
- package/types/utils/isRemoved.js +1 -2
- package/types/utils/isRequire.js +1 -2
- package/types/utils/isSerializable.js +1 -2
- package/types/utils/isUnnecessaryReactCall.js +1 -2
- package/types/utils/parseRequest.d.ts +7 -0
- package/types/utils/parseRequest.js +29 -0
- package/types/utils/removeDangerousCode.js +37 -2
- package/types/utils/replaceImportMetaEnv.d.ts +3 -0
- package/types/utils/replaceImportMetaEnv.js +39 -0
- package/types/utils/scopeHelpers.js +7 -8
- package/types/utils/traversalCache.d.ts +1 -1
- package/types/utils/unwrapExpression.d.ts +2 -0
- package/types/utils/unwrapExpression.js +57 -0
- package/types/utils/unwrapSequence.js +1 -2
- package/types/utils/valueToLiteral.js +1 -2
- package/types/utils/visitors/JSXElementsRemover.js +1 -2
- package/types/vm/createVmContext.d.ts +0 -1
- package/types/vm/createVmContext.js +68 -9
- package/types/vm/process.d.ts +0 -2
- package/LICENSE +0 -21
- package/esm/options/babel-merge.d.js +0 -2
- package/esm/options/babel-merge.d.js.map +0 -1
- package/lib/options/babel-merge.d.js +0 -2
- package/lib/options/babel-merge.d.js.map +0 -1
package/lib/cache.js
CHANGED
|
@@ -8,7 +8,8 @@ var _crypto = require("crypto");
|
|
|
8
8
|
var _nodeFs = _interopRequireDefault(require("node:fs"));
|
|
9
9
|
var _shared = require("@wyw-in-js/shared");
|
|
10
10
|
var _getFileIdx = require("./utils/getFileIdx");
|
|
11
|
-
|
|
11
|
+
var _parseRequest = require("./utils/parseRequest");
|
|
12
|
+
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
|
|
12
13
|
function hashContent(content) {
|
|
13
14
|
return (0, _crypto.createHash)('sha256').update(content).digest('hex');
|
|
14
15
|
}
|
|
@@ -27,11 +28,19 @@ class TransformCacheCollection {
|
|
|
27
28
|
add(cacheName, key, value) {
|
|
28
29
|
const cache = this[cacheName];
|
|
29
30
|
loggers[cacheName]('%s:add %s %f', (0, _getFileIdx.getFileIdx)(key), key, () => {
|
|
31
|
+
if (value === undefined) {
|
|
32
|
+
return cache.has(key) ? 'removed' : 'noop';
|
|
33
|
+
}
|
|
30
34
|
if (!cache.has(key)) {
|
|
31
35
|
return 'added';
|
|
32
36
|
}
|
|
33
37
|
return cache.get(key) === value ? 'unchanged' : 'updated';
|
|
34
38
|
});
|
|
39
|
+
if (value === undefined) {
|
|
40
|
+
cache.delete(key);
|
|
41
|
+
this.contentHashes.delete(key);
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
35
44
|
cache.set(key, value);
|
|
36
45
|
if ('initialCode' in value) {
|
|
37
46
|
var _value$initialCode;
|
|
@@ -77,17 +86,19 @@ class TransformCacheCollection {
|
|
|
77
86
|
this.invalidate(cacheName, filename);
|
|
78
87
|
});
|
|
79
88
|
}
|
|
80
|
-
invalidateIfChanged(filename, content) {
|
|
89
|
+
invalidateIfChanged(filename, content, previousVisitedFiles) {
|
|
90
|
+
const visitedFiles = new Set(previousVisitedFiles);
|
|
81
91
|
const fileEntrypoint = this.get('entrypoints', filename);
|
|
82
92
|
|
|
83
93
|
// We need to check all dependencies of the file
|
|
84
94
|
// because they might have changed as well.
|
|
85
|
-
if (fileEntrypoint) {
|
|
95
|
+
if (fileEntrypoint && !visitedFiles.has(filename)) {
|
|
96
|
+
visitedFiles.add(filename);
|
|
86
97
|
for (const [, dependency] of fileEntrypoint.dependencies) {
|
|
87
98
|
const dependencyFilename = dependency.resolved;
|
|
88
99
|
if (dependencyFilename) {
|
|
89
|
-
const dependencyContent = _nodeFs.default.readFileSync(dependencyFilename, 'utf8');
|
|
90
|
-
this.invalidateIfChanged(dependencyFilename, dependencyContent);
|
|
100
|
+
const dependencyContent = _nodeFs.default.readFileSync((0, _parseRequest.stripQueryAndHash)(dependencyFilename), 'utf8');
|
|
101
|
+
this.invalidateIfChanged(dependencyFilename, dependencyContent, visitedFiles);
|
|
91
102
|
}
|
|
92
103
|
}
|
|
93
104
|
}
|
package/lib/cache.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cache.js","names":["_crypto","require","_nodeFs","_interopRequireDefault","_shared","_getFileIdx","
|
|
1
|
+
{"version":3,"file":"cache.js","names":["_crypto","require","_nodeFs","_interopRequireDefault","_shared","_getFileIdx","_parseRequest","e","__esModule","default","hashContent","content","createHash","update","digest","cacheLogger","logger","extend","cacheNames","loggers","reduce","acc","key","TransformCacheCollection","contentHashes","Map","constructor","caches","entrypoints","exports","add","cacheName","value","cache","getFileIdx","undefined","has","get","delete","set","_value$initialCode","initialCode","clear","forEach","name","invalidate","res","invalidateForFile","filename","invalidateIfChanged","previousVisitedFiles","visitedFiles","Set","fileEntrypoint","dependency","dependencies","dependencyFilename","resolved","dependencyContent","fs","readFileSync","stripQueryAndHash","hash","newHash"],"sources":["../src/cache.ts"],"sourcesContent":["import { createHash } from 'crypto';\nimport fs from 'node:fs';\nimport { logger } from '@wyw-in-js/shared';\n\nimport type { Entrypoint } from './transform/Entrypoint';\nimport type { IEvaluatedEntrypoint } from './transform/EvaluatedEntrypoint';\nimport { getFileIdx } from './utils/getFileIdx';\nimport { stripQueryAndHash } from './utils/parseRequest';\n\nfunction hashContent(content: string) {\n return createHash('sha256').update(content).digest('hex');\n}\n\ninterface IBaseCachedEntrypoint {\n dependencies: Map<string, { resolved: string | null }>;\n initialCode?: string;\n}\n\ninterface ICaches<TEntrypoint extends IBaseCachedEntrypoint> {\n entrypoints: Map<string, TEntrypoint>;\n exports: Map<string, string[]>;\n}\n\ntype MapValue<T> = T extends Map<string, infer V> ? V : never;\n\nconst cacheLogger = logger.extend('cache');\n\nconst cacheNames = ['entrypoints', 'exports'] as const;\ntype CacheNames = (typeof cacheNames)[number];\n\nconst loggers = cacheNames.reduce(\n (acc, key) => ({\n ...acc,\n [key]: cacheLogger.extend(key),\n }),\n {} as Record<CacheNames, typeof logger>\n);\n\nexport class TransformCacheCollection<\n TEntrypoint extends IBaseCachedEntrypoint = Entrypoint | IEvaluatedEntrypoint,\n> {\n public readonly entrypoints: Map<string, TEntrypoint>;\n\n public readonly exports: Map<string, string[]>;\n\n private contentHashes = new Map<string, string>();\n\n constructor(caches: Partial<ICaches<TEntrypoint>> = {}) {\n this.entrypoints = caches.entrypoints || new Map();\n this.exports = caches.exports || new Map();\n }\n\n public add<\n TCache extends CacheNames,\n TValue extends MapValue<ICaches<TEntrypoint>[TCache]>,\n >(cacheName: TCache, key: string, value: TValue): void {\n const cache = this[cacheName] as Map<string, TValue>;\n loggers[cacheName]('%s:add %s %f', getFileIdx(key), key, () => {\n if (value === undefined) {\n return cache.has(key) ? 'removed' : 'noop';\n }\n\n if (!cache.has(key)) {\n return 'added';\n }\n\n return cache.get(key) === value ? 'unchanged' : 'updated';\n });\n\n if (value === undefined) {\n cache.delete(key);\n this.contentHashes.delete(key);\n return;\n }\n\n cache.set(key, value);\n\n if ('initialCode' in value) {\n this.contentHashes.set(key, hashContent(value.initialCode ?? ''));\n }\n }\n\n public clear(cacheName: CacheNames | 'all'): void {\n if (cacheName === 'all') {\n cacheNames.forEach((name) => {\n this.clear(name);\n });\n\n return;\n }\n\n loggers[cacheName]('clear');\n const cache = this[cacheName] as Map<string, unknown>;\n\n cache.clear();\n }\n\n public delete(cacheName: CacheNames, key: string): void {\n this.invalidate(cacheName, key);\n }\n\n public get<\n TCache extends CacheNames,\n TValue extends MapValue<ICaches<TEntrypoint>[TCache]>,\n >(cacheName: TCache, key: string): TValue | undefined {\n const cache = this[cacheName] as Map<string, TValue>;\n\n const res = cache.get(key);\n loggers[cacheName]('get', key, res === undefined ? 'miss' : 'hit');\n return res;\n }\n\n public has(cacheName: CacheNames, key: string): boolean {\n const cache = this[cacheName] as Map<string, unknown>;\n\n const res = cache.has(key);\n loggers[cacheName]('has', key, res);\n return res;\n }\n\n public invalidate(cacheName: CacheNames, key: string): void {\n const cache = this[cacheName] as Map<string, unknown>;\n if (!cache.has(key)) {\n return;\n }\n\n loggers[cacheName]('invalidate', key);\n\n cache.delete(key);\n }\n\n public invalidateForFile(filename: string) {\n cacheNames.forEach((cacheName) => {\n this.invalidate(cacheName, filename);\n });\n }\n\n public invalidateIfChanged(\n filename: string,\n content: string,\n previousVisitedFiles?: Set<string>\n ) {\n const visitedFiles = new Set(previousVisitedFiles);\n const fileEntrypoint = this.get('entrypoints', filename);\n\n // We need to check all dependencies of the file\n // because they might have changed as well.\n if (fileEntrypoint && !visitedFiles.has(filename)) {\n visitedFiles.add(filename);\n\n for (const [, dependency] of fileEntrypoint.dependencies) {\n const dependencyFilename = dependency.resolved;\n\n if (dependencyFilename) {\n const dependencyContent = fs.readFileSync(\n stripQueryAndHash(dependencyFilename),\n 'utf8'\n );\n this.invalidateIfChanged(\n dependencyFilename,\n dependencyContent,\n visitedFiles\n );\n }\n }\n }\n\n const hash = this.contentHashes.get(filename);\n const newHash = hashContent(content);\n\n if (hash !== newHash) {\n cacheLogger('content has changed, invalidate all for %s', filename);\n this.contentHashes.set(filename, newHash);\n this.invalidateForFile(filename);\n\n return true;\n }\n\n return false;\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,OAAA,GAAAC,sBAAA,CAAAF,OAAA;AACA,IAAAG,OAAA,GAAAH,OAAA;AAIA,IAAAI,WAAA,GAAAJ,OAAA;AACA,IAAAK,aAAA,GAAAL,OAAA;AAAyD,SAAAE,uBAAAI,CAAA,WAAAA,CAAA,IAAAA,CAAA,C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C,IAAID,kBAAkB,EAAE;UACtB,MAAME,iBAAiB,GAAGC,eAAE,CAACC,YAAY,CACvC,IAAAC,+BAAiB,EAACL,kBAAkB,CAAC,EACrC,MACF,CAAC;UACD,IAAI,CAACP,mBAAmB,CACtBO,kBAAkB,EAClBE,iBAAiB,EACjBP,YACF,CAAC;QACH;MACF;IACF;IAEA,MAAMW,IAAI,GAAG,IAAI,CAACtC,aAAa,CAACa,GAAG,CAACW,QAAQ,CAAC;IAC7C,MAAMe,OAAO,GAAGrD,WAAW,CAACC,OAAO,CAAC;IAEpC,IAAImD,IAAI,KAAKC,OAAO,EAAE;MACpBhD,WAAW,CAAC,4CAA4C,EAAEiC,QAAQ,CAAC;MACnE,IAAI,CAACxB,aAAa,CAACe,GAAG,CAACS,QAAQ,EAAEe,OAAO,CAAC;MACzC,IAAI,CAAChB,iBAAiB,CAACC,QAAQ,CAAC;MAEhC,OAAO,IAAI;IACb;IAEA,OAAO,KAAK;EACd;AACF;AAACnB,OAAA,CAAAN,wBAAA,GAAAA,wBAAA","ignoreList":[]}
|
|
@@ -7,7 +7,7 @@ exports.createFileReporter = void 0;
|
|
|
7
7
|
var _fs = require("fs");
|
|
8
8
|
var _path = _interopRequireDefault(require("path"));
|
|
9
9
|
var _EventEmitter = require("../utils/EventEmitter");
|
|
10
|
-
function _interopRequireDefault(
|
|
10
|
+
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
|
|
11
11
|
/* eslint-disable no-console */
|
|
12
12
|
|
|
13
13
|
const workingDir = process.cwd();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileReporter.js","names":["_fs","require","_path","_interopRequireDefault","_EventEmitter","obj","__esModule","default","workingDir","process","cwd","replacer","_key","value","path","isAbsolute","relative","Map","Array","from","entries","reduce","k","v","key","printTimings","timings","startedAt","sourceRoot","size","console","log","performance","now","toFixed","forEach","label","byLabel","array","sort","a","b","localeCompare","time","name","startsWith","writeJSONl","stream","data","write","JSON","stringify","createFileReporter","options","dir","emitter","EventEmitter","dummy","onDone","reportFolder","existsSync","mkdirSync","recursive","Error","actionStream","createWriteStream","join","dependenciesStream","entrypointStream","addTiming","has","set","forLabel","get","Math","round","processDependencyEvent","file","only","imports","fileIdx","processSingleEvent","meta","type","startTimes","onEvent","Object","startTime","String","actionId","onAction","args","isOnActionStartArgs","timestamp","idx","entrypointRef","result","id","isAsync","error","finishedAt","onEntrypointEvent","emitterId","event","print","memoryUsage","end","clear","exports"],"sources":["../../src/debug/fileReporter.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport { createWriteStream, existsSync, mkdirSync } from 'fs';\nimport path from 'path';\n\nimport type {\n OnAction,\n OnEvent,\n OnActionFinishArgs,\n OnActionStartArgs,\n OnEntrypointEvent,\n} from '../utils/EventEmitter';\nimport { EventEmitter, isOnActionStartArgs } from '../utils/EventEmitter';\n\ntype Timings = Map<string, Map<string, number>>;\n\nexport interface IFileReporterOptions {\n dir?: string;\n print?: boolean;\n}\n\nexport interface IProcessedEvent {\n file: string;\n fileIdx: string;\n imports: { from: string; what: string[] }[];\n only: string[];\n type: 'dependency';\n}\n\nexport interface IQueueActionEvent {\n action: string;\n args?: string[];\n datetime: Date;\n file: string;\n queueIdx: string;\n type: 'queue-action';\n}\n\nconst workingDir = process.cwd();\n\nfunction replacer(_key: string, value: unknown): unknown {\n if (typeof value === 'string' && path.isAbsolute(value)) {\n return path.relative(workingDir, value);\n }\n\n if (value instanceof Map) {\n return Array.from(value.entries()).reduce((obj, [k, v]) => {\n const key = replacer(k, k) as string;\n return {\n ...obj,\n [key]: replacer(key, v),\n };\n }, {});\n }\n\n return value;\n}\n\nfunction printTimings(timings: Timings, startedAt: number, sourceRoot: string) {\n if (timings.size === 0) {\n return;\n }\n\n console.log(`\\nTimings:`);\n console.log(` Total: ${(performance.now() - startedAt).toFixed()}ms`);\n\n Array.from(timings.entries()).forEach(([label, byLabel]) => {\n console.log(`\\n By ${label}:`);\n\n const array = Array.from(byLabel.entries());\n // array.sort(([, a], [, b]) => b - a);\n array\n .sort(([a], [b]) => a.localeCompare(b))\n .forEach(([value, time]) => {\n const name = value.startsWith(sourceRoot)\n ? path.relative(sourceRoot, value)\n : value;\n console.log(` ${name}: ${time}ms`);\n });\n });\n}\n\nconst writeJSONl = (stream: NodeJS.WritableStream, data: unknown) => {\n stream.write(`${JSON.stringify(data, replacer)}\\n`);\n};\n\nexport const createFileReporter = (\n options: IFileReporterOptions | false = false\n) => {\n if (!options || !options.dir) {\n return {\n emitter: EventEmitter.dummy,\n onDone: () => {},\n };\n }\n\n const reportFolder = existsSync(options.dir)\n ? options.dir\n : mkdirSync(options.dir, {\n recursive: true,\n });\n\n if (!reportFolder) {\n throw new Error(`Could not create directory ${options.dir}`);\n }\n\n const actionStream = createWriteStream(\n path.join(options.dir, 'actions.jsonl')\n );\n\n const dependenciesStream = createWriteStream(\n path.join(options.dir, 'dependencies.jsonl')\n );\n\n const entrypointStream = createWriteStream(\n path.join(options.dir, 'entrypoints.jsonl')\n );\n\n const startedAt = performance.now();\n const timings: Timings = new Map();\n const addTiming = (label: string, key: string, value: number) => {\n if (!timings.has(label)) {\n timings.set(label, new Map());\n }\n\n const forLabel = timings.get(label)!;\n forLabel.set(key, Math.round((forLabel.get(key) || 0) + value));\n };\n\n const processDependencyEvent = ({\n file,\n only,\n imports,\n fileIdx,\n }: IProcessedEvent) => {\n writeJSONl(dependenciesStream, {\n file,\n only,\n imports,\n fileIdx,\n });\n };\n\n const processSingleEvent = (\n meta: Record<string, unknown> | IProcessedEvent | IQueueActionEvent\n ) => {\n if (meta.type === 'dependency') {\n processDependencyEvent(meta as IProcessedEvent);\n }\n };\n\n const startTimes = new Map<string, number>();\n\n const onEvent: OnEvent = (meta, type) => {\n if (type === 'single') {\n processSingleEvent(meta);\n return;\n }\n\n if (type === 'start') {\n Object.entries(meta).forEach(([label, value]) => {\n startTimes.set(`${label}\\0${value}`, performance.now());\n });\n } else {\n Object.entries(meta).forEach(([label, value]) => {\n const startTime = startTimes.get(`${label}\\0${value}`);\n if (startTime) {\n addTiming(label, String(value), performance.now() - startTime);\n }\n });\n }\n };\n\n let actionId = 0;\n const onAction: OnAction = (\n ...args: OnActionStartArgs | OnActionFinishArgs\n ) => {\n if (isOnActionStartArgs(args)) {\n const [, timestamp, type, idx, entrypointRef] = args;\n writeJSONl(actionStream, {\n actionId,\n entrypointRef,\n idx,\n startedAt: timestamp,\n type,\n });\n\n // eslint-disable-next-line no-plusplus\n return actionId++;\n }\n\n const [result, timestamp, id, isAsync, error] = args;\n writeJSONl(actionStream, {\n actionId: id,\n error,\n finishedAt: timestamp,\n isAsync,\n result: `${result}ed`,\n });\n\n return id;\n };\n\n const onEntrypointEvent: OnEntrypointEvent = (\n emitterId,\n timestamp,\n event\n ) => {\n entrypointStream.write(\n `${JSON.stringify([emitterId, timestamp, event])}\\n`\n );\n };\n\n const emitter = new EventEmitter(onEvent, onAction, onEntrypointEvent);\n\n return {\n emitter,\n onDone: (sourceRoot: string) => {\n if (options.print) {\n printTimings(timings, startedAt, sourceRoot);\n\n console.log('\\nMemory usage:', process.memoryUsage());\n }\n\n actionStream.end();\n dependenciesStream.end();\n timings.clear();\n },\n };\n};\n"],"mappings":";;;;;;AACA,IAAAA,GAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAC,sBAAA,CAAAF,OAAA;AASA,IAAAG,aAAA,GAAAH,OAAA;AAA0E,SAAAE,uBAAAE,GAAA,WAAAA,GAAA,IAAAA,GAAA,CAAAC,UAAA,GAAAD,GAAA,KAAAE,OAAA,EAAAF,GAAA;AAX1E;;AAqCA,MAAMG,UAAU,GAAGC,OAAO,CAACC,GAAG,CAAC,CAAC;AAEhC,SAASC,QAAQA,CAACC,IAAY,EAAEC,KAAc,EAAW;EACvD,IAAI,OAAOA,KAAK,KAAK,QAAQ,IAAIC,aAAI,CAACC,UAAU,CAACF,KAAK,CAAC,EAAE;IACvD,OAAOC,aAAI,CAACE,QAAQ,CAACR,UAAU,EAAEK,KAAK,CA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pB,CAAC,CAAC;IAEF,OAAOC,EAAE;EACX,CAAC;EAED,MAAMI,iBAAoC,GAAGA,CAC3CC,SAAS,EACTT,SAAS,EACTU,KAAK,KACF;IACHnC,gBAAgB,CAACnB,KAAK,CACnB,GAAEC,IAAI,CAACC,SAAS,CAAC,CAACmD,SAAS,EAAET,SAAS,EAAEU,KAAK,CAAC,CAAE,IACnD,CAAC;EACH,CAAC;EAED,MAAMhD,OAAO,GAAG,IAAIC,0BAAY,CAAC6B,OAAO,EAAEK,QAAQ,EAAEW,iBAAiB,CAAC;EAEtE,OAAO;IACL9C,OAAO;IACPG,MAAM,EAAG9B,UAAkB,IAAK;MAC9B,IAAIyB,OAAO,CAACmD,KAAK,EAAE;QACjB/E,YAAY,CAACC,OAAO,EAAEC,SAAS,EAAEC,UAAU,CAAC;QAE5CE,OAAO,CAACC,GAAG,CAAC,iBAAiB,EAAEtB,OAAO,CAACgG,WAAW,CAAC,CAAC,CAAC;MACvD;MAEAzC,YAAY,CAAC0C,GAAG,CAAC,CAAC;MAClBvC,kBAAkB,CAACuC,GAAG,CAAC,CAAC;MACxBhF,OAAO,CAACiF,KAAK,CAAC,CAAC;IACjB;EACF,CAAC;AACH,CAAC;AAACC,OAAA,CAAAxD,kBAAA,GAAAA,kBAAA"}
|
|
1
|
+
{"version":3,"file":"fileReporter.js","names":["_fs","require","_path","_interopRequireDefault","_EventEmitter","e","__esModule","default","workingDir","process","cwd","replacer","_key","value","path","isAbsolute","relative","Map","Array","from","entries","reduce","obj","k","v","key","printTimings","timings","startedAt","sourceRoot","size","console","log","performance","now","toFixed","forEach","label","byLabel","array","sort","a","b","localeCompare","time","name","startsWith","writeJSONl","stream","data","write","JSON","stringify","createFileReporter","options","dir","emitter","EventEmitter","dummy","onDone","reportFolder","existsSync","mkdirSync","recursive","Error","actionStream","createWriteStream","join","dependenciesStream","entrypointStream","addTiming","has","set","forLabel","get","Math","round","processDependencyEvent","file","only","imports","fileIdx","processSingleEvent","meta","type","startTimes","onEvent","Object","startTime","String","actionId","onAction","args","isOnActionStartArgs","timestamp","idx","entrypointRef","result","id","isAsync","error","finishedAt","onEntrypointEvent","emitterId","event","print","memoryUsage","end","clear","exports"],"sources":["../../src/debug/fileReporter.ts"],"sourcesContent":["/* eslint-disable no-console */\nimport { createWriteStream, existsSync, mkdirSync } from 'fs';\nimport path from 'path';\n\nimport type {\n OnAction,\n OnEvent,\n OnActionFinishArgs,\n OnActionStartArgs,\n OnEntrypointEvent,\n} from '../utils/EventEmitter';\nimport { EventEmitter, isOnActionStartArgs } from '../utils/EventEmitter';\n\ntype Timings = Map<string, Map<string, number>>;\n\nexport interface IFileReporterOptions {\n dir?: string;\n print?: boolean;\n}\n\nexport interface IProcessedEvent {\n file: string;\n fileIdx: string;\n imports: { from: string; what: string[] }[];\n only: string[];\n type: 'dependency';\n}\n\nexport interface IQueueActionEvent {\n action: string;\n args?: string[];\n datetime: Date;\n file: string;\n queueIdx: string;\n type: 'queue-action';\n}\n\nconst workingDir = process.cwd();\n\nfunction replacer(_key: string, value: unknown): unknown {\n if (typeof value === 'string' && path.isAbsolute(value)) {\n return path.relative(workingDir, value);\n }\n\n if (value instanceof Map) {\n return Array.from(value.entries()).reduce((obj, [k, v]) => {\n const key = replacer(k, k) as string;\n return {\n ...obj,\n [key]: replacer(key, v),\n };\n }, {});\n }\n\n return value;\n}\n\nfunction printTimings(timings: Timings, startedAt: number, sourceRoot: string) {\n if (timings.size === 0) {\n return;\n }\n\n console.log(`\\nTimings:`);\n console.log(` Total: ${(performance.now() - startedAt).toFixed()}ms`);\n\n Array.from(timings.entries()).forEach(([label, byLabel]) => {\n console.log(`\\n By ${label}:`);\n\n const array = Array.from(byLabel.entries());\n // array.sort(([, a], [, b]) => b - a);\n array\n .sort(([a], [b]) => a.localeCompare(b))\n .forEach(([value, time]) => {\n const name = value.startsWith(sourceRoot)\n ? path.relative(sourceRoot, value)\n : value;\n console.log(` ${name}: ${time}ms`);\n });\n });\n}\n\nconst writeJSONl = (stream: NodeJS.WritableStream, data: unknown) => {\n stream.write(`${JSON.stringify(data, replacer)}\\n`);\n};\n\nexport const createFileReporter = (\n options: IFileReporterOptions | false = false\n) => {\n if (!options || !options.dir) {\n return {\n emitter: EventEmitter.dummy,\n onDone: () => {},\n };\n }\n\n const reportFolder = existsSync(options.dir)\n ? options.dir\n : mkdirSync(options.dir, {\n recursive: true,\n });\n\n if (!reportFolder) {\n throw new Error(`Could not create directory ${options.dir}`);\n }\n\n const actionStream = createWriteStream(\n path.join(options.dir, 'actions.jsonl')\n );\n\n const dependenciesStream = createWriteStream(\n path.join(options.dir, 'dependencies.jsonl')\n );\n\n const entrypointStream = createWriteStream(\n path.join(options.dir, 'entrypoints.jsonl')\n );\n\n const startedAt = performance.now();\n const timings: Timings = new Map();\n const addTiming = (label: string, key: string, value: number) => {\n if (!timings.has(label)) {\n timings.set(label, new Map());\n }\n\n const forLabel = timings.get(label)!;\n forLabel.set(key, Math.round((forLabel.get(key) || 0) + value));\n };\n\n const processDependencyEvent = ({\n file,\n only,\n imports,\n fileIdx,\n }: IProcessedEvent) => {\n writeJSONl(dependenciesStream, {\n file,\n only,\n imports,\n fileIdx,\n });\n };\n\n const processSingleEvent = (\n meta: Record<string, unknown> | IProcessedEvent | IQueueActionEvent\n ) => {\n if (meta.type === 'dependency') {\n processDependencyEvent(meta as IProcessedEvent);\n }\n };\n\n const startTimes = new Map<string, number>();\n\n const onEvent: OnEvent = (meta, type) => {\n if (type === 'single') {\n processSingleEvent(meta);\n return;\n }\n\n if (type === 'start') {\n Object.entries(meta).forEach(([label, value]) => {\n startTimes.set(`${label}\\0${value}`, performance.now());\n });\n } else {\n Object.entries(meta).forEach(([label, value]) => {\n const startTime = startTimes.get(`${label}\\0${value}`);\n if (startTime) {\n addTiming(label, String(value), performance.now() - startTime);\n }\n });\n }\n };\n\n let actionId = 0;\n const onAction: OnAction = (\n ...args: OnActionStartArgs | OnActionFinishArgs\n ) => {\n if (isOnActionStartArgs(args)) {\n const [, timestamp, type, idx, entrypointRef] = args;\n writeJSONl(actionStream, {\n actionId,\n entrypointRef,\n idx,\n startedAt: timestamp,\n type,\n });\n\n // eslint-disable-next-line no-plusplus\n return actionId++;\n }\n\n const [result, timestamp, id, isAsync, error] = args;\n writeJSONl(actionStream, {\n actionId: id,\n error,\n finishedAt: timestamp,\n isAsync,\n result: `${result}ed`,\n });\n\n return id;\n };\n\n const onEntrypointEvent: OnEntrypointEvent = (\n emitterId,\n timestamp,\n event\n ) => {\n entrypointStream.write(\n `${JSON.stringify([emitterId, timestamp, event])}\\n`\n );\n };\n\n const emitter = new EventEmitter(onEvent, onAction, onEntrypointEvent);\n\n return {\n emitter,\n onDone: (sourceRoot: string) => {\n if (options.print) {\n printTimings(timings, startedAt, sourceRoot);\n\n console.log('\\nMemory usage:', process.memoryUsage());\n }\n\n actionStream.end();\n dependenciesStream.end();\n timings.clear();\n },\n };\n};\n"],"mappings":";;;;;;AACA,IAAAA,GAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAC,sBAAA,CAAAF,OAAA;AASA,IAAAG,aAAA,GAAAH,OAAA;AAA0E,SAAAE,uBAAAE,CAAA,WAAAA,CAAA,IAAAA,CAAA,CAAAC,UAAA,GAAAD,CAAA,KAAAE,OAAA,EAAAF,CAAA;AAX1E;;AAqCA,MAAMG,UAAU,GAAGC,OAAO,CAACC,GAAG,CAAC,CAAC;AAEhC,SAASC,QAAQA,CAACC,IAAY,EAAEC,KAAc,EAAW;EACvD,IAAI,OAAOA,KAAK,KAAK,QAAQ,IAAIC,aAAI,CAACC,UAAU,CAACF,KAAK,CAAC,EAAE;IACvD,OAAOC,aAAI,CAACE,QAAQ,CAACR,UAAU,EAAEK,KAAK,CAAC;EACzC;EAEA,IAAIA,KAAK,YAAYI,GAAG,EAAE;IACxB,OAAOC,KAAK,CAACC,IAAI,CAACN,KAAK,CAACO,OAAO,CAAC,CAAC,CAAC,CAACC,MAAM,CAAC,CAACC,GAAG,EAAE,CAACC,CAAC,EAAEC,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SAAS,CAAC,CAACmD,SAAS,EAAET,SAAS,EAAEU,KAAK,CAAC,CAAC,IAClD,CAAC;EACH,CAAC;EAED,MAAMhD,OAAO,GAAG,IAAIC,0BAAY,CAAC6B,OAAO,EAAEK,QAAQ,EAAEW,iBAAiB,CAAC;EAEtE,OAAO;IACL9C,OAAO;IACPG,MAAM,EAAG9B,UAAkB,IAAK;MAC9B,IAAIyB,OAAO,CAACmD,KAAK,EAAE;QACjB/E,YAAY,CAACC,OAAO,EAAEC,SAAS,EAAEC,UAAU,CAAC;QAE5CE,OAAO,CAACC,GAAG,CAAC,iBAAiB,EAAEvB,OAAO,CAACiG,WAAW,CAAC,CAAC,CAAC;MACvD;MAEAzC,YAAY,CAAC0C,GAAG,CAAC,CAAC;MAClBvC,kBAAkB,CAACuC,GAAG,CAAC,CAAC;MACxBhF,OAAO,CAACiF,KAAK,CAAC,CAAC;IACjB;EACF,CAAC;AACH,CAAC;AAACC,OAAA,CAAAxD,kBAAA,GAAAA,kBAAA","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_module","require","evaluate","services","entrypoint","m","Module","value","exports","dependencies"],"sources":["../../src/evaluators/index.ts"],"sourcesContent":["/**\n * This file is an entry point for module evaluation for getting lazy dependencies.\n */\n\nimport { Module } from '../module';\nimport type { Entrypoint } from '../transform/Entrypoint';\nimport type { Services } from '../transform/types';\n\nexport interface IEvaluateResult {\n dependencies: string[];\n value: Record<string | symbol, unknown>;\n}\n\nexport default function evaluate(\n services: Services,\n entrypoint: Entrypoint\n): IEvaluateResult {\n const m = new Module(services, entrypoint);\n\n m.evaluate();\n\n return {\n value: entrypoint.exports,\n dependencies: m.dependencies,\n };\n}\n"],"mappings":";;;;;;AAIA,IAAAA,OAAA,GAAAC,OAAA;AAJA;AACA;AACA;;AAWe,SAASC,QAAQA,CAC9BC,QAAkB,EAClBC,UAAsB,EACL;EACjB,MAAMC,CAAC,GAAG,IAAIC,cAAM,CAACH,QAAQ,EAAEC,UAAU,CAAC;EAE1CC,CAAC,CAACH,QAAQ,CAAC,CAAC;EAEZ,OAAO;IACLK,KAAK,EAAEH,UAAU,CAACI,OAAO;IACzBC,YAAY,EAAEJ,CAAC,CAACI;EAClB,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["_module","require","evaluate","services","entrypoint","m","Module","value","exports","dependencies"],"sources":["../../src/evaluators/index.ts"],"sourcesContent":["/**\n * This file is an entry point for module evaluation for getting lazy dependencies.\n */\n\nimport { Module } from '../module';\nimport type { Entrypoint } from '../transform/Entrypoint';\nimport type { Services } from '../transform/types';\n\nexport interface IEvaluateResult {\n dependencies: string[];\n value: Record<string | symbol, unknown>;\n}\n\nexport default function evaluate(\n services: Services,\n entrypoint: Entrypoint\n): IEvaluateResult {\n const m = new Module(services, entrypoint);\n\n m.evaluate();\n\n return {\n value: entrypoint.exports,\n dependencies: m.dependencies,\n };\n}\n"],"mappings":";;;;;;AAIA,IAAAA,OAAA,GAAAC,OAAA;AAJA;AACA;AACA;;AAWe,SAASC,QAAQA,CAC9BC,QAAkB,EAClBC,UAAsB,EACL;EACjB,MAAMC,CAAC,GAAG,IAAIC,cAAM,CAACH,QAAQ,EAAEC,UAAU,CAAC;EAE1CC,CAAC,CAACH,QAAQ,CAAC,CAAC;EAEZ,OAAO;IACLK,KAAK,EAAEH,UAAU,CAACI,OAAO;IACzBC,YAAY,EAAEJ,CAAC,CAACI;EAClB,CAAC;AACH","ignoreList":[]}
|
package/lib/index.js
CHANGED
|
@@ -253,5 +253,5 @@ var _getVisitorKeys = require("./utils/getVisitorKeys");
|
|
|
253
253
|
var _peek = require("./utils/peek");
|
|
254
254
|
var _cache = require("./cache");
|
|
255
255
|
var _findIdentifiers = require("./utils/findIdentifiers");
|
|
256
|
-
function _interopRequireDefault(
|
|
256
|
+
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
|
|
257
257
|
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["_shared","require","_fileReporter","_babelTransform","_interopRequireDefault","_preeval","_TransformMetadata","_module","_shaker","_transform","_UnprocessedEntrypointError","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_EvaluatedEntrypoint","_Entrypoint","_generators","_transform2","_Entrypoint2","_createStylisPreprocessor","_resolveImports","_loadWywOptions","_withDefaultServices","_EventEmitter","_isNode","_getFileIdx","_getTagProcessor","_getVisitorKeys","_peek","_cache","_findIdentifiers","
|
|
1
|
+
{"version":3,"file":"index.js","names":["_shared","require","_fileReporter","_babelTransform","_interopRequireDefault","_preeval","_TransformMetadata","_module","_shaker","_transform","_UnprocessedEntrypointError","_types","Object","keys","forEach","key","prototype","hasOwnProperty","call","_exportNames","exports","defineProperty","enumerable","get","_EvaluatedEntrypoint","_Entrypoint","_generators","_transform2","_Entrypoint2","_createStylisPreprocessor","_resolveImports","_loadWywOptions","_withDefaultServices","_EventEmitter","_isNode","_getFileIdx","_getTagProcessor","_getVisitorKeys","_peek","_cache","_findIdentifiers","e","__esModule","default"],"sources":["../src/index.ts"],"sourcesContent":["export { slugify } from '@wyw-in-js/shared';\n\nexport { createFileReporter } from './debug/fileReporter';\nexport type { IFileReporterOptions } from './debug/fileReporter';\nexport { default as babelTransformPlugin } from './plugins/babel-transform';\nexport { default as preeval } from './plugins/preeval';\nexport {\n getTransformMetadata,\n withTransformMetadata,\n} from './utils/TransformMetadata';\nexport type { WYWTransformMetadata } from './utils/TransformMetadata';\nexport { Module, DefaultModuleImplementation } from './module';\nexport { default as shaker } from './shaker';\nexport { transform } from './transform';\nexport {\n isUnprocessedEntrypointError,\n UnprocessedEntrypointError,\n} from './transform/actions/UnprocessedEntrypointError';\nexport * from './types';\nexport { EvaluatedEntrypoint } from './transform/EvaluatedEntrypoint';\nexport type { IEvaluatedEntrypoint } from './transform/EvaluatedEntrypoint';\nexport { parseFile } from './transform/Entrypoint.helpers';\nexport type { LoadAndParseFn } from './transform/Entrypoint.types';\nexport { baseHandlers } from './transform/generators';\nexport { prepareCode } from './transform/generators/transform';\nexport { Entrypoint } from './transform/Entrypoint';\nexport { transformUrl } from './transform/generators/createStylisPreprocessor';\nexport {\n asyncResolveImports,\n syncResolveImports,\n} from './transform/generators/resolveImports';\nexport { loadWywOptions } from './transform/helpers/loadWywOptions';\nexport { withDefaultServices } from './transform/helpers/withDefaultServices';\nexport type { Services } from './transform/types';\nexport { EventEmitter } from './utils/EventEmitter';\nexport type {\n EntrypointEvent,\n OnEvent,\n OnActionStartArgs,\n OnActionFinishArgs,\n} from './utils/EventEmitter';\nexport { isNode } from './utils/isNode';\nexport { getFileIdx } from './utils/getFileIdx';\nexport { applyProcessors } from './utils/getTagProcessor';\nexport { getVisitorKeys } from './utils/getVisitorKeys';\nexport type { VisitorKeys } from './utils/getVisitorKeys';\nexport { peek } from './utils/peek';\nexport { TransformCacheCollection } from './cache';\nexport { findIdentifiers } from './utils/findIdentifiers';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAAAA,OAAA,GAAAC,OAAA;AAEA,IAAAC,aAAA,GAAAD,OAAA;AAEA,IAAAE,eAAA,GAAAC,sBAAA,CAAAH,OAAA;AACA,IAAAI,QAAA,GAAAD,sBAAA,CAAAH,OAAA;AACA,IAAAK,kBAAA,GAAAL,OAAA;AAKA,IAAAM,OAAA,GAAAN,OAAA;AACA,IAAAO,OAAA,GAAAJ,sBAAA,CAAAH,OAAA;AACA,IAAAQ,UAAA,GAAAR,OAAA;AACA,IAAAS,2BAAA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|
|
14
14
|
var _Entrypoint = require("./transform/Entrypoint");
|
|
15
15
|
var _Entrypoint2 = require("./transform/Entrypoint.helpers");
|
|
16
16
|
var _UnprocessedEntrypointError = require("./transform/actions/UnprocessedEntrypointError");
|
|
17
|
+
var _importOverrides = require("./utils/importOverrides");
|
|
18
|
+
var _parseRequest = require("./utils/parseRequest");
|
|
17
19
|
var _createVmContext = require("./vm/createVmContext");
|
|
18
|
-
function _interopRequireDefault(
|
|
20
|
+
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
|
|
19
21
|
/**
|
|
20
22
|
* This is a custom implementation for the module system for evaluating code,
|
|
21
23
|
* used for resolving values for dependencies interpolated in `css` or `styled`.
|
|
@@ -68,7 +70,31 @@ const builtins = {
|
|
|
68
70
|
vm: true,
|
|
69
71
|
zlib: true
|
|
70
72
|
};
|
|
73
|
+
const VITE_VIRTUAL_PREFIX = '/@';
|
|
74
|
+
const REACT_REFRESH_VIRTUAL_ID = '/@react-refresh';
|
|
75
|
+
const reactRefreshRuntime = {
|
|
76
|
+
createSignatureFunctionForTransform: () => () => {}
|
|
77
|
+
};
|
|
71
78
|
const NOOP = () => {};
|
|
79
|
+
const warnedUnknownImportsByServices = new WeakMap();
|
|
80
|
+
function emitWarning(services, message) {
|
|
81
|
+
if (services.emitWarning) {
|
|
82
|
+
services.emitWarning(message);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// eslint-disable-next-line no-console
|
|
87
|
+
console.warn(message);
|
|
88
|
+
}
|
|
89
|
+
function getWarnedUnknownImports(services) {
|
|
90
|
+
const cached = warnedUnknownImportsByServices.get(services);
|
|
91
|
+
if (cached) {
|
|
92
|
+
return cached;
|
|
93
|
+
}
|
|
94
|
+
const created = new Set();
|
|
95
|
+
warnedUnknownImportsByServices.set(services, created);
|
|
96
|
+
return created;
|
|
97
|
+
}
|
|
72
98
|
function getUncached(cached, test) {
|
|
73
99
|
const cachedSet = new Set(typeof cached === 'string' ? cached.split(',') : cached);
|
|
74
100
|
if (cachedSet.has('*')) {
|
|
@@ -83,10 +109,24 @@ function resolve(id) {
|
|
|
83
109
|
(0, _tsInvariant.invariant)(resolved, `Unable to resolve "${id}"`);
|
|
84
110
|
return resolved;
|
|
85
111
|
}
|
|
112
|
+
const defaultImportLoaders = {
|
|
113
|
+
raw: 'raw',
|
|
114
|
+
url: 'url'
|
|
115
|
+
};
|
|
86
116
|
class Module {
|
|
87
117
|
callstack = [];
|
|
88
118
|
isEvaluated = false;
|
|
89
119
|
require = Object.assign(id => {
|
|
120
|
+
if (id === REACT_REFRESH_VIRTUAL_ID) {
|
|
121
|
+
this.dependencies.push(id);
|
|
122
|
+
this.debug('require', `vite virtual '${id}'`);
|
|
123
|
+
return reactRefreshRuntime;
|
|
124
|
+
}
|
|
125
|
+
if (id.startsWith(VITE_VIRTUAL_PREFIX)) {
|
|
126
|
+
this.dependencies.push(id);
|
|
127
|
+
this.debug('require', `vite virtual '${id}'`);
|
|
128
|
+
return {};
|
|
129
|
+
}
|
|
90
130
|
if (id in builtins) {
|
|
91
131
|
// The module is in the allowed list of builtin node modules
|
|
92
132
|
// Ideally we should prevent importing them, but webpack polyfills some
|
|
@@ -105,6 +145,12 @@ class Module {
|
|
|
105
145
|
throw new Error(`Unable to import "${id}". Importing Node builtins is not supported in the sandbox.`);
|
|
106
146
|
}
|
|
107
147
|
(0, _tsInvariant.invariant)(dependency.resolved, `Dependency ${dependency.source} cannot be resolved`);
|
|
148
|
+
const loaded = this.loadByImportLoaders(id, dependency.resolved);
|
|
149
|
+
if (loaded.handled) {
|
|
150
|
+
this.dependencies.push(id);
|
|
151
|
+
this.debug('require', `${id} -> ${dependency.resolved} (loader)`);
|
|
152
|
+
return loaded.value;
|
|
153
|
+
}
|
|
108
154
|
this.dependencies.push(id);
|
|
109
155
|
this.debug('require', `${id} -> ${dependency.resolved}`);
|
|
110
156
|
const entrypoint = this.getEntrypoint(dependency.resolved, dependency.only, this.debug);
|
|
@@ -184,9 +230,7 @@ class Module {
|
|
|
184
230
|
this.debug('evaluate');
|
|
185
231
|
this.debug.extend('source')('%s', source);
|
|
186
232
|
this.isEvaluated = true;
|
|
187
|
-
const
|
|
188
|
-
filename
|
|
189
|
-
} = this;
|
|
233
|
+
const filename = (0, _parseRequest.stripQueryAndHash)(this.filename);
|
|
190
234
|
if (/\.json$/.test(filename)) {
|
|
191
235
|
// For JSON files, parse it to a JS object similar to Node
|
|
192
236
|
this.exports = JSON.parse(source);
|
|
@@ -199,7 +243,7 @@ class Module {
|
|
|
199
243
|
module: this,
|
|
200
244
|
exports: entrypoint.exports,
|
|
201
245
|
require: this.require,
|
|
202
|
-
__wyw_dynamic_import: async id => this.require(id),
|
|
246
|
+
__wyw_dynamic_import: async id => this.require(String(id)),
|
|
203
247
|
__dirname: _path.default.dirname(filename)
|
|
204
248
|
}, pluginOptions.overrideContext);
|
|
205
249
|
try {
|
|
@@ -228,7 +272,8 @@ class Module {
|
|
|
228
272
|
}
|
|
229
273
|
getEntrypoint(filename, only, log) {
|
|
230
274
|
var _entrypoint$evaluated;
|
|
231
|
-
const
|
|
275
|
+
const strippedFilename = (0, _parseRequest.stripQueryAndHash)(filename);
|
|
276
|
+
const extension = _path.default.extname(strippedFilename);
|
|
232
277
|
if (extension !== '.json' && !this.extensions.includes(extension)) {
|
|
233
278
|
return null;
|
|
234
279
|
}
|
|
@@ -243,31 +288,36 @@ class Module {
|
|
|
243
288
|
}
|
|
244
289
|
if (this.ignored) {
|
|
245
290
|
log('✅ one of the parent files has been ignored during prepare stage. Original code will be used');
|
|
246
|
-
const newEntrypoint = this.entrypoint.createChild(filename, ['*'], _fs.default.readFileSync(
|
|
291
|
+
const newEntrypoint = this.entrypoint.createChild(filename, ['*'], _fs.default.readFileSync(strippedFilename, 'utf-8'));
|
|
247
292
|
if (newEntrypoint === 'loop') {
|
|
248
293
|
const stack = (0, _Entrypoint2.getStack)(this.entrypoint);
|
|
249
294
|
throw new Error(`Circular dependency detected: ${stack.join(' -> ')} -> ${filename}`);
|
|
250
295
|
}
|
|
251
296
|
return newEntrypoint;
|
|
252
297
|
}
|
|
253
|
-
|
|
298
|
+
let uncachedExports = null;
|
|
299
|
+
let reprocessOnly = only;
|
|
254
300
|
// Requested file can be already prepared for evaluation on the stage 1
|
|
255
301
|
if (only && entrypoint) {
|
|
256
|
-
var _entrypoint$only;
|
|
257
|
-
const
|
|
302
|
+
var _entrypoint$evaluated2, _entrypoint$only, _entrypoint$evaluated3;
|
|
303
|
+
const evaluatedExports = ((_entrypoint$evaluated2 = entrypoint.evaluatedOnly) === null || _entrypoint$evaluated2 === void 0 ? void 0 : _entrypoint$evaluated2.length) !== 0 ? entrypoint.evaluatedOnly : (_entrypoint$only = entrypoint.only) !== null && _entrypoint$only !== void 0 ? _entrypoint$only : [];
|
|
304
|
+
uncachedExports = getUncached(evaluatedExports, only);
|
|
258
305
|
if (uncachedExports.length === 0) {
|
|
259
306
|
log('✅ ready for evaluation');
|
|
260
307
|
return entrypoint;
|
|
261
308
|
}
|
|
262
|
-
|
|
309
|
+
if ((_entrypoint$evaluated3 = entrypoint.evaluatedOnly) !== null && _entrypoint$evaluated3 !== void 0 && _entrypoint$evaluated3.length) {
|
|
310
|
+
reprocessOnly = (0, _Entrypoint2.mergeOnly)(evaluatedExports, only);
|
|
311
|
+
}
|
|
312
|
+
log('❌ file has been processed during prepare stage but %o is not evaluated yet (evaluated: %o)', uncachedExports, evaluatedExports);
|
|
263
313
|
} else {
|
|
264
314
|
log('❌ file has not been processed during prepare stage');
|
|
265
315
|
}
|
|
266
316
|
|
|
267
317
|
// If code wasn't extracted from cache, it indicates that we were unable
|
|
268
318
|
// to process some of the imports on stage1. Let's try to reprocess.
|
|
269
|
-
const code = _fs.default.readFileSync(
|
|
270
|
-
const newEntrypoint = _Entrypoint.Entrypoint.createRoot(this.services, filename,
|
|
319
|
+
const code = _fs.default.readFileSync(strippedFilename, 'utf-8');
|
|
320
|
+
const newEntrypoint = _Entrypoint.Entrypoint.createRoot(this.services, filename, reprocessOnly, code);
|
|
271
321
|
if (newEntrypoint.evaluated) {
|
|
272
322
|
log('✅ file has been already evaluated');
|
|
273
323
|
return newEntrypoint;
|
|
@@ -290,6 +340,7 @@ class Module {
|
|
|
290
340
|
const extensions = this.moduleImpl._extensions;
|
|
291
341
|
const added = [];
|
|
292
342
|
try {
|
|
343
|
+
var _this$services$option, _override$unknown;
|
|
293
344
|
// Check for supported extensions
|
|
294
345
|
this.extensions.forEach(ext => {
|
|
295
346
|
if (ext in extensions) {
|
|
@@ -305,15 +356,57 @@ class Module {
|
|
|
305
356
|
const {
|
|
306
357
|
filename
|
|
307
358
|
} = this;
|
|
308
|
-
const
|
|
359
|
+
const strippedId = (0, _parseRequest.stripQueryAndHash)(id);
|
|
360
|
+
let resolved = this.moduleImpl._resolveFilename(strippedId, {
|
|
309
361
|
id: filename,
|
|
310
362
|
filename,
|
|
311
363
|
paths: this.moduleImpl._nodeModulePaths(_path.default.dirname(filename))
|
|
312
364
|
});
|
|
365
|
+
const isFileSpecifier = strippedId.startsWith('.') || _path.default.isAbsolute(strippedId);
|
|
366
|
+
if (isFileSpecifier && _path.default.extname(strippedId) === '' && resolved.endsWith('.cjs') && _fs.default.existsSync(`${resolved.slice(0, -4)}.js`)) {
|
|
367
|
+
// When both `.cjs` and `.js` exist for an extensionless specifier, the
|
|
368
|
+
// resolver may pick `.cjs` depending on the environment/extensions.
|
|
369
|
+
// Prefer `.js` to keep resolved paths stable (e.g. importOverrides keys).
|
|
370
|
+
resolved = `${resolved.slice(0, -4)}.js`;
|
|
371
|
+
}
|
|
372
|
+
const {
|
|
373
|
+
root
|
|
374
|
+
} = this.services.options;
|
|
375
|
+
const keyInfo = (0, _importOverrides.toImportKey)({
|
|
376
|
+
source: id,
|
|
377
|
+
resolved,
|
|
378
|
+
root
|
|
379
|
+
});
|
|
380
|
+
const override = (_this$services$option = this.services.options.pluginOptions.importOverrides) === null || _this$services$option === void 0 ? void 0 : _this$services$option[keyInfo.key];
|
|
381
|
+
const policy = (_override$unknown = override === null || override === void 0 ? void 0 : override.unknown) !== null && _override$unknown !== void 0 ? _override$unknown : override !== null && override !== void 0 && override.mock ? 'allow' : 'warn';
|
|
382
|
+
const shouldWarn = !this.ignored && policy === 'warn';
|
|
383
|
+
let finalResolved = resolved;
|
|
384
|
+
if (override !== null && override !== void 0 && override.mock) {
|
|
385
|
+
try {
|
|
386
|
+
finalResolved = (0, _importOverrides.resolveMockSpecifier)({
|
|
387
|
+
mock: override.mock,
|
|
388
|
+
importer: filename,
|
|
389
|
+
root,
|
|
390
|
+
stack: this.callstack
|
|
391
|
+
});
|
|
392
|
+
} catch (e) {
|
|
393
|
+
var _message;
|
|
394
|
+
const errorMessage = String((_message = e === null || e === void 0 ? void 0 : e.message) !== null && _message !== void 0 ? _message : e);
|
|
395
|
+
throw new Error(`[wyw-in-js] Failed to resolve import mock for "${keyInfo.key}" (${id} from ${filename}): ${errorMessage}`);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
if (policy === 'error') {
|
|
399
|
+
throw new Error([`[wyw-in-js] Unknown import reached during eval (Node resolver fallback)`, ``, `importer: ${filename}`, `source: ${id}`, `resolved: ${resolved}`, override !== null && override !== void 0 && override.mock ? `mock: ${override.mock} -> ${finalResolved}` : ``, ``, `callstack:`, ...this.callstack.map(item => ` ${item}`), ``, `config key: ${keyInfo.key}`].filter(Boolean).join('\n'));
|
|
400
|
+
}
|
|
401
|
+
const warnedUnknownImports = getWarnedUnknownImports(this.services);
|
|
402
|
+
if (shouldWarn && !warnedUnknownImports.has(keyInfo.key)) {
|
|
403
|
+
warnedUnknownImports.add(keyInfo.key);
|
|
404
|
+
emitWarning(this.services, [`[wyw-in-js] Unknown import reached during eval (Node resolver fallback)`, ``, `importer: ${filename}`, `source: ${id}`, `resolved: ${resolved}`, override !== null && override !== void 0 && override.mock ? `mock: ${override.mock} -> ${finalResolved}` : ``, ``, `callstack:`, ...this.callstack.map(item => ` ${item}`), ``, `config key: ${keyInfo.key}`, `hint: add { importOverrides: { ${JSON.stringify(keyInfo.key)}: { unknown: 'allow' } } } to silence warnings, or use { mock } / { noShake: true } overrides.`].filter(Boolean).join('\n'));
|
|
405
|
+
}
|
|
313
406
|
return {
|
|
314
407
|
source: id,
|
|
315
|
-
only: ['*'],
|
|
316
|
-
resolved
|
|
408
|
+
only: (0, _importOverrides.applyImportOverrideToOnly)(['*'], override),
|
|
409
|
+
resolved: finalResolved
|
|
317
410
|
};
|
|
318
411
|
} finally {
|
|
319
412
|
// Cleanup the extensions we added to restore previous behaviour
|
|
@@ -323,6 +416,74 @@ class Module {
|
|
|
323
416
|
createChild(entrypoint) {
|
|
324
417
|
return new Module(this.services, entrypoint, this, this.moduleImpl);
|
|
325
418
|
}
|
|
419
|
+
loadByImportLoaders(request, resolved) {
|
|
420
|
+
const {
|
|
421
|
+
pluginOptions
|
|
422
|
+
} = this.services.options;
|
|
423
|
+
const importLoaders = pluginOptions.importLoaders === undefined ? defaultImportLoaders : {
|
|
424
|
+
...defaultImportLoaders,
|
|
425
|
+
...pluginOptions.importLoaders
|
|
426
|
+
};
|
|
427
|
+
const {
|
|
428
|
+
query,
|
|
429
|
+
hash
|
|
430
|
+
} = (0, _parseRequest.parseRequest)(request);
|
|
431
|
+
if (!query) return {
|
|
432
|
+
handled: false,
|
|
433
|
+
value: undefined
|
|
434
|
+
};
|
|
435
|
+
const params = new URLSearchParams(query);
|
|
436
|
+
const matchedKey = Array.from(params.keys()).find(key => importLoaders[key] !== undefined && importLoaders[key] !== false);
|
|
437
|
+
if (!matchedKey) return {
|
|
438
|
+
handled: false,
|
|
439
|
+
value: undefined
|
|
440
|
+
};
|
|
441
|
+
const loader = importLoaders[matchedKey];
|
|
442
|
+
const filename = (0, _parseRequest.stripQueryAndHash)(resolved);
|
|
443
|
+
const importer = (0, _parseRequest.stripQueryAndHash)(this.filename);
|
|
444
|
+
const importerDir = _path.default.dirname(importer);
|
|
445
|
+
const toUrl = () => {
|
|
446
|
+
const relative = _path.default.relative(importerDir, filename).replace(/\\/g, _path.default.posix.sep);
|
|
447
|
+
if (relative.startsWith('.') || _path.default.isAbsolute(relative)) {
|
|
448
|
+
return relative;
|
|
449
|
+
}
|
|
450
|
+
return `./${relative}`;
|
|
451
|
+
};
|
|
452
|
+
const readFile = () => _fs.default.readFileSync(filename, 'utf-8');
|
|
453
|
+
const context = {
|
|
454
|
+
importer,
|
|
455
|
+
request,
|
|
456
|
+
resolved,
|
|
457
|
+
filename,
|
|
458
|
+
query,
|
|
459
|
+
hash,
|
|
460
|
+
emitWarning: message => emitWarning(this.services, message),
|
|
461
|
+
readFile,
|
|
462
|
+
toUrl
|
|
463
|
+
};
|
|
464
|
+
if (loader === 'raw') {
|
|
465
|
+
return {
|
|
466
|
+
handled: true,
|
|
467
|
+
value: context.readFile()
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
if (loader === 'url') {
|
|
471
|
+
return {
|
|
472
|
+
handled: true,
|
|
473
|
+
value: context.toUrl()
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
if (typeof loader === 'function') {
|
|
477
|
+
return {
|
|
478
|
+
handled: true,
|
|
479
|
+
value: loader(context)
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
return {
|
|
483
|
+
handled: false,
|
|
484
|
+
value: undefined
|
|
485
|
+
};
|
|
486
|
+
}
|
|
326
487
|
}
|
|
327
488
|
exports.Module = Module;
|
|
328
489
|
//# sourceMappingURL=module.js.map
|