@rspack/core 2.0.8 → 2.1.0-beta.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/dist/index.js CHANGED
@@ -2,8 +2,8 @@ let _computedKey, _computedKey1, _computedKey2, createMd4, createXxhash64, servi
2
2
  import node_util, { inspect, promisify } from "node:util";
3
3
  import { createRequire, createRequire as __rspack_createRequire } from "node:module";
4
4
  import node_path, { isAbsolute, join, relative, resolve as external_node_path_resolve, sep } from "node:path";
5
- import node_querystring from "node:querystring";
6
5
  import node_fs, { readFileSync } from "node:fs";
6
+ import node_querystring from "node:querystring";
7
7
  import { __webpack_require__ } from "./612.js";
8
8
  let __rspack_createRequire_require = __rspack_createRequire(import.meta.url);
9
9
  import * as __rspack_external_node_util_1b29d436 from "node:util";
@@ -982,6 +982,9 @@ class ModuleGraph {
982
982
  getUsedExports(module, runtime) {
983
983
  return this.#inner.getUsedExports(module, runtime);
984
984
  }
985
+ getProvidedExports(module) {
986
+ return this.#inner.getProvidedExports(module);
987
+ }
985
988
  getParentModule(dependency) {
986
989
  return this.#inner.getParentModule(dependency);
987
990
  }
@@ -2922,18 +2925,25 @@ let unsupported = (name, issue)=>{
2922
2925
  return innerSubCache?.set(identifier, result), result;
2923
2926
  };
2924
2927
  }, cachedFn;
