@rspack/core 0.0.0-20220909025136

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.
Files changed (85) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +1 -0
  3. package/bin.js +1 -0
  4. package/dist/bin/index.d.ts +1 -0
  5. package/dist/bin/index.js +32 -0
  6. package/dist/build.d.ts +1 -0
  7. package/dist/build.js +12 -0
  8. package/dist/config.d.ts +51 -0
  9. package/dist/config.js +26 -0
  10. package/dist/index.d.ts +73 -0
  11. package/dist/index.js +229 -0
  12. package/dist/server/index.d.ts +0 -0
  13. package/dist/server/index.js +0 -0
  14. package/example/basic.ts +71 -0
  15. package/example/react-example/index.html +12 -0
  16. package/example/react-example/package.json +17 -0
  17. package/example/react-example/rspack.config.json +13 -0
  18. package/example/react-example/src/app.jsx +44 -0
  19. package/example/react-example/src/base.css +9 -0
  20. package/example/react-example/src/button.jsx +3 -0
  21. package/example/react-example/src/dark.svg +1 -0
  22. package/example/react-example/src/data.json +5 -0
  23. package/example/react-example/src/file.jpg +0 -0
  24. package/example/react-example/src/file.png +0 -0
  25. package/example/react-example/src/file.svg +1 -0
  26. package/example/react-example/src/foo.css +3 -0
  27. package/example/react-example/src/index.html +32 -0
  28. package/example/react-example/src/index.js +1 -0
  29. package/example/react-example/src/light.svg +48 -0
  30. package/example/react-example/src/logo.svg +18 -0
  31. package/example/react-with-sass.ts +28 -0
  32. package/lib/bin/index.d.ts +1 -0
  33. package/lib/bin/index.js +32 -0
  34. package/lib/build.d.ts +1 -0
  35. package/lib/build.js +12 -0
  36. package/lib/config/builtins.d.ts +3 -0
  37. package/lib/config/builtins.js +2 -0
  38. package/lib/config/context.d.ts +2 -0
  39. package/lib/config/context.js +2 -0
  40. package/lib/config/define.d.ts +2 -0
  41. package/lib/config/define.js +2 -0
  42. package/lib/config/dev.d.ts +17 -0
  43. package/lib/config/dev.js +17 -0
  44. package/lib/config/entry.d.ts +2 -0
  45. package/lib/config/entry.js +2 -0
  46. package/lib/config/external.d.ts +2 -0
  47. package/lib/config/external.js +2 -0
  48. package/lib/config/index.d.ts +45 -0
  49. package/lib/config/index.js +37 -0
  50. package/lib/config/mode.d.ts +2 -0
  51. package/lib/config/mode.js +2 -0
  52. package/lib/config/module.d.ts +64 -0
  53. package/lib/config/module.js +121 -0
  54. package/lib/config/output.d.ts +17 -0
  55. package/lib/config/output.js +14 -0
  56. package/lib/config/plugin.d.ts +5 -0
  57. package/lib/config/plugin.js +2 -0
  58. package/lib/config/resolve.d.ts +6 -0
  59. package/lib/config/resolve.js +2 -0
  60. package/lib/config/target.d.ts +5 -0
  61. package/lib/config/target.js +13 -0
  62. package/lib/index.d.ts +39 -0
  63. package/lib/index.js +154 -0
  64. package/lib/server/index.d.ts +0 -0
  65. package/lib/server/index.js +0 -0
  66. package/package.json +49 -0
  67. package/src/bin/index.ts +36 -0
  68. package/src/build.ts +8 -0
  69. package/src/config/builtins.ts +5 -0
  70. package/src/config/context.ts +3 -0
  71. package/src/config/define.ts +3 -0
  72. package/src/config/dev.ts +32 -0
  73. package/src/config/entry.ts +3 -0
  74. package/src/config/external.ts +3 -0
  75. package/src/config/index.ts +80 -0
  76. package/src/config/mode.ts +2 -0
  77. package/src/config/module.ts +240 -0
  78. package/src/config/output.ts +29 -0
  79. package/src/config/plugin.ts +6 -0
  80. package/src/config/resolve.ts +6 -0
  81. package/src/config/target.ts +29 -0
  82. package/src/index.ts +140 -0
  83. package/src/server/index.ts +0 -0
  84. package/tests/config.test.ts +40 -0
  85. package/tsconfig.json +14 -0
package/lib/index.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ export * from "./build";
2
+ import * as binding from "@rspack/binding";
3
+ import * as tapable from "tapable";
4
+ import { RspackOptions, ResolvedRspackOptions, Asset } from "./config";
5
+ import { Source } from "webpack-sources";
6
+ declare class RspackCompilation {
7
+ #private;
8
+ hooks: {
9
+ processAssets: tapable.AsyncSeriesHook<Record<string, Source>>;
10
+ };
11
+ constructor();
12
+ /**
13
+ * unsafe to call out of processAssets
14
+ * @param filename
15
+ * @param asset
16
+ */
17
+ updateAsset(filename: string, asset: Asset): void;
18
+ /**
19
+ * unsafe to call out of processAssets
20
+ * @param filename
21
+ * @param asset
22
+ */
23
+ emitAsset(filename: string, asset: Asset): void;
24
+ processAssets(err: Error, value: string, emitAsset: any): Promise<string>;
25
+ }
26
+ declare class Rspack {
27
+ #private;
28
+ compilation: RspackCompilation;
29
+ hooks: {
30
+ done: tapable.AsyncSeriesHook<void>;
31
+ compilation: tapable.SyncHook<RspackCompilation>;
32
+ };
33
+ options: ResolvedRspackOptions;
34
+ constructor(options: RspackOptions);
35
+ build(): Promise<binding.Stats>;
36
+ rebuild(changeFiles: string[]): Promise<Record<string, string>>;
37
+ }
38
+ export { Rspack };
39
+ export default Rspack;
package/lib/index.js ADDED
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
19
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
20
+ };
21
+ var __importStar = (this && this.__importStar) || function (mod) {
22
+ if (mod && mod.__esModule) return mod;
23
+ var result = {};
24
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
25
+ __setModuleDefault(result, mod);
26
+ return result;
27
+ };
28
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
29
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
30
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
31
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
32
+ };
33
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
34
+ if (kind === "m") throw new TypeError("Private method is not writable");
35
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
36
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
37
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
38
+ };
39
+ var _RspackCompilation_emitAssetCallback, _Rspack_instances, _Rspack_plugins, _Rspack_instance, _Rspack_done, _Rspack_processAssets, _Rspack_newCompilation;
40
+ Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.Rspack = void 0;
42
+ __exportStar(require("./build"), exports);
43
+ const binding = __importStar(require("@rspack/binding"));
44
+ const tapable = __importStar(require("tapable"));
45
+ const config_1 = require("./config");
46
+ const webpack_sources_1 = require("webpack-sources");
47
+ const createDummyResult = (id) => {
48
+ const result = {
49
+ id,
50
+ inner: null
51
+ };
52
+ return JSON.stringify(result);
53
+ };
54
+ class RspackCompilation {
55
+ constructor() {
56
+ _RspackCompilation_emitAssetCallback.set(this, void 0);
57
+ this.hooks = {
58
+ processAssets: new tapable.AsyncSeriesHook([
59
+ "assets"
60
+ ])
61
+ };
62
+ }
63
+ /**
64
+ * unsafe to call out of processAssets
65
+ * @param filename
66
+ * @param asset
67
+ */
68
+ updateAsset(filename, asset) {
69
+ this.emitAsset(filename, asset);
70
+ }
71
+ /**
72
+ * unsafe to call out of processAssets
73
+ * @param filename
74
+ * @param asset
75
+ */
76
+ emitAsset(filename, asset) {
77
+ if (!__classPrivateFieldGet(this, _RspackCompilation_emitAssetCallback, "f")) {
78
+ throw new Error("can't call emitAsset outof processAssets hook for now");
79
+ }
80
+ __classPrivateFieldGet(this, _RspackCompilation_emitAssetCallback, "f").call(this, {
81
+ filename: filename,
82
+ asset
83
+ });
84
+ }
85
+ async processAssets(err, value, emitAsset) {
86
+ var _a;
87
+ __classPrivateFieldSet(this, _RspackCompilation_emitAssetCallback, emitAsset, "f");
88
+ if (err) {
89
+ throw err;
90
+ }
91
+ const context = JSON.parse(value);
92
+ let content = (_a = context.inner) !== null && _a !== void 0 ? _a : {};
93
+ let assets = {};
94
+ for (const [key, value] of Object.entries(content)) {
95
+ // webpack-sources's type definition is wrong, it actually could accept Buffer type
96
+ let source = value.source;
97
+ if (Array.isArray(value.source)) {
98
+ source = Buffer.from(value.source);
99
+ }
100
+ assets[key] = new webpack_sources_1.RawSource(source);
101
+ }
102
+ await this.hooks.processAssets.promise(assets);
103
+ return createDummyResult(context.id);
104
+ }
105
+ }
106
+ _RspackCompilation_emitAssetCallback = new WeakMap();
107
+ class Rspack {
108
+ constructor(options) {
109
+ var _a;
110
+ _Rspack_instances.add(this);
111
+ _Rspack_plugins.set(this, void 0);
112
+ _Rspack_instance.set(this, void 0);
113
+ this.options = (0, config_1.resolveOptions)(options);
114
+ // @ts-ignored
115
+ __classPrivateFieldSet(this, _Rspack_instance, binding.newRspack(this.options, {
116
+ doneCallback: __classPrivateFieldGet(this, _Rspack_instances, "m", _Rspack_done).bind(this),
117
+ processAssetsCallback: __classPrivateFieldGet(this, _Rspack_instances, "m", _Rspack_processAssets).bind(this)
118
+ }), "f");
119
+ this.hooks = {
120
+ done: new tapable.AsyncSeriesHook(),
121
+ compilation: new tapable.SyncHook(["compilation"])
122
+ };
123
+ __classPrivateFieldSet(this, _Rspack_plugins, (_a = options.plugins) !== null && _a !== void 0 ? _a : [], "f");
124
+ for (const plugin of __classPrivateFieldGet(this, _Rspack_plugins, "f")) {
125
+ plugin.apply(this);
126
+ }
127
+ }
128
+ async build() {
129
+ const compilation = __classPrivateFieldGet(this, _Rspack_instances, "m", _Rspack_newCompilation).call(this);
130
+ const stats = await binding.build(__classPrivateFieldGet(this, _Rspack_instance, "f"));
131
+ return stats;
132
+ }
133
+ async rebuild(changeFiles) {
134
+ const stats = await binding.rebuild(__classPrivateFieldGet(this, _Rspack_instance, "f"), changeFiles);
135
+ return stats;
136
+ }
137
+ }
138
+ exports.Rspack = Rspack;
139
+ _Rspack_plugins = new WeakMap(), _Rspack_instance = new WeakMap(), _Rspack_instances = new WeakSet(), _Rspack_done = async function _Rspack_done(err, value) {
140
+ if (err) {
141
+ throw err;
142
+ }
143
+ const context = JSON.parse(value);
144
+ await this.hooks.done.promise();
145
+ return createDummyResult(context.id);
146
+ }, _Rspack_processAssets = async function _Rspack_processAssets(err, value, emitAsset) {
147
+ return this.compilation.processAssets(err, value, emitAsset);
148
+ }, _Rspack_newCompilation = function _Rspack_newCompilation() {
149
+ const compilation = new RspackCompilation();
150
+ this.compilation = compilation;
151
+ this.hooks.compilation.call(compilation);
152
+ return compilation;
153
+ };
154
+ exports.default = Rspack;
File without changes
File without changes
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@rspack/core",
3
+ "version": "0.0.0-20220909025136",
4
+ "bin": {
5
+ "rspack": "./bin.js"
6
+ },
7
+ "main": "./lib/index.js",
8
+ "types": "./lib/index.d.ts",
9
+ "devDependencies": {
10
+ "@types/node": "^18.6.3",
11
+ "tsm": "^2.2.2",
12
+ "ts-node": "10.9.1",
13
+ "typescript": "4.7.3",
14
+ "@types/ws": "8.5.3",
15
+ "@types/connect": "3.4.35",
16
+ "uvu": "0.5.6",
17
+ "@rspack/core": "0.0.0-20220909025136",
18
+ "@types/webpack-sources": "3.2.0"
19
+ },
20
+ "dependencies": {
21
+ "@rspack/binding": "0.0.0-20220909025136",
22
+ "commander": "9.4.0",
23
+ "ws": "8.8.1",
24
+ "connect": "3.7.0",
25
+ "chokidar": "3.5.3",
26
+ "open": "8.4.0",
27
+ "clipanion": "3.2.0-rc.11",
28
+ "@rspack/dev-server": "^0.0.0-20220909025136",
29
+ "sirv": "2.0.2",
30
+ "@rspack/plugin-postcss": "^0.0.0-20220909025136",
31
+ "tapable": "2.2.1",
32
+ "webpack-sources": "3.2.3"
33
+ },
34
+ "optionalDependencies": {
35
+ "@tmp-sass-embedded/darwin-arm64": "1.54.4",
36
+ "@tmp-sass-embedded/darwin-x64": "1.54.4",
37
+ "@tmp-sass-embedded/linux-arm64": "1.54.4",
38
+ "@tmp-sass-embedded/linux-ia32": "1.54.4",
39
+ "@tmp-sass-embedded/linux-x64": "1.54.4",
40
+ "@tmp-sass-embedded/win32-ia32": "1.54.4",
41
+ "@tmp-sass-embedded/win32-x64": "1.54.4"
42
+ },
43
+ "scripts": {
44
+ "build": "rm -rf lib/ && tsc",
45
+ "dev": "tsc -w",
46
+ "example": "node -r ts-node/register ./example/basic.ts",
47
+ "test": "uvu -r tsm tests"
48
+ }
49
+ }
@@ -0,0 +1,36 @@
1
+ import { Command } from "commander";
2
+ import { createServer } from "@rspack/dev-server";
3
+ import { Rspack } from "..";
4
+ import fs from "fs";
5
+ import { build } from "../build";
6
+
7
+ const program = new Command();
8
+
9
+ program
10
+ .option("--env", "env")
11
+ .command("build", {
12
+ isDefault: true
13
+ })
14
+ .description("Rspack build cli")
15
+
16
+ .argument("<config-file>", "rspack config file path")
17
+ .action(async configPath => {
18
+ const config = require(configPath);
19
+ const stats = await build(config);
20
+ console.log(stats);
21
+ });
22
+
23
+ program
24
+ .command("dev")
25
+ .description("Rspack build cli")
26
+ .argument("<config-file>", "rspack config file path")
27
+ .action(async configPath => {
28
+ const config = require(configPath);
29
+ const rspack = new Rspack(config);
30
+ const { options: { dev: { port = 8080 } = {} } = {} } = rspack;
31
+ await rspack.build();
32
+ const server = await createServer(rspack.options);
33
+ server.listen(port, () => console.log(`Server listening on port: ${port}`));
34
+ });
35
+
36
+ program.parse();
package/src/build.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { Rspack } from ".";
2
+ export async function build(config: any) {
3
+ const rspack = new Rspack(config);
4
+ const stats = await rspack.build();
5
+ if (stats.errors.length > 0) {
6
+ throw new Error(stats.errors[0].message);
7
+ }
8
+ }
@@ -0,0 +1,5 @@
1
+ import type { RawBuiltins } from "@rspack/binding";
2
+
3
+ export type Builtins = RawBuiltins;
4
+
5
+ export type ResolvedBuiltins = RawBuiltins | any[];
@@ -0,0 +1,3 @@
1
+ export type Context = string;
2
+
3
+ export type ResolvedContext = string;
@@ -0,0 +1,3 @@
1
+ export type Define = Record<string, string>;
2
+
3
+ export type ResolvedDefine = Record<string, string>;
@@ -0,0 +1,32 @@
1
+ import path from "node:path";
2
+
3
+ export interface Dev {
4
+ port?: number;
5
+ static?: {
6
+ directory?: string;
7
+ };
8
+ }
9
+
10
+ export interface ResolvedDev {
11
+ port: number;
12
+ static: {
13
+ directory: string;
14
+ };
15
+ }
16
+
17
+ interface ResolveDevConfigContext {
18
+ context: string;
19
+ }
20
+
21
+ export function resolveDevOptions(
22
+ devConfig: Dev = {},
23
+ context: ResolveDevConfigContext
24
+ ): ResolvedDev {
25
+ return {
26
+ port: devConfig.port ?? 8080,
27
+ static: {
28
+ directory:
29
+ devConfig.static?.directory ?? path.resolve(context.context, "dist")
30
+ }
31
+ };
32
+ }
@@ -0,0 +1,3 @@
1
+ export type Entry = Record<string, string>;
2
+
3
+ export type ResolvedEntry = Record<string, string>;
@@ -0,0 +1,3 @@
1
+ export type External = Record<string, string>;
2
+
3
+ export type ResolvedExternal = Record<string, string>;
@@ -0,0 +1,80 @@
1
+ import type { Context, ResolvedContext } from "./context";
2
+ import type { Define, ResolvedDefine } from "./define";
3
+ import type { Dev, ResolvedDev } from "./dev";
4
+ import type { Entry, ResolvedEntry } from "./entry";
5
+ import type { External, ResolvedExternal } from "./external";
6
+ import type { Mode, ResolvedMode } from "./mode";
7
+ import type { Module, ResolvedModule } from "./module";
8
+ import type { Plugin } from "./plugin";
9
+ import type { ResolvedTarget, Target } from "./target";
10
+ import type { Output, ResolvedOutput } from "./output";
11
+ import { resolveTargetOptions } from "./target";
12
+ import { resolveOutputOptions } from "./output";
13
+ import { resolveDevOptions } from "./dev";
14
+ import { resolveModuleOptions } from "./module";
15
+ import { Builtins, ResolvedBuiltins } from "./builtins";
16
+ import { Resolve, ResolvedResolve } from "./resolve";
17
+
18
+ export type Asset = {
19
+ source: string;
20
+ };
21
+ export type Assets = Record<string, Asset>;
22
+
23
+ export interface RspackOptions {
24
+ entry?: Entry;
25
+ context?: Context;
26
+ plugins?: Plugin[];
27
+ dev?: Dev;
28
+ module?: Module;
29
+ define?: Define;
30
+ target?: Target;
31
+ mode?: Mode;
32
+ external?: External;
33
+ output?: Output;
34
+ builtins: Builtins;
35
+ resolve: Resolve;
36
+ }
37
+
38
+ export interface ResolvedRspackOptions {
39
+ entry: ResolvedEntry;
40
+ context: ResolvedContext;
41
+ plugins: Plugin[];
42
+ dev: ResolvedDev;
43
+ module: ResolvedModule;
44
+ define: ResolvedDefine;
45
+ target: ResolvedTarget;
46
+ mode: ResolvedMode;
47
+ external: ResolvedExternal;
48
+ output: ResolvedOutput;
49
+ builtins: ResolvedBuiltins;
50
+ resolve: ResolvedResolve;
51
+ }
52
+
53
+ export function resolveOptions(config: RspackOptions): ResolvedRspackOptions {
54
+ const context = config.context ?? process.cwd();
55
+ const mode = config.mode ?? "development";
56
+ const dev = resolveDevOptions(config.dev, { context });
57
+ const entry = config.entry ?? {};
58
+ const output = resolveOutputOptions(config.output);
59
+ const define = config.define ?? {};
60
+ const target = resolveTargetOptions(config.target);
61
+ const external = config.external ?? {};
62
+ const plugins = config.plugins ?? [];
63
+ const builtins = config.builtins ?? [];
64
+ const resolve = config.resolve ?? {};
65
+ const module = resolveModuleOptions(config.module);
66
+ return {
67
+ context,
68
+ mode,
69
+ dev,
70
+ entry,
71
+ output,
72
+ define,
73
+ target,
74
+ external,
75
+ plugins,
76
+ builtins,
77
+ module,
78
+ resolve
79
+ };
80
+ }
@@ -0,0 +1,2 @@
1
+ export type Mode = string;
2
+ export type ResolvedMode = string;
@@ -0,0 +1,240 @@
1
+ import type { RawModuleRuleUse, RawModuleRule } from "@rspack/binding";
2
+ import assert from "node:assert";
3
+
4
+ export interface ModuleRule {
5
+ test?: RawModuleRule["test"];
6
+ resource?: RawModuleRule["resource"];
7
+ resourceQuery?: RawModuleRule["resourceQuery"];
8
+ uses?: ModuleRuleUse[];
9
+ type?: RawModuleRule["type"];
10
+ }
11
+
12
+ export interface Module {
13
+ rules?: ModuleRule[];
14
+ parser?: {
15
+ dataUrlCondition?: {
16
+ maxSize?: number;
17
+ };
18
+ };
19
+ }
20
+
21
+ interface ResolvedModuleRule {
22
+ test?: RawModuleRule["test"];
23
+ resource?: RawModuleRule["resource"];
24
+ resourceQuery?: RawModuleRule["resourceQuery"];
25
+ uses?: RawModuleRuleUse[];
26
+ type?: RawModuleRule["type"];
27
+ }
28
+
29
+ export interface ResolvedModule {
30
+ rules: ResolvedModuleRule[];
31
+ parser?: {
32
+ dataUrlCondition: {
33
+ maxSize: number;
34
+ };
35
+ };
36
+ }
37
+
38
+ interface LoaderContextInternal {
39
+ // TODO: It's not a good way to do this, we should split the `source` into a separate type and avoid using `serde_json`, but it's a temporary solution.
40
+ source: number[];
41
+ resource: String;
42
+ resourcePath: String;
43
+ resourceQuery: String | null;
44
+ resourceFragment: String | null;
45
+ }
46
+
47
+ interface LoaderResult {
48
+ content: Buffer | string;
49
+ meta: Buffer | string;
50
+ }
51
+
52
+ interface LoaderThreadsafeResult {
53
+ id: number;
54
+ p: LoaderResultInternal | null | undefined;
55
+ }
56
+
57
+ interface LoaderResultInternal {
58
+ content: number[];
59
+ meta: number[];
60
+ }
61
+
62
+ interface LoaderContext
63
+ extends Pick<
64
+ LoaderContextInternal,
65
+ "resource" | "resourcePath" | "resourceQuery" | "resourceFragment"
66
+ > {
67
+ source: {
68
+ getCode(): string;
69
+ getBuffer(): Buffer;
70
+ };
71
+ }
72
+
73
+ const toBuffer = (bufLike: string | Buffer): Buffer => {
74
+ if (Buffer.isBuffer(bufLike)) {
75
+ return bufLike;
76
+ } else if (typeof bufLike === "string") {
77
+ return Buffer.from(bufLike);
78
+ }
79
+
80
+ throw new Error("Buffer or string expected");
81
+ };
82
+
83
+ interface LoaderThreadsafeContext {
84
+ id: number;
85
+ p: LoaderContextInternal;
86
+ }
87
+
88
+ function composeJsUse(uses: ModuleRuleUse[]): RawModuleRuleUse | null {
89
+ if (!uses.length) {
90
+ return null;
91
+ }
92
+
93
+ async function loader(err: any, data: Buffer): Promise<Buffer> {
94
+ if (err) {
95
+ throw err;
96
+ }
97
+
98
+ const loaderThreadsafeContext: LoaderThreadsafeContext = JSON.parse(
99
+ data.toString("utf-8")
100
+ );
101
+
102
+ const { p: payload, id } = loaderThreadsafeContext;
103
+
104
+ const loaderContextInternal: LoaderContextInternal = {
105
+ source: payload.source,
106
+ resourcePath: payload.resourcePath,
107
+ resourceQuery: payload.resourceQuery,
108
+ resource: payload.resource,
109
+ resourceFragment: payload.resourceFragment
110
+ };
111
+
112
+ let sourceBuffer = Buffer.from(loaderContextInternal.source);
113
+ let meta = Buffer.from("");
114
+ // Loader is executed from right to left
115
+ for (const use of uses) {
116
+ assert("loader" in use);
117
+ const loaderContext = {
118
+ ...loaderContextInternal,
119
+ source: {
120
+ getCode(): string {
121
+ return sourceBuffer.toString("utf-8");
122
+ },
123
+ getBuffer(): Buffer {
124
+ return sourceBuffer;
125
+ }
126
+ },
127
+ getOptions() {
128
+ return use.options;
129
+ }
130
+ };
131
+
132
+ let loaderResult: LoaderResult;
133
+ if (
134
+ (loaderResult = await Promise.resolve().then(() =>
135
+ use.loader.apply(loaderContext, [loaderContext])
136
+ ))
137
+ ) {
138
+ const content = loaderResult.content;
139
+ meta = meta.length > 0 ? meta : toBuffer(loaderResult.meta);
140
+ sourceBuffer = toBuffer(content);
141
+ }
142
+ }
143
+
144
+ const loaderResultPayload: LoaderResultInternal = {
145
+ content: [...sourceBuffer],
146
+ meta: [...meta]
147
+ };
148
+
149
+ const loaderThreadsafeResult: LoaderThreadsafeResult = {
150
+ id: id,
151
+ p: loaderResultPayload
152
+ };
153
+ return Buffer.from(JSON.stringify(loaderThreadsafeResult), "utf-8");
154
+ }
155
+ loader.displayName = `NodeLoaderAdapter(${uses
156
+ .map(item => {
157
+ assert("loader" in item);
158
+ return item.loader.displayName || item.loader.name || "unknown-loader";
159
+ })
160
+ .join(" -> ")})`;
161
+ return {
162
+ loader
163
+ };
164
+ }
165
+
166
+ interface JsLoader {
167
+ (this: LoaderContext, loaderContext: LoaderContext):
168
+ | Promise<LoaderResult | void>
169
+ | LoaderResult
170
+ | void;
171
+ displayName?: string;
172
+ }
173
+
174
+ type BuiltinLoader = string;
175
+
176
+ type ModuleRuleUse =
177
+ | {
178
+ builtinLoader: BuiltinLoader;
179
+ options?: unknown;
180
+ }
181
+ | {
182
+ loader: JsLoader;
183
+ options?: unknown;
184
+ };
185
+
186
+ export function createRawModuleRuleUses(
187
+ uses: ModuleRuleUse[]
188
+ ): RawModuleRuleUse[] {
189
+ return createRawModuleRuleUsesImpl([...uses].reverse());
190
+ }
191
+
192
+ function createRawModuleRuleUsesImpl(
193
+ uses: ModuleRuleUse[]
194
+ ): RawModuleRuleUse[] {
195
+ if (!uses.length) {
196
+ return [];
197
+ }
198
+
199
+ const index = uses.findIndex(use => "builtinLoader" in use);
200
+ if (index < 0) {
201
+ return [composeJsUse(uses)];
202
+ }
203
+
204
+ const before = uses.slice(0, index);
205
+ const after = uses.slice(index + 1);
206
+ return [
207
+ composeJsUse(before),
208
+ createNativeUse(uses[index]),
209
+ ...createRawModuleRuleUsesImpl(after)
210
+ ].filter((item): item is RawModuleRuleUse => Boolean(item));
211
+ }
212
+
213
+ function createNativeUse(use: ModuleRuleUse): RawModuleRuleUse {
214
+ assert("builtinLoader" in use);
215
+
216
+ if (use.builtinLoader === "sass-loader") {
217
+ (use.options ??= {} as any).__exePath = require.resolve(
218
+ `@tmp-sass-embedded/${process.platform}-${
219
+ process.arch
220
+ }/dart-sass-embedded/dart-sass-embedded${
221
+ process.platform === "win32" ? ".bat" : ""
222
+ }`
223
+ );
224
+ }
225
+
226
+ return {
227
+ builtinLoader: use.builtinLoader,
228
+ options: JSON.stringify(use.options)
229
+ };
230
+ }
231
+
232
+ export function resolveModuleOptions(module: Module = {}): ResolvedModule {
233
+ const rules = (module.rules ?? []).map(rule => ({
234
+ ...rule,
235
+ uses: createRawModuleRuleUses(rule.uses || [])
236
+ }));
237
+ return {
238
+ rules
239
+ };
240
+ }