2925
- }, makePathsRelative = makeCacheableWithContext((context, identifier)=>identifier.split(SEGMENTS_SPLIT_REGEXP).map((str)=>absoluteToRequest(context, str)).join('')), contextify = makeCacheableWithContext((context, request)=>request.split('!').map((r)=>absoluteToRequest(context, r)).join('!')), absolutify = makeCacheableWithContext((context, request)=>request.split('!').map((r)=>r.startsWith('./') || r.startsWith('../') ? node_path.join(context, r) : r).join('!')), PATH_QUERY_FRAGMENT_REGEXP = /^((?:\u200b.|[^?#\u200b])*)(\?(?:\u200b.|[^#\u200b])*)?(#.*)?$/, PATH_QUERY_REGEXP = /^((?:\u200b.|[^?\u200b])*)(\?.*)?$/, parseResource = makeCacheable((str)=>{
2928
+ }, makePathsRelative = makeCacheableWithContext((context, identifier)=>identifier.split(SEGMENTS_SPLIT_REGEXP).map((str)=>absoluteToRequest(context, str)).join('')), contextify = makeCacheableWithContext((context, request)=>request.split('!').map((r)=>absoluteToRequest(context, r)).join('!')), absolutify = makeCacheableWithContext((context, request)=>request.split('!').map((r)=>r.startsWith('./') || r.startsWith('../') ? node_path.join(context, r) : r).join('!')), PATH_QUERY_FRAGMENT_REGEXP = /^((?:\u200b.|[^?#\u200b])*)(\?(?:\u200b.|[^#\u200b])*)?(#.*)?$/, PATH_QUERY_REGEXP = /^((?:\u200b.|[^?\u200b])*)(\?.*)?$/, parseResource = makeCacheable(function(str) {
2929
+ if (!str.includes('?') && !str.includes('#') && !str.includes('\u200b')) return {
2930
+ path: str,
2931
+ query: '',
2932
+ fragment: ''
2933
+ };
2926
2934
  let match = PATH_QUERY_FRAGMENT_REGEXP.exec(str);
2927
- return {
2928
- resource: str,
2935
+ return match ? {
2929
2936
  path: match[1].replace(/\u200b(.)/g, '$1'),
2930
2937
  query: match[2] ? match[2].replace(/\u200b(.)/g, '$1') : '',
2931
2938
  fragment: match[3] || ''
2939
+ } : {
2940
+ path: '',
2941
+ query: '',
2942
+ fragment: ''
2932
2943
  };
2933
2944
  }), parseResourceWithoutFragment = makeCacheable((str)=>{
2934
2945
  let match = PATH_QUERY_REGEXP.exec(str);
2935
2946
  return {
2936
- resource: str,
2937
2947
  path: match[1].replace(/\u200b(.)/g, '$1'),
2938
2948
  query: match[2] ? match[2].replace(/\u200b(.)/g, '$1') : ''
2939
2949
  };
@@ -3070,1912 +3080,1887 @@ function resolvePluginImport(pluginImport) {
3070
3080
  }), rawConfig;
3071
3081
  });
3072
3082
  }
3073
- let $assets = Symbol('assets');
3074
- Object.defineProperty(binding_default().KnownBuildInfo.prototype, node_util.inspect.custom, {
3075
- enumerable: !0,
3076
- configurable: !0,
3077
- value () {
3083
+ let BUILTIN_LOADER_PREFIX = 'builtin:';
3084
+ function createRawModuleRuleUses(uses, path, options) {
3085
+ var uses1, path1, options1;
3086
+ let normalizeRuleSetUseItem = (item)=>'string' == typeof item ? {
3087
+ loader: item
3088
+ } : item;
3089
+ return uses1 = Array.isArray(uses) ? [
3090
+ ...uses
3091
+ ].map(normalizeRuleSetUseItem) : [
3092
+ normalizeRuleSetUseItem(uses)
3093
+ ], path1 = path, options1 = options, uses1.length ? uses1.filter(Boolean).map((use, index)=>{
3094
+ let o, isBuiltin = !1;
3095
+ if (use.loader.startsWith(BUILTIN_LOADER_PREFIX)) {
3096
+ let temp = function(identifier, o, options) {
3097
+ if (identifier.startsWith(`${BUILTIN_LOADER_PREFIX}swc-loader`)) return ((o, composeOptions)=>{
3098
+ let options = o ?? {};
3099
+ if ('object' == typeof options) {
3100
+ var options1;
3101
+ if (options.jsc ??= {}, options.jsc.experimental ??= {}, options.jsc.experimental.disableAllLints ??= !0, options.env?.targets === void 0 && options.jsc?.target === void 0) {
3102
+ if (composeOptions.compiler.target?.targets) options.env ??= {}, options.env.targets ??= function(targets) {
3103
+ let REMAP = {
3104
+ and_chr: 'chrome',
3105
+ and_ff: 'firefox',
3106
+ ie_mob: 'ie',
3107
+ ios_saf: 'ios',
3108
+ op_mob: 'opera',
3109
+ and_qq: null,
3110
+ and_uc: null,
3111
+ baidu: null,
3112
+ bb: null,
3113
+ kaios: null,
3114
+ op_mini: null
3115
+ }, result = {};
3116
+ for (let [k, version] of Object.entries(targets)){
3117
+ let remap = REMAP[k];
3118
+ null !== remap && (result[remap || k] = version);
3119
+ }
3120
+ return result;
3121
+ }(composeOptions.compiler.target.targets);
3122
+ else if (composeOptions.compiler.target?.esVersion) {
3123
+ let { esVersion } = composeOptions.compiler.target;
3124
+ options.jsc.target ??= esVersion >= 2015 ? `es${esVersion}` : 'es5';
3125
+ }
3126
+ }
3127
+ options.collectTypeScriptInfo && (options.collectTypeScriptInfo = {
3128
+ typeExports: (options1 = options.collectTypeScriptInfo).typeExports,
3129
+ exportedEnum: !0 === options1.exportedEnum ? 'all' : !1 === options1.exportedEnum || void 0 === options1.exportedEnum ? 'none' : 'const-only'
3130
+ }), options.transformImport && (options.transformImport = resolvePluginImport(options.transformImport));
3131
+ let { rspackExperiments } = options;
3132
+ rspackExperiments && (rspackExperiments.import || rspackExperiments.pluginImport) && (rspackExperiments.import = resolvePluginImport(rspackExperiments.import || rspackExperiments.pluginImport));
3133
+ }
3134
+ return options;
3135
+ })(o, options);
3136
+ if (identifier.startsWith(`${BUILTIN_LOADER_PREFIX}lightningcss-loader`)) {
3137
+ let options1;
3138
+ return 'object' == typeof (options1 = o ?? {}) && ('string' == typeof options1.targets ? options1.targets = [
3139
+ options1.targets
3140
+ ] : 'object' != typeof options1.targets || Array.isArray(options1.targets) ? void 0 === options1.targets && options.compiler.target?.targets && (options1.targets = defaultTargetsFromRspackTargets(options.compiler.target.targets)) : options1.targets = encodeTargets(options1.targets), options1.include && 'object' == typeof options1.include && (options1.include = toFeatures(options1.include)), options1.exclude && 'object' == typeof options1.exclude && (options1.exclude = toFeatures(options1.exclude))), options1;
3141
+ }
3142
+ return o;
3143
+ }(use.loader, use.options, options1);
3144
+ o = isNil(temp) ? void 0 : 'string' == typeof temp ? temp : JSON.stringify(temp, null, 2), isBuiltin = !0;
3145
+ }
3078
3146
  return {
3079
- ...this,
3080
- assets: this.assets,
3081
- fileDependencies: this.fileDependencies,
3082
- contextDependencies: this.contextDependencies,
3083
- missingDependencies: this.missingDependencies,
3084
- buildDependencies: this.buildDependencies
3147
+ loader: function(use, path, compiler, isBuiltin) {
3148
+ let obj = parseResource(use.loader), ident = use.ident;
3149
+ null === use.options || void 0 === use.options || ('string' == typeof use.options ? obj.query = `?${use.options}` : use.ident ? obj.query = `??${ident = use.ident}` : 'object' == typeof use.options && use.options.ident ? obj.query = `??${ident = use.options.ident}` : 'object' == typeof use.options ? obj.query = `??${ident = path}` : obj.query = `?${JSON.stringify(use.options)}`);
3150
+ let parallelism = use.parallel;
3151
+ if (parallelism && (!use.options || 'object' != typeof use.options)) throw Error(`\`Rule.use.parallel\` requires \`Rule.use.options\` to be an object.\nHowever the received value is \`${use.options}\` under option path \`${path}\`\nInternally, parallelism is provided by passing \`Rule.use.ident\` to the loader as an identifier to ident the parallelism option\nYou can either replace the \`Rule.use.loader\` with \`Rule.use.options = {}\` or remove \`Rule.use.parallel\`.`);
3152
+ return use.options && 'object' == typeof use.options && (ident || (ident = '[[missing ident]]'), compiler.__internal__ruleSet.references.set(ident, use.options), compiler.__internal__ruleSet.references.set(`${ident}$$parallelism`, parallelism), isBuiltin && compiler.__internal__ruleSet.builtinReferences.set(ident, use.options)), obj.path + obj.query + obj.fragment;
3153
+ }(use, `${path1}[${index}]`, options1.compiler, isBuiltin),
3154
+ options: o
3085
3155
  };
3086
- }
3087
- }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'assets', {
3088
- enumerable: !0,
3089
- configurable: !0,
3090
- get () {
3091
- if (this[binding_default().BUILD_INFO_ASSETS_SYMBOL][$assets]) return this[binding_default().BUILD_INFO_ASSETS_SYMBOL][$assets];
3092
- let assets = new Proxy(Object.create(null), {
3093
- ownKeys: ()=>this[binding_default().BUILD_INFO_ASSETS_SYMBOL].keys(),
3094
- getOwnPropertyDescriptor: ()=>({
3095
- enumerable: !0,
3096
- configurable: !0
3097
- })
3098
- });
3099
- return Object.defineProperty(this[binding_default().BUILD_INFO_ASSETS_SYMBOL], $assets, {
3100
- enumerable: !1,
3101
- configurable: !0,
3102
- value: assets
3103
- }), assets;
3104
- }
3105
- }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'fileDependencies', {
3106
- enumerable: !0,
3107
- configurable: !0,
3108
- get () {
3109
- return new Set(this[binding_default().BUILD_INFO_FILE_DEPENDENCIES_SYMBOL]);
3110
- }
3111
- }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'contextDependencies', {
3112
- enumerable: !0,
3113
- configurable: !0,
3114
- get () {
3115
- return new Set(this[binding_default().BUILD_INFO_CONTEXT_DEPENDENCIES_SYMBOL]);
3116
- }
3117
- }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'missingDependencies', {
3118
- enumerable: !0,
3119
- configurable: !0,
3120
- get () {
3121
- return new Set(this[binding_default().BUILD_INFO_MISSING_DEPENDENCIES_SYMBOL]);
3122
- }
3123
- }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'buildDependencies', {
3124
- enumerable: !0,
3125
- configurable: !0,
3126
- get () {
3127
- return new Set(this[binding_default().BUILD_INFO_BUILD_DEPENDENCIES_SYMBOL]);
3128
- }
3129
- });
3130
- let knownBuildInfoFields = new Set([
3131
- 'assets',
3132
- 'fileDependencies',
3133
- 'contextDependencies',
3134
- 'missingDependencies',
3135
- 'buildDependencies'
3136
- ]);
3137
- Object.defineProperty(binding_default().NormalModule.prototype, 'identifier', {
3138
- enumerable: !0,
3139
- configurable: !0,
3140
- value () {
3141
- return this[binding_default().MODULE_IDENTIFIER_SYMBOL];
3142
- }
3143
- }), Object.defineProperty(binding_default().NormalModule.prototype, 'originalSource', {
3144
- enumerable: !0,
3145
- configurable: !0,
3146
- value () {
3147
- let originalSource = this._originalSource();
3148
- return originalSource ? SourceAdapter.fromBinding(originalSource) : null;
3149
- }
3150
- }), Object.defineProperty(binding_default().NormalModule.prototype, 'emitFile', {
3151
- enumerable: !0,
3152
- configurable: !0,
3153
- value (filename, source, assetInfo) {
3154
- return this._emitFile(filename, SourceAdapter.toBinding(source), assetInfo);
3155
- }
3156
- }), Object.defineProperty(binding_default().NormalModule, 'getCompilationHooks', {
3157
- enumerable: !0,
3158
- configurable: !0,
3159
- value (compilation) {
3160
- if (!(binding_default().COMPILATION_HOOKS_MAP_SYMBOL in compilation)) throw TypeError("The 'compilation' argument must be an instance of Compilation");
3161
- let compilationHooksMap = compilation[binding_default().COMPILATION_HOOKS_MAP_SYMBOL], hooks = compilationHooksMap.get(compilation);
3162
- return void 0 === hooks && (hooks = {
3163
- loader: new SyncHook([
3164
- 'loaderContext',
3165
- 'module'
3166
- ]),
3167
- readResource: new HookMap(()=>new AsyncSeriesBailHook([
3168
- 'loaderContext'
3169
- ]))
3170
- }, compilationHooksMap.set(compilation, hooks)), hooks;
3171
- }
3172
- });
3173
- class NonErrorEmittedError extends Error {
3174
- constructor(error){
3175
- super(), this.name = 'NonErrorEmittedError', this.message = `(Emitted value instead of an instance of Error) ${error}`;
3176
- }
3156
+ }) : [];
3177
3157
  }
3178
- class DeadlockRiskError extends Error {
3179
- constructor(message){
3180
- super(message), this.name = 'DeadlockRiskError', this.stack = '';
3181
- }
3158
+ function isUseSourceMap(devtool) {
3159
+ return !!devtool && devtool.includes('source-map') && (devtool.includes('module') || !devtool.includes('cheap'));
3182
3160
  }
3183
- class ValidationError extends Error {
3184
- constructor(message){
3185
- super(message), this.name = 'ValidationError';
3186
- }
3161
+ function getRawAlias(alias = {}) {
3162
+ return !('object' != typeof alias || null === alias || Array.isArray(alias)) && Object.entries(alias).map(([key, value])=>({
3163
+ path: key,
3164
+ redirect: Array.isArray(value) ? value : [
3165
+ value
3166
+ ]
3167
+ }));
3187
3168
  }
3188
- class JavaScriptTracer {
3189
- static state = 'uninitialized';
3190
- static startTime;
3191
- static events;
3192
- static layer;
3193
- static output;
3194
- static session;
3195
- static counter = 10000;
3196
- static async initJavaScriptTrace(layer, output) {
3197
- let { Session } = await import("node:inspector");
3198
- this.session = new Session(), this.layer = layer, this.output = output, this.events = [], this.state = 'on', this.startTime = process.hrtime.bigint();
3199
- }
3200
- static uuid() {
3201
- return this.counter++;
3202
- }
3203
- static initCpuProfiler() {
3204
- this.layer && (this.session.connect(), this.session.post('Profiler.enable'), this.session.post('Profiler.start'));
3169
+ function getRawResolve(resolve) {
3170
+ var byDependency;
3171
+ return {
3172
+ ...resolve,
3173
+ alias: getRawAlias(resolve.alias),
3174
+ fallback: getRawAlias(resolve.fallback),
3175
+ extensionAlias: function(alias = {}) {
3176
+ if ('object' == typeof alias && null !== alias) return Object.fromEntries(Object.entries(alias).map(([key, value])=>Array.isArray(value) ? [
3177
+ key,
3178
+ value
3179
+ ] : [
3180
+ key,
3181
+ [
3182
+ value
3183
+ ]
3184
+ ]));
3185
+ }(resolve.extensionAlias),
3186
+ tsconfig: function(tsConfig) {
3187
+ if ('string' == typeof tsConfig) throw Error('should resolve string tsConfig in normalization');
3188
+ if (void 0 === tsConfig) return tsConfig;
3189
+ let { configFile, references } = tsConfig;
3190
+ return {
3191
+ configFile,
3192
+ referencesType: 'auto' === references ? 'auto' : references ? 'manual' : 'disabled',
3193
+ references: 'auto' === references ? void 0 : references
3194
+ };
3195
+ }(resolve.tsConfig),
3196
+ byDependency: void 0 === (byDependency = resolve.byDependency) ? byDependency : Object.fromEntries(Object.entries(byDependency).map(([k, v])=>[
3197
+ k,
3198
+ getRawResolve(v)
3199
+ ]))
3200
+ };
3201
+ }
3202
+ function tryMatch(payload, condition) {
3203
+ if ('string' == typeof condition) return payload.startsWith(condition);
3204
+ if (condition instanceof RegExp) return condition.test(payload);
3205
+ if ('function' == typeof condition) return condition(payload);
3206
+ if (Array.isArray(condition)) return condition.some((c)=>tryMatch(payload, c));
3207
+ if (condition && 'object' == typeof condition) {
3208
+ if (condition.and) return condition.and.every((c)=>tryMatch(payload, c));
3209
+ if (condition.or) return condition.or.some((c)=>tryMatch(payload, c));
3210
+ if (condition.not) return !tryMatch(payload, condition.not);
3205
3211
  }
3206
- static async cleanupJavaScriptTrace() {
3207
- if ('uninitialized' === this.state) throw Error('JavaScriptTracer is not initialized, please call initJavaScriptTrace first');
3208
- if (!this.layer || 'off' === this.state) return;
3209
- let profileHandler = (err, param)=>{
3210
- let cpu_profile;
3211
- if (err ? console.error('Error stopping profiler:', err) : cpu_profile = param.profile, cpu_profile) {
3212
- let uuid = this.uuid();
3213
- this.pushEvent({
3214
- name: 'Profile',
3215
- ph: 'P',
3216
- trackName: 'JavaScript CPU Profiler',
3217
- processName: 'JavaScript CPU',
3218
- uuid,
3219
- ...this.getCommonEv(),
3220
- categories: [
3221
- 'disabled-by-default-v8.cpu_profiler'
3222
- ],
3223
- args: {
3224
- data: {
3225
- startTime: 0
3226
- }
3227
- }
3228
- }), this.pushEvent({
3229
- name: 'ProfileChunk',
3230
- ph: 'P',
3231
- trackName: 'JavaScript CPU Profiler',
3232
- processName: 'JavaScript CPU',
3233
- ...this.getCommonEv(),
3234
- categories: [
3235
- 'disabled-by-default-v8.cpu_profiler'
3236
- ],
3237
- uuid,
3238
- args: {
3239
- data: {
3240
- cpuProfile: cpu_profile,
3241
- timeDeltas: cpu_profile.timeDeltas
3212
+ return !1;
3213
+ }
3214
+ let getRawModuleRule = (rule, path, options, upperType)=>{
3215
+ let funcUse, normalizedUse = rule.loader ? [
3216
+ {
3217
+ loader: rule.loader,
3218
+ options: rule.options
3219
+ }
3220
+ ] : rule.use;
3221
+ 'function' == typeof normalizedUse && (funcUse = (rawContext)=>createRawModuleRuleUses(normalizedUse({
3222
+ ...rawContext,
3223
+ compiler: options.compiler
3224
+ }) ?? [], `${path}.use`, options));
3225
+ let rawModuleRule = {
3226
+ test: rule.test ? getRawRuleSetCondition(rule.test) : void 0,
3227
+ include: rule.include ? getRawRuleSetCondition(rule.include) : void 0,
3228
+ exclude: rule.exclude ? getRawRuleSetCondition(rule.exclude) : void 0,
3229
+ issuer: rule.issuer ? getRawRuleSetCondition(rule.issuer) : void 0,
3230
+ issuerLayer: rule.issuerLayer ? getRawRuleSetCondition(rule.issuerLayer) : void 0,
3231
+ dependency: rule.dependency ? getRawRuleSetCondition(rule.dependency) : void 0,
3232
+ phase: rule.phase ? getRawRuleSetCondition(rule.phase) : void 0,
3233
+ descriptionData: rule.descriptionData ? Object.fromEntries(Object.entries(rule.descriptionData).map(([k, v])=>[
3234
+ k,
3235
+ getRawRuleSetCondition(v)
3236
+ ])) : void 0,
3237
+ with: rule.with ? Object.fromEntries(Object.entries(rule.with).map(([k, v])=>[
3238
+ k,
3239
+ getRawRuleSetCondition(v)
3240
+ ])) : void 0,
3241
+ resource: rule.resource ? getRawRuleSetCondition(rule.resource) : void 0,
3242
+ resourceQuery: rule.resourceQuery ? getRawRuleSetCondition(rule.resourceQuery) : void 0,
3243
+ resourceFragment: rule.resourceFragment ? getRawRuleSetCondition(rule.resourceFragment) : void 0,
3244
+ scheme: rule.scheme ? getRawRuleSetCondition(rule.scheme) : void 0,
3245
+ mimetype: rule.mimetype ? getRawRuleSetCondition(rule.mimetype) : void 0,
3246
+ sideEffects: rule.sideEffects,
3247
+ use: 'function' == typeof normalizedUse ? funcUse : createRawModuleRuleUses(normalizedUse ?? [], `${path}.use`, options),
3248
+ type: rule.type,
3249
+ layer: rule.layer,
3250
+ parser: rule.parser ? getRawParserOptions(rule.parser, rule.type ?? upperType) : void 0,
3251
+ generator: rule.generator ? getRawGeneratorOptions(rule.generator, rule.type ?? upperType) : void 0,
3252
+ resolve: rule.resolve ? getRawResolve(rule.resolve) : void 0,
3253
+ oneOf: rule.oneOf ? rule.oneOf.filter(Boolean).map((rule, index)=>getRawModuleRule(rule, `${path}.oneOf[${index}]`, options, rule.type ?? upperType)) : void 0,
3254
+ rules: rule.rules ? rule.rules.filter(Boolean).map((rule, index)=>getRawModuleRule(rule, `${path}.rules[${index}]`, options, rule.type ?? upperType)) : void 0,
3255
+ enforce: rule.enforce,
3256
+ extractSourceMap: rule.extractSourceMap
3257
+ };
3258
+ return ('function' == typeof rule.test || 'function' == typeof rule.resource || 'function' == typeof rule.resourceQuery || 'function' == typeof rule.resourceFragment) && (delete rawModuleRule.test, delete rawModuleRule.resource, delete rawModuleRule.resourceQuery, delete rawModuleRule.resourceFragment, rawModuleRule.rspackResource = getRawRuleSetCondition((resourceQueryFragment)=>{
3259
+ let { path, query, fragment } = parseResource(resourceQueryFragment);
3260
+ return (!rule.test || !!tryMatch(path, rule.test)) && (!rule.resource || !!tryMatch(path, rule.resource)) && (!rule.resourceQuery || !!tryMatch(query, rule.resourceQuery)) && (!rule.resourceFragment || !!tryMatch(fragment, rule.resourceFragment));
3261
+ })), rawModuleRule;
3262
+ };
3263
+ function getRawRuleSetCondition(condition) {
3264
+ if ('string' == typeof condition) return {
3265
+ type: binding_namespaceObject.RawRuleSetConditionType.string,
3266
+ string: condition
3267
+ };
3268
+ if (condition instanceof RegExp) return {
3269
+ type: binding_namespaceObject.RawRuleSetConditionType.regexp,
3270
+ regexp: condition
3271
+ };
3272
+ if ('function' == typeof condition) return {
3273
+ type: binding_namespaceObject.RawRuleSetConditionType.func,
3274
+ func: condition
3275
+ };
3276
+ if (Array.isArray(condition)) return {
3277
+ type: binding_namespaceObject.RawRuleSetConditionType.array,
3278
+ array: condition.map((i)=>getRawRuleSetCondition(i))
3279
+ };
3280
+ if ('object' == typeof condition && null !== condition) {
3281
+ var logical;
3282
+ return {
3283
+ type: binding_namespaceObject.RawRuleSetConditionType.logical,
3284
+ logical: [
3285
+ {
3286
+ and: (logical = condition).and ? logical.and.map((i)=>getRawRuleSetCondition(i)) : void 0,
3287
+ or: logical.or ? logical.or.map((i)=>getRawRuleSetCondition(i)) : void 0,
3288
+ not: logical.not ? getRawRuleSetCondition(logical.not) : void 0
3289
+ }
3290
+ ]
3291
+ };
3292
+ }
3293
+ throw Error('unreachable: condition should be one of string, RegExp, Array, Object');
3294
+ }
3295
+ function getRawParserOptions(parser, type) {
3296
+ var parser1, parser2, parser3;
3297
+ if ('asset' === type) {
3298
+ return {
3299
+ type: 'asset',
3300
+ asset: {
3301
+ dataUrlCondition: (parser1 = parser).dataUrlCondition ? function(dataUrlCondition) {
3302
+ if ('object' == typeof dataUrlCondition && null !== dataUrlCondition) return {
3303
+ type: 'options',
3304
+ options: {
3305
+ maxSize: dataUrlCondition.maxSize
3242
3306
  }
3243
- }
3244
- });
3307
+ };
3308
+ throw Error(`unreachable: AssetParserDataUrl type should be one of "options", but got ${dataUrlCondition}`);
3309
+ }(parser1.dataUrlCondition) : void 0
3245
3310
  }
3246
3311
  };
3247
- await new Promise((resolve, reject)=>{
3248
- this.session.post('Profiler.stop', (err, params)=>{
3249
- if (err) reject(err);
3250
- else try {
3251
- profileHandler(err, params), resolve();
3252
- } catch (err) {
3253
- reject(err);
3254
- }
3255
- });
3256
- }), this.state = 'off';
3257
- }
3258
- static getTs() {
3259
- return process.hrtime.bigint() - this.startTime;
3260
3312
  }
3261
- static getCommonEv() {
3313
+ if ("javascript" === type) return {
3314
+ type: "javascript",
3315
+ javascript: getRawJavascriptParserOptions(parser)
3316
+ };
3317
+ if ("javascript/auto" === type) return {
3318
+ type: "javascript/auto",
3319
+ javascript: getRawJavascriptParserOptions(parser)
3320
+ };
3321
+ if ("javascript/dynamic" === type) return {
3322
+ type: "javascript/dynamic",
3323
+ javascript: getRawJavascriptParserOptions(parser)
3324
+ };
3325
+ if ("javascript/esm" === type) return {
3326
+ type: "javascript/esm",
3327
+ javascript: getRawJavascriptParserOptions(parser)
3328
+ };
3329
+ if ('css' === type) {
3262
3330
  return {
3263
- ts: this.getTs(),
3264
- cat: 'rspack'
3331
+ type: 'css',
3332
+ css: {
3333
+ namedExports: (parser2 = parser).namedExports,
3334
+ url: parser2.url,
3335
+ import: parser2.import,
3336
+ resolveImport: parser2.resolveImport
3337
+ }
3265
3338
  };
3266
3339
  }
3267
- static pushEvent(event) {
3268
- let stringifiedArgs = Object.keys(event.args || {}).reduce((acc, key)=>(acc[key] = JSON.stringify(event.args[key]), acc), {});
3269
- this.events.push({
3270
- ...event,
3271
- args: stringifiedArgs
3272
- });
3273
- }
3274
- static startAsync(events) {
3275
- this.layer && this.pushEvent({
3276
- ...this.getCommonEv(),
3277
- ...events,
3278
- ph: 'b'
3279
- });
3280
- }
3281
- static endAsync(events) {
3282
- this.layer && this.pushEvent({
3283
- ...this.getCommonEv(),
3284
- ...events,
3285
- ph: 'e'
3286
- });
3340
+ if ('css/auto' === type) return {
3341
+ type: 'css/auto',
3342
+ cssAuto: getRawCssAutoOrModuleParserOptions(parser)
3343
+ };
3344
+ if ('css/global' === type) return {
3345
+ type: 'css/global',
3346
+ cssGlobal: getRawCssModuleParserOptions(parser)
3347
+ };
3348
+ if ('css/module' === type) return {
3349
+ type: 'css/module',
3350
+ cssModule: getRawCssAutoOrModuleParserOptions(parser)
3351
+ };
3352
+ if ('json' === type) {
3353
+ return {
3354
+ type: 'json',
3355
+ json: {
3356
+ exportsDepth: (parser3 = parser).exportsDepth,
3357
+ parse: 'function' == typeof parser3.parse ? (str)=>JSON.stringify(parser3.parse(str)) : void 0
3358
+ }
3359
+ };
3287
3360
  }
3361
+ throw Error(`unreachable: unknown module type: ${type}`);
3288
3362
  }
3289
- let CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/;
3290
- function createMessage(method) {
3291
- return `Abstract method${method ? ` ${method}` : ''}. Must be overridden.`;
3292
- }
3293
- class Message extends Error {
3294
- constructor(){
3295
- super(), this.stack = void 0, Error.captureStackTrace(this);
3296
- let match = this.stack.split('\n')[3].match(CURRENT_METHOD_REGEXP);
3297
- this.message = match?.[1] ? createMessage(match[1]) : createMessage();
3298
- }
3363
+ function getRawJavascriptParserOptions(parser) {
3364
+ return {
3365
+ dynamicImportMode: parser.dynamicImportMode,
3366
+ dynamicImportPreload: parser.dynamicImportPreload?.toString(),
3367
+ dynamicImportPrefetch: parser.dynamicImportPrefetch?.toString(),
3368
+ dynamicImportFetchPriority: parser.dynamicImportFetchPriority,
3369
+ importMeta: 'boolean' == typeof parser.importMeta ? String(parser.importMeta) : parser.importMeta,
3370
+ url: parser.url?.toString(),
3371
+ exprContextCritical: parser.exprContextCritical,
3372
+ unknownContextCritical: parser.unknownContextCritical,
3373
+ wrappedContextCritical: parser.wrappedContextCritical,
3374
+ strictThisContextOnImports: parser.strictThisContextOnImports,
3375
+ wrappedContextRegExp: parser.wrappedContextRegExp,
3376
+ exportsPresence: !1 === parser.exportsPresence ? 'false' : parser.exportsPresence,
3377
+ importExportsPresence: !1 === parser.importExportsPresence ? 'false' : parser.importExportsPresence,
3378
+ reexportExportsPresence: !1 === parser.reexportExportsPresence ? 'false' : parser.reexportExportsPresence,
3379
+ worker: 'boolean' == typeof parser.worker ? parser.worker ? [
3380
+ '...'
3381
+ ] : [] : parser.worker,
3382
+ overrideStrict: parser.overrideStrict,
3383
+ requireAsExpression: parser.requireAsExpression,
3384
+ requireAlias: parser.requireAlias,
3385
+ requireDynamic: parser.requireDynamic,
3386
+ requireResolve: parser.requireResolve,
3387
+ commonjs: parser.commonjs,
3388
+ importDynamic: parser.importDynamic,
3389
+ commonjsMagicComments: parser.commonjsMagicComments,
3390
+ createRequire: parser.createRequire,
3391
+ typeReexportsPresence: parser.typeReexportsPresence,
3392
+ jsx: parser.jsx,
3393
+ deferImport: parser.deferImport,
3394
+ sourceImport: parser.sourceImport,
3395
+ importMetaResolve: parser.importMetaResolve,
3396
+ pureFunctions: parser.pureFunctions
3397
+ };
3299
3398
  }
3300
- class AbstractMethodError extends lib_WebpackError {
3301
- constructor(){
3302
- super(new Message().message), this.name = 'AbstractMethodError';
3303
- }
3399
+ function getRawCssModuleParserOptions(parser) {
3400
+ return {
3401
+ namedExports: parser.namedExports,
3402
+ url: parser.url,
3403
+ import: parser.import,
3404
+ resolveImport: parser.resolveImport,
3405
+ animation: parser.animation,
3406
+ container: parser.container,
3407
+ customIdents: parser.customIdents,
3408
+ dashedIdents: parser.dashedIdents,
3409
+ function: parser.function,
3410
+ grid: parser.grid
3411
+ };
3304
3412
  }
3305
- class Hash {
3306
- update() {
3307
- throw new AbstractMethodError();
3308
- }
3309
- digest() {
3310
- throw new AbstractMethodError();
3311
- }
3413
+ function getRawCssAutoOrModuleParserOptions(parser) {
3414
+ return {
3415
+ ...getRawCssModuleParserOptions(parser),
3416
+ pure: parser.pure
3417
+ };
3312
3418
  }
3313
- let MAX_SHORT_STRING = -4 & Math.floor(16368);
3314
- class WasmHash {
3315
- exports;
3316
- instancesPool;
3317
- buffered;
3318
- mem;
3319
- chunkSize;
3320
- digestSize;
3321
- constructor(instance, instancesPool, chunkSize, digestSize){
3322
- let exports = instance.exports;
3323
- exports.init(), this.exports = exports, this.mem = Buffer.from(exports.memory.buffer, 0, 65536), this.buffered = 0, this.instancesPool = instancesPool, this.chunkSize = chunkSize, this.digestSize = digestSize;
3324
- }
3325
- reset() {
3326
- this.buffered = 0, this.exports.init();
3327
- }
3328
- update(data, encoding) {
3329
- if ('string' == typeof data) {
3330
- let normalizedData = data;
3331
- for(; normalizedData.length > MAX_SHORT_STRING;)this._updateWithShortString(normalizedData.slice(0, MAX_SHORT_STRING), encoding), normalizedData = normalizedData.slice(MAX_SHORT_STRING);
3332
- return this._updateWithShortString(normalizedData, encoding), this;
3333
- }
3334
- return this._updateWithBuffer(data), this;
3419
+ function getRawGeneratorOptions(generator, type) {
3420
+ var options, options1;
3421
+ if ('asset' === type) {
3422
+ return {
3423
+ type: 'asset',
3424
+ asset: generator ? {
3425
+ ...getRawAssetInlineGeneratorOptions(options = generator),
3426
+ ...getRawAssetResourceGeneratorOptions(options)
3427
+ } : void 0
3428
+ };
3335
3429
  }
3336
- _updateWithShortString(data, encoding) {
3337
- let endPos, { exports, buffered, mem, chunkSize } = this;
3338
- if (data.length < 70) if (encoding && 'utf-8' !== encoding && 'utf8' !== encoding) if ('latin1' === encoding) {
3339
- endPos = buffered;
3340
- for(let i = 0; i < data.length; i++){
3341
- let cc = data.charCodeAt(i);
3342
- mem[endPos++] = cc;
3343
- }
3344
- } else endPos = buffered + mem.write(data, buffered, encoding);
3345
- else {
3346
- endPos = buffered;
3347
- for(let i = 0; i < data.length; i++){
3348
- let cc = data.charCodeAt(i);
3349
- if (cc < 0x80) mem[endPos++] = cc;
3350
- else if (cc < 0x800) mem[endPos] = cc >> 6 | 0xc0, mem[endPos + 1] = 0x3f & cc | 0x80, endPos += 2;
3351
- else {
3352
- endPos += mem.write(data.slice(i), endPos, encoding);
3353
- break;
3354
- }
3430
+ if ('asset/inline' === type) return {
3431
+ type: 'asset/inline',
3432
+ assetInline: generator ? getRawAssetInlineGeneratorOptions(generator) : void 0
3433
+ };
3434
+ if ('asset/resource' === type) return {
3435
+ type: 'asset/resource',
3436
+ assetResource: generator ? getRawAssetResourceGeneratorOptions(generator) : void 0
3437
+ };
3438
+ if ('css' === type) {
3439
+ return {
3440
+ type: 'css',
3441
+ css: {
3442
+ exportsOnly: (options1 = generator).exportsOnly,
3443
+ esModule: options1.esModule
3355
3444
  }
3356
- }
3357
- else endPos = buffered + mem.write(data, buffered, encoding);
3358
- if (endPos < chunkSize) this.buffered = endPos;
3359
- else {
3360
- let l = endPos & ~(this.chunkSize - 1);
3361
- exports.update(l);
3362
- let newBuffered = endPos - l;
3363
- this.buffered = newBuffered, newBuffered > 0 && mem.copyWithin(0, l, endPos);
3364
- }
3445
+ };
3365
3446
  }
3366
- _updateWithBuffer(data) {
3367
- let { exports, buffered, mem } = this, length = data.length;
3368
- if (buffered + length < this.chunkSize) data.copy(mem, buffered, 0, length), this.buffered += length;
3369
- else {
3370
- let l = buffered + length & ~(this.chunkSize - 1);
3371
- if (l > 65536) {
3372
- let i = 65536 - buffered;
3373
- data.copy(mem, buffered, 0, i), exports.update(65536);
3374
- let stop = l - buffered - 65536;
3375
- for(; i < stop;)data.copy(mem, 0, i, i + 65536), exports.update(65536), i += 65536;
3376
- data.copy(mem, 0, i, l - buffered), exports.update(l - buffered - i);
3377
- } else data.copy(mem, buffered, 0, l - buffered), exports.update(l);
3378
- let newBuffered = length + buffered - l;
3379
- this.buffered = newBuffered, newBuffered > 0 && data.copy(mem, 0, length - newBuffered, length);
3447
+ if ('css/auto' === type) return {
3448
+ type: 'css/auto',
3449
+ cssAuto: getRawCssAutoOrModuleGeneratorOptions(generator)
3450
+ };
3451
+ if ('css/global' === type) return {
3452
+ type: 'css/global',
3453
+ cssGlobal: getRawCssAutoOrModuleGeneratorOptions(generator)
3454
+ };
3455
+ if ('css/module' === type) return {
3456
+ type: 'css/module',
3457
+ cssModule: getRawCssAutoOrModuleGeneratorOptions(generator)
3458
+ };
3459
+ if ('json' === type) return {
3460
+ type: 'json',
3461
+ json: {
3462
+ JSONParse: generator.JSONParse
3380
3463
  }
3381
- }
3382
- digest(type) {
3383
- let { exports, buffered, mem, digestSize } = this;
3384
- exports.final(buffered), this.instancesPool.push(this);
3385
- let hex = mem.toString('latin1', 0, digestSize);
3386
- return 'hex' === type ? hex : 'binary' !== type && type ? Buffer.from(hex, 'hex').toString(type) : Buffer.from(hex, 'hex');
3387
- }
3464
+ };
3465
+ if (![
3466
+ 'asset/source',
3467
+ 'asset/bytes',
3468
+ "javascript",
3469
+ "javascript/auto",
3470
+ "javascript/dynamic",
3471
+ "javascript/esm"
3472
+ ].includes(type)) throw Error(`unreachable: unknown module type: ${type}`);
3388
3473
  }
3389
- let wasm_hash = (wasmModule, instancesPool, chunkSize, digestSize)=>{
3390
- if (instancesPool.length > 0) {
3391
- let old = instancesPool.pop();
3392
- return old.reset(), old;
3393
- }
3394
- return new WasmHash(new WebAssembly.Instance(wasmModule), instancesPool, chunkSize, digestSize);
3395
- }, createHash_require = createRequire(import.meta.url), digestCaches = {};
3396
- class BulkUpdateDecorator extends Hash {
3397
- hash;
3398
- hashFactory;
3399
- hashKey;
3400
- buffer;
3401
- constructor(hashOrFactory, hashKey){
3402
- super(), this.hashKey = hashKey, 'function' == typeof hashOrFactory ? (this.hashFactory = hashOrFactory, this.hash = void 0) : (this.hashFactory = void 0, this.hash = hashOrFactory), this.buffer = '';
3403
- }
3404
- update(data, inputEncoding) {
3405
- return void 0 !== inputEncoding || 'string' != typeof data || data.length > 2000 ? (void 0 === this.hash && (this.hash = this.hashFactory()), this.buffer.length > 0 && (this.hash.update(Buffer.from(this.buffer)), this.buffer = ''), Buffer.isBuffer(data) ? this.hash.update(data) : this.hash.update(data, inputEncoding)) : (this.buffer += data, this.buffer.length > 2000 && (void 0 === this.hash && (this.hash = this.hashFactory()), this.hash.update(Buffer.from(this.buffer)), this.buffer = '')), this;
3406
- }
3407
- digest(encoding) {
3408
- let digestCache, buffer = this.buffer;
3409
- if (void 0 === this.hash) {
3410
- let cacheKey = `${this.hashKey}-${encoding}`;
3411
- void 0 === (digestCache = digestCaches[cacheKey]) && (digestCache = digestCaches[cacheKey] = new Map());
3412
- let cacheEntry = digestCache.get(buffer);
3413
- if (void 0 !== cacheEntry) return encoding ? cacheEntry : Buffer.from(cacheEntry, 'hex');
3414
- this.hash = this.hashFactory();
3415
- }
3416
- buffer.length > 0 && this.hash.update(Buffer.from(buffer));
3417
- let result = encoding ? this.hash.digest(encoding) : this.hash.digest();
3418
- return void 0 !== digestCache && 'string' == typeof result && digestCache.set(buffer, result), result;
3419
- }
3474
+ function getRawAssetInlineGeneratorOptions(options) {
3475
+ return {
3476
+ dataUrl: options.dataUrl ? function(dataUrl) {
3477
+ if ('object' == typeof dataUrl && null !== dataUrl) return {
3478
+ encoding: !1 === dataUrl.encoding ? 'false' : dataUrl.encoding,
3479
+ mimetype: dataUrl.mimetype
3480
+ };
3481
+ if ('function' == typeof dataUrl && null !== dataUrl) return (source, context)=>dataUrl(source, context);
3482
+ throw Error(`unreachable: AssetGeneratorDataUrl type should be one of "options", "function", but got ${dataUrl}`);
3483
+ }(options.dataUrl) : void 0,
3484
+ binary: options.binary
3485
+ };
3420
3486
  }
3421
- class WasmHashAdapter extends Hash {
3422
- wasmHash;
3423
- constructor(wasmHash){
3424
- super(), this.wasmHash = wasmHash;
3487
+ function getRawAssetResourceGeneratorOptions(options) {
3488
+ return {
3489
+ emit: options.emit,
3490
+ filename: options.filename,
3491
+ outputPath: options.outputPath,
3492
+ publicPath: options.publicPath,
3493
+ importMode: options.importMode,
3494
+ binary: options.binary
3495
+ };
3496
+ }
3497
+ function getRawCssAutoOrModuleGeneratorOptions(options) {
3498
+ return {
3499
+ localIdentName: options.localIdentName,
3500
+ localIdentHashDigest: options.localIdentHashDigest,
3501
+ localIdentHashDigestLength: options.localIdentHashDigestLength,
3502
+ localIdentHashFunction: options.localIdentHashFunction,
3503
+ localIdentHashSalt: options.localIdentHashSalt,
3504
+ exportsConvention: options.exportsConvention,
3505
+ exportsOnly: options.exportsOnly,
3506
+ esModule: options.esModule
3507
+ };
3508
+ }
3509
+ class ExternalsPlugin extends RspackBuiltinPlugin {
3510
+ type;
3511
+ externals;
3512
+ placeInInitial;
3513
+ fallbackType;
3514
+ name = binding_namespaceObject.BuiltinPluginName.ExternalsPlugin;
3515
+ #resolveRequestCache = new Map();
3516
+ constructor(type, externals, placeInInitial, fallbackType){
3517
+ super(), this.type = type, this.externals = externals, this.placeInInitial = placeInInitial, this.fallbackType = fallbackType;
3425
3518
  }
3426
- update(data, inputEncoding) {
3427
- return Buffer.isBuffer(data) ? this.wasmHash.update(data) : this.wasmHash.update(data, inputEncoding), this;
3519
+ raw() {
3520
+ let type = this.type, externals = this.externals, raw = {
3521
+ type,
3522
+ fallbackType: this.fallbackType,
3523
+ externals: (Array.isArray(externals) ? externals : [
3524
+ externals
3525
+ ]).filter(Boolean).map((item)=>this.#getRawExternalItem(item)),
3526
+ placeInInitial: this.placeInInitial ?? !1
3527
+ };
3528
+ return createBuiltinPlugin(this.name, raw);
3428
3529
  }
3429
- digest(encoding) {
3430
- return encoding ? this.wasmHash.digest(encoding) : this.wasmHash.digest();
3530
+ #processResolveResult = (text)=>{
3531
+ if (!text) return;
3532
+ let resolveRequest = this.#resolveRequestCache.get(text);
3533
+ return resolveRequest || (resolveRequest = JSON.parse(text), this.#resolveRequestCache.set(text, resolveRequest)), Object.assign({}, resolveRequest);
3534
+ };
3535
+ #processRequest(req) {
3536
+ return `${req.path.replace(/#/g, '\u200b#')}${req.query.replace(/#/g, '\u200b#')}${req.fragment}`;
3431
3537
  }
3432
- }
3433
- let createHash_createHash = (algorithm)=>{
3434
- if ('function' == typeof algorithm) return new BulkUpdateDecorator(()=>new algorithm());
3435
- switch(algorithm){
3436
- case 'xxhash64':
3437
- return new WasmHashAdapter((()=>{
3438
- if (!createXxhash64) {
3439
- let xxhash64 = new WebAssembly.Module(Buffer.from('AGFzbQEAAAABCAJgAX8AYAAAAwQDAQAABQMBAAEGGgV+AUIAC34BQgALfgFCAAt+AUIAC34BQgALByIEBGluaXQAAAZ1cGRhdGUAAQVmaW5hbAACBm1lbW9yeQIACrIIAzAAQtbrgu7q/Yn14AAkAELP1tO+0ser2UIkAUIAJAJC+erQ0OfJoeThACQDQgAkBAvUAQIBfwR+IABFBEAPCyMEIACtfCQEIwAhAiMBIQMjAiEEIwMhBQNAIAIgASkDAELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiECIAMgASkDCELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEDIAQgASkDEELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEEIAUgASkDGELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEFIAAgAUEgaiIBSw0ACyACJAAgAyQBIAQkAiAFJAMLqAYCAX8EfiMEQgBSBH4jACICQgGJIwEiA0IHiXwjAiIEQgyJfCMDIgVCEol8IAJCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0gA0LP1tO+0ser2UJ+Qh+JQoeVr6+Ytt6bnn9+hUKHla+vmLbem55/fkKdo7Xqg7GNivoAfSAEQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IAVCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0FQsXP2bLx5brqJwsjBCAArXx8IQIDQCABQQhqIABNBEAgAiABKQMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQhuJQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IQIgAUEIaiEBDAELCyABQQRqIABNBEAgAiABNQIAQoeVr6+Ytt6bnn9+hUIXiULP1tO+0ser2UJ+Qvnz3fGZ9pmrFnwhAiABQQRqIQELA0AgACABRwRAIAIgATEAAELFz9my8eW66id+hUILiUKHla+vmLbem55/fiECIAFBAWohAQwBCwtBACACIAJCIYiFQs/W077Sx6vZQn4iAkIdiCAChUL5893xmfaZqxZ+IgJCIIggAoUiAkIgiCIDQv//A4NCIIYgA0KAgPz/D4NCEIiEIgNC/4GAgPAfg0IQhiADQoD+g4CA4D+DQgiIhCIDQo+AvIDwgcAHg0IIhiADQvCBwIeAnoD4AINCBIiEIgNChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IANCsODAgYOGjJgwhHw3AwBBCCACQv////8PgyICQv//A4NCIIYgAkKAgPz/D4NCEIiEIgJC/4GAgPAfg0IQhiACQoD+g4CA4D+DQgiIhCICQo+AvIDwgcAHg0IIhiACQvCBwIeAnoD4AINCBIiEIgJChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IAJCsODAgYOGjJgwhHw3AwAL', 'base64'));
3440
- createXxhash64 = wasm_hash.bind(null, xxhash64, [], 32, 16);
3441
- }
3442
- return createXxhash64();
3443
- })());
3444
- case 'md4':
3445
- return new WasmHashAdapter((()=>{
3446
- if (!createMd4) {
3447
- let md4 = new WebAssembly.Module(Buffer.from('AGFzbQEAAAABCAJgAX8AYAAAAwUEAQAAAAUDAQABBhoFfwFBAAt/AUEAC38BQQALfwFBAAt/AUEACwciBARpbml0AAAGdXBkYXRlAAIFZmluYWwAAwZtZW1vcnkCAAqLEAQmAEGBxpS6BiQBQYnXtv5+JAJB/rnrxXkkA0H2qMmBASQEQQAkAAvSCgEZfyMBIQUjAiECIwMhAyMEIQQDQCAAIAFLBEAgASgCJCISIAEoAiAiEyABKAIcIgkgASgCGCIIIAEoAhQiByABKAIQIg4gASgCDCIGIAEoAggiDyABKAIEIhAgASgCACIRIAMgBHMgAnEgBHMgBWpqQQN3IgogAiADc3EgA3MgBGpqQQd3IgsgAiAKc3EgAnMgA2pqQQt3IgwgCiALc3EgCnMgAmpqQRN3Ig0gCyAMc3EgC3MgCmpqQQN3IgogDCANc3EgDHMgC2pqQQd3IgsgCiANc3EgDXMgDGpqQQt3IgwgCiALc3EgCnMgDWpqQRN3Ig0gCyAMc3EgC3MgCmpqQQN3IhQgDCANc3EgDHMgC2pqQQd3IRUgASgCLCILIAEoAigiCiAMIA0gDSAUcyAVcXNqakELdyIWIBQgFXNxIBRzIA1qakETdyEXIAEoAjQiGCABKAIwIhkgFSAWcyAXcSAVcyAUampBA3ciFCAWIBdzcSAWcyAVampBB3chFSABKAI8Ig0gASgCOCIMIBQgF3MgFXEgF3MgFmpqQQt3IhYgFCAVc3EgFHMgF2pqQRN3IRcgEyAOIBEgFCAVIBZyIBdxIBUgFnFyampBmfOJ1AVqQQN3IhQgFiAXcnEgFiAXcXIgFWpqQZnzidQFakEFdyIVIBQgF3JxIBQgF3FyIBZqakGZ84nUBWpBCXchFiAPIBggEiAWIAcgFSAQIBQgGSAUIBVyIBZxIBQgFXFyIBdqakGZ84nUBWpBDXciFCAVIBZycSAVIBZxcmpqQZnzidQFakEDdyIVIBQgFnJxIBQgFnFyampBmfOJ1AVqQQV3IhcgFCAVcnEgFCAVcXJqakGZ84nUBWpBCXciFiAVIBdycSAVIBdxciAUampBmfOJ1AVqQQ13IhQgFiAXcnEgFiAXcXIgFWpqQZnzidQFakEDdyEVIBEgBiAVIAwgFCAKIBYgCCAUIBZyIBVxIBQgFnFyIBdqakGZ84nUBWpBBXciFyAUIBVycSAUIBVxcmpqQZnzidQFakEJdyIWIBUgF3JxIBUgF3FyampBmfOJ1AVqQQ13IhQgFiAXcnEgFiAXcXJqakGZ84nUBWpBA3ciFSALIBYgCSAUIBZyIBVxIBQgFnFyIBdqakGZ84nUBWpBBXciFiAUIBVycSAUIBVxcmpqQZnzidQFakEJdyIXIA0gFSAWciAXcSAVIBZxciAUampBmfOJ1AVqQQ13IhRzIBZzampBodfn9gZqQQN3IREgByAIIA4gFCARIBcgESAUc3MgFmogE2pBodfn9gZqQQl3IhNzcyAXampBodfn9gZqQQt3Ig4gDyARIBMgDiARIA4gE3NzIBRqIBlqQaHX5/YGakEPdyIRc3NqakGh1+f2BmpBA3ciDyAOIA8gEXNzIBNqIApqQaHX5/YGakEJdyIKcyARc2pqQaHX5/YGakELdyIIIBAgDyAKIAggDCAPIAggCnNzIBFqakGh1+f2BmpBD3ciDHNzampBodfn9gZqQQN3Ig4gEiAIIAwgDnNzIApqakGh1+f2BmpBCXciCHMgDHNqakGh1+f2BmpBC3chByAFIAYgCCAHIBggDiAHIAhzcyAMampBodfn9gZqQQ93IgpzcyAOampBodfn9gZqQQN3IgZqIQUgDSAGIAkgByAGIAsgByAGIApzcyAIampBodfn9gZqQQl3IgdzIApzampBodfn9gZqQQt3IgYgB3NzIApqakGh1+f2BmpBD3cgAmohAiADIAZqIQMgBCAHaiEEIAFBQGshAQwBCwsgBSQBIAIkAiADJAMgBCQECw0AIAAQASAAIwBqJAAL/wQCA38BfiAAIwBqrUIDhiEEIABByABqQUBxIgJBCGshAyAAIgFBAWohACABQYABOgAAA0AgACACSUEAIABBB3EbBEAgAEEAOgAAIABBAWohAAwBCwsDQCAAIAJJBEAgAEIANwMAIABBCGohAAwBCwsgAyAENwMAIAIQAUEAIwGtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIwKtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEQIwOtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEYIwStIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAAs=', 'base64'));
3448
- createMd4 = wasm_hash.bind(null, md4, [], 64, 32);
3449
- }
3450
- return createMd4();
3451
- })());
3452
- case 'native-md4':
3453
- return new BulkUpdateDecorator(()=>{
3454
- let { createHash } = createHash_require('node:crypto');
3455
- return createHash('md4');
3456
- }, 'md4');
3457
- default:
3458
- return new BulkUpdateDecorator(()=>{
3459
- let { createHash } = createHash_require('node:crypto');
3460
- return createHash(algorithm);
3461
- }, algorithm);
3538
+ #getRawExternalItem = (item)=>{
3539
+ if ('string' == typeof item || item instanceof RegExp) return item;
3540
+ if ('function' == typeof item) {
3541
+ let processResolveResult = this.#processResolveResult;
3542
+ return async (ctx)=>new Promise((resolve, reject)=>{
3543
+ let data = ctx.data(), promise = item({
3544
+ request: data.request,
3545
+ dependencyType: data.dependencyType,
3546
+ context: data.context,
3547
+ contextInfo: {
3548
+ issuer: data.contextInfo.issuer,
3549
+ issuerLayer: data.contextInfo.issuerLayer ?? null
3550
+ },
3551
+ getResolve: (options)=>{
3552
+ let rawResolve = options ? getRawResolve(options) : void 0, resolve = ctx.getResolve(rawResolve);
3553
+ return (context, request, callback)=>{
3554
+ if (!callback) return new Promise((promiseResolve, promiseReject)=>{
3555
+ resolve(context, request, (error, text)=>{
3556
+ if (error) promiseReject(error);
3557
+ else {
3558
+ let req = processResolveResult(text);
3559
+ promiseResolve(req ? this.#processRequest(req) : void 0);
3560
+ }
3561
+ });
3562
+ });
3563
+ resolve(context, request, (error, text)=>{
3564
+ if (error) callback(error);
3565
+ else {
3566
+ let req = processResolveResult(text);
3567
+ callback(null, !!req && this.#processRequest(req), req);
3568
+ }
3569
+ });
3570
+ };
3571
+ }
3572
+ }, (err, result, type)=>{
3573
+ err && reject(err), resolve({
3574
+ result: getRawExternalItemValueFormFnResult(result),
3575
+ externalType: type
3576
+ });
3577
+ });
3578
+ promise?.then ? promise.then((result)=>resolve({
3579
+ result: getRawExternalItemValueFormFnResult(result),
3580
+ externalType: void 0
3581
+ }), (e)=>reject(e)) : 1 === item.length && resolve({
3582
+ result: getRawExternalItemValueFormFnResult(promise),
3583
+ externalType: void 0
3584
+ });
3585
+ });
3586
+ }
3587
+ if ('object' == typeof item) return Object.fromEntries(Object.entries(item).map(([k, v])=>[
3588
+ k,
3589
+ getRawExternalItemValue(v)
3590
+ ]));
3591
+ throw TypeError(`Unexpected type of external item: ${typeof item}`);
3592
+ };
3593
+ }
3594
+ function getRawExternalItemValueFormFnResult(result) {
3595
+ return void 0 === result ? result : getRawExternalItemValue(result);
3596
+ }
3597
+ function getRawExternalItemValue(value) {
3598
+ return value && 'object' == typeof value && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).map(([k, v])=>[
3599
+ k,
3600
+ Array.isArray(v) ? v : [
3601
+ v
3602
+ ]
3603
+ ])) : value;
3604
+ }
3605
+ let FetchCompileAsyncWasmPlugin = base_create(binding_namespaceObject.BuiltinPluginName.FetchCompileAsyncWasmPlugin, ()=>{}, 'thisCompilation'), FileUriPlugin = base_create(binding_namespaceObject.BuiltinPluginName.FileUriPlugin, ()=>{}, 'compilation'), FlagDependencyExportsPlugin = base_create(binding_namespaceObject.BuiltinPluginName.FlagDependencyExportsPlugin, ()=>{}, 'compilation');
3606
+ class FlagDependencyUsagePlugin extends RspackBuiltinPlugin {
3607
+ global;
3608
+ name = binding_namespaceObject.BuiltinPluginName.FlagDependencyUsagePlugin;
3609
+ affectedHooks = 'compilation';
3610
+ constructor(global){
3611
+ super(), this.global = global;
3462
3612
  }
3463
- }, memoize = (fn)=>{
3613
+ raw() {
3614
+ return createBuiltinPlugin(this.name, this.global);
3615
+ }
3616
+ }
3617
+ let HashedModuleIdsPlugin = base_create(binding_namespaceObject.BuiltinPluginName.HashedModuleIdsPlugin, (options)=>({
3618
+ ...options
3619
+ }), 'compilation');
3620
+ class HotModuleReplacementPlugin extends RspackBuiltinPlugin {
3621
+ name = binding_namespaceObject.BuiltinPluginName.HotModuleReplacementPlugin;
3622
+ raw(compiler) {
3623
+ return void 0 === compiler.options.output.strictModuleErrorHandling && (compiler.options.output.strictModuleErrorHandling = !0), createBuiltinPlugin(this.name, void 0);
3624
+ }
3625
+ }
3626
+ let HttpExternalsRspackPlugin = base_create(binding_namespaceObject.BuiltinPluginName.HttpExternalsRspackPlugin, (webAsync)=>({
3627
+ webAsync
3628
+ })), memoize = (fn)=>{
3464
3629
  let result, cache = !1, callback = fn;
3465
3630
  return ()=>(cache || (result = callback(), cache = !0, callback = void 0), result);
3466
3631
  }, memoizeFn = (fn)=>{
3467
3632
  let cache = null;
3468
3633
  return (...args)=>(cache || (cache = fn()), cache(...args));
3469
- }, ModuleError_createMessage = (err, type, from)=>{
3470
- let message = `Module ${type}${from ? ` (from ${from}):\n` : ': '}`;
3471
- return err && 'object' == typeof err && err.message ? message += err.message : err && (message += err), message;
3472
- }, getErrorDetails = (err)=>{
3473
- var stack, name, message, stack1, name1, message1;
3474
- let details, nextLine;
3475
- return err && 'object' == typeof err && err.stack ? (stack = err.stack, name = err.name, message = err.message, cutOffLoaderExecution(stack), stack1 = stack, name1 = name, message1 = message, details = -1 === (nextLine = stack1.indexOf('\n')) ? stack1 === message1 ? '' : stack1 : stack1.slice(0, nextLine) === `${name1}: ${message1}` ? stack1.slice(nextLine + 1) : stack1) : void 0;
3634
+ }, HttpUriPlugin_require = createRequire(import.meta.url), getHttp = memoize(()=>HttpUriPlugin_require('node:http')), getHttps = memoize(()=>HttpUriPlugin_require('node:https')), defaultHttpClientForNode = async (url, headers)=>{
3635
+ let { res, body } = await function(url, options) {
3636
+ let send = 'https:' === new URL(url).protocol ? getHttps() : getHttp(), { createBrotliDecompress, createGunzip, createInflate } = HttpUriPlugin_require('node:zlib');
3637
+ return new Promise((resolve, reject)=>{
3638
+ send.get(url, options, (res)=>{
3639
+ let contentEncoding = res.headers['content-encoding'], stream = res;
3640
+ 'gzip' === contentEncoding ? stream = stream.pipe(createGunzip()) : 'br' === contentEncoding ? stream = stream.pipe(createBrotliDecompress()) : 'deflate' === contentEncoding && (stream = stream.pipe(createInflate()));
3641
+ let chunks = [];
3642
+ stream.on('data', (chunk)=>{
3643
+ chunks.push(chunk);
3644
+ }), stream.on('end', ()=>{
3645
+ let bodyBuffer = Buffer.concat(chunks);
3646
+ res.complete ? resolve({
3647
+ res,
3648
+ body: bodyBuffer
3649
+ }) : reject(Error(`${url} request was terminated early`));
3650
+ });
3651
+ }).on('error', reject);
3652
+ });
3653
+ }(url, {
3654
+ headers
3655
+ }), responseHeaders = {};
3656
+ for (let [key, value] of Object.entries(res.headers))Array.isArray(value) ? responseHeaders[key] = value.join(', ') : responseHeaders[key] = value;
3657
+ return {
3658
+ status: res.statusCode,
3659
+ headers: responseHeaders,
3660
+ body: Buffer.from(body)
3661
+ };
3476
3662
  };
3477
- class ModuleError extends lib_WebpackError {
3478
- error;
3479
- constructor(err, { from } = {}){
3480
- super(ModuleError_createMessage(err, 'Error', from)), this.name = 'ModuleError', this.error = err, this.details = getErrorDetails(err);
3663
+ class HttpUriPlugin extends RspackBuiltinPlugin {
3664
+ options;
3665
+ name = binding_namespaceObject.BuiltinPluginName.HttpUriPlugin;
3666
+ affectedHooks = 'compilation';
3667
+ constructor(options){
3668
+ super(), this.options = options;
3481
3669
  }
3482
- }
3483
- class ModuleWarning extends lib_WebpackError {
3484
- error;
3485
- constructor(err, { from } = {}){
3486
- super(ModuleError_createMessage(err, 'Warning', from)), this.name = 'ModuleWarning', this.error = err, this.details = getErrorDetails(err);
3670
+ raw(compiler) {
3671
+ let options = this.options, lockfileLocation = options.lockfileLocation ?? node_path.join(compiler.context, compiler.name ? `${compiler.name}.rspack.lock` : 'rspack.lock'), cacheLocation = !1 === options.cacheLocation ? void 0 : options.cacheLocation ?? `${lockfileLocation}.data`, raw = {
3672
+ allowedUris: options.allowedUris,
3673
+ lockfileLocation,
3674
+ cacheLocation,
3675
+ upgrade: options.upgrade ?? !1,
3676
+ httpClient: options.httpClient ?? defaultHttpClientForNode
3677
+ };
3678
+ return createBuiltinPlugin(this.name, raw);
3487
3679
  }
3488
3680
  }
3489
- let service_require = createRequire(import.meta.url), ensureLoaderWorkerPool = async (workerOptions)=>service_pool || (service_pool = import("../compiled/tinypool/dist/index.js").then(({ Tinypool })=>{
3490
- let availableThreads = Math.max(service_require('node:os').cpus().length - 1, 1), maxWorkers = workerOptions?.maxWorkers ? Math.max(workerOptions.maxWorkers, 1) : void 0, maxWorkersFromEnv = parseInt(process.env.RSPACK_LOADER_WORKER_THREADS || '', 10);
3491
- return new Tinypool({
3492
- filename: node_path.resolve(import.meta.dirname, 'worker.js'),
3493
- useAtomics: !1,
3494
- maxThreads: maxWorkers || maxWorkersFromEnv || availableThreads,
3495
- minThreads: maxWorkers || maxWorkersFromEnv || availableThreads,
3496
- concurrentTasksPerWorker: 1
3681
+ let compilationOptionsMap = new WeakMap(), hooks_compilationHooksMap = new WeakMap(), plugin_require = createRequire(import.meta.url), HTML_PLUGIN_UID = 0, HtmlRspackPlugin = base_create(binding_namespaceObject.BuiltinPluginName.HtmlRspackPlugin, function(c = {}) {
3682
+ let templateFn, templateParameters, filenames, uid = HTML_PLUGIN_UID++, meta = {};
3683
+ for(let key in c.meta){
3684
+ let value = c.meta[key];
3685
+ 'string' == typeof value ? meta[key] = {
3686
+ name: key,
3687
+ content: value
3688
+ } : meta[key] = {
3689
+ name: key,
3690
+ ...value
3691
+ };
3692
+ }
3693
+ let scriptLoading = c.scriptLoading ?? 'defer', configInject = c.inject ?? !0, base = 'string' == typeof c.base ? {
3694
+ href: c.base
3695
+ } : c.base, chunksSortMode = c.chunksSortMode ?? 'auto', compilation = null;
3696
+ function generateRenderData(data) {
3697
+ let json = JSON.parse(data);
3698
+ 'function' != typeof c.templateParameters && (json.compilation = compilation);
3699
+ let renderTag = function() {
3700
+ var tag;
3701
+ let attributes;
3702
+ return tag = this, attributes = Object.keys(tag.attributes || {}).filter((attributeName)=>'' === tag.attributes[attributeName] || tag.attributes[attributeName]).map((attributeName)=>'true' === tag.attributes[attributeName] ? attributeName : `${attributeName}="${tag.attributes[attributeName]}"`), `<${[
3703
+ tag.tagName
3704
+ ].concat(attributes).join(' ')}${tag.voidTag && !tag.innerHTML ? '/' : ''}>${tag.innerHTML || ''}${tag.voidTag && !tag.innerHTML ? '' : `</${tag.tagName}>`}`;
3705
+ }, renderTagList = function() {
3706
+ return this.join('');
3707
+ };
3708
+ if (Array.isArray(json.htmlRspackPlugin?.tags?.headTags)) {
3709
+ for (let tag of json.htmlRspackPlugin.tags.headTags)tag.toString = renderTag;
3710
+ json.htmlRspackPlugin.tags.headTags.toString = renderTagList;
3711
+ }
3712
+ if (Array.isArray(json.htmlRspackPlugin?.tags?.bodyTags)) {
3713
+ for (let tag of json.htmlRspackPlugin.tags.bodyTags)tag.toString = renderTag;
3714
+ json.htmlRspackPlugin.tags.bodyTags.toString = renderTagList;
3715
+ }
3716
+ return json;
3717
+ }
3718
+ this.hooks.compilation.tap('HtmlRspackPlugin', (compilationInstance)=>{
3719
+ var compilation1;
3720
+ let optionsMap;
3721
+ compilation1 = compilation = compilationInstance, (optionsMap = compilationOptionsMap.get(compilation1) || {})[uid] = c, compilationOptionsMap.set(compilation1, optionsMap);
3722
+ }), this.hooks.done.tap('HtmlRspackPlugin', (stats)=>{
3723
+ var compilation, compilation1;
3724
+ let optionsMap;
3725
+ compilation = stats.compilation, hooks_compilationHooksMap.delete(compilation), compilation1 = stats.compilation, optionsMap = compilationOptionsMap.get(compilation1) || {}, delete optionsMap[uid], 0 === Object.keys(optionsMap).length ? compilationOptionsMap.delete(compilation1) : compilationOptionsMap.set(compilation1, optionsMap);
3726
+ });
3727
+ let templateContent = c.templateContent;
3728
+ if ('function' == typeof templateContent) templateFn = async (data)=>{
3729
+ try {
3730
+ let renderer = c.templateContent;
3731
+ if (!1 === c.templateParameters) return await renderer({});
3732
+ return await renderer(generateRenderData(data));
3733
+ } catch (e) {
3734
+ let error = Error(`HtmlRspackPlugin: render template function failed, ${e.message}`);
3735
+ throw error.stack = e.stack, error;
3736
+ }
3737
+ }, templateContent = '';
3738
+ else if (c.template) {
3739
+ let filename = c.template.split('?')[0];
3740
+ [
3741
+ '.js',
3742
+ '.cjs'
3743
+ ].includes(node_path.extname(filename)) && (templateFn = async (data)=>{
3744
+ let context = this.options.context || process.cwd(), templateFilePath = node_path.resolve(context, filename);
3745
+ if (!node_fs.existsSync(templateFilePath)) throw Error(`HtmlRspackPlugin: could not load file \`${filename}\` from \`${context}\``);
3746
+ try {
3747
+ let renderer = plugin_require(templateFilePath);
3748
+ if (!1 === c.templateParameters) return await renderer({});
3749
+ return await renderer(generateRenderData(data));
3750
+ } catch (e) {
3751
+ let error = Error(`HtmlRspackPlugin: render template function failed, ${e.message}`);
3752
+ throw error.stack = e.stack, error;
3753
+ }
3497
3754
  });
3498
- }));
3499
- function serializeError(error) {
3500
- if (error instanceof Error || error && 'object' == typeof error && 'message' in error) return {
3501
- ...error,
3502
- name: error.name,
3503
- stack: error.stack,
3504
- message: error.message
3505
- };
3506
- if ('string' == typeof error) return {
3507
- name: 'Error',
3508
- message: error
3755
+ }
3756
+ let rawTemplateParameters = c.templateParameters;
3757
+ if (templateParameters = 'function' == typeof rawTemplateParameters ? async (data)=>JSON.stringify(await rawTemplateParameters(JSON.parse(data))) : rawTemplateParameters, 'string' == typeof c.filename) if (filenames = new Set(), c.filename.includes('[name]')) if ('object' == typeof this.options.entry) for (let entryName of Object.keys(this.options.entry))filenames.add(c.filename.replace(/\[name\]/g, entryName));
3758
+ else throw Error('HtmlRspackPlugin: filename with `[name]` does not support function entry');
3759
+ else filenames.add(c.filename);
3760
+ else if ('function' == typeof c.filename) if (filenames = new Set(), 'object' == typeof this.options.entry) for (let entryName of Object.keys(this.options.entry))filenames.add(c.filename(entryName));
3761
+ else throw Error('HtmlRspackPlugin: function filename does not support function entry');
3762
+ return {
3763
+ filename: filenames ? Array.from(filenames) : void 0,
3764
+ template: c.template,
3765
+ hash: c.hash,
3766
+ title: c.title,
3767
+ favicon: c.favicon,
3768
+ publicPath: c.publicPath,
3769
+ chunks: c.chunks,
3770
+ excludeChunks: c.excludeChunks,
3771
+ chunksSortMode,
3772
+ minify: c.minify,
3773
+ meta,
3774
+ scriptLoading,
3775
+ inject: !0 === configInject ? 'blocking' === scriptLoading ? 'body' : 'head' : !1 === configInject ? 'false' : configInject,
3776
+ base,
3777
+ templateFn,
3778
+ templateContent,
3779
+ templateParameters,
3780
+ uid
3509
3781
  };
3510
- throw Error('Failed to serialize error, only string, Error instances and objects with a message property are supported');
3782
+ }), voidTags = [
3783
+ 'area',
3784
+ 'base',
3785
+ 'br',
3786
+ 'col',
3787
+ 'embed',
3788
+ 'hr',
3789
+ 'img',
3790
+ 'input',
3791
+ 'keygen',
3792
+ 'link',
3793
+ 'meta',
3794
+ 'param',
3795
+ 'source',
3796
+ 'track',
3797
+ 'wbr'
3798
+ ];
3799
+ HtmlRspackPlugin.createHtmlTagObject = (tagName, attributes, innerHTML)=>({
3800
+ tagName,
3801
+ voidTag: voidTags.includes(tagName),
3802
+ attributes: attributes || {},
3803
+ innerHTML
3804
+ }), HtmlRspackPlugin.getCompilationHooks = (compilation)=>{
3805
+ checkCompilation(compilation);
3806
+ let hooks = hooks_compilationHooksMap.get(compilation);
3807
+ return void 0 === hooks && (hooks = {
3808
+ beforeAssetTagGeneration: new AsyncSeriesWaterfallHook([
3809
+ 'data'
3810
+ ]),
3811
+ alterAssetTags: new AsyncSeriesWaterfallHook([
3812
+ 'data'
3813
+ ]),
3814
+ alterAssetTagGroups: new AsyncSeriesWaterfallHook([
3815
+ 'data'
3816
+ ]),
3817
+ afterTemplateExecution: new AsyncSeriesWaterfallHook([
3818
+ 'data'
3819
+ ]),
3820
+ beforeEmit: new AsyncSeriesWaterfallHook([
3821
+ 'data'
3822
+ ]),
3823
+ afterEmit: new AsyncSeriesWaterfallHook([
3824
+ 'data'
3825
+ ])
3826
+ }, hooks_compilationHooksMap.set(compilation, hooks)), hooks;
3827
+ }, HtmlRspackPlugin.version = 5;
3828
+ let IgnorePlugin = base_create(binding_namespaceObject.BuiltinPluginName.IgnorePlugin, (options)=>options), InferAsyncModulesPlugin = base_create(binding_namespaceObject.BuiltinPluginName.InferAsyncModulesPlugin, ()=>{}, 'compilation'), InlineExportsPlugin = base_create(binding_namespaceObject.BuiltinPluginName.InlineExportsPlugin, ()=>{}, 'compilation'), JavascriptModulesPlugin_compilationHooksMap = new WeakMap();
3829
+ class JavascriptModulesPlugin extends RspackBuiltinPlugin {
3830
+ name = binding_namespaceObject.BuiltinPluginName.JavascriptModulesPlugin;
3831
+ affectedHooks = 'compilation';
3832
+ raw() {
3833
+ return createBuiltinPlugin(this.name, void 0);
3834
+ }
3835
+ static getCompilationHooks(compilation) {
3836
+ checkCompilation(compilation);
3837
+ let hooks = JavascriptModulesPlugin_compilationHooksMap.get(compilation);
3838
+ return void 0 === hooks && (hooks = {
3839
+ chunkHash: new SyncHook([
3840
+ 'chunk',
3841
+ 'hash'
3842
+ ])
3843
+ }, JavascriptModulesPlugin_compilationHooksMap.set(compilation, hooks)), hooks;
3844
+ }
3511
3845
  }
3512
- let service_run = async (loaderName, task, options, workerOptions)=>ensureLoaderWorkerPool(workerOptions).then(async (pool)=>{
3513
- let { MessageChannel } = await import("node:worker_threads"), { port1: mainPort, port2: workerPort } = new MessageChannel(), { port1: mainSyncPort, port2: workerSyncPort } = new MessageChannel();
3514
- return new Promise((resolve, reject)=>{
3515
- let handleError = (error)=>{
3516
- mainPort.close(), mainSyncPort.close(), reject(error);
3517
- }, pendingRequests = new Map();
3518
- mainPort.on('message', (message)=>{
3519
- 'done' === message.type ? Promise.allSettled(pendingRequests.values()).then(()=>{
3520
- mainPort.close(), mainSyncPort.close(), resolve(message.data);
3521
- }) : 'done-error' === message.type ? Promise.allSettled(pendingRequests.values()).then(()=>{
3522
- mainPort.close(), mainSyncPort.close(), reject(message.error);
3523
- }) : 'request' === message.type && pendingRequests.set(message.id, Promise.resolve().then(()=>options.handleIncomingRequest(message.requestType, ...message.data)).then((result)=>(mainPort.postMessage({
3524
- type: 'response',
3525
- id: message.id,
3526
- data: result
3527
- }), result)).catch((error)=>{
3528
- mainPort.postMessage({
3529
- type: 'response-error',
3530
- id: message.id,
3531
- error: serializeError(error)
3532
- });
3533
- }));
3534
- }), mainPort.on('messageerror', handleError), mainSyncPort.on('message', async (message)=>{
3535
- let result, { sharedBuffer } = message, sharedBufferView = new Int32Array(sharedBuffer);
3536
- try {
3537
- if ("WaitForPendingRequest" === message.requestType) {
3538
- let pendingRequestId = message.data[0], isArray = Array.isArray(pendingRequestId), ids = isArray ? pendingRequestId : [
3539
- pendingRequestId
3540
- ];
3541
- result = await Promise.all(ids.map((id)=>pendingRequests.get(id))), isArray || (result = result[0]);
3542
- } else throw Error(`Unknown request type: ${message.requestType}`);
3543
- mainSyncPort.postMessage({
3544
- type: 'response',
3545
- id: message.id,
3546
- data: result
3547
- });
3548
- } catch (e) {
3549
- mainSyncPort.postMessage({
3550
- type: 'response-error',
3551
- id: message.id,
3552
- error: serializeError(e)
3553
- });
3554
- }
3555
- Atomics.add(sharedBufferView, 0, 1), Atomics.notify(sharedBufferView, 0, 1 / 0);
3556
- }), mainSyncPort.on('messageerror', handleError);
3557
- let errors = [];
3558
- for (let key of Object.keys(task))try {
3559
- structuredClone(task[key]);
3560
- } catch (e) {
3561
- errors.push({
3562
- key,
3563
- type: typeof task[key],
3564
- reason: e.message
3565
- });
3566
- }
3567
- if (errors.length > 0) {
3568
- let errorMsg = errors.map((err)=>`option "${err.key}" (type: ${err.type}) is not cloneable: ${err.reason}`).join('\n');
3569
- throw Error(`The options for ${loaderName} are not cloneable, which is not supported by parallelLoader. Consider disabling parallel for this loader or removing the non-cloneable properties from the options:\n${errorMsg}`);
3570
- }
3571
- pool.run({
3572
- ...task,
3573
- workerData: {
3574
- workerPort,
3575
- workerSyncPort
3576
- }
3577
- }, {
3578
- ...options,
3579
- transferList: [
3580
- ...options?.transferList || [],
3581
- workerPort,
3582
- workerSyncPort
3583
- ]
3584
- }).catch(handleError);
3846
+ let $assets = Symbol('assets');
3847
+ Object.defineProperty(binding_default().KnownBuildInfo.prototype, node_util.inspect.custom, {
3848
+ enumerable: !0,
3849
+ configurable: !0,
3850
+ value () {
3851
+ return {
3852
+ ...this,
3853
+ assets: this.assets,
3854
+ fileDependencies: this.fileDependencies,
3855
+ contextDependencies: this.contextDependencies,
3856
+ missingDependencies: this.missingDependencies,
3857
+ buildDependencies: this.buildDependencies
3858
+ };
3859
+ }
3860
+ }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'assets', {
3861
+ enumerable: !0,
3862
+ configurable: !0,
3863
+ get () {
3864
+ if (this[binding_default().BUILD_INFO_ASSETS_SYMBOL][$assets]) return this[binding_default().BUILD_INFO_ASSETS_SYMBOL][$assets];
3865
+ let assets = new Proxy(Object.create(null), {
3866
+ ownKeys: ()=>this[binding_default().BUILD_INFO_ASSETS_SYMBOL].keys(),
3867
+ getOwnPropertyDescriptor: ()=>({
3868
+ enumerable: !0,
3869
+ configurable: !0
3870
+ })
3585
3871
  });
3586
- }), LoaderLoadingError = class extends Error {
3587
- constructor(message){
3588
- super(message), this.name = 'LoaderRunnerError', Error.captureStackTrace(this, this.constructor);
3872
+ return Object.defineProperty(this[binding_default().BUILD_INFO_ASSETS_SYMBOL], $assets, {
3873
+ enumerable: !1,
3874
+ configurable: !0,
3875
+ value: assets
3876
+ }), assets;
3589
3877
  }
3590
- }, loadLoader_require = createRequire(import.meta.url);
3591
- function loadLoader(loader, compiler, callback) {
3592
- if ('module' === loader.type) try {
3593
- void 0 === loadLoader_url && (loadLoader_url = loadLoader_require('node:url')), import(loadLoader_url.pathToFileURL(loader.path).toString()).then((module)=>{
3594
- handleResult(loader, module, callback);
3595
- }, callback);
3596
- return;
3597
- } catch (e) {
3598
- callback(e);
3878
+ }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'fileDependencies', {
3879
+ enumerable: !0,
3880
+ configurable: !0,
3881
+ get () {
3882
+ return new Set(this[binding_default().BUILD_INFO_FILE_DEPENDENCIES_SYMBOL]);
3599
3883
  }
3600
- else {
3601
- let module;
3602
- try {
3603
- module = loadLoader_require(loader.path);
3604
- } catch (e) {
3605
- if (e instanceof Error && 'EMFILE' === e.code) return void setImmediate(loadLoader.bind(null, loader, compiler, callback));
3606
- return callback(e);
3607
- }
3608
- return handleResult(loader, module, callback);
3884
+ }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'contextDependencies', {
3885
+ enumerable: !0,
3886
+ configurable: !0,
3887
+ get () {
3888
+ return new Set(this[binding_default().BUILD_INFO_CONTEXT_DEPENDENCIES_SYMBOL]);
3609
3889
  }
3610
- }
3611
- function handleResult(loader, module, callback) {
3612
- return 'function' != typeof module && 'object' != typeof module ? callback(new LoaderLoadingError(`Module '${loader.path}' is not a loader (export function or es6 module)`)) : (loader.normal = 'function' == typeof module ? module : module.default, loader.pitch = module.pitch, loader.raw = module.raw, loader.pitch || (loader.noPitch = !0), 'function' != typeof loader.normal && 'function' != typeof loader.pitch) ? callback(new LoaderLoadingError(`Module '${loader.path}' is not a loader (must have normal or pitch function)`)) : void callback();
3613
- }
3614
- let decoder = new TextDecoder(), utils_loadLoader = promisify(loadLoader), utils_runSyncOrAsync = promisify(function(fn, context, args, callback) {
3615
- let isSync = !0, isDone = !1, isError = !1, reportedError = !1;
3616
- context.async = function() {
3617
- if (isDone) {
3618
- if (reportedError) return;
3619
- throw Error('async(): The callback was already called.');
3620
- }
3621
- return isSync = !1, innerCallback;
3622
- };
3623
- let innerCallback = (err, ...args)=>{
3624
- if (isDone) {
3625
- if (reportedError) return;
3626
- throw Error('callback(): The callback was already called.');
3627
- }
3628
- isDone = !0, isSync = !1;
3629
- try {
3630
- callback(err, args);
3631
- } catch (e) {
3632
- throw isError = !0, e;
3633
- }
3634
- };
3635
- context.callback = innerCallback;
3636
- try {
3637
- let result = fn.apply(context, args);
3638
- if (isSync) {
3639
- if (isDone = !0, void 0 === result) return void callback(null, []);
3640
- if (result && 'object' == typeof result && 'function' == typeof result.then) return void result.then((r)=>{
3641
- callback(null, [
3642
- r
3643
- ]);
3644
- }, callback);
3645
- callback(null, [
3646
- result
3647
- ]);
3648
- return;
3649
- }
3650
- } catch (e) {
3651
- if ('hideStack' in e && e.hideStack && (e.hideStack = 'true'), isError) throw e;
3652
- if (isDone) return void (e instanceof Error ? console.error(e.stack) : console.error(e));
3653
- isDone = !0, reportedError = !0, callback(e, []);
3654
- }
3655
- }), LOADER_PROCESS_NAME = 'Loader Analysis';
3656
- class LoaderObject {
3657
- request;
3658
- path;
3659
- query;
3660
- fragment;
3661
- options;
3662
- ident;
3663
- normal;
3664
- pitch;
3665
- raw;
3666
- type;
3667
- parallel;
3668
- loaderItem;
3669
- constructor(loaderItem, compiler){
3670
- let obj, { request, path, query, fragment, options, ident, normal, pitch, raw, type } = (Object.defineProperty(obj = {
3671
- path: null,
3672
- query: null,
3673
- fragment: null,
3674
- options: null,
3675
- ident: null,
3676
- normal: null,
3677
- pitch: null,
3678
- raw: null,
3679
- data: null,
3680
- pitchExecuted: !1,
3681
- normalExecuted: !1
3682
- }, 'request', {
3683
- enumerable: !0,
3684
- get: ()=>obj.path.replace(/#/g, '\u200b#') + obj.query.replace(/#/g, '\u200b#') + obj.fragment,
3685
- set: (value)=>{
3686
- let splittedRequest = parseResourceWithoutFragment(value.loader);
3687
- if (obj.path = splittedRequest.path, obj.query = splittedRequest.query, obj.fragment = '', obj.options = null === obj.options ? splittedRequest.query ? splittedRequest.query.slice(1) : void 0 : obj.options, 'string' == typeof obj.options && '?' === obj.options[0]) {
3688
- let ident = obj.options.slice(1);
3689
- if ('[[missing ident]]' === ident) throw Error("No ident is provided by referenced loader. When using a function for Rule.use in config you need to provide an 'ident' property for referenced loader options.");
3690
- if (obj.options = compiler.__internal__ruleSet.references.get(ident), void 0 === obj.options) throw Error('Invalid ident is provided by referenced loader');
3691
- obj.ident = ident;
3692
- }
3693
- obj.type = '' === value.type ? void 0 : value.type, null === obj.options || void 0 === obj.options ? obj.query = '' : 'string' == typeof obj.options ? obj.query = `?${obj.options}` : obj.ident ? obj.query = `??${obj.ident}` : 'object' == typeof obj.options && obj.options.ident ? obj.query = `??${obj.options.ident}` : obj.query = `?${JSON.stringify(obj.options)}`;
3694
- }
3695
- }), obj.request = loaderItem, Object.preventExtensions && Object.preventExtensions(obj), obj);
3696
- this.request = request, this.path = path, this.query = query, this.fragment = fragment, this.options = options, this.ident = ident, this.normal = normal, this.pitch = pitch, this.raw = raw, this.type = type, this.parallel = !!ident && compiler.__internal__ruleSet.references.get(`${ident}$$parallelism`), this.loaderItem = loaderItem, this.loaderItem.data = this.loaderItem.data ?? {};
3890
+ }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'missingDependencies', {
3891
+ enumerable: !0,
3892
+ configurable: !0,
3893
+ get () {
3894
+ return new Set(this[binding_default().BUILD_INFO_MISSING_DEPENDENCIES_SYMBOL]);
3697
3895
  }
3698
- get pitchExecuted() {
3699
- return this.loaderItem.pitchExecuted;
3896
+ }), Object.defineProperty(binding_default().KnownBuildInfo.prototype, 'buildDependencies', {
3897
+ enumerable: !0,
3898
+ configurable: !0,
3899
+ get () {
3900
+ return new Set(this[binding_default().BUILD_INFO_BUILD_DEPENDENCIES_SYMBOL]);
3700
3901
  }
3701
- set pitchExecuted(value) {
3702
- if (!value) throw Error('pitchExecuted should be true');
3703
- this.loaderItem.pitchExecuted = !0;
3902
+ });
3903
+ let knownBuildInfoFields = new Set([
3904
+ 'assets',
3905
+ 'fileDependencies',
3906
+ 'contextDependencies',
3907
+ 'missingDependencies',
3908
+ 'buildDependencies'
3909
+ ]);
3910
+ Object.defineProperty(binding_default().NormalModule.prototype, 'identifier', {
3911
+ enumerable: !0,
3912
+ configurable: !0,
3913
+ value () {
3914
+ return this[binding_default().MODULE_IDENTIFIER_SYMBOL];
3704
3915
  }
3705
- get normalExecuted() {
3706
- return this.loaderItem.normalExecuted;
3916
+ }), Object.defineProperty(binding_default().NormalModule.prototype, 'originalSource', {
3917
+ enumerable: !0,
3918
+ configurable: !0,
3919
+ value () {
3920
+ let originalSource = this._originalSource();
3921
+ return originalSource ? SourceAdapter.fromBinding(originalSource) : null;
3707
3922
  }
3708
- set normalExecuted(value) {
3709
- if (!value) throw Error('normalExecuted should be true');
3710
- this.loaderItem.normalExecuted = !0;
3923
+ }), Object.defineProperty(binding_default().NormalModule.prototype, 'emitFile', {
3924
+ enumerable: !0,
3925
+ configurable: !0,
3926
+ value (filename, source, assetInfo) {
3927
+ return this._emitFile(filename, SourceAdapter.toBinding(source), assetInfo);
3711
3928
  }
3712
- set noPitch(value) {
3713
- if (!value) throw Error('noPitch should be true');
3714
- this.loaderItem.noPitch = !0;
3929
+ }), Object.defineProperty(binding_default().NormalModule, 'getCompilationHooks', {
3930
+ enumerable: !0,
3931
+ configurable: !0,
3932
+ value (compilation) {
3933
+ if (!(binding_default().COMPILATION_HOOKS_MAP_SYMBOL in compilation)) throw TypeError("The 'compilation' argument must be an instance of Compilation");
3934
+ let compilationHooksMap = compilation[binding_default().COMPILATION_HOOKS_MAP_SYMBOL], hooks = compilationHooksMap.get(compilation);
3935
+ return void 0 === hooks && (hooks = {
3936
+ loader: new SyncHook([
3937
+ 'loaderContext',
3938
+ 'module'
3939
+ ]),
3940
+ readResource: new HookMap(()=>new AsyncSeriesBailHook([
3941
+ 'loaderContext'
3942
+ ]))
3943
+ }, compilationHooksMap.set(compilation, hooks)), hooks;
3715
3944
  }
3716
- shouldYield() {
3717
- return this.request.startsWith(BUILTIN_LOADER_PREFIX);
3945
+ });
3946
+ class NonErrorEmittedError extends Error {
3947
+ constructor(error){
3948
+ super(), this.name = 'NonErrorEmittedError', this.message = `(Emitted value instead of an instance of Error) ${error}`;
3718
3949
  }
3719
- static __from_binding(loaderItem, compiler) {
3720
- return new this(loaderItem, compiler);
3950
+ }
3951
+ class DeadlockRiskError extends Error {
3952
+ constructor(message){
3953
+ super(message), this.name = 'DeadlockRiskError', this.stack = '';
3721
3954
  }
3722
- static __to_binding(loader) {
3723
- return loader.loaderItem;
3955
+ }
3956
+ class ValidationError extends Error {
3957
+ constructor(message){
3958
+ super(message), this.name = 'ValidationError';
3724
3959
  }
3725
3960
  }
3726
- class JsSourceMap {
3727
- static __from_binding(map) {
3728
- return isNil(map) ? void 0 : ((input)=>{
3729
- let s;
3730
- if (Buffer.isBuffer(input)) s = input.toString('utf8');
3731
- else if (input && 'object' == typeof input) return input;
3732
- else if ('string' == typeof input) s = input;
3733
- else throw Error('Buffer or string or object expected');
3734
- return JSON.parse(s);
3735
- })(map);
3961
+ class JavaScriptTracer {
3962
+ static state = 'uninitialized';
3963
+ static startTime;
3964
+ static events;
3965
+ static layer;
3966
+ static output;
3967
+ static session;
3968
+ static counter = 10000;
3969
+ static async initJavaScriptTrace(layer, output) {
3970
+ let { Session } = await import("node:inspector");
3971
+ this.session = new Session(), this.layer = layer, this.output = output, this.events = [], this.state = 'on', this.startTime = process.hrtime.bigint();
3736
3972
  }
3737
- static __to_binding(map) {
3738
- return serializeObject(map);
3973
+ static uuid() {
3974
+ return this.counter++;
3739
3975
  }
3740
- }
3741
- function getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) {
3742
- return loaderContext.loaders?.length && index < loaderContext.loaders.length && index >= 0 && loaderContext.loaders[index] ? loaderContext.loaders[index] : null;
3743
- }
3744
- async function runLoaders(compiler, context) {
3745
- var buildInfo;
3746
- let loaderState = context.loaderState, pitch = loaderState === binding_namespaceObject.JsLoaderState.Pitching, { resource } = context, uuid = JavaScriptTracer.uuid();
3747
- JavaScriptTracer.startAsync({
3748
- name: 'run_js_loaders',
3749
- processName: LOADER_PROCESS_NAME,
3750
- uuid,
3751
- ph: 'b',
3752
- args: {
3753
- is_pitch: pitch,
3754
- resource: resource
3755
- }
3756
- });
3757
- let splittedResource = resource && parsePathQueryFragment(resource), resourcePath = splittedResource ? splittedResource.path : void 0, resourceQuery = splittedResource ? splittedResource.query : void 0, resourceFragment = splittedResource ? splittedResource.fragment : void 0, contextDirectory = resourcePath ? function(path) {
3758
- if ('/' === path) return '/';
3759
- let i = path.lastIndexOf('/'), j = path.lastIndexOf('\\'), i2 = path.indexOf('/'), j2 = path.indexOf('\\'), idx = i > j ? i : j, idx2 = i > j ? i2 : j2;
3760
- return idx < 0 ? path : idx === idx2 ? path.slice(0, idx + 1) : path.slice(0, idx);
3761
- }(resourcePath) : null, fileDependencies = context.fileDependencies, contextDependencies = context.contextDependencies, missingDependencies = context.missingDependencies, buildDependencies = context.buildDependencies, loaderContext = {};
3762
- loaderContext.loaders = context.loaderItems.map((item)=>LoaderObject.__from_binding(item, compiler)), loaderContext.hot = context.hot, loaderContext.context = contextDirectory, loaderContext.resourcePath = resourcePath, loaderContext.resourceQuery = resourceQuery, loaderContext.resourceFragment = resourceFragment, loaderContext.dependency = loaderContext.addDependency = function(file) {
3763
- fileDependencies.push(file);
3764
- }, loaderContext.addContextDependency = function(context) {
3765
- contextDependencies.push(context);
3766
- }, loaderContext.addMissingDependency = function(context) {
3767
- missingDependencies.push(context);
3768
- }, loaderContext.addBuildDependency = function(file) {
3769
- buildDependencies.push(file);
3770
- }, loaderContext.getDependencies = function() {
3771
- return fileDependencies.slice();
3772
- }, loaderContext.getContextDependencies = function() {
3773
- return contextDependencies.slice();
3774
- }, loaderContext.getMissingDependencies = function() {
3775
- return missingDependencies.slice();
3776
- }, loaderContext.clearDependencies = function() {
3777
- fileDependencies.length = 0, contextDependencies.length = 0, missingDependencies.length = 0, context.cacheable = !0;
3778
- }, loaderContext.importModule = function(request, userOptions, callback) {
3779
- JavaScriptTracer.startAsync({
3780
- name: 'importModule',
3781
- processName: LOADER_PROCESS_NAME,
3782
- uuid,
3783
- args: {
3784
- is_pitch: pitch,
3785
- resource: resource
3786
- }
3787
- });
3788
- let options = userOptions || {};
3789
- function finalCallback(onError, onDone) {
3790
- return function(err, res) {
3791
- if (err) JavaScriptTracer.endAsync({
3792
- name: 'importModule',
3793
- processName: LOADER_PROCESS_NAME,
3976
+ static isEnabled() {
3977
+ return 'on' === this.state;
3978
+ }
3979
+ static initCpuProfiler() {
3980
+ this.isEnabled() && (this.session.connect(), this.session.post('Profiler.enable'), this.session.post('Profiler.start'));
3981
+ }
3982
+ static async cleanupJavaScriptTrace() {
3983
+ if ('uninitialized' === this.state) throw Error('JavaScriptTracer is not initialized, please call initJavaScriptTrace first');
3984
+ if (!this.isEnabled()) return;
3985
+ let profileHandler = (err, param)=>{
3986
+ let cpu_profile;
3987
+ if (err ? console.error('Error stopping profiler:', err) : cpu_profile = param.profile, cpu_profile) {
3988
+ let uuid = this.uuid();
3989
+ this.pushEvent({
3990
+ name: 'Profile',
3991
+ ph: 'P',
3992
+ trackName: 'JavaScript CPU Profiler',
3993
+ processName: 'JavaScript CPU',
3794
3994
  uuid,
3995
+ ...this.getCommonEv(),
3996
+ categories: [
3997
+ 'disabled-by-default-v8.cpu_profiler'
3998
+ ],
3795
3999
  args: {
3796
- is_pitch: pitch,
3797
- resource: resource
4000
+ data: {
4001
+ startTime: 0
4002
+ }
3798
4003
  }
3799
- }), onError(err);
3800
- else {
3801
- for (let dep of res.buildDependencies)loaderContext.addBuildDependency(dep);
3802
- for (let dep of res.contextDependencies)loaderContext.addContextDependency(dep);
3803
- for (let dep of res.missingDependencies)loaderContext.addMissingDependency(dep);
3804
- for (let dep of res.fileDependencies)loaderContext.addDependency(dep);
3805
- !1 === res.cacheable && loaderContext.cacheable(!1), JavaScriptTracer.endAsync({
3806
- name: 'importModule',
3807
- processName: LOADER_PROCESS_NAME,
3808
- uuid,
3809
- args: {
3810
- is_pitch: pitch,
3811
- resource: resource
4004
+ }), this.pushEvent({
4005
+ name: 'ProfileChunk',
4006
+ ph: 'P',
4007
+ trackName: 'JavaScript CPU Profiler',
4008
+ processName: 'JavaScript CPU',
4009
+ ...this.getCommonEv(),
4010
+ categories: [
4011
+ 'disabled-by-default-v8.cpu_profiler'
4012
+ ],
4013
+ uuid,
4014
+ args: {
4015
+ data: {
4016
+ cpuProfile: cpu_profile,
4017
+ timeDeltas: cpu_profile.timeDeltas
3812
4018
  }
3813
- }), res.error ? onError(compiler.__internal__takeModuleExecutionResult(res.id) ?? Error(res.error)) : onDone(compiler.__internal__takeModuleExecutionResult(res.id));
4019
+ }
4020
+ });
4021
+ }
4022
+ };
4023
+ await new Promise((resolve, reject)=>{
4024
+ this.session.post('Profiler.stop', (err, params)=>{
4025
+ if (err) reject(err);
4026
+ else try {
4027
+ profileHandler(err, params), resolve();
4028
+ } catch (err) {
4029
+ reject(err);
3814
4030
  }
3815
- };
3816
- }
3817
- return callback ? compiler._lastCompilation.__internal_getInner().importModule(request, options.layer, options.publicPath, options.baseUri, loaderContext._module.identifier(), loaderContext.context, finalCallback((err)=>callback(err), (res)=>callback(void 0, res))) : new Promise((resolve, reject)=>{
3818
- compiler._lastCompilation.__internal_getInner().importModule(request, options.layer, options.publicPath, options.baseUri, loaderContext._module.identifier(), loaderContext.context, finalCallback(reject, resolve));
3819
- });
3820
- }, Object.defineProperty(loaderContext, 'resource', {
3821
- enumerable: !0,
3822
- get: ()=>{
3823
- if (void 0 !== loaderContext.resourcePath) return loaderContext.resourcePath.replace(/#/g, '\u200b#') + loaderContext.resourceQuery.replace(/#/g, '\u200b#') + loaderContext.resourceFragment;
3824
- },
3825
- set: (value)=>{
3826
- let splittedResource = value && parsePathQueryFragment(value);
3827
- loaderContext.resourcePath = splittedResource ? splittedResource.path : void 0, loaderContext.resourceQuery = splittedResource ? splittedResource.query : void 0, loaderContext.resourceFragment = splittedResource ? splittedResource.fragment : void 0;
3828
- }
3829
- }), Object.defineProperty(loaderContext, 'request', {
3830
- enumerable: !0,
3831
- get: ()=>loaderContext.loaders.map((o)=>o.request).concat(loaderContext.resource || '').join('!')
3832
- }), Object.defineProperty(loaderContext, 'remainingRequest', {
3833
- enumerable: !0,
3834
- get: ()=>loaderContext.loaderIndex >= loaderContext.loaders.length - 1 && !loaderContext.resource ? '' : loaderContext.loaders.slice(loaderContext.loaderIndex + 1).map((o)=>o.request).concat(loaderContext.resource || '').join('!')
3835
- }), Object.defineProperty(loaderContext, 'currentRequest', {
3836
- enumerable: !0,
3837
- get: ()=>loaderContext.loaders.slice(loaderContext.loaderIndex).map((o)=>o.request).concat(loaderContext.resource || '').join('!')
3838
- }), Object.defineProperty(loaderContext, 'previousRequest', {
3839
- enumerable: !0,
3840
- get: ()=>loaderContext.loaders.slice(0, loaderContext.loaderIndex).map((o)=>o.request).join('!')
3841
- }), Object.defineProperty(loaderContext, 'query', {
3842
- enumerable: !0,
3843
- get: ()=>{
3844
- let entry = loaderContext.loaders[loaderContext.loaderIndex];
3845
- return entry.options && 'object' == typeof entry.options ? entry.options : entry.query;
3846
- }
3847
- }), loaderContext.version = 2, loaderContext.sourceMap = compiler.options.devtool ? isUseSourceMap(compiler.options.devtool) : context._module.useSourceMap ?? !1, loaderContext.mode = compiler.options.mode, Object.assign(loaderContext, compiler.options.loader);
3848
- let getResolveContext = ()=>({
3849
- fileDependencies: {
3850
- add: (d)=>{
3851
- loaderContext.addDependency(d);
3852
- }
3853
- },
3854
- contextDependencies: {
3855
- add: (d)=>{
3856
- loaderContext.addContextDependency(d);
3857
- }
3858
- },
3859
- missingDependencies: {
3860
- add: (d)=>{
3861
- loaderContext.addMissingDependency(d);
3862
- }
3863
- }
3864
- }), getResolver = memoize(()=>compiler._lastCompilation.resolverFactory.get('normal'));
3865
- loaderContext.resolve = function(context, request, callback) {
3866
- getResolver().resolve({}, context, request, getResolveContext(), callback);
3867
- }, loaderContext.getResolve = function(options) {
3868
- let resolver = getResolver(), child = options ? resolver.withOptions(options) : resolver;
3869
- return (context, request, callback)=>callback ? void child.resolve({}, context, request, getResolveContext(), callback) : new Promise((resolve, reject)=>{
3870
- child.resolve({}, context, request, getResolveContext(), (err, result)=>{
3871
- err ? reject(err) : resolve(result);
3872
- });
3873
4031
  });
3874
- }, loaderContext.getLogger = function(name) {
3875
- return compiler._lastCompilation.getLogger([
3876
- name,
3877
- resource
3878
- ].filter(Boolean).join('|'));
3879
- }, loaderContext.rootContext = compiler.context, loaderContext.emitError = function(e) {
3880
- e instanceof Error || (e = new NonErrorEmittedError(e));
3881
- let error = new ModuleError(e, {
3882
- from: stringifyLoaderObject(loaderContext.loaders[loaderContext.loaderIndex])
3883
- });
3884
- error.module = loaderContext._module, compiler._lastCompilation.__internal__pushRspackDiagnostic({
3885
- error,
3886
- severity: binding_namespaceObject.JsRspackSeverity.Error
4032
+ }), this.state = 'off';
4033
+ }
4034
+ static getTs() {
4035
+ return process.hrtime.bigint() - this.startTime;
4036
+ }
4037
+ static getCommonEv() {
4038
+ return {
4039
+ ts: this.getTs(),
4040
+ cat: 'rspack'
4041
+ };
4042
+ }
4043
+ static pushEvent(event) {
4044
+ let stringifiedArgs = Object.keys(event.args || {}).reduce((acc, key)=>(acc[key] = JSON.stringify(event.args[key]), acc), {});
4045
+ this.events.push({
4046
+ ...event,
4047
+ args: stringifiedArgs
3887
4048
  });
3888
- }, loaderContext.emitWarning = function(e) {
3889
- e instanceof Error || (e = new NonErrorEmittedError(e));
3890
- let warning = new ModuleWarning(e, {
3891
- from: stringifyLoaderObject(loaderContext.loaders[loaderContext.loaderIndex])
4049
+ }
4050
+ static startAsync(events) {
4051
+ this.isEnabled() && this.pushEvent({
4052
+ ...this.getCommonEv(),
4053
+ ...events,
4054
+ ph: 'b'
3892
4055
  });
3893
- warning.module = loaderContext._module, compiler._lastCompilation.__internal__pushRspackDiagnostic({
3894
- error: warning,
3895
- severity: binding_namespaceObject.JsRspackSeverity.Warn
4056
+ }
4057
+ static endAsync(events) {
4058
+ this.isEnabled() && this.pushEvent({
4059
+ ...this.getCommonEv(),
4060
+ ...events,
4061
+ ph: 'e'
3896
4062
  });
3897
- }, loaderContext.emitFile = function(name, content, sourceMap, assetInfo) {
3898
- var devtool;
3899
- let source;
3900
- sourceMap ? ('string' == typeof sourceMap && (loaderContext.sourceMap || compiler.options.devtool && (devtool = compiler.options.devtool) && devtool.includes('source-map') && !isUseSourceMap(devtool)) && (source = new index_js_namespaceObject.OriginalSource(content, makePathsRelative(contextDirectory, sourceMap, compiler))), loaderContext.sourceMap && (source = new index_js_namespaceObject.SourceMapSource(content, name, makePathsRelative(contextDirectory, sourceMap, compiler)))) : source = new index_js_namespaceObject.RawSource(content), loaderContext._module.emitFile(name, source, assetInfo);
3901
- }, loaderContext.fs = compiler.inputFileSystem, loaderContext.experiments = {
3902
- emitDiagnostic: (diagnostic)=>{
3903
- let d = Object.assign({}, diagnostic, {
3904
- message: 'warning' === diagnostic.severity ? `ModuleWarning: ${diagnostic.message}` : `ModuleError: ${diagnostic.message}`,
3905
- moduleIdentifier: context._module.identifier()
3906
- });
3907
- compiler._lastCompilation.__internal__pushDiagnostic((0, binding_namespaceObject.formatDiagnostic)(d));
3908
- }
3909
- };
3910
- let getAbsolutify = memoize(()=>absolutify.bindCache(compiler.root)), getAbsolutifyInContext = memoize(()=>absolutify.bindContextCache(contextDirectory, compiler.root)), getContextify = memoize(()=>contextify.bindCache(compiler.root)), getContextifyInContext = memoize(()=>contextify.bindContextCache(contextDirectory, compiler.root));
3911
- loaderContext.utils = {
3912
- absolutify: (context, request)=>context === contextDirectory ? getAbsolutifyInContext()(request) : getAbsolutify()(context, request),
3913
- contextify: (context, request)=>context === contextDirectory ? getContextifyInContext()(request) : getContextify()(context, request),
3914
- createHash: (type)=>createHash_createHash(type || compiler._lastCompilation.outputOptions.hashFunction)
3915
- }, loaderContext._compiler = compiler, loaderContext._compilation = compiler._lastCompilation, loaderContext._module = context._module, loaderContext.getOptions = ()=>{
3916
- let loader = getCurrentLoader(loaderContext), options = loader?.options;
3917
- if ('string' == typeof options) if (options.startsWith('{') && options.endsWith('}')) try {
3918
- options = JSON.parse(options);
3919
- } catch (e) {
3920
- throw Error(`JSON parsing failed for loader's string options: ${e.message}`);
4063
+ }
4064
+ }
4065
+ let CURRENT_METHOD_REGEXP = /at ([a-zA-Z0-9_.]*)/;
4066
+ function createMessage(method) {
4067
+ return `Abstract method${method ? ` ${method}` : ''}. Must be overridden.`;
4068
+ }
4069
+ class Message extends Error {
4070
+ constructor(){
4071
+ super(), this.stack = void 0, Error.captureStackTrace(this);
4072
+ let match = this.stack.split('\n')[3].match(CURRENT_METHOD_REGEXP);
4073
+ this.message = match?.[1] ? createMessage(match[1]) : createMessage();
4074
+ }
4075
+ }
4076
+ class AbstractMethodError extends lib_WebpackError {
4077
+ constructor(){
4078
+ super(new Message().message), this.name = 'AbstractMethodError';
4079
+ }
4080
+ }
4081
+ class Hash {
4082
+ update() {
4083
+ throw new AbstractMethodError();
4084
+ }
4085
+ digest() {
4086
+ throw new AbstractMethodError();
4087
+ }
4088
+ }
4089
+ let MAX_SHORT_STRING = -4 & Math.floor(16368);
4090
+ class WasmHash {
4091
+ exports;
4092
+ instancesPool;
4093
+ buffered;
4094
+ mem;
4095
+ chunkSize;
4096
+ digestSize;
4097
+ constructor(instance, instancesPool, chunkSize, digestSize){
4098
+ let exports = instance.exports;
4099
+ exports.init(), this.exports = exports, this.mem = Buffer.from(exports.memory.buffer, 0, 65536), this.buffered = 0, this.instancesPool = instancesPool, this.chunkSize = chunkSize, this.digestSize = digestSize;
4100
+ }
4101
+ reset() {
4102
+ this.buffered = 0, this.exports.init();
4103
+ }
4104
+ update(data, encoding) {
4105
+ if ('string' == typeof data) {
4106
+ let normalizedData = data;
4107
+ for(; normalizedData.length > MAX_SHORT_STRING;)this._updateWithShortString(normalizedData.slice(0, MAX_SHORT_STRING), encoding), normalizedData = normalizedData.slice(MAX_SHORT_STRING);
4108
+ return this._updateWithShortString(normalizedData, encoding), this;
3921
4109
  }
3922
- else options = node_querystring.parse(options);
3923
- return null == options && (options = {}), options;
3924
- };
3925
- let compilation = compiler._lastCompilation, step = 0;
3926
- for(; compilation;)if (binding_namespaceObject.NormalModule.getCompilationHooks(compilation).loader.call(loaderContext, loaderContext._module), compilation = compilation.compiler.parentCompilation, ++step > 1000) throw Error('Too many nested child compiler, exceeded max limitation 1000');
3927
- Object.defineProperty(loaderContext, 'loaderIndex', {
3928
- enumerable: !0,
3929
- get: ()=>context.loaderIndex,
3930
- set: (loaderIndex)=>context.loaderIndex = loaderIndex
3931
- }), Object.defineProperty(loaderContext, 'cacheable', {
3932
- enumerable: !0,
3933
- get: ()=>(cacheable)=>{
3934
- !1 === cacheable && (context.cacheable = cacheable);
3935
- }
3936
- }), Object.defineProperty(loaderContext, 'data', {
3937
- enumerable: !0,
3938
- get: ()=>loaderContext.loaders[loaderContext.loaderIndex].loaderItem.data,
3939
- set: (data)=>loaderContext.loaders[loaderContext.loaderIndex].loaderItem.data = data
3940
- }), loaderContext.__internal__setParseMeta = (key, value)=>{
3941
- context.__internal__parseMeta[key] = value;
3942
- };
3943
- let enableParallelism = (currentLoaderObject)=>currentLoaderObject?.parallel, isomorphoicRun = async (fn, args)=>{
3944
- let result, currentLoaderObject = getCurrentLoader(loaderContext), parallelism = enableParallelism(currentLoaderObject), pitch = loaderState === binding_namespaceObject.JsLoaderState.Pitching, loaderName = function(loaderPath, cwd = '') {
3945
- let res = loaderPath.replace(cwd, '');
3946
- if (!node_path.isAbsolute(res)) return res;
3947
- let nms = '/node_modules/', idx = res.lastIndexOf(nms);
3948
- if (-1 !== idx) {
3949
- res = res.slice(idx + nms.length);
3950
- let ln = 'loader', lnIdx = res.lastIndexOf(ln);
3951
- lnIdx > -1 && (res = res.slice(0, lnIdx + ln.length));
4110
+ return this._updateWithBuffer(data), this;
4111
+ }
4112
+ _updateWithShortString(data, encoding) {
4113
+ let endPos, { exports, buffered, mem, chunkSize } = this;
4114
+ if (data.length < 70) if (encoding && 'utf-8' !== encoding && 'utf8' !== encoding) if ('latin1' === encoding) {
4115
+ endPos = buffered;
4116
+ for(let i = 0; i < data.length; i++){
4117
+ let cc = data.charCodeAt(i);
4118
+ mem[endPos++] = cc;
3952
4119
  }
3953
- return res;
3954
- }(currentLoaderObject.request);
3955
- if (JavaScriptTracer.startAsync({
3956
- name: loaderName,
3957
- trackName: loaderName,
3958
- processName: LOADER_PROCESS_NAME,
3959
- uuid,
3960
- args: {
3961
- is_pitch: pitch,
3962
- resource: resource
4120
+ } else endPos = buffered + mem.write(data, buffered, encoding);
4121
+ else {
4122
+ endPos = buffered;
4123
+ for(let i = 0; i < data.length; i++){
4124
+ let cc = data.charCodeAt(i);
4125
+ if (cc < 0x80) mem[endPos++] = cc;
4126
+ else if (cc < 0x800) mem[endPos] = cc >> 6 | 0xc0, mem[endPos + 1] = 0x3f & cc | 0x80, endPos += 2;
4127
+ else {
4128
+ endPos += mem.write(data.slice(i), endPos, encoding);
4129
+ break;
4130
+ }
3963
4131
  }
3964
- }), parallelism) {
3965
- let normalModule, workerLoaderContext;
3966
- result = await service_run(loaderName, {
3967
- loaderContext: (normalModule = loaderContext._module instanceof binding_namespaceObject.NormalModule ? loaderContext._module : void 0, Object.assign(workerLoaderContext = {
3968
- hot: loaderContext.hot,
3969
- context: loaderContext.context,
3970
- resourcePath: loaderContext.resourcePath,
3971
- resourceQuery: loaderContext.resourceQuery,
3972
- resourceFragment: loaderContext.resourceFragment,
3973
- resource: loaderContext.resource,
3974
- mode: loaderContext.mode,
3975
- sourceMap: loaderContext.sourceMap,
3976
- rootContext: loaderContext.rootContext,
3977
- loaderIndex: loaderContext.loaderIndex,
3978
- loaders: loaderContext.loaders.map((item)=>{
3979
- let options = item.options;
3980
- return (!item.parallel || item.request.startsWith(BUILTIN_LOADER_PREFIX)) && (options = void 0), {
3981
- ...item,
3982
- options,
3983
- pitch: void 0,
3984
- normal: void 0,
3985
- normalExecuted: item.normalExecuted,
3986
- pitchExecuted: item.pitchExecuted
3987
- };
3988
- }),
3989
- __internal__workerInfo: {
3990
- hashFunction: compiler._lastCompilation.outputOptions.hashFunction
3991
- },
3992
- _compiler: {
3993
- options: {
3994
- experiments: {
3995
- css: !0
3996
- }
3997
- }
3998
- },
3999
- _compilation: {
4000
- options: {
4001
- output: {
4002
- environment: compiler._lastCompilation.outputOptions.environment
4003
- }
4004
- },
4005
- outputOptions: {
4006
- hashSalt: compiler._lastCompilation.outputOptions.hashSalt,
4007
- hashFunction: compiler._lastCompilation.outputOptions.hashFunction,
4008
- hashDigest: compiler._lastCompilation.outputOptions.hashDigest,
4009
- hashDigestLength: compiler._lastCompilation.outputOptions.hashDigestLength
4010
- }
4011
- },
4012
- _module: {
4013
- type: loaderContext._module.type,
4014
- identifier: loaderContext._module.identifier(),
4015
- matchResource: normalModule?.matchResource,
4016
- request: normalModule?.request,
4017
- userRequest: normalModule?.userRequest,
4018
- rawRequest: normalModule?.rawRequest
4019
- }
4020
- }, compiler.options.loader), workerLoaderContext),
4021
- loaderState,
4022
- args
4023
- }, {
4024
- handleIncomingRequest (requestType, ...args) {
4025
- switch(requestType){
4026
- case "AddDependency":
4027
- loaderContext.addDependency(args[0]);
4028
- break;
4029
- case "AddContextDependency":
4030
- loaderContext.addContextDependency(args[0]);
4031
- break;
4032
- case "AddMissingDependency":
4033
- loaderContext.addMissingDependency(args[0]);
4034
- break;
4035
- case "AddBuildDependency":
4036
- loaderContext.addBuildDependency(args[0]);
4037
- break;
4038
- case "GetDependencies":
4039
- return loaderContext.getDependencies();
4040
- case "GetContextDependencies":
4041
- return loaderContext.getContextDependencies();
4042
- case "GetMissingDependencies":
4043
- return loaderContext.getMissingDependencies();
4044
- case "ClearDependencies":
4045
- loaderContext.clearDependencies();
4046
- break;
4047
- case "Resolve":
4048
- return new Promise((resolve, reject)=>{
4049
- loaderContext.resolve(args[0], args[1], (err, result)=>{
4050
- err ? reject(err) : resolve(result);
4051
- });
4052
- });
4053
- case "GetResolve":
4054
- return new Promise((resolve, reject)=>{
4055
- loaderContext.getResolve(args[0])(args[1], args[2], (err, result)=>{
4056
- err ? reject(err) : resolve(result);
4057
- });
4058
- });
4059
- case "GetLogger":
4060
- {
4061
- let [type, name, arg] = args;
4062
- loaderContext.getLogger(name)[type](...arg);
4063
- break;
4064
- }
4065
- case "EmitError":
4066
- {
4067
- let workerError = args[0], error = Error(workerError.message);
4068
- error.stack = workerError.stack, error.name = workerError.name, loaderContext.emitError(error);
4069
- break;
4070
- }
4071
- case "EmitWarning":
4072
- {
4073
- let workerError = args[0], error = Error(workerError.message);
4074
- error.stack = workerError.stack, error.name = workerError.name, loaderContext.emitWarning(error);
4075
- break;
4076
- }
4077
- case "EmitFile":
4078
- {
4079
- let [name, content, sourceMap, assetInfo] = args;
4080
- loaderContext.emitFile(name, content, sourceMap, assetInfo);
4081
- break;
4082
- }
4083
- case "EmitDiagnostic":
4084
- {
4085
- let diagnostic = args[0];
4086
- loaderContext.experiments.emitDiagnostic(diagnostic);
4087
- break;
4088
- }
4089
- case "SetCacheable":
4090
- {
4091
- let cacheable = args[0];
4092
- loaderContext.cacheable(cacheable);
4093
- break;
4094
- }
4095
- case "ImportModule":
4096
- return loaderContext.importModule(args[0], args[1]);
4097
- case "UpdateLoaderObjects":
4098
- {
4099
- let updates = args[0];
4100
- loaderContext.loaders = loaderContext.loaders.map((item, index)=>{
4101
- let update = updates[index];
4102
- return item.loaderItem.data = update.data, update.pitchExecuted && (item.pitchExecuted = !0), update.normalExecuted && (item.normalExecuted = !0), item;
4103
- });
4104
- break;
4105
- }
4106
- case "CompilationGetPath":
4107
- {
4108
- let filename = args[0], data = args[1];
4109
- return compiler._lastCompilation.getPath(filename, data);
4110
- }
4111
- case "CompilationGetPathWithInfo":
4112
- {
4113
- let filename = args[0], data = args[1];
4114
- return compiler._lastCompilation.getPathWithInfo(filename, data);
4115
- }
4116
- case "CompilationGetAssetPath":
4117
- {
4118
- let filename = args[0], data = args[1];
4119
- return compiler._lastCompilation.getAssetPath(filename, data);
4120
- }
4121
- case "CompilationGetAssetPathWithInfo":
4122
- {
4123
- let filename = args[0], data = args[1];
4124
- return compiler._lastCompilation.getAssetPathWithInfo(filename, data);
4125
- }
4126
- default:
4127
- throw Error(`Unknown request type: ${requestType}`);
4128
- }
4129
- }
4130
- }, 'object' == typeof currentLoaderObject?.parallel ? currentLoaderObject.parallel : void 0) || [];
4131
- } else loaderState === binding_namespaceObject.JsLoaderState.Normal && function(args, raw) {
4132
- if (!raw && args[0] instanceof Uint8Array) {
4133
- var buf;
4134
- let isShared, str;
4135
- args[0] = (isShared = (buf = args[0]).buffer instanceof SharedArrayBuffer || buf.buffer.constructor?.name === 'SharedArrayBuffer', 0xfeff === (str = decoder.decode(isShared ? Buffer.from(buf) : buf)).charCodeAt(0) ? str.slice(1) : str);
4136
- } else raw && 'string' == typeof args[0] && (args[0] = Buffer.from(args[0], 'utf-8'));
4137
- raw && args[0] instanceof Uint8Array && !Buffer.isBuffer(args[0]) && (args[0] = Buffer.from(args[0].buffer));
4138
- }(args, !!currentLoaderObject?.raw), result = await utils_runSyncOrAsync(fn, loaderContext, args) || [];
4139
- return JavaScriptTracer.endAsync({
4140
- name: loaderName,
4141
- trackName: loaderName,
4142
- processName: LOADER_PROCESS_NAME,
4143
- uuid,
4144
- args: {
4145
- is_pitch: pitch,
4146
- resource: resource
4147
- }
4148
- }), result;
4149
- };
4150
- try {
4151
- switch(loaderState){
4152
- case binding_namespaceObject.JsLoaderState.Pitching:
4153
- for(; loaderContext.loaderIndex < loaderContext.loaders.length;){
4154
- let currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex], parallelism = enableParallelism(currentLoaderObject);
4155
- if (currentLoaderObject.shouldYield()) break;
4156
- if (currentLoaderObject.pitchExecuted) {
4157
- loaderContext.loaderIndex += 1;
4158
- continue;
4159
- }
4160
- await utils_loadLoader(currentLoaderObject, compiler);
4161
- let fn = currentLoaderObject.pitch;
4162
- if (parallelism && fn || (currentLoaderObject.pitchExecuted = !0), !fn) continue;
4163
- let args = await isomorphoicRun(fn, [
4164
- loaderContext.remainingRequest,
4165
- loaderContext.previousRequest,
4166
- currentLoaderObject.loaderItem.data
4167
- ]);
4168
- if (args.some((value)=>void 0 !== value)) {
4169
- let [content, sourceMap, additionalData] = args;
4170
- context.content = isNil(content) ? null : toBuffer(content), context.sourceMap = serializeObject(sourceMap), context.additionalData = additionalData || void 0;
4171
- break;
4172
- }
4173
- }
4174
- break;
4175
- case binding_namespaceObject.JsLoaderState.Normal:
4176
- {
4177
- let content = context.content, sourceMap = JsSourceMap.__from_binding(context.sourceMap), additionalData = context.additionalData;
4178
- for(; loaderContext.loaderIndex >= 0;){
4179
- let currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex], parallelism = enableParallelism(currentLoaderObject);
4180
- if (currentLoaderObject.shouldYield()) break;
4181
- if (currentLoaderObject.normalExecuted) {
4182
- loaderContext.loaderIndex--;
4183
- continue;
4184
- }
4185
- await utils_loadLoader(currentLoaderObject, compiler);
4186
- let fn = currentLoaderObject.normal;
4187
- parallelism && fn || (currentLoaderObject.normalExecuted = !0), fn && ([content, sourceMap, additionalData] = await isomorphoicRun(fn, [
4188
- content,
4189
- sourceMap,
4190
- additionalData
4191
- ]));
4192
- }
4193
- context.content = isNil(content) ? null : toBuffer(content), context.sourceMap = JsSourceMap.__to_binding(sourceMap), context.additionalData = additionalData || void 0, context.__internal__utf8Hint = 'string' == typeof content;
4194
- break;
4195
- }
4196
- default:
4197
- throw Error(`Unexpected loader runner state: ${loaderState}`);
4198
- }
4199
- context.loaderItems = loaderContext.loaders.map((item)=>LoaderObject.__to_binding(item));
4200
- } catch (e) {
4201
- if ('object' != typeof e || null === e) {
4202
- let error = Error(`(Emitted value instead of an instance of Error) ${e}`);
4203
- error.name = 'NonErrorEmittedError', context.__internal__error = error;
4204
- } else context.__internal__error = e;
4205
- }
4206
- return JavaScriptTracer.endAsync({
4207
- name: 'run_js_loaders',
4208
- uuid,
4209
- args: {
4210
- is_pitch: pitch,
4211
- resource: resource
4212
4132
  }
4213
- }), compiler.options?.cache && Object.keys(buildInfo = context._module.buildInfo).some((key)=>!knownBuildInfoFields.has(key)) && buildInfo[binding_default().COMMIT_CUSTOM_FIELDS_SYMBOL](), context;
4214
- }
4215
- let loader_runner_PATH_QUERY_FRAGMENT_REGEXP = /^((?:\u200b.|[^?#\u200b])*)(\?(?:\u200b.|[^#\u200b])*)?(#.*)?$/;
4216
- function parsePathQueryFragment(str) {
4217
- let match = loader_runner_PATH_QUERY_FRAGMENT_REGEXP.exec(str);
4218
- return {
4219
- path: match?.[1].replace(/\u200b(.)/g, '$1') || '',
4220
- query: match?.[2] ? match[2].replace(/\u200b(.)/g, '$1') : '',
4221
- fragment: match?.[3] || ''
4222
- };
4223
- }
4224
- let BUILTIN_LOADER_PREFIX = 'builtin:';
4225
- function createRawModuleRuleUses(uses, path, options) {
4226
- var uses1, path1, options1;
4227
- let normalizeRuleSetUseItem = (item)=>'string' == typeof item ? {
4228
- loader: item
4229
- } : item;
4230
- return uses1 = Array.isArray(uses) ? [
4231
- ...uses
4232
- ].map(normalizeRuleSetUseItem) : [
4233
- normalizeRuleSetUseItem(uses)
4234
- ], path1 = path, options1 = options, uses1.length ? uses1.filter(Boolean).map((use, index)=>{
4235
- let o, isBuiltin = !1;
4236
- if (use.loader.startsWith(BUILTIN_LOADER_PREFIX)) {
4237
- let temp = function(identifier, o, options) {
4238
- if (identifier.startsWith(`${BUILTIN_LOADER_PREFIX}swc-loader`)) return ((o, composeOptions)=>{
4239
- let options = o ?? {};
4240
- if ('object' == typeof options) {
4241
- var options1;
4242
- if (options.jsc ??= {}, options.jsc.experimental ??= {}, options.jsc.experimental.disableAllLints ??= !0, options.env?.targets === void 0 && options.jsc?.target === void 0) {
4243
- if (composeOptions.compiler.target?.targets) options.env ??= {}, options.env.targets ??= function(targets) {
4244
- let REMAP = {
4245
- and_chr: 'chrome',
4246
- and_ff: 'firefox',
4247
- ie_mob: 'ie',
4248
- ios_saf: 'ios',
4249
- op_mob: 'opera',
4250
- and_qq: null,
4251
- and_uc: null,
4252
- baidu: null,
4253
- bb: null,
4254
- kaios: null,
4255
- op_mini: null
4256
- }, result = {};
4257
- for (let [k, version] of Object.entries(targets)){
4258
- let remap = REMAP[k];
4259
- null !== remap && (result[remap || k] = version);
4260
- }
4261
- return result;
4262
- }(composeOptions.compiler.target.targets);
4263
- else if (composeOptions.compiler.target?.esVersion) {
4264
- let { esVersion } = composeOptions.compiler.target;
4265
- options.jsc.target ??= esVersion >= 2015 ? `es${esVersion}` : 'es5';
4266
- }
4267
- }
4268
- options.collectTypeScriptInfo && (options.collectTypeScriptInfo = {
4269
- typeExports: (options1 = options.collectTypeScriptInfo).typeExports,
4270
- exportedEnum: !0 === options1.exportedEnum ? 'all' : !1 === options1.exportedEnum || void 0 === options1.exportedEnum ? 'none' : 'const-only'
4271
- }), options.transformImport && (options.transformImport = resolvePluginImport(options.transformImport));
4272
- let { rspackExperiments } = options;
4273
- rspackExperiments && (rspackExperiments.import || rspackExperiments.pluginImport) && (rspackExperiments.import = resolvePluginImport(rspackExperiments.import || rspackExperiments.pluginImport));
4274
- }
4275
- return options;
4276
- })(o, options);
4277
- if (identifier.startsWith(`${BUILTIN_LOADER_PREFIX}lightningcss-loader`)) {
4278
- let options1;
4279
- return 'object' == typeof (options1 = o ?? {}) && ('string' == typeof options1.targets ? options1.targets = [
4280
- options1.targets
4281
- ] : 'object' != typeof options1.targets || Array.isArray(options1.targets) ? void 0 === options1.targets && options.compiler.target?.targets && (options1.targets = defaultTargetsFromRspackTargets(options.compiler.target.targets)) : options1.targets = encodeTargets(options1.targets), options1.include && 'object' == typeof options1.include && (options1.include = toFeatures(options1.include)), options1.exclude && 'object' == typeof options1.exclude && (options1.exclude = toFeatures(options1.exclude))), options1;
4282
- }
4283
- return o;
4284
- }(use.loader, use.options, options1);
4285
- o = isNil(temp) ? void 0 : 'string' == typeof temp ? temp : JSON.stringify(temp, null, 2), isBuiltin = !0;
4133
+ else endPos = buffered + mem.write(data, buffered, encoding);
4134
+ if (endPos < chunkSize) this.buffered = endPos;
4135
+ else {
4136
+ let l = endPos & ~(this.chunkSize - 1);
4137
+ exports.update(l);
4138
+ let newBuffered = endPos - l;
4139
+ this.buffered = newBuffered, newBuffered > 0 && mem.copyWithin(0, l, endPos);
4286
4140
  }
4287
- return {
4288
- loader: function(use, path, compiler, isBuiltin) {
4289
- let obj = parsePathQueryFragment(use.loader), ident = use.ident;
4290
- null === use.options || void 0 === use.options || ('string' == typeof use.options ? obj.query = `?${use.options}` : use.ident ? obj.query = `??${ident = use.ident}` : 'object' == typeof use.options && use.options.ident ? obj.query = `??${ident = use.options.ident}` : 'object' == typeof use.options ? obj.query = `??${ident = path}` : obj.query = `?${JSON.stringify(use.options)}`);
4291
- let parallelism = use.parallel;
4292
- if (parallelism && (!use.options || 'object' != typeof use.options)) throw Error(`\`Rule.use.parallel\` requires \`Rule.use.options\` to be an object.\nHowever the received value is \`${use.options}\` under option path \`${path}\`\nInternally, parallelism is provided by passing \`Rule.use.ident\` to the loader as an identifier to ident the parallelism option\nYou can either replace the \`Rule.use.loader\` with \`Rule.use.options = {}\` or remove \`Rule.use.parallel\`.`);
4293
- return use.options && 'object' == typeof use.options && (ident || (ident = '[[missing ident]]'), compiler.__internal__ruleSet.references.set(ident, use.options), compiler.__internal__ruleSet.references.set(`${ident}$$parallelism`, parallelism), isBuiltin && compiler.__internal__ruleSet.builtinReferences.set(ident, use.options)), obj.path + obj.query + obj.fragment;
4294
- }(use, `${path1}[${index}]`, options1.compiler, isBuiltin),
4295
- options: o
4296
- };
4297
- }) : [];
4298
- }
4299
- function isUseSourceMap(devtool) {
4300
- return !!devtool && devtool.includes('source-map') && (devtool.includes('module') || !devtool.includes('cheap'));
4301
- }
4302
- function getRawAlias(alias = {}) {
4303
- return !('object' != typeof alias || null === alias || Array.isArray(alias)) && Object.entries(alias).map(([key, value])=>({
4304
- path: key,
4305
- redirect: Array.isArray(value) ? value : [
4306
- value
4307
- ]
4308
- }));
4309
- }
4310
- function getRawResolve(resolve) {
4311
- var byDependency;
4312
- return {
4313
- ...resolve,
4314
- alias: getRawAlias(resolve.alias),
4315
- fallback: getRawAlias(resolve.fallback),
4316
- extensionAlias: function(alias = {}) {
4317
- if ('object' == typeof alias && null !== alias) return Object.fromEntries(Object.entries(alias).map(([key, value])=>Array.isArray(value) ? [
4318
- key,
4319
- value
4320
- ] : [
4321
- key,
4322
- [
4323
- value
4324
- ]
4325
- ]));
4326
- }(resolve.extensionAlias),
4327
- tsconfig: function(tsConfig) {
4328
- if ('string' == typeof tsConfig) throw Error('should resolve string tsConfig in normalization');
4329
- if (void 0 === tsConfig) return tsConfig;
4330
- let { configFile, references } = tsConfig;
4331
- return {
4332
- configFile,
4333
- referencesType: 'auto' === references ? 'auto' : references ? 'manual' : 'disabled',
4334
- references: 'auto' === references ? void 0 : references
4335
- };
4336
- }(resolve.tsConfig),
4337
- byDependency: void 0 === (byDependency = resolve.byDependency) ? byDependency : Object.fromEntries(Object.entries(byDependency).map(([k, v])=>[
4338
- k,
4339
- getRawResolve(v)
4340
- ]))
4341
- };
4342
- }
4343
- function tryMatch(payload, condition) {
4344
- if ('string' == typeof condition) return payload.startsWith(condition);
4345
- if (condition instanceof RegExp) return condition.test(payload);
4346
- if ('function' == typeof condition) return condition(payload);
4347
- if (Array.isArray(condition)) return condition.some((c)=>tryMatch(payload, c));
4348
- if (condition && 'object' == typeof condition) {
4349
- if (condition.and) return condition.and.every((c)=>tryMatch(payload, c));
4350
- if (condition.or) return condition.or.some((c)=>tryMatch(payload, c));
4351
- if (condition.not) return !tryMatch(payload, condition.not);
4352
4141
  }
4353
- return !1;
4354
- }
4355
- let getRawModuleRule = (rule, path, options, upperType)=>{
4356
- let funcUse, normalizedUse = rule.loader ? [
4357
- {
4358
- loader: rule.loader,
4359
- options: rule.options
4360
- }
4361
- ] : rule.use;
4362
- 'function' == typeof normalizedUse && (funcUse = (rawContext)=>createRawModuleRuleUses(normalizedUse({
4363
- ...rawContext,
4364
- compiler: options.compiler
4365
- }) ?? [], `${path}.use`, options));
4366
- let rawModuleRule = {
4367
- test: rule.test ? getRawRuleSetCondition(rule.test) : void 0,
4368
- include: rule.include ? getRawRuleSetCondition(rule.include) : void 0,
4369
- exclude: rule.exclude ? getRawRuleSetCondition(rule.exclude) : void 0,
4370
- issuer: rule.issuer ? getRawRuleSetCondition(rule.issuer) : void 0,
4371
- issuerLayer: rule.issuerLayer ? getRawRuleSetCondition(rule.issuerLayer) : void 0,
4372
- dependency: rule.dependency ? getRawRuleSetCondition(rule.dependency) : void 0,
4373
- phase: rule.phase ? getRawRuleSetCondition(rule.phase) : void 0,
4374
- descriptionData: rule.descriptionData ? Object.fromEntries(Object.entries(rule.descriptionData).map(([k, v])=>[
4375
- k,
4376
- getRawRuleSetCondition(v)
4377
- ])) : void 0,
4378
- with: rule.with ? Object.fromEntries(Object.entries(rule.with).map(([k, v])=>[
4379
- k,
4380
- getRawRuleSetCondition(v)
4381
- ])) : void 0,
4382
- resource: rule.resource ? getRawRuleSetCondition(rule.resource) : void 0,
4383
- resourceQuery: rule.resourceQuery ? getRawRuleSetCondition(rule.resourceQuery) : void 0,
4384
- resourceFragment: rule.resourceFragment ? getRawRuleSetCondition(rule.resourceFragment) : void 0,
4385
- scheme: rule.scheme ? getRawRuleSetCondition(rule.scheme) : void 0,
4386
- mimetype: rule.mimetype ? getRawRuleSetCondition(rule.mimetype) : void 0,
4387
- sideEffects: rule.sideEffects,
4388
- use: 'function' == typeof normalizedUse ? funcUse : createRawModuleRuleUses(normalizedUse ?? [], `${path}.use`, options),
4389
- type: rule.type,
4390
- layer: rule.layer,
4391
- parser: rule.parser ? getRawParserOptions(rule.parser, rule.type ?? upperType) : void 0,
4392
- generator: rule.generator ? getRawGeneratorOptions(rule.generator, rule.type ?? upperType) : void 0,
4393
- resolve: rule.resolve ? getRawResolve(rule.resolve) : void 0,
4394
- oneOf: rule.oneOf ? rule.oneOf.filter(Boolean).map((rule, index)=>getRawModuleRule(rule, `${path}.oneOf[${index}]`, options, rule.type ?? upperType)) : void 0,
4395
- rules: rule.rules ? rule.rules.filter(Boolean).map((rule, index)=>getRawModuleRule(rule, `${path}.rules[${index}]`, options, rule.type ?? upperType)) : void 0,
4396
- enforce: rule.enforce,
4397
- extractSourceMap: rule.extractSourceMap
4398
- };
4399
- return ('function' == typeof rule.test || 'function' == typeof rule.resource || 'function' == typeof rule.resourceQuery || 'function' == typeof rule.resourceFragment) && (delete rawModuleRule.test, delete rawModuleRule.resource, delete rawModuleRule.resourceQuery, delete rawModuleRule.resourceFragment, rawModuleRule.rspackResource = getRawRuleSetCondition((resourceQueryFragment)=>{
4400
- let { path, query, fragment } = parseResource(resourceQueryFragment);
4401
- return (!rule.test || !!tryMatch(path, rule.test)) && (!rule.resource || !!tryMatch(path, rule.resource)) && (!rule.resourceQuery || !!tryMatch(query, rule.resourceQuery)) && (!rule.resourceFragment || !!tryMatch(fragment, rule.resourceFragment));
4402
- })), rawModuleRule;
4403
- };
4404
- function getRawRuleSetCondition(condition) {
4405
- if ('string' == typeof condition) return {
4406
- type: binding_namespaceObject.RawRuleSetConditionType.string,
4407
- string: condition
4408
- };
4409
- if (condition instanceof RegExp) return {
4410
- type: binding_namespaceObject.RawRuleSetConditionType.regexp,
4411
- regexp: condition
4412
- };
4413
- if ('function' == typeof condition) return {
4414
- type: binding_namespaceObject.RawRuleSetConditionType.func,
4415
- func: condition
4416
- };
4417
- if (Array.isArray(condition)) return {
4418
- type: binding_namespaceObject.RawRuleSetConditionType.array,
4419
- array: condition.map((i)=>getRawRuleSetCondition(i))
4420
- };
4421
- if ('object' == typeof condition && null !== condition) {
4422
- var logical;
4423
- return {
4424
- type: binding_namespaceObject.RawRuleSetConditionType.logical,
4425
- logical: [
4426
- {
4427
- and: (logical = condition).and ? logical.and.map((i)=>getRawRuleSetCondition(i)) : void 0,
4428
- or: logical.or ? logical.or.map((i)=>getRawRuleSetCondition(i)) : void 0,
4429
- not: logical.not ? getRawRuleSetCondition(logical.not) : void 0
4430
- }
4431
- ]
4432
- };
4142
+ _updateWithBuffer(data) {
4143
+ let { exports, buffered, mem } = this, length = data.length;
4144
+ if (buffered + length < this.chunkSize) data.copy(mem, buffered, 0, length), this.buffered += length;
4145
+ else {
4146
+ let l = buffered + length & ~(this.chunkSize - 1);
4147
+ if (l > 65536) {
4148
+ let i = 65536 - buffered;
4149
+ data.copy(mem, buffered, 0, i), exports.update(65536);
4150
+ let stop = l - buffered - 65536;
4151
+ for(; i < stop;)data.copy(mem, 0, i, i + 65536), exports.update(65536), i += 65536;
4152
+ data.copy(mem, 0, i, l - buffered), exports.update(l - buffered - i);
4153
+ } else data.copy(mem, buffered, 0, l - buffered), exports.update(l);
4154
+ let newBuffered = length + buffered - l;
4155
+ this.buffered = newBuffered, newBuffered > 0 && data.copy(mem, 0, length - newBuffered, length);
4156
+ }
4157
+ }
4158
+ digest(type) {
4159
+ let { exports, buffered, mem, digestSize } = this;
4160
+ exports.final(buffered), this.instancesPool.push(this);
4161
+ let hex = mem.toString('latin1', 0, digestSize);
4162
+ return 'hex' === type ? hex : 'binary' !== type && type ? Buffer.from(hex, 'hex').toString(type) : Buffer.from(hex, 'hex');
4433
4163
  }
4434
- throw Error('unreachable: condition should be one of string, RegExp, Array, Object');
4435
4164
  }
4436
- function getRawParserOptions(parser, type) {
4437
- var parser1, parser2, parser3;
4438
- if ('asset' === type) {
4439
- return {
4440
- type: 'asset',
4441
- asset: {
4442
- dataUrlCondition: (parser1 = parser).dataUrlCondition ? function(dataUrlCondition) {
4443
- if ('object' == typeof dataUrlCondition && null !== dataUrlCondition) return {
4444
- type: 'options',
4445
- options: {
4446
- maxSize: dataUrlCondition.maxSize
4447
- }
4448
- };
4449
- throw Error(`unreachable: AssetParserDataUrl type should be one of "options", but got ${dataUrlCondition}`);
4450
- }(parser1.dataUrlCondition) : void 0
4451
- }
4452
- };
4165
+ let wasm_hash = (wasmModule, instancesPool, chunkSize, digestSize)=>{
4166
+ if (instancesPool.length > 0) {
4167
+ let old = instancesPool.pop();
4168
+ return old.reset(), old;
4453
4169
  }
4454
- if ("javascript" === type) return {
4455
- type: "javascript",
4456
- javascript: getRawJavascriptParserOptions(parser)
4457
- };
4458
- if ("javascript/auto" === type) return {
4459
- type: "javascript/auto",
4460
- javascript: getRawJavascriptParserOptions(parser)
4461
- };
4462
- if ("javascript/dynamic" === type) return {
4463
- type: "javascript/dynamic",
4464
- javascript: getRawJavascriptParserOptions(parser)
4465
- };
4466
- if ("javascript/esm" === type) return {
4467
- type: "javascript/esm",
4468
- javascript: getRawJavascriptParserOptions(parser)
4469
- };
4470
- if ('css' === type) {
4471
- return {
4472
- type: 'css',
4473
- css: {
4474
- namedExports: (parser2 = parser).namedExports,
4475
- url: parser2.url,
4476
- import: parser2.import,
4477
- resolveImport: parser2.resolveImport
4478
- }
4479
- };
4170
+ return new WasmHash(new WebAssembly.Instance(wasmModule), instancesPool, chunkSize, digestSize);
4171
+ }, createHash_require = createRequire(import.meta.url), digestCaches = {};
4172
+ class BulkUpdateDecorator extends Hash {
4173
+ hash;
4174
+ hashFactory;
4175
+ hashKey;
4176
+ buffer;
4177
+ constructor(hashOrFactory, hashKey){
4178
+ super(), this.hashKey = hashKey, 'function' == typeof hashOrFactory ? (this.hashFactory = hashOrFactory, this.hash = void 0) : (this.hashFactory = void 0, this.hash = hashOrFactory), this.buffer = '';
4480
4179
  }
4481
- if ('css/auto' === type) return {
4482
- type: 'css/auto',
4483
- cssAuto: getRawCssAutoOrModuleParserOptions(parser)
4484
- };
4485
- if ('css/global' === type) return {
4486
- type: 'css/global',
4487
- cssGlobal: getRawCssModuleParserOptions(parser)
4488
- };
4489
- if ('css/module' === type) return {
4490
- type: 'css/module',
4491
- cssModule: getRawCssAutoOrModuleParserOptions(parser)
4492
- };
4493
- if ('json' === type) {
4494
- return {
4495
- type: 'json',
4496
- json: {
4497
- exportsDepth: (parser3 = parser).exportsDepth,
4498
- parse: 'function' == typeof parser3.parse ? (str)=>JSON.stringify(parser3.parse(str)) : void 0
4499
- }
4500
- };
4180
+ update(data, inputEncoding) {
4181
+ return void 0 !== inputEncoding || 'string' != typeof data || data.length > 2000 ? (void 0 === this.hash && (this.hash = this.hashFactory()), this.buffer.length > 0 && (this.hash.update(Buffer.from(this.buffer)), this.buffer = ''), Buffer.isBuffer(data) ? this.hash.update(data) : this.hash.update(data, inputEncoding)) : (this.buffer += data, this.buffer.length > 2000 && (void 0 === this.hash && (this.hash = this.hashFactory()), this.hash.update(Buffer.from(this.buffer)), this.buffer = '')), this;
4182
+ }
4183
+ digest(encoding) {
4184
+ let digestCache, buffer = this.buffer;
4185
+ if (void 0 === this.hash) {
4186
+ let cacheKey = `${this.hashKey}-${encoding}`;
4187
+ void 0 === (digestCache = digestCaches[cacheKey]) && (digestCache = digestCaches[cacheKey] = new Map());
4188
+ let cacheEntry = digestCache.get(buffer);
4189
+ if (void 0 !== cacheEntry) return encoding ? cacheEntry : Buffer.from(cacheEntry, 'hex');
4190
+ this.hash = this.hashFactory();
4191
+ }
4192
+ buffer.length > 0 && this.hash.update(Buffer.from(buffer));
4193
+ let result = encoding ? this.hash.digest(encoding) : this.hash.digest();
4194
+ return void 0 !== digestCache && 'string' == typeof result && digestCache.set(buffer, result), result;
4501
4195
  }
4502
- throw Error(`unreachable: unknown module type: ${type}`);
4503
- }
4504
- function getRawJavascriptParserOptions(parser) {
4505
- return {
4506
- dynamicImportMode: parser.dynamicImportMode,
4507
- dynamicImportPreload: parser.dynamicImportPreload?.toString(),
4508
- dynamicImportPrefetch: parser.dynamicImportPrefetch?.toString(),
4509
- dynamicImportFetchPriority: parser.dynamicImportFetchPriority,
4510
- importMeta: 'boolean' == typeof parser.importMeta ? String(parser.importMeta) : parser.importMeta,
4511
- url: parser.url?.toString(),
4512
- exprContextCritical: parser.exprContextCritical,
4513
- unknownContextCritical: parser.unknownContextCritical,
4514
- wrappedContextCritical: parser.wrappedContextCritical,
4515
- strictThisContextOnImports: parser.strictThisContextOnImports,
4516
- wrappedContextRegExp: parser.wrappedContextRegExp,
4517
- exportsPresence: !1 === parser.exportsPresence ? 'false' : parser.exportsPresence,
4518
- importExportsPresence: !1 === parser.importExportsPresence ? 'false' : parser.importExportsPresence,
4519
- reexportExportsPresence: !1 === parser.reexportExportsPresence ? 'false' : parser.reexportExportsPresence,
4520
- worker: 'boolean' == typeof parser.worker ? parser.worker ? [
4521
- '...'
4522
- ] : [] : parser.worker,
4523
- overrideStrict: parser.overrideStrict,
4524
- requireAsExpression: parser.requireAsExpression,
4525
- requireAlias: parser.requireAlias,
4526
- requireDynamic: parser.requireDynamic,
4527
- requireResolve: parser.requireResolve,
4528
- commonjs: parser.commonjs,
4529
- importDynamic: parser.importDynamic,
4530
- commonjsMagicComments: parser.commonjsMagicComments,
4531
- typeReexportsPresence: parser.typeReexportsPresence,
4532
- jsx: parser.jsx,
4533
- deferImport: parser.deferImport,
4534
- sourceImport: parser.sourceImport,
4535
- importMetaResolve: parser.importMetaResolve,
4536
- pureFunctions: parser.pureFunctions
4537
- };
4538
- }
4539
- function getRawCssModuleParserOptions(parser) {
4540
- return {
4541
- namedExports: parser.namedExports,
4542
- url: parser.url,
4543
- import: parser.import,
4544
- resolveImport: parser.resolveImport,
4545
- animation: parser.animation,
4546
- container: parser.container,
4547
- customIdents: parser.customIdents,
4548
- dashedIdents: parser.dashedIdents,
4549
- function: parser.function,
4550
- grid: parser.grid
4551
- };
4552
- }
4553
- function getRawCssAutoOrModuleParserOptions(parser) {
4554
- return {
4555
- ...getRawCssModuleParserOptions(parser),
4556
- pure: parser.pure
4557
- };
4558
4196
  }
4559
- function getRawGeneratorOptions(generator, type) {
4560
- var options, options1;
4561
- if ('asset' === type) {
4562
- return {
4563
- type: 'asset',
4564
- asset: generator ? {
4565
- ...getRawAssetInlineGeneratorOptions(options = generator),
4566
- ...getRawAssetResourceGeneratorOptions(options)
4567
- } : void 0
4568
- };
4197
+ class WasmHashAdapter extends Hash {
4198
+ wasmHash;
4199
+ constructor(wasmHash){
4200
+ super(), this.wasmHash = wasmHash;
4569
4201
  }
4570
- if ('asset/inline' === type) return {
4571
- type: 'asset/inline',
4572
- assetInline: generator ? getRawAssetInlineGeneratorOptions(generator) : void 0
4573
- };
4574
- if ('asset/resource' === type) return {
4575
- type: 'asset/resource',
4576
- assetResource: generator ? getRawAssetResourceGeneratorOptions(generator) : void 0
4577
- };
4578
- if ('css' === type) {
4579
- return {
4580
- type: 'css',
4581
- css: {
4582
- exportsOnly: (options1 = generator).exportsOnly,
4583
- esModule: options1.esModule
4584
- }
4585
- };
4202
+ update(data, inputEncoding) {
4203
+ return Buffer.isBuffer(data) ? this.wasmHash.update(data) : this.wasmHash.update(data, inputEncoding), this;
4204
+ }
4205
+ digest(encoding) {
4206
+ return encoding ? this.wasmHash.digest(encoding) : this.wasmHash.digest();
4207
+ }
4208
+ }
4209
+ let createHash_createHash = (algorithm)=>{
4210
+ if ('function' == typeof algorithm) return new BulkUpdateDecorator(()=>new algorithm());
4211
+ switch(algorithm){
4212
+ case 'xxhash64':
4213
+ return new WasmHashAdapter((()=>{
4214
+ if (!createXxhash64) {
4215
+ let xxhash64 = new WebAssembly.Module(Buffer.from('AGFzbQEAAAABCAJgAX8AYAAAAwQDAQAABQMBAAEGGgV+AUIAC34BQgALfgFCAAt+AUIAC34BQgALByIEBGluaXQAAAZ1cGRhdGUAAQVmaW5hbAACBm1lbW9yeQIACrIIAzAAQtbrgu7q/Yn14AAkAELP1tO+0ser2UIkAUIAJAJC+erQ0OfJoeThACQDQgAkBAvUAQIBfwR+IABFBEAPCyMEIACtfCQEIwAhAiMBIQMjAiEEIwMhBQNAIAIgASkDAELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiECIAMgASkDCELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEDIAQgASkDEELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEEIAUgASkDGELP1tO+0ser2UJ+fEIfiUKHla+vmLbem55/fiEFIAAgAUEgaiIBSw0ACyACJAAgAyQBIAQkAiAFJAMLqAYCAX8EfiMEQgBSBH4jACICQgGJIwEiA0IHiXwjAiIEQgyJfCMDIgVCEol8IAJCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0gA0LP1tO+0ser2UJ+Qh+JQoeVr6+Ytt6bnn9+hUKHla+vmLbem55/fkKdo7Xqg7GNivoAfSAEQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IAVCz9bTvtLHq9lCfkIfiUKHla+vmLbem55/foVCh5Wvr5i23puef35CnaO16oOxjYr6AH0FQsXP2bLx5brqJwsjBCAArXx8IQIDQCABQQhqIABNBEAgAiABKQMAQs/W077Sx6vZQn5CH4lCh5Wvr5i23puef36FQhuJQoeVr6+Ytt6bnn9+Qp2jteqDsY2K+gB9IQIgAUEIaiEBDAELCyABQQRqIABNBEAgAiABNQIAQoeVr6+Ytt6bnn9+hUIXiULP1tO+0ser2UJ+Qvnz3fGZ9pmrFnwhAiABQQRqIQELA0AgACABRwRAIAIgATEAAELFz9my8eW66id+hUILiUKHla+vmLbem55/fiECIAFBAWohAQwBCwtBACACIAJCIYiFQs/W077Sx6vZQn4iAkIdiCAChUL5893xmfaZqxZ+IgJCIIggAoUiAkIgiCIDQv//A4NCIIYgA0KAgPz/D4NCEIiEIgNC/4GAgPAfg0IQhiADQoD+g4CA4D+DQgiIhCIDQo+AvIDwgcAHg0IIhiADQvCBwIeAnoD4AINCBIiEIgNChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IANCsODAgYOGjJgwhHw3AwBBCCACQv////8PgyICQv//A4NCIIYgAkKAgPz/D4NCEIiEIgJC/4GAgPAfg0IQhiACQoD+g4CA4D+DQgiIhCICQo+AvIDwgcAHg0IIhiACQvCBwIeAnoD4AINCBIiEIgJChoyYsODAgYMGfEIEiEKBgoSIkKDAgAGDQid+IAJCsODAgYOGjJgwhHw3AwAL', 'base64'));
4216
+ createXxhash64 = wasm_hash.bind(null, xxhash64, [], 32, 16);
4217
+ }
4218
+ return createXxhash64();
4219
+ })());
4220
+ case 'md4':
4221
+ return new WasmHashAdapter((()=>{
4222
+ if (!createMd4) {
4223
+ let md4 = new WebAssembly.Module(Buffer.from('AGFzbQEAAAABCAJgAX8AYAAAAwUEAQAAAAUDAQABBhoFfwFBAAt/AUEAC38BQQALfwFBAAt/AUEACwciBARpbml0AAAGdXBkYXRlAAIFZmluYWwAAwZtZW1vcnkCAAqLEAQmAEGBxpS6BiQBQYnXtv5+JAJB/rnrxXkkA0H2qMmBASQEQQAkAAvSCgEZfyMBIQUjAiECIwMhAyMEIQQDQCAAIAFLBEAgASgCJCISIAEoAiAiEyABKAIcIgkgASgCGCIIIAEoAhQiByABKAIQIg4gASgCDCIGIAEoAggiDyABKAIEIhAgASgCACIRIAMgBHMgAnEgBHMgBWpqQQN3IgogAiADc3EgA3MgBGpqQQd3IgsgAiAKc3EgAnMgA2pqQQt3IgwgCiALc3EgCnMgAmpqQRN3Ig0gCyAMc3EgC3MgCmpqQQN3IgogDCANc3EgDHMgC2pqQQd3IgsgCiANc3EgDXMgDGpqQQt3IgwgCiALc3EgCnMgDWpqQRN3Ig0gCyAMc3EgC3MgCmpqQQN3IhQgDCANc3EgDHMgC2pqQQd3IRUgASgCLCILIAEoAigiCiAMIA0gDSAUcyAVcXNqakELdyIWIBQgFXNxIBRzIA1qakETdyEXIAEoAjQiGCABKAIwIhkgFSAWcyAXcSAVcyAUampBA3ciFCAWIBdzcSAWcyAVampBB3chFSABKAI8Ig0gASgCOCIMIBQgF3MgFXEgF3MgFmpqQQt3IhYgFCAVc3EgFHMgF2pqQRN3IRcgEyAOIBEgFCAVIBZyIBdxIBUgFnFyampBmfOJ1AVqQQN3IhQgFiAXcnEgFiAXcXIgFWpqQZnzidQFakEFdyIVIBQgF3JxIBQgF3FyIBZqakGZ84nUBWpBCXchFiAPIBggEiAWIAcgFSAQIBQgGSAUIBVyIBZxIBQgFXFyIBdqakGZ84nUBWpBDXciFCAVIBZycSAVIBZxcmpqQZnzidQFakEDdyIVIBQgFnJxIBQgFnFyampBmfOJ1AVqQQV3IhcgFCAVcnEgFCAVcXJqakGZ84nUBWpBCXciFiAVIBdycSAVIBdxciAUampBmfOJ1AVqQQ13IhQgFiAXcnEgFiAXcXIgFWpqQZnzidQFakEDdyEVIBEgBiAVIAwgFCAKIBYgCCAUIBZyIBVxIBQgFnFyIBdqakGZ84nUBWpBBXciFyAUIBVycSAUIBVxcmpqQZnzidQFakEJdyIWIBUgF3JxIBUgF3FyampBmfOJ1AVqQQ13IhQgFiAXcnEgFiAXcXJqakGZ84nUBWpBA3ciFSALIBYgCSAUIBZyIBVxIBQgFnFyIBdqakGZ84nUBWpBBXciFiAUIBVycSAUIBVxcmpqQZnzidQFakEJdyIXIA0gFSAWciAXcSAVIBZxciAUampBmfOJ1AVqQQ13IhRzIBZzampBodfn9gZqQQN3IREgByAIIA4gFCARIBcgESAUc3MgFmogE2pBodfn9gZqQQl3IhNzcyAXampBodfn9gZqQQt3Ig4gDyARIBMgDiARIA4gE3NzIBRqIBlqQaHX5/YGakEPdyIRc3NqakGh1+f2BmpBA3ciDyAOIA8gEXNzIBNqIApqQaHX5/YGakEJdyIKcyARc2pqQaHX5/YGakELdyIIIBAgDyAKIAggDCAPIAggCnNzIBFqakGh1+f2BmpBD3ciDHNzampBodfn9gZqQQN3Ig4gEiAIIAwgDnNzIApqakGh1+f2BmpBCXciCHMgDHNqakGh1+f2BmpBC3chByAFIAYgCCAHIBggDiAHIAhzcyAMampBodfn9gZqQQ93IgpzcyAOampBodfn9gZqQQN3IgZqIQUgDSAGIAkgByAGIAsgByAGIApzcyAIampBodfn9gZqQQl3IgdzIApzampBodfn9gZqQQt3IgYgB3NzIApqakGh1+f2BmpBD3cgAmohAiADIAZqIQMgBCAHaiEEIAFBQGshAQwBCwsgBSQBIAIkAiADJAMgBCQECw0AIAAQASAAIwBqJAAL/wQCA38BfiAAIwBqrUIDhiEEIABByABqQUBxIgJBCGshAyAAIgFBAWohACABQYABOgAAA0AgACACSUEAIABBB3EbBEAgAEEAOgAAIABBAWohAAwBCwsDQCAAIAJJBEAgAEIANwMAIABBCGohAAwBCwsgAyAENwMAIAIQAUEAIwGtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEIIwKtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEQIwOtIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAEEYIwStIgRC//8DgyAEQoCA/P8Pg0IQhoQiBEL/gYCA8B+DIARCgP6DgIDgP4NCCIaEIgRCj4C8gPCBwAeDQgiGIARC8IHAh4CegPgAg0IEiIQiBEKGjJiw4MCBgwZ8QgSIQoGChIiQoMCAAYNCJ34gBEKw4MCBg4aMmDCEfDcDAAs=', 'base64'));
4224
+ createMd4 = wasm_hash.bind(null, md4, [], 64, 32);
4225
+ }
4226
+ return createMd4();
4227
+ })());
4228
+ case 'native-md4':
4229
+ return new BulkUpdateDecorator(()=>{
4230
+ let { createHash } = createHash_require('node:crypto');
4231
+ return createHash('md4');
4232
+ }, 'md4');
4233
+ default:
4234
+ return new BulkUpdateDecorator(()=>{
4235
+ let { createHash } = createHash_require('node:crypto');
4236
+ return createHash(algorithm);
4237
+ }, algorithm);
4238
+ }
4239
+ }, ModuleError_createMessage = (err, type, from)=>{
4240
+ let message = `Module ${type}${from ? ` (from ${from}):\n` : ': '}`;
4241
+ return err && 'object' == typeof err && err.message ? message += err.message : err && (message += err), message;
4242
+ }, getErrorDetails = (err)=>{
4243
+ var stack, name, message, stack1, name1, message1;
4244
+ let details, nextLine;
4245
+ return err && 'object' == typeof err && err.stack ? (stack = err.stack, name = err.name, message = err.message, cutOffLoaderExecution(stack), stack1 = stack, name1 = name, message1 = message, details = -1 === (nextLine = stack1.indexOf('\n')) ? stack1 === message1 ? '' : stack1 : stack1.slice(0, nextLine) === `${name1}: ${message1}` ? stack1.slice(nextLine + 1) : stack1) : void 0;
4246
+ };
4247
+ class ModuleError extends lib_WebpackError {
4248
+ error;
4249
+ constructor(err, { from } = {}){
4250
+ super(ModuleError_createMessage(err, 'Error', from)), this.name = 'ModuleError', this.error = err, this.details = getErrorDetails(err);
4586
4251
  }
4587
- if ('css/auto' === type) return {
4588
- type: 'css/auto',
4589
- cssAuto: getRawCssAutoOrModuleGeneratorOptions(generator)
4590
- };
4591
- if ('css/global' === type) return {
4592
- type: 'css/global',
4593
- cssGlobal: getRawCssAutoOrModuleGeneratorOptions(generator)
4594
- };
4595
- if ('css/module' === type) return {
4596
- type: 'css/module',
4597
- cssModule: getRawCssAutoOrModuleGeneratorOptions(generator)
4598
- };
4599
- if ('json' === type) return {
4600
- type: 'json',
4601
- json: {
4602
- JSONParse: generator.JSONParse
4603
- }
4604
- };
4605
- if (![
4606
- 'asset/source',
4607
- 'asset/bytes',
4608
- "javascript",
4609
- "javascript/auto",
4610
- "javascript/dynamic",
4611
- "javascript/esm"
4612
- ].includes(type)) throw Error(`unreachable: unknown module type: ${type}`);
4613
4252
  }
4614
- function getRawAssetInlineGeneratorOptions(options) {
4615
- return {
4616
- dataUrl: options.dataUrl ? function(dataUrl) {
4617
- if ('object' == typeof dataUrl && null !== dataUrl) return {
4618
- encoding: !1 === dataUrl.encoding ? 'false' : dataUrl.encoding,
4619
- mimetype: dataUrl.mimetype
4620
- };
4621
- if ('function' == typeof dataUrl && null !== dataUrl) return (source, context)=>dataUrl(source, context);
4622
- throw Error(`unreachable: AssetGeneratorDataUrl type should be one of "options", "function", but got ${dataUrl}`);
4623
- }(options.dataUrl) : void 0,
4624
- binary: options.binary
4625
- };
4253
+ class ModuleWarning extends lib_WebpackError {
4254
+ error;
4255
+ constructor(err, { from } = {}){
4256
+ super(ModuleError_createMessage(err, 'Warning', from)), this.name = 'ModuleWarning', this.error = err, this.details = getErrorDetails(err);
4257
+ }
4626
4258
  }
4627
- function getRawAssetResourceGeneratorOptions(options) {
4628
- return {
4629
- emit: options.emit,
4630
- filename: options.filename,
4631
- outputPath: options.outputPath,
4632
- publicPath: options.publicPath,
4633
- importMode: options.importMode,
4634
- binary: options.binary
4259
+ let service_require = createRequire(import.meta.url), ensureLoaderWorkerPool = async (workerOptions)=>service_pool || (service_pool = import("../compiled/tinypool/dist/index.js").then(({ Tinypool })=>{
4260
+ let availableThreads = Math.max(service_require('node:os').cpus().length - 1, 1), maxWorkers = workerOptions?.maxWorkers ? Math.max(workerOptions.maxWorkers, 1) : void 0, maxWorkersFromEnv = parseInt(process.env.RSPACK_LOADER_WORKER_THREADS || '', 10);
4261
+ return new Tinypool({
4262
+ filename: node_path.resolve(import.meta.dirname, 'worker.js'),
4263
+ useAtomics: !1,
4264
+ maxThreads: maxWorkers || maxWorkersFromEnv || availableThreads,
4265
+ minThreads: maxWorkers || maxWorkersFromEnv || availableThreads,
4266
+ concurrentTasksPerWorker: 1
4267
+ });
4268
+ }));
4269
+ function serializeError(error) {
4270
+ if (error instanceof Error || error && 'object' == typeof error && 'message' in error) return {
4271
+ ...error,
4272
+ name: error.name,
4273
+ stack: error.stack,
4274
+ message: error.message
4635
4275
  };
4636
- }
4637
- function getRawCssAutoOrModuleGeneratorOptions(options) {
4638
- return {
4639
- localIdentName: options.localIdentName,
4640
- localIdentHashDigest: options.localIdentHashDigest,
4641
- localIdentHashDigestLength: options.localIdentHashDigestLength,
4642
- localIdentHashFunction: options.localIdentHashFunction,
4643
- localIdentHashSalt: options.localIdentHashSalt,
4644
- exportsConvention: options.exportsConvention,
4645
- exportsOnly: options.exportsOnly,
4646
- esModule: options.esModule
4276
+ if ('string' == typeof error) return {
4277
+ name: 'Error',
4278
+ message: error
4647
4279
  };
4280
+ throw Error('Failed to serialize error, only string, Error instances and objects with a message property are supported');
4648
4281
  }
4649
- class ExternalsPlugin extends RspackBuiltinPlugin {
4650
- type;
4651
- externals;
4652
- placeInInitial;
4653
- fallbackType;
4654
- name = binding_namespaceObject.BuiltinPluginName.ExternalsPlugin;
4655
- #resolveRequestCache = new Map();
4656
- constructor(type, externals, placeInInitial, fallbackType){
4657
- super(), this.type = type, this.externals = externals, this.placeInInitial = placeInInitial, this.fallbackType = fallbackType;
4658
- }
4659
- raw() {
4660
- let type = this.type, externals = this.externals, raw = {
4661
- type,
4662
- fallbackType: this.fallbackType,
4663
- externals: (Array.isArray(externals) ? externals : [
4664
- externals
4665
- ]).filter(Boolean).map((item)=>this.#getRawExternalItem(item)),
4666
- placeInInitial: this.placeInInitial ?? !1
4667
- };
4668
- return createBuiltinPlugin(this.name, raw);
4669
- }
4670
- #processResolveResult = (text)=>{
4671
- if (!text) return;
4672
- let resolveRequest = this.#resolveRequestCache.get(text);
4673
- return resolveRequest || (resolveRequest = JSON.parse(text), this.#resolveRequestCache.set(text, resolveRequest)), Object.assign({}, resolveRequest);
4674
- };
4675
- #processRequest(req) {
4676
- return `${req.path.replace(/#/g, '\u200b#')}${req.query.replace(/#/g, '\u200b#')}${req.fragment}`;
4677
- }
4678
- #getRawExternalItem = (item)=>{
4679
- if ('string' == typeof item || item instanceof RegExp) return item;
4680
- if ('function' == typeof item) {
4681
- let processResolveResult = this.#processResolveResult;
4682
- return async (ctx)=>new Promise((resolve, reject)=>{
4683
- let data = ctx.data(), promise = item({
4684
- request: data.request,
4685
- dependencyType: data.dependencyType,
4686
- context: data.context,
4687
- contextInfo: {
4688
- issuer: data.contextInfo.issuer,
4689
- issuerLayer: data.contextInfo.issuerLayer ?? null
4690
- },
4691
- getResolve: (options)=>{
4692
- let rawResolve = options ? getRawResolve(options) : void 0, resolve = ctx.getResolve(rawResolve);
4693
- return (context, request, callback)=>{
4694
- if (!callback) return new Promise((promiseResolve, promiseReject)=>{
4695
- resolve(context, request, (error, text)=>{
4696
- if (error) promiseReject(error);
4697
- else {
4698
- let req = processResolveResult(text);
4699
- promiseResolve(req ? this.#processRequest(req) : void 0);
4700
- }
4701
- });
4702
- });
4703
- resolve(context, request, (error, text)=>{
4704
- if (error) callback(error);
4705
- else {
4706
- let req = processResolveResult(text);
4707
- callback(null, !!req && this.#processRequest(req), req);
4708
- }
4709
- });
4710
- };
4711
- }
4712
- }, (err, result, type)=>{
4713
- err && reject(err), resolve({
4714
- result: getRawExternalItemValueFormFnResult(result),
4715
- externalType: type
4716
- });
4282
+ let service_run = async (loaderName, task, options, workerOptions)=>ensureLoaderWorkerPool(workerOptions).then(async (pool)=>{
4283
+ let { MessageChannel } = await import("node:worker_threads"), { port1: mainPort, port2: workerPort } = new MessageChannel(), { port1: mainSyncPort, port2: workerSyncPort } = new MessageChannel();
4284
+ return new Promise((resolve, reject)=>{
4285
+ let handleError = (error)=>{
4286
+ mainPort.close(), mainSyncPort.close(), reject(error);
4287
+ }, pendingRequests = new Map();
4288
+ mainPort.on('message', (message)=>{
4289
+ 'done' === message.type ? Promise.allSettled(pendingRequests.values()).then(()=>{
4290
+ mainPort.close(), mainSyncPort.close(), resolve(message.data);
4291
+ }) : 'done-error' === message.type ? Promise.allSettled(pendingRequests.values()).then(()=>{
4292
+ mainPort.close(), mainSyncPort.close(), reject(message.error);
4293
+ }) : 'request' === message.type && pendingRequests.set(message.id, Promise.resolve().then(()=>options.handleIncomingRequest(message.requestType, ...message.data)).then((result)=>(mainPort.postMessage({
4294
+ type: 'response',
4295
+ id: message.id,
4296
+ data: result
4297
+ }), result)).catch((error)=>{
4298
+ mainPort.postMessage({
4299
+ type: 'response-error',
4300
+ id: message.id,
4301
+ error: serializeError(error)
4717
4302
  });
4718
- promise?.then ? promise.then((result)=>resolve({
4719
- result: getRawExternalItemValueFormFnResult(result),
4720
- externalType: void 0
4721
- }), (e)=>reject(e)) : 1 === item.length && resolve({
4722
- result: getRawExternalItemValueFormFnResult(promise),
4723
- externalType: void 0
4303
+ }));
4304
+ }), mainPort.on('messageerror', handleError), mainSyncPort.on('message', async (message)=>{
4305
+ let result, { sharedBuffer } = message, sharedBufferView = new Int32Array(sharedBuffer);
4306
+ try {
4307
+ if ("WaitForPendingRequest" === message.requestType) {
4308
+ let pendingRequestId = message.data[0], isArray = Array.isArray(pendingRequestId), ids = isArray ? pendingRequestId : [
4309
+ pendingRequestId
4310
+ ];
4311
+ result = await Promise.all(ids.map((id)=>pendingRequests.get(id))), isArray || (result = result[0]);
4312
+ } else throw Error(`Unknown request type: ${message.requestType}`);
4313
+ mainSyncPort.postMessage({
4314
+ type: 'response',
4315
+ id: message.id,
4316
+ data: result
4317
+ });
4318
+ } catch (e) {
4319
+ mainSyncPort.postMessage({
4320
+ type: 'response-error',
4321
+ id: message.id,
4322
+ error: serializeError(e)
4724
4323
  });
4324
+ }
4325
+ Atomics.add(sharedBufferView, 0, 1), Atomics.notify(sharedBufferView, 0, 1 / 0);
4326
+ }), mainSyncPort.on('messageerror', handleError);
4327
+ let errors = [];
4328
+ for (let key of Object.keys(task))try {
4329
+ structuredClone(task[key]);
4330
+ } catch (e) {
4331
+ errors.push({
4332
+ key,
4333
+ type: typeof task[key],
4334
+ reason: e.message
4725
4335
  });
4726
- }
4727
- if ('object' == typeof item) return Object.fromEntries(Object.entries(item).map(([k, v])=>[
4728
- k,
4729
- getRawExternalItemValue(v)
4730
- ]));
4731
- throw TypeError(`Unexpected type of external item: ${typeof item}`);
4732
- };
4733
- }
4734
- function getRawExternalItemValueFormFnResult(result) {
4735
- return void 0 === result ? result : getRawExternalItemValue(result);
4736
- }
4737
- function getRawExternalItemValue(value) {
4738
- return value && 'object' == typeof value && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).map(([k, v])=>[
4739
- k,
4740
- Array.isArray(v) ? v : [
4741
- v
4742
- ]
4743
- ])) : value;
4744
- }
4745
- let FetchCompileAsyncWasmPlugin = base_create(binding_namespaceObject.BuiltinPluginName.FetchCompileAsyncWasmPlugin, ()=>{}, 'thisCompilation'), FileUriPlugin = base_create(binding_namespaceObject.BuiltinPluginName.FileUriPlugin, ()=>{}, 'compilation'), FlagDependencyExportsPlugin = base_create(binding_namespaceObject.BuiltinPluginName.FlagDependencyExportsPlugin, ()=>{}, 'compilation');
4746
- class FlagDependencyUsagePlugin extends RspackBuiltinPlugin {
4747
- global;
4748
- name = binding_namespaceObject.BuiltinPluginName.FlagDependencyUsagePlugin;
4749
- affectedHooks = 'compilation';
4750
- constructor(global){
4751
- super(), this.global = global;
4336
+ }
4337
+ if (errors.length > 0) {
4338
+ let errorMsg = errors.map((err)=>`option "${err.key}" (type: ${err.type}) is not cloneable: ${err.reason}`).join('\n');
4339
+ throw Error(`The options for ${loaderName} are not cloneable, which is not supported by parallelLoader. Consider disabling parallel for this loader or removing the non-cloneable properties from the options:\n${errorMsg}`);
4340
+ }
4341
+ pool.run({
4342
+ ...task,
4343
+ workerData: {
4344
+ workerPort,
4345
+ workerSyncPort
4346
+ }
4347
+ }, {
4348
+ ...options,
4349
+ transferList: [
4350
+ ...options?.transferList || [],
4351
+ workerPort,
4352
+ workerSyncPort
4353
+ ]
4354
+ }).catch(handleError);
4355
+ });
4356
+ }), LoaderLoadingError = class extends Error {
4357
+ constructor(message){
4358
+ super(message), this.name = 'LoaderRunnerError', Error.captureStackTrace(this, this.constructor);
4752
4359
  }
4753
- raw() {
4754
- return createBuiltinPlugin(this.name, this.global);
4360
+ }, loadLoader_require = createRequire(import.meta.url), loadLoader_moduleCache = new Map(), modulePromiseCache = new Map(), loaderUrlCache = new Map();
4361
+ function loadLoader(loader, compiler, callback) {
4362
+ let cacheKey = `${loader.type ?? 'commonjs'}\0${loader.path}`, cachedModule = loadLoader_moduleCache.get(cacheKey);
4363
+ if (void 0 !== cachedModule) return handleResult(loader, cachedModule, callback);
4364
+ if ('module' === loader.type) try {
4365
+ let modulePromise = modulePromiseCache.get(cacheKey);
4366
+ if (void 0 === modulePromise) {
4367
+ void 0 === loadLoader_url && (loadLoader_url = loadLoader_require('node:url'));
4368
+ let loaderUrl = loaderUrlCache.get(loader.path);
4369
+ void 0 === loaderUrl && (loaderUrl = loadLoader_url.pathToFileURL(loader.path).toString(), loaderUrlCache.set(loader.path, loaderUrl)), modulePromise = import(loaderUrl).then((module)=>(loadLoader_moduleCache.set(cacheKey, module), modulePromiseCache.delete(cacheKey), module), (err)=>{
4370
+ throw modulePromiseCache.delete(cacheKey), err;
4371
+ }), modulePromiseCache.set(cacheKey, modulePromise);
4372
+ }
4373
+ modulePromise.then((module)=>{
4374
+ handleResult(loader, module, callback);
4375
+ }, callback);
4376
+ return;
4377
+ } catch (e) {
4378
+ callback(e);
4379
+ }
4380
+ else {
4381
+ let module;
4382
+ try {
4383
+ module = loadLoader_require(loader.path);
4384
+ } catch (e) {
4385
+ if (e instanceof Error && 'EMFILE' === e.code) return void setImmediate(loadLoader.bind(null, loader, compiler, callback));
4386
+ return callback(e);
4387
+ }
4388
+ return handleResult(loader, module, callback);
4755
4389
  }
4756
4390
  }
4757
- let HashedModuleIdsPlugin = base_create(binding_namespaceObject.BuiltinPluginName.HashedModuleIdsPlugin, (options)=>({
4758
- ...options
4759
- }), 'compilation');
4760
- class HotModuleReplacementPlugin extends RspackBuiltinPlugin {
4761
- name = binding_namespaceObject.BuiltinPluginName.HotModuleReplacementPlugin;
4762
- raw(compiler) {
4763
- return void 0 === compiler.options.output.strictModuleErrorHandling && (compiler.options.output.strictModuleErrorHandling = !0), createBuiltinPlugin(this.name, void 0);
4764
- }
4391
+ function handleResult(loader, module, callback) {
4392
+ return 'function' != typeof module && 'object' != typeof module ? callback(new LoaderLoadingError(`Module '${loader.path}' is not a loader (export function or es6 module)`)) : (loader.normal = 'function' == typeof module ? module : module.default, loader.pitch = module.pitch, loader.raw = module.raw, loader.pitch || (loader.noPitch = !0), 'function' != typeof loader.normal && 'function' != typeof loader.pitch) ? callback(new LoaderLoadingError(`Module '${loader.path}' is not a loader (must have normal or pitch function)`)) : void callback();
4765
4393
  }
4766
- let HttpExternalsRspackPlugin = base_create(binding_namespaceObject.BuiltinPluginName.HttpExternalsRspackPlugin, (webAsync)=>({
4767
- webAsync
4768
- })), HttpUriPlugin_require = createRequire(import.meta.url), getHttp = memoize(()=>HttpUriPlugin_require('node:http')), getHttps = memoize(()=>HttpUriPlugin_require('node:https')), defaultHttpClientForNode = async (url, headers)=>{
4769
- let { res, body } = await function(url, options) {
4770
- let send = 'https:' === new URL(url).protocol ? getHttps() : getHttp(), { createBrotliDecompress, createGunzip, createInflate } = HttpUriPlugin_require('node:zlib');
4771
- return new Promise((resolve, reject)=>{
4772
- send.get(url, options, (res)=>{
4773
- let contentEncoding = res.headers['content-encoding'], stream = res;
4774
- 'gzip' === contentEncoding ? stream = stream.pipe(createGunzip()) : 'br' === contentEncoding ? stream = stream.pipe(createBrotliDecompress()) : 'deflate' === contentEncoding && (stream = stream.pipe(createInflate()));
4775
- let chunks = [];
4776
- stream.on('data', (chunk)=>{
4777
- chunks.push(chunk);
4778
- }), stream.on('end', ()=>{
4779
- let bodyBuffer = Buffer.concat(chunks);
4780
- res.complete ? resolve({
4781
- res,
4782
- body: bodyBuffer
4783
- }) : reject(Error(`${url} request was terminated early`));
4784
- });
4785
- }).on('error', reject);
4786
- });
4787
- }(url, {
4788
- headers
4789
- }), responseHeaders = {};
4790
- for (let [key, value] of Object.entries(res.headers))Array.isArray(value) ? responseHeaders[key] = value.join(', ') : responseHeaders[key] = value;
4791
- return {
4792
- status: res.statusCode,
4793
- headers: responseHeaders,
4794
- body: Buffer.from(body)
4394
+ let decoder = new TextDecoder(), utils_loadLoader = promisify(loadLoader), utils_runSyncOrAsync = promisify(function(fn, context, args, callback) {
4395
+ let isSync = !0, isDone = !1, isError = !1, reportedError = !1;
4396
+ context.async = function() {
4397
+ if (isDone) {
4398
+ if (reportedError) return;
4399
+ throw Error('async(): The callback was already called.');
4400
+ }
4401
+ return isSync = !1, innerCallback;
4795
4402
  };
4796
- };
4797
- class HttpUriPlugin extends RspackBuiltinPlugin {
4403
+ let innerCallback = (err, ...args)=>{
4404
+ if (isDone) {
4405
+ if (reportedError) return;
4406
+ throw Error('callback(): The callback was already called.');
4407
+ }
4408
+ isDone = !0, isSync = !1;
4409
+ try {
4410
+ callback(err, args);
4411
+ } catch (e) {
4412
+ throw isError = !0, e;
4413
+ }
4414
+ };
4415
+ context.callback = innerCallback;
4416
+ try {
4417
+ let result = fn.apply(context, args);
4418
+ if (isSync) {
4419
+ if (isDone = !0, void 0 === result) return void callback(null, []);
4420
+ if (result && 'object' == typeof result && 'function' == typeof result.then) return void result.then((r)=>{
4421
+ callback(null, [
4422
+ r
4423
+ ]);
4424
+ }, callback);
4425
+ callback(null, [
4426
+ result
4427
+ ]);
4428
+ return;
4429
+ }
4430
+ } catch (e) {
4431
+ if ('hideStack' in e && e.hideStack && (e.hideStack = 'true'), isError) throw e;
4432
+ if (isDone) return void (e instanceof Error ? console.error(e.stack) : console.error(e));
4433
+ isDone = !0, reportedError = !0, callback(e, []);
4434
+ }
4435
+ }), LOADER_PROCESS_NAME = 'Loader Analysis';
4436
+ class LoaderObject {
4437
+ request;
4438
+ path;
4439
+ query;
4440
+ fragment;
4798
4441
  options;
4799
- name = binding_namespaceObject.BuiltinPluginName.HttpUriPlugin;
4800
- affectedHooks = 'compilation';
4801
- constructor(options){
4802
- super(), this.options = options;
4442
+ ident;
4443
+ normal;
4444
+ pitch;
4445
+ raw;
4446
+ type;
4447
+ parallel;
4448
+ loaderItem;
4449
+ constructor(loaderItem, compiler){
4450
+ var path, query, fragment;
4451
+ let splittedRequest = parseResourceWithoutFragment(loaderItem.loader);
4452
+ if (this.path = splittedRequest.path, this.fragment = '', this.options = splittedRequest.query ? splittedRequest.query.slice(1) : void 0, this.ident = null, this.normal = null, this.pitch = null, this.raw = null, 'string' == typeof this.options && '?' === this.options[0]) {
4453
+ let ident = this.options.slice(1);
4454
+ if ('[[missing ident]]' === ident) throw Error("No ident is provided by referenced loader. When using a function for Rule.use in config you need to provide an 'ident' property for referenced loader options.");
4455
+ if (this.options = compiler.__internal__ruleSet.references.get(ident), void 0 === this.options) throw Error('Invalid ident is provided by referenced loader');
4456
+ this.ident = ident;
4457
+ }
4458
+ this.type = '' === loaderItem.type ? void 0 : loaderItem.type, null === this.options || void 0 === this.options ? this.query = '' : 'string' == typeof this.options ? this.query = `?${this.options}` : this.ident ? this.query = `??${this.ident}` : this.options.ident ? this.query = `??${this.options.ident}` : this.query = `?${JSON.stringify(this.options)}`, this.request = (path = this.path, query = this.query, fragment = this.fragment, path.replace(/#/g, '\u200b#') + query.replace(/#/g, '\u200b#') + fragment), this.parallel = !!this.ident && compiler.__internal__ruleSet.references.get(`${this.ident}$$parallelism`), this.loaderItem = loaderItem, this.loaderItem.data = this.loaderItem.data ?? {};
4803
4459
  }
4804
- raw(compiler) {
4805
- let options = this.options, lockfileLocation = options.lockfileLocation ?? node_path.join(compiler.context, compiler.name ? `${compiler.name}.rspack.lock` : 'rspack.lock'), cacheLocation = !1 === options.cacheLocation ? void 0 : options.cacheLocation ?? `${lockfileLocation}.data`, raw = {
4806
- allowedUris: options.allowedUris,
4807
- lockfileLocation,
4808
- cacheLocation,
4809
- upgrade: options.upgrade ?? !1,
4810
- httpClient: options.httpClient ?? defaultHttpClientForNode
4811
- };
4812
- return createBuiltinPlugin(this.name, raw);
4460
+ get pitchExecuted() {
4461
+ return this.loaderItem.pitchExecuted;
4462
+ }
4463
+ set pitchExecuted(value) {
4464
+ if (!value) throw Error('pitchExecuted should be true');
4465
+ this.loaderItem.pitchExecuted = !0;
4466
+ }
4467
+ get normalExecuted() {
4468
+ return this.loaderItem.normalExecuted;
4469
+ }
4470
+ set normalExecuted(value) {
4471
+ if (!value) throw Error('normalExecuted should be true');
4472
+ this.loaderItem.normalExecuted = !0;
4473
+ }
4474
+ set noPitch(value) {
4475
+ if (!value) throw Error('noPitch should be true');
4476
+ this.loaderItem.noPitch = !0;
4477
+ }
4478
+ shouldYield() {
4479
+ return this.request.startsWith(BUILTIN_LOADER_PREFIX);
4480
+ }
4481
+ static __from_binding(loaderItem, compiler) {
4482
+ return new this(loaderItem, compiler);
4483
+ }
4484
+ static __to_binding(loader) {
4485
+ return loader.loaderItem;
4813
4486
  }
4814
4487
  }
4815
- let compilationOptionsMap = new WeakMap(), hooks_compilationHooksMap = new WeakMap(), plugin_require = createRequire(import.meta.url), HTML_PLUGIN_UID = 0, HtmlRspackPlugin = base_create(binding_namespaceObject.BuiltinPluginName.HtmlRspackPlugin, function(c = {}) {
4816
- let templateFn, templateParameters, filenames, uid = HTML_PLUGIN_UID++, meta = {};
4817
- for(let key in c.meta){
4818
- let value = c.meta[key];
4819
- 'string' == typeof value ? meta[key] = {
4820
- name: key,
4821
- content: value
4822
- } : meta[key] = {
4823
- name: key,
4824
- ...value
4825
- };
4488
+ class JsSourceMap {
4489
+ static __from_binding(map) {
4490
+ return isNil(map) ? void 0 : ((input)=>{
4491
+ let s;
4492
+ if (Buffer.isBuffer(input)) s = input.toString('utf8');
4493
+ else if (input && 'object' == typeof input) return input;
4494
+ else if ('string' == typeof input) s = input;
4495
+ else throw Error('Buffer or string or object expected');
4496
+ return JSON.parse(s);
4497
+ })(map);
4826
4498
  }
4827
- let scriptLoading = c.scriptLoading ?? 'defer', configInject = c.inject ?? !0, base = 'string' == typeof c.base ? {
4828
- href: c.base
4829
- } : c.base, chunksSortMode = c.chunksSortMode ?? 'auto', compilation = null;
4830
- function generateRenderData(data) {
4831
- let json = JSON.parse(data);
4832
- 'function' != typeof c.templateParameters && (json.compilation = compilation);
4833
- let renderTag = function() {
4834
- var tag;
4835
- let attributes;
4836
- return tag = this, attributes = Object.keys(tag.attributes || {}).filter((attributeName)=>'' === tag.attributes[attributeName] || tag.attributes[attributeName]).map((attributeName)=>'true' === tag.attributes[attributeName] ? attributeName : `${attributeName}="${tag.attributes[attributeName]}"`), `<${[
4837
- tag.tagName
4838
- ].concat(attributes).join(' ')}${tag.voidTag && !tag.innerHTML ? '/' : ''}>${tag.innerHTML || ''}${tag.voidTag && !tag.innerHTML ? '' : `</${tag.tagName}>`}`;
4839
- }, renderTagList = function() {
4840
- return this.join('');
4841
- };
4842
- if (Array.isArray(json.htmlRspackPlugin?.tags?.headTags)) {
4843
- for (let tag of json.htmlRspackPlugin.tags.headTags)tag.toString = renderTag;
4844
- json.htmlRspackPlugin.tags.headTags.toString = renderTagList;
4499
+ static __to_binding(map) {
4500
+ return serializeObject(map);
4501
+ }
4502
+ }
4503
+ function getCurrentLoader(loaderContext, index = loaderContext.loaderIndex) {
4504
+ return loaderContext.loaders?.length && index < loaderContext.loaders.length && index >= 0 && loaderContext.loaders[index] ? loaderContext.loaders[index] : null;
4505
+ }
4506
+ async function runLoaders(compiler, context) {
4507
+ var buildInfo;
4508
+ let loaderState = context.loaderState, pitch = loaderState === binding_namespaceObject.JsLoaderState.Pitching, { resource } = context, traceData = JavaScriptTracer.isEnabled() ? {
4509
+ uuid: JavaScriptTracer.uuid(),
4510
+ args: {
4511
+ is_pitch: pitch,
4512
+ resource: resource
4513
+ }
4514
+ } : void 0;
4515
+ traceData && JavaScriptTracer.startAsync({
4516
+ name: 'run_js_loaders',
4517
+ processName: LOADER_PROCESS_NAME,
4518
+ uuid: traceData.uuid,
4519
+ ph: 'b',
4520
+ args: traceData.args
4521
+ });
4522
+ let splittedResource = resource && parseResource(resource), resourcePath = splittedResource ? splittedResource.path : void 0, resourceQuery = splittedResource ? splittedResource.query : void 0, resourceFragment = splittedResource ? splittedResource.fragment : void 0, contextDirectory = resourcePath ? function(path) {
4523
+ if ('/' === path) return '/';
4524
+ let i = path.lastIndexOf('/'), j = path.lastIndexOf('\\'), i2 = path.indexOf('/'), j2 = path.indexOf('\\'), idx = i > j ? i : j, idx2 = i > j ? i2 : j2;
4525
+ return idx < 0 ? path : idx === idx2 ? path.slice(0, idx + 1) : path.slice(0, idx);
4526
+ }(resourcePath) : null, fileDependencies = context.fileDependencies, contextDependencies = context.contextDependencies, missingDependencies = context.missingDependencies, buildDependencies = context.buildDependencies, loaderContext = {};
4527
+ loaderContext.loaders = context.loaderItems.map((item)=>LoaderObject.__from_binding(item, compiler)), loaderContext.hot = context.hot, loaderContext.context = contextDirectory, loaderContext.resourcePath = resourcePath, loaderContext.resourceQuery = resourceQuery, loaderContext.resourceFragment = resourceFragment, loaderContext.dependency = loaderContext.addDependency = function(file) {
4528
+ fileDependencies.push(file);
4529
+ }, loaderContext.addContextDependency = function(context) {
4530
+ contextDependencies.push(context);
4531
+ }, loaderContext.addMissingDependency = function(context) {
4532
+ missingDependencies.push(context);
4533
+ }, loaderContext.addBuildDependency = function(file) {
4534
+ buildDependencies.push(file);
4535
+ }, loaderContext.getDependencies = function() {
4536
+ return fileDependencies.slice();
4537
+ }, loaderContext.getContextDependencies = function() {
4538
+ return contextDependencies.slice();
4539
+ }, loaderContext.getMissingDependencies = function() {
4540
+ return missingDependencies.slice();
4541
+ }, loaderContext.clearDependencies = function() {
4542
+ fileDependencies.length = 0, contextDependencies.length = 0, missingDependencies.length = 0, context.cacheable = !0;
4543
+ }, loaderContext.importModule = function(request, userOptions, callback) {
4544
+ traceData && JavaScriptTracer.startAsync({
4545
+ name: 'importModule',
4546
+ processName: LOADER_PROCESS_NAME,
4547
+ uuid: traceData.uuid,
4548
+ args: traceData.args
4549
+ });
4550
+ let options = userOptions || {};
4551
+ function finalCallback(onError, onDone) {
4552
+ return function(err, res) {
4553
+ if (err) traceData && JavaScriptTracer.endAsync({
4554
+ name: 'importModule',
4555
+ processName: LOADER_PROCESS_NAME,
4556
+ uuid: traceData.uuid,
4557
+ args: traceData.args
4558
+ }), onError(err);
4559
+ else {
4560
+ for (let dep of res.buildDependencies)loaderContext.addBuildDependency(dep);
4561
+ for (let dep of res.contextDependencies)loaderContext.addContextDependency(dep);
4562
+ for (let dep of res.missingDependencies)loaderContext.addMissingDependency(dep);
4563
+ for (let dep of res.fileDependencies)loaderContext.addDependency(dep);
4564
+ !1 === res.cacheable && loaderContext.cacheable(!1), traceData && JavaScriptTracer.endAsync({
4565
+ name: 'importModule',
4566
+ processName: LOADER_PROCESS_NAME,
4567
+ uuid: traceData.uuid,
4568
+ args: traceData.args
4569
+ }), res.error ? onError(compiler.__internal__takeModuleExecutionResult(res.id) ?? Error(res.error)) : onDone(compiler.__internal__takeModuleExecutionResult(res.id));
4570
+ }
4571
+ };
4572
+ }
4573
+ return callback ? compiler._lastCompilation.__internal_getInner().importModule(request, options.layer, options.publicPath, options.baseUri, loaderContext._module.identifier(), loaderContext.context, finalCallback((err)=>callback(err), (res)=>callback(void 0, res))) : new Promise((resolve, reject)=>{
4574
+ compiler._lastCompilation.__internal_getInner().importModule(request, options.layer, options.publicPath, options.baseUri, loaderContext._module.identifier(), loaderContext.context, finalCallback(reject, resolve));
4575
+ });
4576
+ }, Object.defineProperty(loaderContext, 'resource', {
4577
+ enumerable: !0,
4578
+ get: ()=>{
4579
+ if (void 0 !== loaderContext.resourcePath) return loaderContext.resourcePath.replace(/#/g, '\u200b#') + loaderContext.resourceQuery.replace(/#/g, '\u200b#') + loaderContext.resourceFragment;
4580
+ },
4581
+ set: (value)=>{
4582
+ let splittedResource = value && parseResource(value);
4583
+ loaderContext.resourcePath = splittedResource ? splittedResource.path : void 0, loaderContext.resourceQuery = splittedResource ? splittedResource.query : void 0, loaderContext.resourceFragment = splittedResource ? splittedResource.fragment : void 0;
4584
+ }
4585
+ }), Object.defineProperty(loaderContext, 'request', {
4586
+ enumerable: !0,
4587
+ get: ()=>loaderContext.loaders.map((o)=>o.request).concat(loaderContext.resource || '').join('!')
4588
+ }), Object.defineProperty(loaderContext, 'remainingRequest', {
4589
+ enumerable: !0,
4590
+ get: ()=>loaderContext.loaderIndex >= loaderContext.loaders.length - 1 && !loaderContext.resource ? '' : loaderContext.loaders.slice(loaderContext.loaderIndex + 1).map((o)=>o.request).concat(loaderContext.resource || '').join('!')
4591
+ }), Object.defineProperty(loaderContext, 'currentRequest', {
4592
+ enumerable: !0,
4593
+ get: ()=>loaderContext.loaders.slice(loaderContext.loaderIndex).map((o)=>o.request).concat(loaderContext.resource || '').join('!')
4594
+ }), Object.defineProperty(loaderContext, 'previousRequest', {
4595
+ enumerable: !0,
4596
+ get: ()=>loaderContext.loaders.slice(0, loaderContext.loaderIndex).map((o)=>o.request).join('!')
4597
+ }), Object.defineProperty(loaderContext, 'query', {
4598
+ enumerable: !0,
4599
+ get: ()=>{
4600
+ let entry = loaderContext.loaders[loaderContext.loaderIndex];
4601
+ return entry.options && 'object' == typeof entry.options ? entry.options : entry.query;
4845
4602
  }
4846
- if (Array.isArray(json.htmlRspackPlugin?.tags?.bodyTags)) {
4847
- for (let tag of json.htmlRspackPlugin.tags.bodyTags)tag.toString = renderTag;
4848
- json.htmlRspackPlugin.tags.bodyTags.toString = renderTagList;
4603
+ }), loaderContext.version = 2, loaderContext.sourceMap = compiler.options.devtool ? isUseSourceMap(compiler.options.devtool) : context._module.useSourceMap ?? !1, loaderContext.mode = compiler.options.mode, Object.assign(loaderContext, compiler.options.loader);
4604
+ let getResolveContext = ()=>({
4605
+ fileDependencies: {
4606
+ add: (d)=>{
4607
+ loaderContext.addDependency(d);
4608
+ }
4609
+ },
4610
+ contextDependencies: {
4611
+ add: (d)=>{
4612
+ loaderContext.addContextDependency(d);
4613
+ }
4614
+ },
4615
+ missingDependencies: {
4616
+ add: (d)=>{
4617
+ loaderContext.addMissingDependency(d);
4618
+ }
4619
+ }
4620
+ }), getResolver = memoize(()=>compiler._lastCompilation.resolverFactory.get('normal'));
4621
+ loaderContext.resolve = function(context, request, callback) {
4622
+ getResolver().resolve({}, context, request, getResolveContext(), callback);
4623
+ }, loaderContext.getResolve = function(options) {
4624
+ let resolver = getResolver(), child = options ? resolver.withOptions(options) : resolver;
4625
+ return (context, request, callback)=>callback ? void child.resolve({}, context, request, getResolveContext(), callback) : new Promise((resolve, reject)=>{
4626
+ child.resolve({}, context, request, getResolveContext(), (err, result)=>{
4627
+ err ? reject(err) : resolve(result);
4628
+ });
4629
+ });
4630
+ }, loaderContext.getLogger = function(name) {
4631
+ return compiler._lastCompilation.getLogger([
4632
+ name,
4633
+ resource
4634
+ ].filter(Boolean).join('|'));
4635
+ }, loaderContext.rootContext = compiler.context, loaderContext.emitError = function(e) {
4636
+ e instanceof Error || (e = new NonErrorEmittedError(e));
4637
+ let error = new ModuleError(e, {
4638
+ from: stringifyLoaderObject(loaderContext.loaders[loaderContext.loaderIndex])
4639
+ });
4640
+ error.module = loaderContext._module, compiler._lastCompilation.__internal__pushRspackDiagnostic({
4641
+ error,
4642
+ severity: binding_namespaceObject.JsRspackSeverity.Error
4643
+ });
4644
+ }, loaderContext.emitWarning = function(e) {
4645
+ e instanceof Error || (e = new NonErrorEmittedError(e));
4646
+ let warning = new ModuleWarning(e, {
4647
+ from: stringifyLoaderObject(loaderContext.loaders[loaderContext.loaderIndex])
4648
+ });
4649
+ warning.module = loaderContext._module, compiler._lastCompilation.__internal__pushRspackDiagnostic({
4650
+ error: warning,
4651
+ severity: binding_namespaceObject.JsRspackSeverity.Warn
4652
+ });
4653
+ }, loaderContext.emitFile = function(name, content, sourceMap, assetInfo) {
4654
+ let source;
4655
+ if (sourceMap) {
4656
+ var devtool;
4657
+ 'string' == typeof sourceMap && (loaderContext.sourceMap || compiler.options.devtool && (devtool = compiler.options.devtool) && devtool.includes('source-map') && !isUseSourceMap(devtool)) && (source = new index_js_namespaceObject.OriginalSource(content, makePathsRelative(contextDirectory, sourceMap, compiler))), loaderContext.sourceMap && (source = new index_js_namespaceObject.SourceMapSource(content, name, makePathsRelative(contextDirectory, sourceMap, compiler)));
4658
+ } else source = new index_js_namespaceObject.RawSource(content);
4659
+ loaderContext._module.emitFile(name, source, assetInfo);
4660
+ }, loaderContext.fs = compiler.inputFileSystem, loaderContext.experiments = {
4661
+ emitDiagnostic: (diagnostic)=>{
4662
+ let d = Object.assign({}, diagnostic, {
4663
+ message: 'warning' === diagnostic.severity ? `ModuleWarning: ${diagnostic.message}` : `ModuleError: ${diagnostic.message}`,
4664
+ moduleIdentifier: context._module.identifier()
4665
+ });
4666
+ compiler._lastCompilation.__internal__pushDiagnostic((0, binding_namespaceObject.formatDiagnostic)(d));
4849
4667
  }
4850
- return json;
4851
- }
4852
- this.hooks.compilation.tap('HtmlRspackPlugin', (compilationInstance)=>{
4853
- var compilation1;
4854
- let optionsMap;
4855
- compilation1 = compilation = compilationInstance, (optionsMap = compilationOptionsMap.get(compilation1) || {})[uid] = c, compilationOptionsMap.set(compilation1, optionsMap);
4856
- }), this.hooks.done.tap('HtmlRspackPlugin', (stats)=>{
4857
- var compilation, compilation1;
4858
- let optionsMap;
4859
- compilation = stats.compilation, hooks_compilationHooksMap.delete(compilation), compilation1 = stats.compilation, optionsMap = compilationOptionsMap.get(compilation1) || {}, delete optionsMap[uid], 0 === Object.keys(optionsMap).length ? compilationOptionsMap.delete(compilation1) : compilationOptionsMap.set(compilation1, optionsMap);
4860
- });
4861
- let templateContent = c.templateContent;
4862
- if ('function' == typeof templateContent) templateFn = async (data)=>{
4863
- try {
4864
- let renderer = c.templateContent;
4865
- if (!1 === c.templateParameters) return await renderer({});
4866
- return await renderer(generateRenderData(data));
4668
+ };
4669
+ let getAbsolutify = memoize(()=>absolutify.bindCache(compiler.root)), getAbsolutifyInContext = memoize(()=>absolutify.bindContextCache(contextDirectory, compiler.root)), getContextify = memoize(()=>contextify.bindCache(compiler.root)), getContextifyInContext = memoize(()=>contextify.bindContextCache(contextDirectory, compiler.root));
4670
+ loaderContext.utils = {
4671
+ absolutify: (context, request)=>context === contextDirectory ? getAbsolutifyInContext()(request) : getAbsolutify()(context, request),
4672
+ contextify: (context, request)=>context === contextDirectory ? getContextifyInContext()(request) : getContextify()(context, request),
4673
+ createHash: (type)=>createHash_createHash(type || compiler._lastCompilation.outputOptions.hashFunction)
4674
+ }, loaderContext._compiler = compiler, loaderContext._compilation = compiler._lastCompilation, loaderContext._module = context._module, loaderContext.getOptions = ()=>{
4675
+ let loader = getCurrentLoader(loaderContext), options = loader?.options;
4676
+ if ('string' == typeof options) if (options.startsWith('{') && options.endsWith('}')) try {
4677
+ options = JSON.parse(options);
4867
4678
  } catch (e) {
4868
- let error = Error(`HtmlRspackPlugin: render template function failed, ${e.message}`);
4869
- throw error.stack = e.stack, error;
4679
+ throw Error(`JSON parsing failed for loader's string options: ${e.message}`);
4870
4680
  }
4871
- }, templateContent = '';
4872
- else if (c.template) {
4873
- let filename = c.template.split('?')[0];
4874
- [
4875
- '.js',
4876
- '.cjs'
4877
- ].includes(node_path.extname(filename)) && (templateFn = async (data)=>{
4878
- let context = this.options.context || process.cwd(), templateFilePath = node_path.resolve(context, filename);
4879
- if (!node_fs.existsSync(templateFilePath)) throw Error(`HtmlRspackPlugin: could not load file \`${filename}\` from \`${context}\``);
4880
- try {
4881
- let renderer = plugin_require(templateFilePath);
4882
- if (!1 === c.templateParameters) return await renderer({});
4883
- return await renderer(generateRenderData(data));
4884
- } catch (e) {
4885
- let error = Error(`HtmlRspackPlugin: render template function failed, ${e.message}`);
4886
- throw error.stack = e.stack, error;
4681
+ else options = node_querystring.parse(options);
4682
+ return null == options && (options = {}), options;
4683
+ };
4684
+ let compilation = compiler._lastCompilation, step = 0;
4685
+ for(; compilation;)if (binding_namespaceObject.NormalModule.getCompilationHooks(compilation).loader.call(loaderContext, loaderContext._module), compilation = compilation.compiler.parentCompilation, ++step > 1000) throw Error('Too many nested child compiler, exceeded max limitation 1000');
4686
+ Object.defineProperty(loaderContext, 'loaderIndex', {
4687
+ enumerable: !0,
4688
+ get: ()=>context.loaderIndex,
4689
+ set: (loaderIndex)=>context.loaderIndex = loaderIndex
4690
+ }), Object.defineProperty(loaderContext, 'cacheable', {
4691
+ enumerable: !0,
4692
+ get: ()=>(cacheable)=>{
4693
+ !1 === cacheable && (context.cacheable = cacheable);
4887
4694
  }
4888
- });
4889
- }
4890
- let rawTemplateParameters = c.templateParameters;
4891
- if (templateParameters = 'function' == typeof rawTemplateParameters ? async (data)=>JSON.stringify(await rawTemplateParameters(JSON.parse(data))) : rawTemplateParameters, 'string' == typeof c.filename) if (filenames = new Set(), c.filename.includes('[name]')) if ('object' == typeof this.options.entry) for (let entryName of Object.keys(this.options.entry))filenames.add(c.filename.replace(/\[name\]/g, entryName));
4892
- else throw Error('HtmlRspackPlugin: filename with `[name]` does not support function entry');
4893
- else filenames.add(c.filename);
4894
- else if ('function' == typeof c.filename) if (filenames = new Set(), 'object' == typeof this.options.entry) for (let entryName of Object.keys(this.options.entry))filenames.add(c.filename(entryName));
4895
- else throw Error('HtmlRspackPlugin: function filename does not support function entry');
4896
- return {
4897
- filename: filenames ? Array.from(filenames) : void 0,
4898
- template: c.template,
4899
- hash: c.hash,
4900
- title: c.title,
4901
- favicon: c.favicon,
4902
- publicPath: c.publicPath,
4903
- chunks: c.chunks,
4904
- excludeChunks: c.excludeChunks,
4905
- chunksSortMode,
4906
- minify: c.minify,
4907
- meta,
4908
- scriptLoading,
4909
- inject: !0 === configInject ? 'blocking' === scriptLoading ? 'body' : 'head' : !1 === configInject ? 'false' : configInject,
4910
- base,
4911
- templateFn,
4912
- templateContent,
4913
- templateParameters,
4914
- uid
4695
+ }), Object.defineProperty(loaderContext, 'data', {
4696
+ enumerable: !0,
4697
+ get: ()=>loaderContext.loaders[loaderContext.loaderIndex].loaderItem.data,
4698
+ set: (data)=>loaderContext.loaders[loaderContext.loaderIndex].loaderItem.data = data
4699
+ }), loaderContext.__internal__setParseMeta = (key, value)=>{
4700
+ context.__internal__parseMeta[key] = value;
4701
+ };
4702
+ let enableParallelism = (currentLoaderObject)=>currentLoaderObject?.parallel, isomorphoicRun = async (fn, args)=>{
4703
+ let loaderName, result, currentLoaderObject = getCurrentLoader(loaderContext), parallelism = enableParallelism(currentLoaderObject);
4704
+ if ((traceData || parallelism) && (loaderName = function(loaderPath, cwd = '') {
4705
+ let res = loaderPath.replace(cwd, '');
4706
+ if (!node_path.isAbsolute(res)) return res;
4707
+ let nms = '/node_modules/', idx = res.lastIndexOf(nms);
4708
+ if (-1 !== idx) {
4709
+ res = res.slice(idx + nms.length);
4710
+ let ln = 'loader', lnIdx = res.lastIndexOf(ln);
4711
+ lnIdx > -1 && (res = res.slice(0, lnIdx + ln.length));
4712
+ }
4713
+ return res;
4714
+ }(currentLoaderObject.request)), traceData && JavaScriptTracer.startAsync({
4715
+ name: loaderName,
4716
+ trackName: loaderName,
4717
+ processName: LOADER_PROCESS_NAME,
4718
+ uuid: traceData.uuid,
4719
+ args: traceData.args
4720
+ }), parallelism) {
4721
+ let normalModule, workerLoaderContext;
4722
+ result = await service_run(loaderName, {
4723
+ loaderContext: (normalModule = loaderContext._module instanceof binding_namespaceObject.NormalModule ? loaderContext._module : void 0, Object.assign(workerLoaderContext = {
4724
+ hot: loaderContext.hot,
4725
+ context: loaderContext.context,
4726
+ resourcePath: loaderContext.resourcePath,
4727
+ resourceQuery: loaderContext.resourceQuery,
4728
+ resourceFragment: loaderContext.resourceFragment,
4729
+ resource: loaderContext.resource,
4730
+ mode: loaderContext.mode,
4731
+ sourceMap: loaderContext.sourceMap,
4732
+ rootContext: loaderContext.rootContext,
4733
+ loaderIndex: loaderContext.loaderIndex,
4734
+ loaders: loaderContext.loaders.map((item)=>{
4735
+ let options = item.options;
4736
+ return (!item.parallel || item.request.startsWith(BUILTIN_LOADER_PREFIX)) && (options = void 0), {
4737
+ ...item,
4738
+ options,
4739
+ pitch: void 0,
4740
+ normal: void 0,
4741
+ normalExecuted: item.normalExecuted,
4742
+ pitchExecuted: item.pitchExecuted
4743
+ };
4744
+ }),
4745
+ __internal__workerInfo: {
4746
+ hashFunction: compiler._lastCompilation.outputOptions.hashFunction
4747
+ },
4748
+ _compiler: {
4749
+ options: {
4750
+ experiments: {
4751
+ css: !0
4752
+ }
4753
+ }
4754
+ },
4755
+ _compilation: {
4756
+ options: {
4757
+ output: {
4758
+ environment: compiler._lastCompilation.outputOptions.environment
4759
+ }
4760
+ },
4761
+ outputOptions: {
4762
+ hashSalt: compiler._lastCompilation.outputOptions.hashSalt,
4763
+ hashFunction: compiler._lastCompilation.outputOptions.hashFunction,
4764
+ hashDigest: compiler._lastCompilation.outputOptions.hashDigest,
4765
+ hashDigestLength: compiler._lastCompilation.outputOptions.hashDigestLength
4766
+ }
4767
+ },
4768
+ _module: {
4769
+ type: loaderContext._module.type,
4770
+ identifier: loaderContext._module.identifier(),
4771
+ matchResource: normalModule?.matchResource,
4772
+ request: normalModule?.request,
4773
+ userRequest: normalModule?.userRequest,
4774
+ rawRequest: normalModule?.rawRequest
4775
+ }
4776
+ }, compiler.options.loader), workerLoaderContext),
4777
+ loaderState,
4778
+ args
4779
+ }, {
4780
+ handleIncomingRequest (requestType, ...args) {
4781
+ switch(requestType){
4782
+ case "AddDependency":
4783
+ loaderContext.addDependency(args[0]);
4784
+ break;
4785
+ case "AddContextDependency":
4786
+ loaderContext.addContextDependency(args[0]);
4787
+ break;
4788
+ case "AddMissingDependency":
4789
+ loaderContext.addMissingDependency(args[0]);
4790
+ break;
4791
+ case "AddBuildDependency":
4792
+ loaderContext.addBuildDependency(args[0]);
4793
+ break;
4794
+ case "GetDependencies":
4795
+ return loaderContext.getDependencies();
4796
+ case "GetContextDependencies":
4797
+ return loaderContext.getContextDependencies();
4798
+ case "GetMissingDependencies":
4799
+ return loaderContext.getMissingDependencies();
4800
+ case "ClearDependencies":
4801
+ loaderContext.clearDependencies();
4802
+ break;
4803
+ case "Resolve":
4804
+ return new Promise((resolve, reject)=>{
4805
+ loaderContext.resolve(args[0], args[1], (err, result)=>{
4806
+ err ? reject(err) : resolve(result);
4807
+ });
4808
+ });
4809
+ case "GetResolve":
4810
+ return new Promise((resolve, reject)=>{
4811
+ loaderContext.getResolve(args[0])(args[1], args[2], (err, result)=>{
4812
+ err ? reject(err) : resolve(result);
4813
+ });
4814
+ });
4815
+ case "GetLogger":
4816
+ {
4817
+ let [type, name, arg] = args;
4818
+ loaderContext.getLogger(name)[type](...arg);
4819
+ break;
4820
+ }
4821
+ case "EmitError":
4822
+ {
4823
+ let workerError = args[0], error = Error(workerError.message);
4824
+ error.stack = workerError.stack, error.name = workerError.name, loaderContext.emitError(error);
4825
+ break;
4826
+ }
4827
+ case "EmitWarning":
4828
+ {
4829
+ let workerError = args[0], error = Error(workerError.message);
4830
+ error.stack = workerError.stack, error.name = workerError.name, loaderContext.emitWarning(error);
4831
+ break;
4832
+ }
4833
+ case "EmitFile":
4834
+ {
4835
+ let [name, content, sourceMap, assetInfo] = args;
4836
+ loaderContext.emitFile(name, content, sourceMap, assetInfo);
4837
+ break;
4838
+ }
4839
+ case "EmitDiagnostic":
4840
+ {
4841
+ let diagnostic = args[0];
4842
+ loaderContext.experiments.emitDiagnostic(diagnostic);
4843
+ break;
4844
+ }
4845
+ case "SetCacheable":
4846
+ {
4847
+ let cacheable = args[0];
4848
+ loaderContext.cacheable(cacheable);
4849
+ break;
4850
+ }
4851
+ case "ImportModule":
4852
+ return loaderContext.importModule(args[0], args[1]);
4853
+ case "UpdateLoaderObjects":
4854
+ {
4855
+ let updates = args[0];
4856
+ loaderContext.loaders = loaderContext.loaders.map((item, index)=>{
4857
+ let update = updates[index];
4858
+ return item.loaderItem.data = update.data, update.pitchExecuted && (item.pitchExecuted = !0), update.normalExecuted && (item.normalExecuted = !0), item;
4859
+ });
4860
+ break;
4861
+ }
4862
+ case "CompilationGetPath":
4863
+ {
4864
+ let filename = args[0], data = args[1];
4865
+ return compiler._lastCompilation.getPath(filename, data);
4866
+ }
4867
+ case "CompilationGetPathWithInfo":
4868
+ {
4869
+ let filename = args[0], data = args[1];
4870
+ return compiler._lastCompilation.getPathWithInfo(filename, data);
4871
+ }
4872
+ case "CompilationGetAssetPath":
4873
+ {
4874
+ let filename = args[0], data = args[1];
4875
+ return compiler._lastCompilation.getAssetPath(filename, data);
4876
+ }
4877
+ case "CompilationGetAssetPathWithInfo":
4878
+ {
4879
+ let filename = args[0], data = args[1];
4880
+ return compiler._lastCompilation.getAssetPathWithInfo(filename, data);
4881
+ }
4882
+ default:
4883
+ throw Error(`Unknown request type: ${requestType}`);
4884
+ }
4885
+ }
4886
+ }, 'object' == typeof currentLoaderObject?.parallel ? currentLoaderObject.parallel : void 0) || [];
4887
+ } else loaderState === binding_namespaceObject.JsLoaderState.Normal && function(args, raw) {
4888
+ if (!raw && args[0] instanceof Uint8Array) {
4889
+ var buf;
4890
+ let isShared, str;
4891
+ args[0] = (isShared = (buf = args[0]).buffer instanceof SharedArrayBuffer || buf.buffer.constructor?.name === 'SharedArrayBuffer', 0xfeff === (str = decoder.decode(isShared ? Buffer.from(buf) : buf)).charCodeAt(0) ? str.slice(1) : str);
4892
+ } else raw && 'string' == typeof args[0] && (args[0] = Buffer.from(args[0], 'utf-8'));
4893
+ raw && args[0] instanceof Uint8Array && !Buffer.isBuffer(args[0]) && (args[0] = Buffer.from(args[0].buffer));
4894
+ }(args, !!currentLoaderObject?.raw), result = await utils_runSyncOrAsync(fn, loaderContext, args) || [];
4895
+ return traceData && JavaScriptTracer.endAsync({
4896
+ name: loaderName,
4897
+ trackName: loaderName,
4898
+ processName: LOADER_PROCESS_NAME,
4899
+ uuid: traceData.uuid,
4900
+ args: traceData.args
4901
+ }), result;
4915
4902
  };
4916
- }), voidTags = [
4917
- 'area',
4918
- 'base',
4919
- 'br',
4920
- 'col',
4921
- 'embed',
4922
- 'hr',
4923
- 'img',
4924
- 'input',
4925
- 'keygen',
4926
- 'link',
4927
- 'meta',
4928
- 'param',
4929
- 'source',
4930
- 'track',
4931
- 'wbr'
4932
- ];
4933
- HtmlRspackPlugin.createHtmlTagObject = (tagName, attributes, innerHTML)=>({
4934
- tagName,
4935
- voidTag: voidTags.includes(tagName),
4936
- attributes: attributes || {},
4937
- innerHTML
4938
- }), HtmlRspackPlugin.getCompilationHooks = (compilation)=>{
4939
- checkCompilation(compilation);
4940
- let hooks = hooks_compilationHooksMap.get(compilation);
4941
- return void 0 === hooks && (hooks = {
4942
- beforeAssetTagGeneration: new AsyncSeriesWaterfallHook([
4943
- 'data'
4944
- ]),
4945
- alterAssetTags: new AsyncSeriesWaterfallHook([
4946
- 'data'
4947
- ]),
4948
- alterAssetTagGroups: new AsyncSeriesWaterfallHook([
4949
- 'data'
4950
- ]),
4951
- afterTemplateExecution: new AsyncSeriesWaterfallHook([
4952
- 'data'
4953
- ]),
4954
- beforeEmit: new AsyncSeriesWaterfallHook([
4955
- 'data'
4956
- ]),
4957
- afterEmit: new AsyncSeriesWaterfallHook([
4958
- 'data'
4959
- ])
4960
- }, hooks_compilationHooksMap.set(compilation, hooks)), hooks;
4961
- }, HtmlRspackPlugin.version = 5;
4962
- let IgnorePlugin = base_create(binding_namespaceObject.BuiltinPluginName.IgnorePlugin, (options)=>options), InferAsyncModulesPlugin = base_create(binding_namespaceObject.BuiltinPluginName.InferAsyncModulesPlugin, ()=>{}, 'compilation'), InlineExportsPlugin = base_create(binding_namespaceObject.BuiltinPluginName.InlineExportsPlugin, ()=>{}, 'compilation'), JavascriptModulesPlugin_compilationHooksMap = new WeakMap();
4963
- class JavascriptModulesPlugin extends RspackBuiltinPlugin {
4964
- name = binding_namespaceObject.BuiltinPluginName.JavascriptModulesPlugin;
4965
- affectedHooks = 'compilation';
4966
- raw() {
4967
- return createBuiltinPlugin(this.name, void 0);
4968
- }
4969
- static getCompilationHooks(compilation) {
4970
- checkCompilation(compilation);
4971
- let hooks = JavascriptModulesPlugin_compilationHooksMap.get(compilation);
4972
- return void 0 === hooks && (hooks = {
4973
- chunkHash: new SyncHook([
4974
- 'chunk',
4975
- 'hash'
4976
- ])
4977
- }, JavascriptModulesPlugin_compilationHooksMap.set(compilation, hooks)), hooks;
4903
+ try {
4904
+ switch(loaderState){
4905
+ case binding_namespaceObject.JsLoaderState.Pitching:
4906
+ for(; loaderContext.loaderIndex < loaderContext.loaders.length;){
4907
+ let currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex], parallelism = enableParallelism(currentLoaderObject);
4908
+ if (currentLoaderObject.shouldYield()) break;
4909
+ if (currentLoaderObject.pitchExecuted) {
4910
+ loaderContext.loaderIndex += 1;
4911
+ continue;
4912
+ }
4913
+ await utils_loadLoader(currentLoaderObject, compiler);
4914
+ let fn = currentLoaderObject.pitch;
4915
+ if (parallelism && fn || (currentLoaderObject.pitchExecuted = !0), !fn) continue;
4916
+ let args = await isomorphoicRun(fn, [
4917
+ loaderContext.remainingRequest,
4918
+ loaderContext.previousRequest,
4919
+ currentLoaderObject.loaderItem.data
4920
+ ]);
4921
+ if (args.some((value)=>void 0 !== value)) {
4922
+ let [content, sourceMap, additionalData] = args;
4923
+ context.content = isNil(content) ? null : toBuffer(content), context.sourceMap = serializeObject(sourceMap), context.additionalData = additionalData || void 0;
4924
+ break;
4925
+ }
4926
+ }
4927
+ break;
4928
+ case binding_namespaceObject.JsLoaderState.Normal:
4929
+ {
4930
+ let content = context.content, sourceMap = JsSourceMap.__from_binding(context.sourceMap), additionalData = context.additionalData;
4931
+ for(; loaderContext.loaderIndex >= 0;){
4932
+ let currentLoaderObject = loaderContext.loaders[loaderContext.loaderIndex], parallelism = enableParallelism(currentLoaderObject);
4933
+ if (currentLoaderObject.shouldYield()) break;
4934
+ if (currentLoaderObject.normalExecuted) {
4935
+ loaderContext.loaderIndex--;
4936
+ continue;
4937
+ }
4938
+ await utils_loadLoader(currentLoaderObject, compiler);
4939
+ let fn = currentLoaderObject.normal;
4940
+ parallelism && fn || (currentLoaderObject.normalExecuted = !0), fn && ([content, sourceMap, additionalData] = await isomorphoicRun(fn, [
4941
+ content,
4942
+ sourceMap,
4943
+ additionalData
4944
+ ]));
4945
+ }
4946
+ context.content = isNil(content) ? null : toBuffer(content), context.sourceMap = JsSourceMap.__to_binding(sourceMap), context.additionalData = additionalData || void 0, context.__internal__utf8Hint = 'string' == typeof content;
4947
+ break;
4948
+ }
4949
+ default:
4950
+ throw Error(`Unexpected loader runner state: ${loaderState}`);
4951
+ }
4952
+ context.loaderItems = loaderContext.loaders.map((item)=>LoaderObject.__to_binding(item));
4953
+ } catch (e) {
4954
+ if ('object' != typeof e || null === e) {
4955
+ let error = Error(`(Emitted value instead of an instance of Error) ${e}`);
4956
+ error.name = 'NonErrorEmittedError', context.__internal__error = error;
4957
+ } else context.__internal__error = e;
4978
4958
  }
4959
+ return traceData && JavaScriptTracer.endAsync({
4960
+ name: 'run_js_loaders',
4961
+ uuid: traceData.uuid,
4962
+ args: traceData.args
4963
+ }), compiler.options?.cache && Object.keys(buildInfo = context._module.buildInfo).some((key)=>!knownBuildInfoFields.has(key)) && buildInfo[binding_default().COMMIT_CUSTOM_FIELDS_SYMBOL](), context;
4979
4964
  }
4980
4965
  let JsLoaderRspackPlugin = base_create(binding_namespaceObject.BuiltinPluginName.JsLoaderRspackPlugin, (compiler)=>runLoaders.bind(null, compiler), 'thisCompilation'), JsonModulesPlugin = base_create(binding_namespaceObject.BuiltinPluginName.JsonModulesPlugin, ()=>{}, 'compilation'), LibManifestPlugin = base_create(binding_namespaceObject.BuiltinPluginName.LibManifestPlugin, (options)=>{
4981
4966
  let { context, entryOnly, format, name, path, type } = options;
@@ -5166,7 +5151,8 @@ let NodeTargetPlugin = base_create(binding_namespaceObject.BuiltinPluginName.Nod
5166
5151
  return {
5167
5152
  moduleGraphFeatures: c.moduleGraphFeatures ?? !0,
5168
5153
  chunkGraphFeatures: c.chunkGraphFeatures ?? !0,
5169
- sourceMapFeatures: c.sourceMapFeatures
5154
+ sourceMapFeatures: c.sourceMapFeatures,
5155
+ exportUsageGraph: c.exportUsageGraph
5170
5156
  };
5171
5157
  }), RsdoctorPlugin_compilationHooksMap = new WeakMap();
5172
5158
  RsdoctorPluginImpl.getCompilationHooks = (compilation)=>{
@@ -6666,7 +6652,7 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
6666
6652
  (hasTrue || hasFalse) && (result[key] = hasFalse && hasTrue ? null : hasTrue);
6667
6653
  }
6668
6654
  return result;
6669
- })(targets.map((t)=>getTargetProperties(t, context))), applyRspackOptionsDefaults = (options)=>{
6655
+ })(targets.map((t)=>getTargetProperties(t, context))), applyRspackOptionsDefaults = (options, compilerIndex)=>{
6670
6656
  F(options, 'context', ()=>process.cwd()), F(options, 'target', ()=>hasBrowserslistConfig(options.context) ? 'browserslist' : 'web');
6671
6657
  let { mode, target } = options;
6672
6658
  if (isNil(target)) throw Error('target should not be nil after defaults');
@@ -6674,11 +6660,18 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
6674
6660
  if ('function' != typeof options.entry) for (let key of Object.keys(options.entry))F(options.entry[key], 'import', ()=>[
6675
6661
  './src'
6676
6662
  ]);
6677
- return F(options, 'devtool', ()=>!!development && 'cheap-module-source-map'), D(options, 'watch', !1), D(options, 'lazyCompilation', !1), D(options, 'bail', !1), F(options, 'cache', ()=>development), applyIncrementalDefaults(options), applyExperimentsDefaults(options.experiments), applyOptimizationDefaults(options.optimization, {
6663
+ return F(options, 'devtool', ()=>!!development && 'cheap-module-source-map'), D(options, 'watch', !1), D(options, 'lazyCompilation', !1), D(options, 'bail', !1), F(options, 'cache', ()=>!!development && {
6664
+ type: 'memory'
6665
+ }), applyCacheDefaults(options.cache, {
6666
+ context: options.context,
6667
+ name: options.name,
6668
+ mode: options.mode,
6669
+ compilerIndex
6670
+ }), applyIncrementalDefaults(options), applyExperimentsDefaults(options.experiments, {
6671
+ production
6672
+ }), applyOptimizationDefaults(options.optimization, {
6678
6673
  production,
6679
6674
  development
6680
- }), applySnapshotDefaults(options.snapshot, {
6681
- production
6682
6675
  }), applyOutputDefaults(options, {
6683
6676
  context: options.context,
6684
6677
  targetProperties,
@@ -6721,11 +6714,23 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
6721
6714
  esVersion: targetProperties.esVersion,
6722
6715
  targets: targetProperties.targets
6723
6716
  };
6724
- }, applyExperimentsDefaults = (experiments)=>{
6725
- D(experiments, 'futureDefaults', !1), D(experiments, 'asyncWebAssembly', !0), D(experiments, 'deferImport', !1), D(experiments, 'sourceImport', !1), D(experiments, 'buildHttp', void 0), experiments.buildHttp && 'object' == typeof experiments.buildHttp && D(experiments.buildHttp, 'upgrade', !1), D(experiments, 'useInputFileSystem', !1), D(experiments, 'pureFunctions', !1);
6717
+ }, applyCacheDefaults = (cache, { context, name, mode, compilerIndex })=>{
6718
+ if (!1 !== cache) switch(cache.type){
6719
+ case 'memory':
6720
+ break;
6721
+ case 'persistent':
6722
+ D(cache, 'version', ''), F(cache, 'buildDependencies', ()=>[]), F(cache.snapshot, 'immutablePaths', ()=>[]), F(cache.snapshot, 'unmanagedPaths', ()=>[]), F(cache.snapshot, 'managedPaths', ()=>[
6723
+ /[\\/]node_modules[\\/][^.]/
6724
+ ]), D(cache.storage, 'type', 'filesystem'), F(cache.storage, 'directory', ()=>{
6725
+ let modeName = mode || 'production', compilerName = name ? `${name}-${modeName}` : modeName, cacheName = compilerIndex ? `${compilerName}-${compilerIndex}` : compilerName;
6726
+ return node_path.resolve(context, 'node_modules/.cache/rspack', cacheName);
6727
+ }), D(cache, 'portable', !1), D(cache, 'readonly', !1);
6728
+ }
6729
+ }, applyExperimentsDefaults = (experiments, { production })=>{
6730
+ D(experiments, 'futureDefaults', !1), D(experiments, 'asyncWebAssembly', !0), D(experiments, 'deferImport', !1), D(experiments, 'sourceImport', !1), D(experiments, 'buildHttp', void 0), experiments.buildHttp && 'object' == typeof experiments.buildHttp && D(experiments.buildHttp, 'upgrade', !1), D(experiments, 'useInputFileSystem', !1), D(experiments, 'pureFunctions', production), D(experiments, 'runtimeMode', 'webpack');
6726
6731
  }, applyIncrementalDefaults = (options)=>{
6727
6732
  D(options, 'incremental', {}), 'object' == typeof options.incremental && (D(options.incremental, 'silent', !0), D(options.incremental, 'buildModuleGraph', !0), D(options.incremental, 'finishModules', !0), D(options.incremental, 'optimizeDependencies', !0), D(options.incremental, 'buildChunkGraph', !0), D(options.incremental, 'optimizeChunkModules', !0), D(options.incremental, 'moduleIds', !0), D(options.incremental, 'chunkIds', !0), D(options.incremental, 'modulesHashes', !0), D(options.incremental, 'modulesCodegen', !0), D(options.incremental, 'modulesRuntimeRequirements', !0), D(options.incremental, 'chunksRuntimeRequirements', !0), D(options.incremental, 'chunksHashes', !0), D(options.incremental, 'chunkAsset', !0), D(options.incremental, 'emitAssets', !0));
6728
- }, applySnapshotDefaults = (_snapshot, _env)=>{}, applyCssParserOptionsDefaults = (parserOptions)=>{
6733
+ }, applyCssParserOptionsDefaults = (parserOptions)=>{
6729
6734
  D(parserOptions, 'namedExports', !0), D(parserOptions, 'url', !0), D(parserOptions, 'import', !0);
6730
6735
  }, applyCssModuleGeneratorOptionsDefaults = (generatorOptions, { hashFunction, hashSalt, localIdentName, targetProperties })=>{
6731
6736
  D(generatorOptions, 'exportsOnly', !targetProperties || !1 === targetProperties.document), D(generatorOptions, 'esModule', !0), D(generatorOptions, 'exportsConvention', 'as-is'), D(generatorOptions, 'localIdentName', localIdentName), D(generatorOptions, 'localIdentHashSalt', hashSalt), D(generatorOptions, 'localIdentHashFunction', hashFunction), D(generatorOptions, 'localIdentHashDigest', 'base64url'), D(generatorOptions, 'localIdentHashDigestLength', 6);
@@ -6737,7 +6742,7 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
6737
6742
  assertNotNill(module.parser), assertNotNill(module.generator), F(module.parser, "asset", ()=>({})), assertNotNill(module.parser.asset), F(module.parser.asset, 'dataUrlCondition', ()=>({})), 'object' == typeof module.parser.asset.dataUrlCondition && D(module.parser.asset.dataUrlCondition, 'maxSize', 8096), F(module.parser, "javascript", ()=>({})), assertNotNill(module.parser.javascript), ((parserOptions, { deferImport, sourceImport, outputModule })=>{
6738
6743
  D(parserOptions, 'dynamicImportMode', 'lazy'), D(parserOptions, 'dynamicImportPrefetch', !1), D(parserOptions, 'dynamicImportPreload', !1), D(parserOptions, 'url', !0), D(parserOptions, 'exprContextCritical', !0), D(parserOptions, 'unknownContextCritical', !0), D(parserOptions, 'wrappedContextCritical', !1), D(parserOptions, 'strictThisContextOnImports', !1), D(parserOptions, 'wrappedContextRegExp', /.*/), D(parserOptions, 'exportsPresence', 'error'), D(parserOptions, 'requireAsExpression', !0), D(parserOptions, 'requireAlias', !1), D(parserOptions, 'requireDynamic', !0), D(parserOptions, 'requireResolve', !0), D(parserOptions, 'commonjs', !0), D(parserOptions, 'importDynamic', !0), D(parserOptions, 'worker', [
6739
6744
  '...'
6740
- ]), D(parserOptions, 'importMeta', !outputModule || 'preserve-unknown'), D(parserOptions, 'typeReexportsPresence', 'no-tolerant'), D(parserOptions, 'jsx', !1), D(parserOptions, 'deferImport', deferImport), D(parserOptions, 'sourceImport', sourceImport), D(parserOptions, 'importMetaResolve', !1);
6745
+ ]), D(parserOptions, 'importMeta', !outputModule || 'preserve-unknown'), D(parserOptions, 'typeReexportsPresence', 'no-tolerant'), D(parserOptions, 'jsx', !1), D(parserOptions, 'deferImport', deferImport), D(parserOptions, 'sourceImport', sourceImport), D(parserOptions, 'importMetaResolve', !1), D(parserOptions, 'createRequire', !1);
6741
6746
  })(module.parser.javascript, {
6742
6747
  deferImport,
6743
6748
  sourceImport,
@@ -7033,7 +7038,7 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
7033
7038
  return output.wasmLoading && enabledWasmLoadingTypes.add(output.wasmLoading), output.workerWasmLoading && enabledWasmLoadingTypes.add(output.workerWasmLoading), forEachEntry((desc)=>{
7034
7039
  desc.wasmLoading && enabledWasmLoadingTypes.add(desc.wasmLoading);
7035
7040
  }), Array.from(enabledWasmLoadingTypes);
7036
- }), D(output, 'bundlerInfo', {}), 'object' == typeof output.bundlerInfo && (D(output.bundlerInfo, 'version', "2.0.8"), D(output.bundlerInfo, 'bundler', 'rspack'), D(output.bundlerInfo, 'force', !1));
7041
+ }), D(output, 'bundlerInfo', {}), 'object' == typeof output.bundlerInfo && (D(output.bundlerInfo, 'version', "2.1.0-beta.0"), D(output.bundlerInfo, 'bundler', 'rspack'), D(output.bundlerInfo, 'force', !1));
7037
7042
  }, applyExternalsPresetsDefaults = (externalsPresets, { targetProperties, buildHttp, outputModule })=>{
7038
7043
  let isUniversal = (key)=>!!(outputModule && targetProperties && null === targetProperties[key]);
7039
7044
  D(externalsPresets, 'web', !buildHttp && targetProperties && (targetProperties.web || isUniversal('node'))), D(externalsPresets, 'node', targetProperties && (targetProperties.node || isUniversal('node'))), D(externalsPresets, 'electron', targetProperties && targetProperties.electron || isUniversal('electron')), D(externalsPresets, 'electronMain', targetProperties && !!targetProperties.electron && (targetProperties.electronMain || isUniversal('electronMain'))), D(externalsPresets, 'electronPreload', targetProperties && !!targetProperties.electron && (targetProperties.electronPreload || isUniversal('electronPreload'))), D(externalsPresets, 'electronRenderer', targetProperties && !!targetProperties.electron && (targetProperties.electronRenderer || isUniversal('electronRenderer'))), D(externalsPresets, 'nwjs', targetProperties && (targetProperties.nwjs || isUniversal('nwjs')));
@@ -7047,7 +7052,16 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
7047
7052
  }
7048
7053
  }), D(loader, 'environment', environment);
7049
7054
  }, applyNodeDefaults = (node, { outputModule, targetProperties })=>{
7050
- !1 !== node && (F(node, 'global', ()=>(!targetProperties || !targetProperties.global) && 'warn'), F(node, '__dirname', ()=>targetProperties && targetProperties.node ? outputModule ? 'node-module' : 'eval-only' : 'warn-mock'), F(node, '__filename', ()=>targetProperties && targetProperties.node ? outputModule ? 'node-module' : 'eval-only' : 'warn-mock'));
7055
+ if (!1 === node) return;
7056
+ F(node, 'global', ()=>(!targetProperties || !targetProperties.global) && 'warn');
7057
+ let handlerForNames = ()=>{
7058
+ if (targetProperties) {
7059
+ if (targetProperties.node) return outputModule ? 'node-module' : 'eval-only';
7060
+ if (outputModule && null === targetProperties.node && null === targetProperties.web) return 'eval-only';
7061
+ }
7062
+ return 'warn-mock';
7063
+ };
7064
+ F(node, '__dirname', handlerForNames), F(node, '__filename', handlerForNames);
7051
7065
  }, applyPerformanceDefaults = (performance, { production })=>{
7052
7066
  !1 !== performance && (D(performance, 'maxAssetSize', 307200), D(performance, 'maxEntrypointSize', 512000), F(performance, 'hints', ()=>!!production && 'warning'));
7053
7067
  }, applyOptimizationDefaults = (optimization, { production, development })=>{
@@ -7325,34 +7339,49 @@ You can also more options via the 'target' option: 'browserslist' / 'browserslis
7325
7339
  ...node
7326
7340
  }),
7327
7341
  loader: cloneObject(config.loader),
7328
- snapshot: nestedConfig(config.snapshot, (_snapshot)=>({})),
7329
7342
  cache: optionalNestedConfig(config.cache, (cache)=>{
7330
- if ('boolean' == typeof cache || 'memory' === cache.type) return cache;
7331
- let snapshot = cache.snapshot || {};
7332
- return {
7333
- type: 'persistent',
7334
- buildDependencies: nestedArray(cache.buildDependencies, (deps)=>deps.map((d)=>node_path.resolve(config.context || process.cwd(), d))),
7335
- version: cache.version || '',
7336
- snapshot: {
7337
- immutablePaths: nestedArray(snapshot.immutablePaths, (p)=>[
7338
- ...p
7339
- ]),
7340
- unmanagedPaths: nestedArray(snapshot.unmanagedPaths, (p)=>[
7341
- ...p
7342
- ]),
7343
- managedPaths: optionalNestedArray(snapshot.managedPaths, (p)=>[
7344
- ...p
7345
- ]) || [
7346
- /[\\/]node_modules[\\/][^.]/
7347
- ]
7348
- },
7349
- storage: {
7350
- type: 'filesystem',
7351
- directory: node_path.resolve(config.context || process.cwd(), cache.storage?.directory || 'node_modules/.cache/rspack')
7352
- },
7353
- portable: cache.portable,
7354
- readonly: cache.readonly
7343
+ if (!1 === cache) return !1;
7344
+ if (!0 === cache) return {
7345
+ type: 'memory'
7355
7346
  };
7347
+ switch(cache.type){
7348
+ case void 0:
7349
+ case 'memory':
7350
+ return {
7351
+ ...cache,
7352
+ type: 'memory'
7353
+ };
7354
+ case 'persistent':
7355
+ {
7356
+ let context = config.context || process.cwd();
7357
+ return {
7358
+ type: 'persistent',
7359
+ version: cache.version,
7360
+ portable: cache.portable,
7361
+ readonly: cache.readonly,
7362
+ buildDependencies: nestedArray(cache.buildDependencies, (deps)=>deps.map((d)=>node_path.resolve(context, d))),
7363
+ snapshot: nestedConfig(cache.snapshot, (snapshot)=>({
7364
+ immutablePaths: optionalNestedArray(snapshot.immutablePaths, (p)=>[
7365
+ ...p
7366
+ ]),
7367
+ unmanagedPaths: optionalNestedArray(snapshot.unmanagedPaths, (p)=>[
7368
+ ...p
7369
+ ]),
7370
+ managedPaths: optionalNestedArray(snapshot.managedPaths, (p)=>[
7371
+ ...p
7372
+ ])
7373
+ })),
7374
+ storage: nestedConfig(cache.storage, (storage)=>({
7375
+ type: storage.type,
7376
+ directory: optionalNestedConfig(storage.directory, (d)=>node_path.resolve(context, d)),
7377
+ maxAge: storage.maxAge,
7378
+ maxGenerations: storage.maxGenerations
7379
+ }))
7380
+ };
7381
+ }
7382
+ default:
7383
+ throw Error(`Not implemented cache.type ${cache.type}`);
7384
+ }
7356
7385
  }),
7357
7386
  stats: nestedConfig(config.stats, (stats)=>!1 === stats ? {
7358
7387
  preset: 'none'
@@ -7490,31 +7519,49 @@ function __to_binding_runtime_globals(runtimeRequirements, compilerRuntimeGlobal
7490
7519
  return res;
7491
7520
  }
7492
7521
  var RuntimeGlobals_RuntimeGlobals = ((RuntimeGlobals = RuntimeGlobals_RuntimeGlobals || {})[RuntimeGlobals.require = 0] = "require", RuntimeGlobals[RuntimeGlobals.requireScope = 1] = "requireScope", RuntimeGlobals[RuntimeGlobals.exports = 2] = "exports", RuntimeGlobals[RuntimeGlobals.thisAsExports = 3] = "thisAsExports", RuntimeGlobals[RuntimeGlobals.returnExportsFromRuntime = 4] = "returnExportsFromRuntime", RuntimeGlobals[RuntimeGlobals.module = 5] = "module", RuntimeGlobals[RuntimeGlobals.moduleId = 6] = "moduleId", RuntimeGlobals[RuntimeGlobals.moduleLoaded = 7] = "moduleLoaded", RuntimeGlobals[RuntimeGlobals.publicPath = 8] = "publicPath", RuntimeGlobals[RuntimeGlobals.entryModuleId = 9] = "entryModuleId", RuntimeGlobals[RuntimeGlobals.moduleCache = 10] = "moduleCache", RuntimeGlobals[RuntimeGlobals.moduleFactories = 11] = "moduleFactories", RuntimeGlobals[RuntimeGlobals.moduleFactoriesAddOnly = 12] = "moduleFactoriesAddOnly", RuntimeGlobals[RuntimeGlobals.ensureChunk = 13] = "ensureChunk", RuntimeGlobals[RuntimeGlobals.ensureChunkHandlers = 14] = "ensureChunkHandlers", RuntimeGlobals[RuntimeGlobals.ensureChunkIncludeEntries = 15] = "ensureChunkIncludeEntries", RuntimeGlobals[RuntimeGlobals.prefetchChunk = 16] = "prefetchChunk", RuntimeGlobals[RuntimeGlobals.prefetchChunkHandlers = 17] = "prefetchChunkHandlers", RuntimeGlobals[RuntimeGlobals.preloadChunk = 18] = "preloadChunk", RuntimeGlobals[RuntimeGlobals.preloadChunkHandlers = 19] = "preloadChunkHandlers", RuntimeGlobals[RuntimeGlobals.definePropertyGetters = 20] = "definePropertyGetters", RuntimeGlobals[RuntimeGlobals.makeNamespaceObject = 21] = "makeNamespaceObject", RuntimeGlobals[RuntimeGlobals.createFakeNamespaceObject = 22] = "createFakeNamespaceObject", RuntimeGlobals[RuntimeGlobals.compatGetDefaultExport = 23] = "compatGetDefaultExport", RuntimeGlobals[RuntimeGlobals.harmonyModuleDecorator = 24] = "harmonyModuleDecorator", RuntimeGlobals[RuntimeGlobals.nodeModuleDecorator = 25] = "nodeModuleDecorator", RuntimeGlobals[RuntimeGlobals.getFullHash = 26] = "getFullHash", RuntimeGlobals[RuntimeGlobals.wasmInstances = 27] = "wasmInstances", RuntimeGlobals[RuntimeGlobals.instantiateWasm = 28] = "instantiateWasm", RuntimeGlobals[RuntimeGlobals.compileWasm = 29] = "compileWasm", RuntimeGlobals[RuntimeGlobals.uncaughtErrorHandler = 30] = "uncaughtErrorHandler", RuntimeGlobals[RuntimeGlobals.scriptNonce = 31] = "scriptNonce", RuntimeGlobals[RuntimeGlobals.loadScript = 32] = "loadScript", RuntimeGlobals[RuntimeGlobals.createScript = 33] = "createScript", RuntimeGlobals[RuntimeGlobals.createScriptUrl = 34] = "createScriptUrl", RuntimeGlobals[RuntimeGlobals.getTrustedTypesPolicy = 35] = "getTrustedTypesPolicy", RuntimeGlobals[RuntimeGlobals.hasFetchPriority = 36] = "hasFetchPriority", RuntimeGlobals[RuntimeGlobals.chunkName = 37] = "chunkName", RuntimeGlobals[RuntimeGlobals.runtimeId = 38] = "runtimeId", RuntimeGlobals[RuntimeGlobals.getChunkScriptFilename = 39] = "getChunkScriptFilename", RuntimeGlobals[RuntimeGlobals.getChunkCssFilename = 40] = "getChunkCssFilename", RuntimeGlobals[RuntimeGlobals.rspackVersion = 41] = "rspackVersion", RuntimeGlobals[RuntimeGlobals.hasCssModules = 42] = "hasCssModules", RuntimeGlobals[RuntimeGlobals.rspackUniqueId = 43] = "rspackUniqueId", RuntimeGlobals[RuntimeGlobals.getChunkUpdateScriptFilename = 44] = "getChunkUpdateScriptFilename", RuntimeGlobals[RuntimeGlobals.getChunkUpdateCssFilename = 45] = "getChunkUpdateCssFilename", RuntimeGlobals[RuntimeGlobals.startup = 46] = "startup", RuntimeGlobals[RuntimeGlobals.startupNoDefault = 47] = "startupNoDefault", RuntimeGlobals[RuntimeGlobals.startupOnlyAfter = 48] = "startupOnlyAfter", RuntimeGlobals[RuntimeGlobals.startupOnlyBefore = 49] = "startupOnlyBefore", RuntimeGlobals[RuntimeGlobals.chunkCallback = 50] = "chunkCallback", RuntimeGlobals[RuntimeGlobals.startupEntrypoint = 51] = "startupEntrypoint", RuntimeGlobals[RuntimeGlobals.startupChunkDependencies = 52] = "startupChunkDependencies", RuntimeGlobals[RuntimeGlobals.onChunksLoaded = 53] = "onChunksLoaded", RuntimeGlobals[RuntimeGlobals.externalInstallChunk = 54] = "externalInstallChunk", RuntimeGlobals[RuntimeGlobals.interceptModuleExecution = 55] = "interceptModuleExecution", RuntimeGlobals[RuntimeGlobals.global = 56] = "global", RuntimeGlobals[RuntimeGlobals.shareScopeMap = 57] = "shareScopeMap", RuntimeGlobals[RuntimeGlobals.initializeSharing = 58] = "initializeSharing", RuntimeGlobals[RuntimeGlobals.currentRemoteGetScope = 59] = "currentRemoteGetScope", RuntimeGlobals[RuntimeGlobals.getUpdateManifestFilename = 60] = "getUpdateManifestFilename", RuntimeGlobals[RuntimeGlobals.hmrDownloadManifest = 61] = "hmrDownloadManifest", RuntimeGlobals[RuntimeGlobals.hmrDownloadUpdateHandlers = 62] = "hmrDownloadUpdateHandlers", RuntimeGlobals[RuntimeGlobals.hmrModuleData = 63] = "hmrModuleData", RuntimeGlobals[RuntimeGlobals.hmrInvalidateModuleHandlers = 64] = "hmrInvalidateModuleHandlers", RuntimeGlobals[RuntimeGlobals.hmrRuntimeStatePrefix = 65] = "hmrRuntimeStatePrefix", RuntimeGlobals[RuntimeGlobals.amdDefine = 66] = "amdDefine", RuntimeGlobals[RuntimeGlobals.amdOptions = 67] = "amdOptions", RuntimeGlobals[RuntimeGlobals.system = 68] = "system", RuntimeGlobals[RuntimeGlobals.hasOwnProperty = 69] = "hasOwnProperty", RuntimeGlobals[RuntimeGlobals.systemContext = 70] = "systemContext", RuntimeGlobals[RuntimeGlobals.baseURI = 71] = "baseURI", RuntimeGlobals[RuntimeGlobals.relativeUrl = 72] = "relativeUrl", RuntimeGlobals[RuntimeGlobals.asyncModule = 73] = "asyncModule", RuntimeGlobals[RuntimeGlobals.asyncModuleExportSymbol = 74] = "asyncModuleExportSymbol", RuntimeGlobals[RuntimeGlobals.makeDeferredNamespaceObject = 75] = "makeDeferredNamespaceObject", RuntimeGlobals[RuntimeGlobals.makeDeferredNamespaceObjectSymbol = 76] = "makeDeferredNamespaceObjectSymbol", RuntimeGlobals);
7493
- function renderRuntimeVariables(variable, _compilerOptions) {
7522
+ function renderRuntimeVariables(variable, compilerOptions) {
7523
+ if (compilerOptions?.experiments.runtimeMode === 'rspack') switch(variable){
7524
+ case 0:
7525
+ return '__rspack_require';
7526
+ case 1:
7527
+ return '__rspack_context';
7528
+ case 2:
7529
+ return '__rspack_modules';
7530
+ case 3:
7531
+ return '__rspack_module_cache';
7532
+ case 4:
7533
+ return '__rspack_module';
7534
+ case 5:
7535
+ return '__rspack_exports';
7536
+ case 6:
7537
+ return '__rspack_exec';
7538
+ }
7494
7539
  switch(variable){
7495
7540
  case 0:
7496
7541
  return '__webpack_require__';
7497
7542
  case 1:
7498
- return '__webpack_modules__';
7543
+ return '__rspack_context';
7499
7544
  case 2:
7500
- return '__webpack_module_cache__';
7545
+ return '__webpack_modules__';
7501
7546
  case 3:
7502
- return '__webpack_module__';
7547
+ return '__webpack_module_cache__';
7503
7548
  case 4:
7504
- return '__webpack_exports__';
7549
+ return '__webpack_module__';
7505
7550
  case 5:
7551
+ return '__webpack_exports__';
7552
+ case 6:
7506
7553
  return '__webpack_exec__';
7507
7554
  }
7508
7555
  }
7509
7556
  function createCompilerRuntimeGlobals(compilerOptions) {
7510
7557
  let res = {};
7511
7558
  for (let key of Object.keys(RuntimeGlobals_RuntimeGlobals))res[key] = function(runtimeGlobals, _compilerOptions) {
7512
- let scope_name = renderRuntimeVariables(0, _compilerOptions), exports_name = renderRuntimeVariables(4, _compilerOptions);
7559
+ let require_name = renderRuntimeVariables(0, _compilerOptions), context_name = renderRuntimeVariables(1, _compilerOptions), usesRuntimeContext = _compilerOptions?.experiments.runtimeMode === 'rspack', scope_name = usesRuntimeContext ? context_name : require_name, exports_name = renderRuntimeVariables(5, _compilerOptions);
7513
7560
  switch(runtimeGlobals){
7514
7561
  case 0:
7515
- return scope_name;
7562
+ return usesRuntimeContext ? `${context_name}.r` : require_name;
7516
7563
  case 1:
7517
- return `${scope_name}.*`;
7564
+ return usesRuntimeContext ? context_name : `${require_name}.*`;
7518
7565
  case 2:
7519
7566
  return exports_name;
7520
7567
  case 3:
@@ -7554,7 +7601,7 @@ function createCompilerRuntimeGlobals(compilerOptions) {
7554
7601
  case 20:
7555
7602
  return `${scope_name}.d`;
7556
7603
  case 21:
7557
- return `${scope_name}.r`;
7604
+ return usesRuntimeContext ? `${context_name}.N` : `${require_name}.r`;
7558
7605
  case 22:
7559
7606
  return `${scope_name}.t`;
7560
7607
  case 23:
@@ -7678,9 +7725,10 @@ class ExecuteModulePlugin {
7678
7725
  compiler.__internal__get_module_execution_results_map().clear(), compilation.hooks.executeModule.tap('executeModule', (options, context)=>{
7679
7726
  let vm = ExecuteModulePlugin_require('node:vm'), moduleObject = options.moduleObject, source = options.codeGenerationResult.get("javascript");
7680
7727
  if (void 0 !== source) try {
7681
- vm.runInThisContext(`(function(module, ${renderRuntimeVariables(3, compiler.options)}, ${renderRuntimeVariables(4, compiler.options)}, exports, ${renderRuntimeVariables(0, compiler.options)}) {\n${source}\n})`, {
7728
+ let isRspackRuntimeMode = compiler.options.experiments?.runtimeMode === 'rspack', moduleArgument = renderRuntimeVariables(4, compiler.options), exportsArgument = renderRuntimeVariables(5, compiler.options), requireArgument = renderRuntimeVariables(0, compiler.options), runtimeContextArgument = renderRuntimeVariables(1, compiler.options), runtimeContext = context[runtimeContextArgument], runtimeModeArguments = isRspackRuntimeMode ? `, ${runtimeContextArgument}` : '';
7729
+ vm.runInThisContext(`(function(module, ${moduleArgument}, ${exportsArgument}, exports, ${requireArgument}${runtimeModeArguments}) {\n${source}\n})`, {
7682
7730
  filename: moduleObject.id
7683
- }).call(moduleObject.exports, moduleObject, moduleObject, moduleObject.exports, moduleObject.exports, context[renderRuntimeVariables(0, compiler.options)]);
7731
+ }).call(moduleObject.exports, moduleObject, moduleObject, moduleObject.exports, moduleObject.exports, context[requireArgument], runtimeContext);
7684
7732
  } catch (e) {
7685
7733
  let err = e instanceof Error ? e : Error(e);
7686
7734
  throw err.stack += printGeneratedCodeForStack(moduleObject.id, source), err;
@@ -8288,7 +8336,7 @@ class MultiStats {
8288
8336
  obj.children = this.stats.map((stat, idx)=>{
8289
8337
  let obj = stat.toJson(childOptions.children[idx]), compilationName = stat.compilation.name;
8290
8338
  return obj.name = compilationName && makePathsRelative(childOptions.context, compilationName, stat.compilation.compiler.root), obj;
8291
- }), childOptions.version && (obj.rspackVersion = "2.0.8", obj.version = "5.75.0"), childOptions.hash && (obj.hash = obj.children.map((j)=>j.hash).join(''));
8339
+ }), childOptions.version && (obj.rspackVersion = "2.1.0-beta.0", obj.version = "5.75.0"), childOptions.hash && (obj.hash = obj.children.map((j)=>j.hash).join(''));
8292
8340
  let mapError = (j, obj)=>({
8293
8341
  ...obj,
8294
8342
  compilerPath: obj.compilerPath ? `${j.name}.${obj.compilerPath}` : j.name
@@ -9562,7 +9610,7 @@ let iterateConfig = (config, options, fn)=>{
9562
9610
  object.hash = context.getStatsCompilation(compilation).hash;
9563
9611
  },
9564
9612
  version: (object)=>{
9565
- object.version = "5.75.0", object.rspackVersion = "2.0.8";
9613
+ object.version = "5.75.0", object.rspackVersion = "2.1.0-beta.0";
9566
9614
  },
9567
9615
  env: (object, _compilation, _context, { _env })=>{
9568
9616
  object.env = _env;
@@ -10827,7 +10875,7 @@ class RspackOptionsApply {
10827
10875
  moduleFilenameTemplate: options.output.devtoolModuleFilenameTemplate,
10828
10876
  namespace: options.output.devtoolNamespace
10829
10877
  }).apply(compiler);
10830
- new JavascriptModulesPlugin().apply(compiler), new URLPlugin().apply(compiler), new JsonModulesPlugin().apply(compiler), new AssetModulesPlugin().apply(compiler), options.experiments.asyncWebAssembly && new AsyncWebAssemblyModulesPlugin().apply(compiler), new CssModulesPlugin().apply(compiler), new lib_EntryOptionPlugin().apply(compiler), assertNotNill(options.context), compiler.hooks.entryOption.call(options.context, options.entry), new RuntimePlugin().apply(compiler), options.output.bundlerInfo && new BundlerInfoRspackPlugin(options.output.bundlerInfo).apply(compiler), new InferAsyncModulesPlugin().apply(compiler), new APIPlugin().apply(compiler), new DataUriPlugin().apply(compiler), new FileUriPlugin().apply(compiler), options.experiments.buildHttp && new HttpUriPlugin(options.experiments.buildHttp).apply(compiler), new EnsureChunkConditionsPlugin().apply(compiler), options.optimization.mergeDuplicateChunks && new MergeDuplicateChunksPlugin().apply(compiler), options.optimization.sideEffects && new SideEffectsFlagPlugin(options.experiments.pureFunctions).apply(compiler), options.optimization.providedExports && new FlagDependencyExportsPlugin().apply(compiler), 'production' === options.mode && new CircularModulesInfoPlugin().apply(compiler), options.optimization.usedExports && new FlagDependencyUsagePlugin('global' === options.optimization.usedExports).apply(compiler), options.optimization.concatenateModules && new ModuleConcatenationPlugin().apply(compiler), options.optimization.inlineExports && new InlineExportsPlugin().apply(compiler), options.optimization.mangleExports && new MangleExportsPlugin('size' !== options.optimization.mangleExports).apply(compiler);
10878
+ new JavascriptModulesPlugin().apply(compiler), new URLPlugin().apply(compiler), new JsonModulesPlugin().apply(compiler), new AssetModulesPlugin().apply(compiler), options.experiments.asyncWebAssembly && new AsyncWebAssemblyModulesPlugin().apply(compiler), new CssModulesPlugin().apply(compiler), new lib_EntryOptionPlugin().apply(compiler), assertNotNill(options.context), compiler.hooks.entryOption.call(options.context, options.entry), new RuntimePlugin().apply(compiler), options.output.bundlerInfo && new BundlerInfoRspackPlugin(options.output.bundlerInfo).apply(compiler), new InferAsyncModulesPlugin().apply(compiler), new APIPlugin().apply(compiler), new DataUriPlugin().apply(compiler), new FileUriPlugin().apply(compiler), options.experiments.buildHttp && new HttpUriPlugin(options.experiments.buildHttp).apply(compiler), new EnsureChunkConditionsPlugin().apply(compiler), options.optimization.mergeDuplicateChunks && new MergeDuplicateChunksPlugin().apply(compiler), options.optimization.sideEffects && new SideEffectsFlagPlugin(options.experiments.pureFunctions && !0 === options.optimization.sideEffects).apply(compiler), options.optimization.providedExports && new FlagDependencyExportsPlugin().apply(compiler), 'production' === options.mode && new CircularModulesInfoPlugin().apply(compiler), options.optimization.usedExports && new FlagDependencyUsagePlugin('global' === options.optimization.usedExports).apply(compiler), options.optimization.concatenateModules && new ModuleConcatenationPlugin().apply(compiler), options.optimization.inlineExports && new InlineExportsPlugin().apply(compiler), options.optimization.mangleExports && new MangleExportsPlugin('size' !== options.optimization.mangleExports).apply(compiler);
10831
10879
  let enableLibSplitChunks = !1;
10832
10880
  if (options.output.enabledLibraryTypes && options.output.enabledLibraryTypes.length > 0) {
10833
10881
  let hasModernModule = options.output.enabledLibraryTypes.includes('modern-module'), hasNonModernModule = options.output.enabledLibraryTypes.some((t)=>'modern-module' !== t);
@@ -10893,6 +10941,12 @@ function validateRspackConfig(config) {
10893
10941
  let { minChunks } = optimization.splitChunks;
10894
10942
  if (void 0 !== minChunks && minChunks < 1) throw Error(`${validateConfig_ERROR_PREFIX} "optimization.splitChunks.minChunks" must be greater than or equal to 1, get \`${minChunks}\`.`);
10895
10943
  }
10944
+ })(config), (({ cache })=>{
10945
+ if ('object' != typeof cache || 'persistent' !== cache.type) return;
10946
+ let maxAge = cache.storage?.maxAge;
10947
+ if (void 0 !== maxAge && (!Number.isSafeInteger(maxAge) || maxAge < 0 || maxAge > 0xffffffff)) throw Error(`${validateConfig_ERROR_PREFIX} "cache.storage.maxAge" must be an integer between 0 and 4294967295, get \`${maxAge}\`.`);
10948
+ let maxGenerations = cache.storage?.maxGenerations;
10949
+ if (void 0 !== maxGenerations && (!Number.isSafeInteger(maxGenerations) || maxGenerations < 0 || maxGenerations > 0xffffffff)) throw Error(`${validateConfig_ERROR_PREFIX} "cache.storage.maxGenerations" must be an integer between 0 and 4294967295, get \`${maxGenerations}\`.`);
10896
10950
  })(config), (({ output, externals, externalsType })=>{
10897
10951
  let library = output?.library;
10898
10952
  if (!('object' == typeof library && 'type' in library && 'umd' === library.type) || void 0 !== externalsType && 'umd' !== externalsType) return;
@@ -10909,7 +10963,7 @@ function validateRspackConfig(config) {
10909
10963
  Array.isArray(externals) ? externals.forEach((external)=>checkExternalItem(external)) : checkExternalItem(externals);
10910
10964
  })(config);
10911
10965
  }
10912
- function createCompiler(userOptions) {
10966
+ function createCompiler(userOptions, compilerIndex) {
10913
10967
  var infrastructureLogging;
10914
10968
  let tty, options = getNormalizedRspackOptions(userOptions);
10915
10969
  if (F(options, 'context', ()=>process.cwd()), F(infrastructureLogging = options.infrastructureLogging, 'stream', ()=>process.stderr), tty = infrastructureLogging.stream?.isTTY && 'dumb' !== process.env.TERM, D(infrastructureLogging, 'level', 'info'), D(infrastructureLogging, 'debug', !1), D(infrastructureLogging, 'colors', tty), D(infrastructureLogging, 'appendOnly', !tty), isNil(options.context)) throw Error('options.context is required');
@@ -10917,7 +10971,7 @@ function createCompiler(userOptions) {
10917
10971
  if (new NodeEnvironmentPlugin({
10918
10972
  infrastructureLogging: options.infrastructureLogging
10919
10973
  }).apply(compiler), Array.isArray(options.plugins)) for (let plugin of options.plugins)'function' == typeof plugin ? plugin.call(compiler, compiler) : plugin && plugin.apply(compiler);
10920
- let tp = applyRspackOptionsDefaults(compiler.options);
10974
+ let tp = applyRspackOptionsDefaults(compiler.options, compilerIndex);
10921
10975
  return tp && (compiler.platform = tp.platform, compiler.target = {
10922
10976
  esVersion: tp.esVersion,
10923
10977
  targets: tp.targets
@@ -10937,7 +10991,7 @@ function rspack_rspack(options, callback) {
10937
10991
  let create = ()=>{
10938
10992
  if (isMultiRspackOptions(options)) {
10939
10993
  let compiler = function(options) {
10940
- let compilers = options.map(createCompiler), compiler = new MultiCompiler(compilers, options);
10994
+ let compilers = options.map((option, index)=>createCompiler(option, index)), compiler = new MultiCompiler(compilers, options);
10941
10995
  for (let childCompiler of compilers)childCompiler.options.dependencies && compiler.setDependencies(childCompiler, childCompiler.options.dependencies);
10942
10996
  return compiler;
10943
10997
  }(options);
@@ -11223,7 +11277,7 @@ class TraceHookPlugin {
11223
11277
  });
11224
11278
  }
11225
11279
  }
11226
- let CORE_VERSION = "2.0.8", VFILES_BY_COMPILER = new WeakMap();
11280
+ let CORE_VERSION = "2.1.0-beta.0", VFILES_BY_COMPILER = new WeakMap();
11227
11281
  class VirtualModulesPlugin {
11228
11282
  #staticModules;
11229
11283
  #compiler;
@@ -11589,7 +11643,7 @@ class Compiler {
11589
11643
  electron: null
11590
11644
  }, this.#target = {}, this.__internal_browser_require = ()=>{
11591
11645
  throw Error('Cannot execute user defined code in browser without `BrowserRequirePlugin`');
11592
- }, this.resolverFactory = new ResolverFactory(options.resolve.pnp ?? getPnpDefault(), options.resolve, options.resolveLoader), new JsLoaderRspackPlugin(this).apply(this), new ExecuteModulePlugin().apply(this), 'on' === JavaScriptTracer.state && new TraceHookPlugin().apply(this), Object.defineProperty(this, GET_COMPILER_ID, {
11646
+ }, this.resolverFactory = new ResolverFactory(options.resolve.pnp ?? getPnpDefault(), options.resolve, options.resolveLoader), new JsLoaderRspackPlugin(this).apply(this), new ExecuteModulePlugin().apply(this), JavaScriptTracer.isEnabled() && new TraceHookPlugin().apply(this), Object.defineProperty(this, GET_COMPILER_ID, {
11593
11647
  writable: !1,
11594
11648
  configurable: !1,
11595
11649
  enumerable: !1,
@@ -11794,7 +11848,7 @@ class Compiler {
11794
11848
  return this.#compilationParams = params, params;
11795
11849
  }
11796
11850
  #getInstance(callback) {
11797
- var output;
11851
+ var output, cache;
11798
11852
  let coreVersion, expectedCoreVersion, statsOptions, mode, experiments, error = CORE_VERSION === binding_default().EXPECTED_RSPACK_CORE_VERSION || CORE_VERSION.includes('canary') ? null : Error((coreVersion = CORE_VERSION, expectedCoreVersion = binding_default().EXPECTED_RSPACK_CORE_VERSION, process.env.RSPACK_BINDING ? `Unmatched version @rspack/core@${coreVersion} and binding version.
11799
11853
 
11800
11854
  Help:
@@ -11878,7 +11932,18 @@ Help:
11878
11932
  return delete obj.preset, obj;
11879
11933
  }(options.stats)).colors ? isStatsColorSupported() : !!statsOptions.colors
11880
11934
  },
11881
- cache: options.cache || !1,
11935
+ cache: !1 !== (cache = options.cache) && ('memory' === cache.type ? cache : {
11936
+ ...cache,
11937
+ storage: {
11938
+ ...cache.storage,
11939
+ directory: cache.storage.directory
11940
+ },
11941
+ snapshot: {
11942
+ immutablePaths: cache.snapshot.immutablePaths,
11943
+ unmanagedPaths: cache.snapshot.unmanagedPaths,
11944
+ managedPaths: cache.snapshot.managedPaths
11945
+ }
11946
+ }),
11882
11947
  experiments,
11883
11948
  incremental: options.incremental,
11884
11949
  node: function(node) {
@@ -12035,7 +12100,10 @@ Help:
12035
12100
  let originSource = module.source?.source;
12036
12101
  queried.call(runtimeModule, chunk);
12037
12102
  let newSource = module.source?.source;
12038
- if (newSource && newSource !== originSource) return module;
12103
+ if (newSource && newSource !== originSource) {
12104
+ if (getCompiler().options.experiments?.runtimeMode === 'rspack') throw Error('Compilation.hooks.runtimeModule source modifications are not supported when experiments.runtimeMode is "rspack".');
12105
+ return module;
12106
+ }
12039
12107
  };
12040
12108
  }),
12041
12109
  registerCompilationBuildModuleTaps: createTap(binding_default().RegisterJsTapKind.CompilationBuildModule, function() {
@@ -12064,7 +12132,7 @@ Help:
12064
12132
  }, function(queried) {
12065
12133
  return function({ entry, id, codegenResults, runtimeModules }) {
12066
12134
  try {
12067
- let RuntimeGlobals = getCompiler().rspack.RuntimeGlobals, moduleRequireFn = (id)=>{
12135
+ let RuntimeGlobals = getCompiler().rspack.RuntimeGlobals, runtimeContext = {}, moduleRequireFn = (id)=>{
12068
12136
  let cached = moduleCache[id];
12069
12137
  if (void 0 !== cached) {
12070
12138
  if (cached.error) throw cached.error;
@@ -12093,10 +12161,13 @@ Help:
12093
12161
  codeGenerationResult: new CodeGenerationResult(result),
12094
12162
  moduleObject
12095
12163
  }, {
12096
- [RuntimeGlobals.require]: moduleRequireFn
12164
+ [RuntimeGlobals.require]: moduleRequireFn,
12165
+ [renderRuntimeVariables(0, getCompiler().options)]: moduleRequireFn,
12166
+ [renderRuntimeVariables(1, getCompiler().options)]: runtimeContext
12097
12167
  }), 'Compilation.hooks.executeModule'), moduleObject.loaded = !0, moduleObject.exports;
12098
12168
  }, moduleCache = moduleRequireFn[RuntimeGlobals.moduleCache.replace(`${RuntimeGlobals.require}.`, '')] = {}, interceptModuleExecution = moduleRequireFn[RuntimeGlobals.interceptModuleExecution.replace(`${RuntimeGlobals.require}.`, '')] = [];
12099
- for (let runtimeModule of runtimeModules)moduleRequireFn(runtimeModule);
12169
+ for (let runtimeModule of (moduleRequireFn.r = moduleRequireFn, runtimeContext.r = moduleRequireFn, runtimeModules))moduleRequireFn(runtimeModule);
12170
+ for (let key of Reflect.ownKeys(moduleRequireFn))runtimeContext[key] = moduleRequireFn[key];
12100
12171
  let executeResult = moduleRequireFn(entry);
12101
12172
  getCompiler().__internal__get_module_execution_results_map().set(id, executeResult);
12102
12173
  } catch (e) {
@@ -13474,6 +13545,7 @@ function getDefaultEntryRuntimeRequest(resource) {
13474
13545
  return `${MF_RUNTIME_LOADER}!=!${resource}`;
13475
13546
  }
13476
13547
  function getDefaultEntryRuntimeSource(paths, options, compiler, treeShakingShareFallbacks) {
13548
+ var source, runtimeRequire;
13477
13549
  let runtimePlugins = options.runtimePlugins ?? [], remoteInfos = getRemoteInfos(options), runtimePluginImports = [], runtimePluginVars = [], libraryType = options.library?.type || 'var', shouldInitializePublicPath = getSharedOptions(options).some(([, config])=>config.treeShaking);
13478
13550
  for(let i = 0; i < runtimePlugins.length; i++){
13479
13551
  let runtimePluginVar = `__module_federation_runtime_plugin_${i}__`, pluginSpec = runtimePlugins[i], pluginPath = Array.isArray(pluginSpec) ? pluginSpec[0] : pluginSpec, pluginParams = Array.isArray(pluginSpec) ? pluginSpec[1] : void 0;
@@ -13481,12 +13553,25 @@ function getDefaultEntryRuntimeSource(paths, options, compiler, treeShakingShare
13481
13553
  let paramsCode = void 0 === pluginParams ? 'undefined' : JSON.stringify(pluginParams);
13482
13554
  runtimePluginVars.push(`{ plugin: ${runtimePluginVar}, params: ${paramsCode} }`);
13483
13555
  }
13556
+ let defaultRuntimeSource = compiler.rspack.Template.getFunctionContent(ModuleFederationPlugin_require('./moduleFederationDefaultRuntime.js').default), compilerRuntimeGlobals = createCompilerRuntimeGlobals(compiler.options), runtimeSource = (source = defaultRuntimeSource, runtimeRequire = 'rspack' === compiler.options.experiments.runtimeMode ? `new Proxy(function (moduleId) {
13557
+ return ${compilerRuntimeGlobals.require}(moduleId);
13558
+ }, {
13559
+ get(_target, key) {
13560
+ return ${compilerRuntimeGlobals.requireScope}[key];
13561
+ },
13562
+ set(_target, key, value) {
13563
+ ${compilerRuntimeGlobals.requireScope}[key] = value;
13564
+ return true;
13565
+ }
13566
+ })` : compilerRuntimeGlobals.require, source.replace('__module_federation_runtime_require__', runtimeRequire));
13484
13567
  return [
13485
13568
  `import __module_federation_bundler_runtime__ from ${JSON.stringify(paths.bundlerRuntime)}`,
13486
13569
  ...runtimePluginImports,
13487
13570
  shouldInitializePublicPath ? function(compiler) {
13488
13571
  let publicPath = compiler.options.output.publicPath;
13489
- if ('string' == typeof publicPath && 'auto' !== publicPath) return `if (typeof __webpack_require__.p === "undefined") __webpack_require__.p = ${JSON.stringify(publicPath)}`;
13572
+ if ('string' != typeof publicPath || 'auto' === publicPath) return;
13573
+ let publicPathRuntimeGlobal = createCompilerRuntimeGlobals().publicPath;
13574
+ return `if (typeof ${publicPathRuntimeGlobal} === "undefined") ${publicPathRuntimeGlobal} = ${JSON.stringify(publicPath)}`;
13490
13575
  }(compiler) : void 0,
13491
13576
  `const __module_federation_runtime_plugins__ = [${runtimePluginVars.join(', ')}].filter(({ plugin }) => plugin).map(({ plugin, params }) => plugin(params))`,
13492
13577
  `const __module_federation_remote_infos__ = ${JSON.stringify(remoteInfos)}`,
@@ -13494,7 +13579,7 @@ function getDefaultEntryRuntimeSource(paths, options, compiler, treeShakingShare
13494
13579
  `const __module_federation_share_strategy__ = ${JSON.stringify(options.shareStrategy ?? 'version-first')}`,
13495
13580
  `const __module_federation_share_fallbacks__ = ${JSON.stringify(treeShakingShareFallbacks)}`,
13496
13581
  `const __module_federation_library_type__ = ${JSON.stringify(libraryType)}`,
13497
- compiler.rspack.Template.getFunctionContent(ModuleFederationPlugin_require('./moduleFederationDefaultRuntime.js').default)
13582
+ runtimeSource
13498
13583
  ].join(';');
13499
13584
  }
13500
13585
  function getDefaultEntryRuntime(paths, options, compiler, treeShakingShareFallbacks) {
@@ -13602,7 +13687,7 @@ async function transform(source, options) {
13602
13687
  let _options = JSON.stringify(options || {});
13603
13688
  return binding_default().transform(source, _options);
13604
13689
  }
13605
- let exports_rspackVersion = "2.0.8", exports_version = "5.75.0", exports_WebpackError = Error, exports_config = {
13690
+ let exports_rspackVersion = "2.1.0-beta.0", exports_version = "5.75.0", exports_WebpackError = Error, exports_config = {
13606
13691
  getNormalizedRspackOptions: getNormalizedRspackOptions,
13607
13692
  applyRspackOptionsDefaults: applyRspackOptionsDefaults,
13608
13693
  getNormalizedWebpackOptions: getNormalizedRspackOptions,