@markopack/compiler 0.1.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/README.md ADDED
@@ -0,0 +1,31 @@
1
+ # @markopack/compiler
2
+
3
+ Marko compiler plugin and loader for rspack. Used internally by `@markopack/rspack`.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install @markopack/compiler @rspack/core marko
9
+ ```
10
+
11
+ ## What it provides
12
+
13
+ - **`MarkoRspackPlugin`** — Coordinates SSR/browser manifest sync across a MultiCompiler. Handles dynamic entry point injection for server-rendered Marko components.
14
+ - **`marko-loader`** — rspack loader that compiles `.marko` files using `@marko/compiler`. Supports `output: "dom"` (browser) and `output: "html"` (server).
15
+
16
+ ## Usage
17
+
18
+ This package is primarily used by `@markopack/rspack`. You typically don't need to use it directly.
19
+
20
+ ```js
21
+ import MarkoRspackPlugin from "@markopack/compiler";
22
+
23
+ const plugin = new MarkoRspackPlugin({
24
+ entries: { web: webEntry, node: nodeEntry },
25
+ sourceMaps: true,
26
+ });
27
+
28
+ plugin.browserApply(webCompiler);
29
+ plugin.serverApply(nodeCompiler);
30
+ plugin.applyDependencies(multiCompiler, isWatchMode);
31
+ ```
package/dist/index.cjs ADDED
@@ -0,0 +1,375 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/MarkoRspackPlugin.ts
31
+ var MarkoRspackPlugin_exports = {};
32
+ __export(MarkoRspackPlugin_exports, {
33
+ default: () => MarkoRspackPlugin
34
+ });
35
+ module.exports = __toCommonJS(MarkoRspackPlugin_exports);
36
+
37
+ // ../../node_modules/tsup/assets/cjs_shims.js
38
+ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
39
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
40
+
41
+ // src/MarkoRspackPlugin.ts
42
+ var import_node_url = require("url");
43
+ var import_core = require("@rspack/core");
44
+
45
+ // src/helpers/module-name.ts
46
+ var import_node_crypto = require("crypto");
47
+ var import_node_path = __toESM(require("path"), 1);
48
+ var CWD = process.cwd();
49
+ function module_name_default(filename) {
50
+ const lastSepIndex = filename.lastIndexOf(import_node_path.default.sep);
51
+ let name = filename.slice(
52
+ lastSepIndex + 1,
53
+ filename.indexOf(".", lastSepIndex)
54
+ );
55
+ if (name === "index" || name === "template") {
56
+ name = filename.slice(
57
+ filename.lastIndexOf(import_node_path.default.sep, lastSepIndex - 1) + 1,
58
+ lastSepIndex
59
+ );
60
+ }
61
+ return `${name}_${(0, import_node_crypto.createHash)("MD5").update(import_node_path.default.relative(CWD, filename)).digest("base64").replace(/[/+]/g, "-").slice(0, 4)}`;
62
+ }
63
+
64
+ // src/MarkoRspackPlugin.ts
65
+ var MarkoRspackPlugin = class {
66
+ options;
67
+ serverCompiler = null;
68
+ browserCompilers = [];
69
+ clientEntries = {};
70
+ clientAssets = {};
71
+ _api = null;
72
+ entriesReady;
73
+ previousClientAssetsJson = "";
74
+ needsManifestSync = false;
75
+ constructor(options = {}) {
76
+ this.options = { ...options };
77
+ if (this.options.runtimeId) {
78
+ this.options.runtimeId = this.normalizeRuntimeId(this.options.runtimeId);
79
+ }
80
+ this.entriesReady = this.createDeferredPromise();
81
+ }
82
+ browserApply(compiler) {
83
+ this.browserCompilers.push(compiler);
84
+ this.applyBrowser(compiler);
85
+ this.setupRules(compiler);
86
+ compiler.options.entry = this.getEntryPoints(compiler);
87
+ }
88
+ serverApply(compiler) {
89
+ this.serverCompiler = compiler;
90
+ this.applyServer(compiler);
91
+ this.setupRules(compiler);
92
+ compiler.options.entry = this.getEntryPoints(compiler);
93
+ }
94
+ applyDependencies(multiCompiler, isWatch) {
95
+ if (!this.needsManifestSync) {
96
+ return;
97
+ }
98
+ if (isWatch) {
99
+ this.entriesReady = this.createDeferredPromise();
100
+ return;
101
+ }
102
+ if (this.serverCompiler && this.browserCompilers.length && typeof multiCompiler.setDependencies === "function") {
103
+ const serverName = this.serverCompiler.options.name;
104
+ if (serverName) {
105
+ for (const browserCompiler of this.browserCompilers) {
106
+ multiCompiler.setDependencies(browserCompiler, [serverName]);
107
+ }
108
+ }
109
+ }
110
+ }
111
+ get entriesReadyPromise() {
112
+ return this.entriesReady;
113
+ }
114
+ setup(api) {
115
+ this._api = api;
116
+ }
117
+ getEntryPoints(compiler) {
118
+ if (this.options.entries) {
119
+ const targets = Array.isArray(compiler.options.target) ? compiler.options.target : [compiler.options.target];
120
+ const isNode = targets.includes("node");
121
+ return (isNode ? this.options.entries.node : this.options.entries.web) || { index: { import: [] } };
122
+ }
123
+ if (!this._api) {
124
+ throw new Error("Plugin API not initialized \u2014 call setup() first or provide entries");
125
+ }
126
+ const config = this._api.getConfig();
127
+ const environments = config.environments || {};
128
+ const source = config.source || {};
129
+ if (environments.node && environments.web) {
130
+ if (compiler.options.target === "node") {
131
+ return environments.node.source?.entry || { index: { import: [] } };
132
+ }
133
+ return environments.web.source?.entry || { index: { import: [] } };
134
+ }
135
+ if (environments.node) {
136
+ return environments.node.source?.entry || { index: { import: [] } };
137
+ }
138
+ if (environments.web) {
139
+ return environments.web.source?.entry || { index: { import: [] } };
140
+ }
141
+ return source.entry || { index: { import: [] } };
142
+ }
143
+ setupRules(compiler) {
144
+ const target = compiler.options.target;
145
+ const isBrowser = target === "web" || Array.isArray(target) && target.includes("web");
146
+ const loaderPath = (0, import_node_url.fileURLToPath)(
147
+ new URL("../dist/marko-loader.js", importMetaUrl)
148
+ );
149
+ const loaderOptions = {
150
+ ...this.options.compiler ? { compiler: this.options.compiler } : {},
151
+ ...this.options.translator ? { translator: this.options.translator } : {},
152
+ ...this.options.modules ? { modules: this.options.modules } : {},
153
+ output: isBrowser ? "dom" : "html",
154
+ sourceMaps: this.options.sourceMaps ?? false,
155
+ ...this.options.babelConfig ? { babelConfig: this.options.babelConfig } : {}
156
+ };
157
+ compiler.options.module = compiler.options.module || { rules: [] };
158
+ compiler.options.module.rules = compiler.options.module.rules || [];
159
+ compiler.options.module.rules.push(
160
+ {
161
+ test: /\.marko$/,
162
+ type: "javascript/auto",
163
+ use: [
164
+ {
165
+ loader: loaderPath,
166
+ options: loaderOptions
167
+ }
168
+ ]
169
+ },
170
+ {
171
+ test: /\.(jpg|jpeg|gif|png|svg)$/,
172
+ type: "asset"
173
+ }
174
+ );
175
+ }
176
+ applyServer(compiler) {
177
+ compiler.hooks.thisCompilation.tap(
178
+ "MarkoRspackServer",
179
+ (compilation) => {
180
+ this.entriesReady = this.createDeferredPromise();
181
+ if (!this.options.runtimeId && compilation.outputOptions.uniqueName) {
182
+ this.options.runtimeId = this.normalizeRuntimeId(
183
+ compilation.outputOptions.uniqueName
184
+ );
185
+ }
186
+ compilation.hooks.finishModules.tap(
187
+ "MarkoRspackServer:finishModules",
188
+ (modules) => {
189
+ let hasChangedEntries = false;
190
+ const removedEntryIds = new Set(Object.keys(this.clientEntries));
191
+ for (const mod of modules) {
192
+ const resource = mod.resource;
193
+ if (!resource?.endsWith(".marko?server-entry")) {
194
+ continue;
195
+ }
196
+ this.needsManifestSync = true;
197
+ const filename = resource.replace(/\?server-entry$/, "");
198
+ const entryTemplateId = module_name_default(filename);
199
+ if (!removedEntryIds.delete(entryTemplateId)) {
200
+ hasChangedEntries = true;
201
+ this.clientEntries[entryTemplateId] = `${filename}?browser-entry`;
202
+ }
203
+ }
204
+ for (const removedEntryId of removedEntryIds) {
205
+ hasChangedEntries = true;
206
+ delete this.clientEntries[removedEntryId];
207
+ for (const compilerName in this.clientAssets) {
208
+ delete this.clientAssets[compilerName][removedEntryId];
209
+ }
210
+ }
211
+ if (hasChangedEntries) {
212
+ for (const browserCompiler of this.browserCompilers) {
213
+ browserCompiler.watching?.invalidate();
214
+ }
215
+ }
216
+ this.entriesReady.resolve();
217
+ }
218
+ );
219
+ compilation.hooks.processAssets.tapPromise(
220
+ {
221
+ name: "MarkoRspackServer:processAssets",
222
+ stage: -100
223
+ },
224
+ async () => {
225
+ if (!this.needsManifestSync || !Object.keys(this.clientEntries).length) {
226
+ return;
227
+ }
228
+ await Promise.all(
229
+ this.browserCompilers.map(
230
+ (browserCompiler) => browserCompiler.markoAssetsPending
231
+ )
232
+ );
233
+ const clientAssets = this.sortKeys(this.clientAssets);
234
+ let placeholderFound = false;
235
+ for (const chunk of compilation.chunks) {
236
+ if (!chunk.canBeInitial()) {
237
+ continue;
238
+ }
239
+ for (const file of chunk.files) {
240
+ compilation.updateAsset(file, (old) => {
241
+ const placeholder = "MARKO_MANIFEST_PLACEHOLDER";
242
+ const placeholderPosition = old.source().toString().indexOf(placeholder);
243
+ if (placeholderPosition < 0) {
244
+ return old;
245
+ }
246
+ placeholderFound = true;
247
+ const hasMultipleBuilds = this.browserCompilers.length > 1;
248
+ const defaultBuild = this.browserCompilers.length > 0 && this.browserCompilers[0].name ? clientAssets[this.browserCompilers[0].name] || {} : {};
249
+ const content = hasMultipleBuilds ? `{
250
+ getAssets(entry, buildName) {
251
+ const buildAssets = this.builds[buildName];
252
+ if (!buildAssets) {
253
+ throw new Error("Unable to load assets for build with a '$global.buildName' of '" + buildName + "'.");
254
+ }
255
+ return buildAssets[entry] || {};
256
+ },
257
+ builds: ${JSON.stringify(clientAssets)}
258
+ }` : `{
259
+ getAssets(entry) {
260
+ return this.build[entry] || {};
261
+ },
262
+ build: ${JSON.stringify(defaultBuild)}
263
+ }`;
264
+ const newSource = new import_core.sources.ReplaceSource(old);
265
+ newSource.replace(
266
+ placeholderPosition,
267
+ placeholderPosition + placeholder.length - 1,
268
+ content
269
+ );
270
+ return newSource;
271
+ });
272
+ }
273
+ }
274
+ if (Object.keys(this.clientEntries).length > 0 && !placeholderFound) {
275
+ throw new Error(
276
+ "Unable to inject the Marko manifest because the server bundle did not contain MARKO_MANIFEST_PLACEHOLDER."
277
+ );
278
+ }
279
+ }
280
+ );
281
+ }
282
+ );
283
+ }
284
+ applyBrowser(compiler) {
285
+ const compilerName = compiler.options.name || "default";
286
+ const entryOption = compiler.options.entry;
287
+ compiler.options.entry = async () => {
288
+ if (this.needsManifestSync && this.serverCompiler?.watching) {
289
+ await this.entriesReady;
290
+ }
291
+ const normalizedEntries = {};
292
+ for (const key in this.clientEntries) {
293
+ normalizedEntries[key] = {
294
+ import: [this.clientEntries[key]]
295
+ };
296
+ }
297
+ if (typeof entryOption === "function") {
298
+ const currentEntry = await entryOption();
299
+ return { ...currentEntry, ...normalizedEntries };
300
+ }
301
+ if (typeof entryOption === "object" && !Array.isArray(entryOption)) {
302
+ return { ...entryOption, ...normalizedEntries };
303
+ }
304
+ return normalizedEntries;
305
+ };
306
+ compiler.hooks.make.tap(
307
+ "MarkoRspackBrowser",
308
+ (compilation) => {
309
+ const pendingAssets = this.createDeferredPromise();
310
+ compiler.markoAssetsPending = pendingAssets;
311
+ compilation.hooks.afterProcessAssets.tap(
312
+ "MarkoRspackBrowser:afterProcessAssets",
313
+ () => {
314
+ for (const [entryName, entrypoint] of compilation.entrypoints) {
315
+ const assetsByType = {};
316
+ for (const chunk of entrypoint.chunks) {
317
+ for (const file of chunk.files) {
318
+ const asset = compilation.getAsset(file);
319
+ if (!asset) {
320
+ continue;
321
+ }
322
+ const source = asset.source;
323
+ if (source instanceof import_core.sources.RawSource && source.buffer().length === 0) {
324
+ compilation.deleteAsset(file);
325
+ continue;
326
+ }
327
+ const ext = file.split(".").pop() || "";
328
+ const type = assetsByType[ext] || [];
329
+ assetsByType[ext] = type;
330
+ type.push(file);
331
+ }
332
+ }
333
+ const buildAssets = this.clientAssets[compilerName] || {};
334
+ this.clientAssets[compilerName] = buildAssets;
335
+ buildAssets[entryName] = assetsByType;
336
+ }
337
+ if (this.needsManifestSync && this.serverCompiler) {
338
+ const assetsJson = JSON.stringify(this.clientAssets);
339
+ if (assetsJson !== this.previousClientAssetsJson) {
340
+ this.previousClientAssetsJson = assetsJson;
341
+ this.serverCompiler.watching?.invalidate();
342
+ }
343
+ }
344
+ pendingAssets.resolve();
345
+ }
346
+ );
347
+ }
348
+ );
349
+ }
350
+ normalizeRuntimeId(id) {
351
+ return id.replace(/[^a-zA-Z0-9_]/g, "_");
352
+ }
353
+ createDeferredPromise() {
354
+ let resolve;
355
+ const promise = new Promise((r) => {
356
+ resolve = r;
357
+ });
358
+ promise.resolve = resolve;
359
+ return promise;
360
+ }
361
+ sortKeys(obj) {
362
+ if (typeof obj !== "object" || obj === null) {
363
+ return obj;
364
+ }
365
+ if (Array.isArray(obj)) {
366
+ return obj.map((item) => this.sortKeys(item));
367
+ }
368
+ const entries = obj;
369
+ const result = {};
370
+ for (const key of Object.keys(entries).sort()) {
371
+ result[key] = this.sortKeys(entries[key]);
372
+ }
373
+ return result;
374
+ }
375
+ };
@@ -0,0 +1,51 @@
1
+ import { Configuration, Compiler } from '@rspack/core';
2
+
3
+ interface ResolvablePromise<T> extends Promise<T> {
4
+ resolve(value: T): void;
5
+ }
6
+ declare module '@rspack/core' {
7
+ interface Compiler {
8
+ watching?: Compiler['watching'];
9
+ markoAssetsPending?: ResolvablePromise<void>;
10
+ }
11
+ }
12
+ interface MarkoPluginOptions {
13
+ isBrowser?: boolean;
14
+ runtimeId?: string;
15
+ compiler?: string;
16
+ translator?: string;
17
+ modules?: 'esm' | 'cjs';
18
+ sourceMaps?: boolean;
19
+ babelConfig?: Record<string, unknown>;
20
+ /** Direct entry points — bypasses setup() API when provided. */
21
+ entries?: {
22
+ web?: Configuration['entry'];
23
+ node?: Configuration['entry'];
24
+ };
25
+ }
26
+ declare class MarkoRspackPlugin {
27
+ private options;
28
+ private serverCompiler;
29
+ private browserCompilers;
30
+ private clientEntries;
31
+ private clientAssets;
32
+ private _api;
33
+ private entriesReady;
34
+ private previousClientAssetsJson;
35
+ private needsManifestSync;
36
+ constructor(options?: MarkoPluginOptions);
37
+ browserApply(compiler: Compiler): void;
38
+ serverApply(compiler: Compiler): void;
39
+ applyDependencies(multiCompiler: Compiler, isWatch: boolean): void;
40
+ get entriesReadyPromise(): ResolvablePromise<void>;
41
+ setup(api: any): void;
42
+ private getEntryPoints;
43
+ private setupRules;
44
+ private applyServer;
45
+ private applyBrowser;
46
+ private normalizeRuntimeId;
47
+ private createDeferredPromise;
48
+ private sortKeys;
49
+ }
50
+
51
+ export { type MarkoPluginOptions, MarkoRspackPlugin as default };
@@ -0,0 +1,51 @@
1
+ import { Configuration, Compiler } from '@rspack/core';
2
+
3
+ interface ResolvablePromise<T> extends Promise<T> {
4
+ resolve(value: T): void;
5
+ }
6
+ declare module '@rspack/core' {
7
+ interface Compiler {
8
+ watching?: Compiler['watching'];
9
+ markoAssetsPending?: ResolvablePromise<void>;
10
+ }
11
+ }
12
+ interface MarkoPluginOptions {
13
+ isBrowser?: boolean;
14
+ runtimeId?: string;
15
+ compiler?: string;
16
+ translator?: string;
17
+ modules?: 'esm' | 'cjs';
18
+ sourceMaps?: boolean;
19
+ babelConfig?: Record<string, unknown>;
20
+ /** Direct entry points — bypasses setup() API when provided. */
21
+ entries?: {
22
+ web?: Configuration['entry'];
23
+ node?: Configuration['entry'];
24
+ };
25
+ }
26
+ declare class MarkoRspackPlugin {
27
+ private options;
28
+ private serverCompiler;
29
+ private browserCompilers;
30
+ private clientEntries;
31
+ private clientAssets;
32
+ private _api;
33
+ private entriesReady;
34
+ private previousClientAssetsJson;
35
+ private needsManifestSync;
36
+ constructor(options?: MarkoPluginOptions);
37
+ browserApply(compiler: Compiler): void;
38
+ serverApply(compiler: Compiler): void;
39
+ applyDependencies(multiCompiler: Compiler, isWatch: boolean): void;
40
+ get entriesReadyPromise(): ResolvablePromise<void>;
41
+ setup(api: any): void;
42
+ private getEntryPoints;
43
+ private setupRules;
44
+ private applyServer;
45
+ private applyBrowser;
46
+ private normalizeRuntimeId;
47
+ private createDeferredPromise;
48
+ private sortKeys;
49
+ }
50
+
51
+ export { type MarkoPluginOptions, MarkoRspackPlugin as default };
package/dist/index.js ADDED
@@ -0,0 +1,338 @@
1
+ // src/MarkoRspackPlugin.ts
2
+ import { fileURLToPath } from "url";
3
+ import { sources } from "@rspack/core";
4
+
5
+ // src/helpers/module-name.ts
6
+ import { createHash } from "crypto";
7
+ import path from "path";
8
+ var CWD = process.cwd();
9
+ function module_name_default(filename) {
10
+ const lastSepIndex = filename.lastIndexOf(path.sep);
11
+ let name = filename.slice(
12
+ lastSepIndex + 1,
13
+ filename.indexOf(".", lastSepIndex)
14
+ );
15
+ if (name === "index" || name === "template") {
16
+ name = filename.slice(
17
+ filename.lastIndexOf(path.sep, lastSepIndex - 1) + 1,
18
+ lastSepIndex
19
+ );
20
+ }
21
+ return `${name}_${createHash("MD5").update(path.relative(CWD, filename)).digest("base64").replace(/[/+]/g, "-").slice(0, 4)}`;
22
+ }
23
+
24
+ // src/MarkoRspackPlugin.ts
25
+ var MarkoRspackPlugin = class {
26
+ options;
27
+ serverCompiler = null;
28
+ browserCompilers = [];
29
+ clientEntries = {};
30
+ clientAssets = {};
31
+ _api = null;
32
+ entriesReady;
33
+ previousClientAssetsJson = "";
34
+ needsManifestSync = false;
35
+ constructor(options = {}) {
36
+ this.options = { ...options };
37
+ if (this.options.runtimeId) {
38
+ this.options.runtimeId = this.normalizeRuntimeId(this.options.runtimeId);
39
+ }
40
+ this.entriesReady = this.createDeferredPromise();
41
+ }
42
+ browserApply(compiler) {
43
+ this.browserCompilers.push(compiler);
44
+ this.applyBrowser(compiler);
45
+ this.setupRules(compiler);
46
+ compiler.options.entry = this.getEntryPoints(compiler);
47
+ }
48
+ serverApply(compiler) {
49
+ this.serverCompiler = compiler;
50
+ this.applyServer(compiler);
51
+ this.setupRules(compiler);
52
+ compiler.options.entry = this.getEntryPoints(compiler);
53
+ }
54
+ applyDependencies(multiCompiler, isWatch) {
55
+ if (!this.needsManifestSync) {
56
+ return;
57
+ }
58
+ if (isWatch) {
59
+ this.entriesReady = this.createDeferredPromise();
60
+ return;
61
+ }
62
+ if (this.serverCompiler && this.browserCompilers.length && typeof multiCompiler.setDependencies === "function") {
63
+ const serverName = this.serverCompiler.options.name;
64
+ if (serverName) {
65
+ for (const browserCompiler of this.browserCompilers) {
66
+ multiCompiler.setDependencies(browserCompiler, [serverName]);
67
+ }
68
+ }
69
+ }
70
+ }
71
+ get entriesReadyPromise() {
72
+ return this.entriesReady;
73
+ }
74
+ setup(api) {
75
+ this._api = api;
76
+ }
77
+ getEntryPoints(compiler) {
78
+ if (this.options.entries) {
79
+ const targets = Array.isArray(compiler.options.target) ? compiler.options.target : [compiler.options.target];
80
+ const isNode = targets.includes("node");
81
+ return (isNode ? this.options.entries.node : this.options.entries.web) || { index: { import: [] } };
82
+ }
83
+ if (!this._api) {
84
+ throw new Error("Plugin API not initialized \u2014 call setup() first or provide entries");
85
+ }
86
+ const config = this._api.getConfig();
87
+ const environments = config.environments || {};
88
+ const source = config.source || {};
89
+ if (environments.node && environments.web) {
90
+ if (compiler.options.target === "node") {
91
+ return environments.node.source?.entry || { index: { import: [] } };
92
+ }
93
+ return environments.web.source?.entry || { index: { import: [] } };
94
+ }
95
+ if (environments.node) {
96
+ return environments.node.source?.entry || { index: { import: [] } };
97
+ }
98
+ if (environments.web) {
99
+ return environments.web.source?.entry || { index: { import: [] } };
100
+ }
101
+ return source.entry || { index: { import: [] } };
102
+ }
103
+ setupRules(compiler) {
104
+ const target = compiler.options.target;
105
+ const isBrowser = target === "web" || Array.isArray(target) && target.includes("web");
106
+ const loaderPath = fileURLToPath(
107
+ new URL("../dist/marko-loader.js", import.meta.url)
108
+ );
109
+ const loaderOptions = {
110
+ ...this.options.compiler ? { compiler: this.options.compiler } : {},
111
+ ...this.options.translator ? { translator: this.options.translator } : {},
112
+ ...this.options.modules ? { modules: this.options.modules } : {},
113
+ output: isBrowser ? "dom" : "html",
114
+ sourceMaps: this.options.sourceMaps ?? false,
115
+ ...this.options.babelConfig ? { babelConfig: this.options.babelConfig } : {}
116
+ };
117
+ compiler.options.module = compiler.options.module || { rules: [] };
118
+ compiler.options.module.rules = compiler.options.module.rules || [];
119
+ compiler.options.module.rules.push(
120
+ {
121
+ test: /\.marko$/,
122
+ type: "javascript/auto",
123
+ use: [
124
+ {
125
+ loader: loaderPath,
126
+ options: loaderOptions
127
+ }
128
+ ]
129
+ },
130
+ {
131
+ test: /\.(jpg|jpeg|gif|png|svg)$/,
132
+ type: "asset"
133
+ }
134
+ );
135
+ }
136
+ applyServer(compiler) {
137
+ compiler.hooks.thisCompilation.tap(
138
+ "MarkoRspackServer",
139
+ (compilation) => {
140
+ this.entriesReady = this.createDeferredPromise();
141
+ if (!this.options.runtimeId && compilation.outputOptions.uniqueName) {
142
+ this.options.runtimeId = this.normalizeRuntimeId(
143
+ compilation.outputOptions.uniqueName
144
+ );
145
+ }
146
+ compilation.hooks.finishModules.tap(
147
+ "MarkoRspackServer:finishModules",
148
+ (modules) => {
149
+ let hasChangedEntries = false;
150
+ const removedEntryIds = new Set(Object.keys(this.clientEntries));
151
+ for (const mod of modules) {
152
+ const resource = mod.resource;
153
+ if (!resource?.endsWith(".marko?server-entry")) {
154
+ continue;
155
+ }
156
+ this.needsManifestSync = true;
157
+ const filename = resource.replace(/\?server-entry$/, "");
158
+ const entryTemplateId = module_name_default(filename);
159
+ if (!removedEntryIds.delete(entryTemplateId)) {
160
+ hasChangedEntries = true;
161
+ this.clientEntries[entryTemplateId] = `${filename}?browser-entry`;
162
+ }
163
+ }
164
+ for (const removedEntryId of removedEntryIds) {
165
+ hasChangedEntries = true;
166
+ delete this.clientEntries[removedEntryId];
167
+ for (const compilerName in this.clientAssets) {
168
+ delete this.clientAssets[compilerName][removedEntryId];
169
+ }
170
+ }
171
+ if (hasChangedEntries) {
172
+ for (const browserCompiler of this.browserCompilers) {
173
+ browserCompiler.watching?.invalidate();
174
+ }
175
+ }
176
+ this.entriesReady.resolve();
177
+ }
178
+ );
179
+ compilation.hooks.processAssets.tapPromise(
180
+ {
181
+ name: "MarkoRspackServer:processAssets",
182
+ stage: -100
183
+ },
184
+ async () => {
185
+ if (!this.needsManifestSync || !Object.keys(this.clientEntries).length) {
186
+ return;
187
+ }
188
+ await Promise.all(
189
+ this.browserCompilers.map(
190
+ (browserCompiler) => browserCompiler.markoAssetsPending
191
+ )
192
+ );
193
+ const clientAssets = this.sortKeys(this.clientAssets);
194
+ let placeholderFound = false;
195
+ for (const chunk of compilation.chunks) {
196
+ if (!chunk.canBeInitial()) {
197
+ continue;
198
+ }
199
+ for (const file of chunk.files) {
200
+ compilation.updateAsset(file, (old) => {
201
+ const placeholder = "MARKO_MANIFEST_PLACEHOLDER";
202
+ const placeholderPosition = old.source().toString().indexOf(placeholder);
203
+ if (placeholderPosition < 0) {
204
+ return old;
205
+ }
206
+ placeholderFound = true;
207
+ const hasMultipleBuilds = this.browserCompilers.length > 1;
208
+ const defaultBuild = this.browserCompilers.length > 0 && this.browserCompilers[0].name ? clientAssets[this.browserCompilers[0].name] || {} : {};
209
+ const content = hasMultipleBuilds ? `{
210
+ getAssets(entry, buildName) {
211
+ const buildAssets = this.builds[buildName];
212
+ if (!buildAssets) {
213
+ throw new Error("Unable to load assets for build with a '$global.buildName' of '" + buildName + "'.");
214
+ }
215
+ return buildAssets[entry] || {};
216
+ },
217
+ builds: ${JSON.stringify(clientAssets)}
218
+ }` : `{
219
+ getAssets(entry) {
220
+ return this.build[entry] || {};
221
+ },
222
+ build: ${JSON.stringify(defaultBuild)}
223
+ }`;
224
+ const newSource = new sources.ReplaceSource(old);
225
+ newSource.replace(
226
+ placeholderPosition,
227
+ placeholderPosition + placeholder.length - 1,
228
+ content
229
+ );
230
+ return newSource;
231
+ });
232
+ }
233
+ }
234
+ if (Object.keys(this.clientEntries).length > 0 && !placeholderFound) {
235
+ throw new Error(
236
+ "Unable to inject the Marko manifest because the server bundle did not contain MARKO_MANIFEST_PLACEHOLDER."
237
+ );
238
+ }
239
+ }
240
+ );
241
+ }
242
+ );
243
+ }
244
+ applyBrowser(compiler) {
245
+ const compilerName = compiler.options.name || "default";
246
+ const entryOption = compiler.options.entry;
247
+ compiler.options.entry = async () => {
248
+ if (this.needsManifestSync && this.serverCompiler?.watching) {
249
+ await this.entriesReady;
250
+ }
251
+ const normalizedEntries = {};
252
+ for (const key in this.clientEntries) {
253
+ normalizedEntries[key] = {
254
+ import: [this.clientEntries[key]]
255
+ };
256
+ }
257
+ if (typeof entryOption === "function") {
258
+ const currentEntry = await entryOption();
259
+ return { ...currentEntry, ...normalizedEntries };
260
+ }
261
+ if (typeof entryOption === "object" && !Array.isArray(entryOption)) {
262
+ return { ...entryOption, ...normalizedEntries };
263
+ }
264
+ return normalizedEntries;
265
+ };
266
+ compiler.hooks.make.tap(
267
+ "MarkoRspackBrowser",
268
+ (compilation) => {
269
+ const pendingAssets = this.createDeferredPromise();
270
+ compiler.markoAssetsPending = pendingAssets;
271
+ compilation.hooks.afterProcessAssets.tap(
272
+ "MarkoRspackBrowser:afterProcessAssets",
273
+ () => {
274
+ for (const [entryName, entrypoint] of compilation.entrypoints) {
275
+ const assetsByType = {};
276
+ for (const chunk of entrypoint.chunks) {
277
+ for (const file of chunk.files) {
278
+ const asset = compilation.getAsset(file);
279
+ if (!asset) {
280
+ continue;
281
+ }
282
+ const source = asset.source;
283
+ if (source instanceof sources.RawSource && source.buffer().length === 0) {
284
+ compilation.deleteAsset(file);
285
+ continue;
286
+ }
287
+ const ext = file.split(".").pop() || "";
288
+ const type = assetsByType[ext] || [];
289
+ assetsByType[ext] = type;
290
+ type.push(file);
291
+ }
292
+ }
293
+ const buildAssets = this.clientAssets[compilerName] || {};
294
+ this.clientAssets[compilerName] = buildAssets;
295
+ buildAssets[entryName] = assetsByType;
296
+ }
297
+ if (this.needsManifestSync && this.serverCompiler) {
298
+ const assetsJson = JSON.stringify(this.clientAssets);
299
+ if (assetsJson !== this.previousClientAssetsJson) {
300
+ this.previousClientAssetsJson = assetsJson;
301
+ this.serverCompiler.watching?.invalidate();
302
+ }
303
+ }
304
+ pendingAssets.resolve();
305
+ }
306
+ );
307
+ }
308
+ );
309
+ }
310
+ normalizeRuntimeId(id) {
311
+ return id.replace(/[^a-zA-Z0-9_]/g, "_");
312
+ }
313
+ createDeferredPromise() {
314
+ let resolve;
315
+ const promise = new Promise((r) => {
316
+ resolve = r;
317
+ });
318
+ promise.resolve = resolve;
319
+ return promise;
320
+ }
321
+ sortKeys(obj) {
322
+ if (typeof obj !== "object" || obj === null) {
323
+ return obj;
324
+ }
325
+ if (Array.isArray(obj)) {
326
+ return obj.map((item) => this.sortKeys(item));
327
+ }
328
+ const entries = obj;
329
+ const result = {};
330
+ for (const key of Object.keys(entries).sort()) {
331
+ result[key] = this.sortKeys(entries[key]);
332
+ }
333
+ return result;
334
+ }
335
+ };
336
+ export {
337
+ MarkoRspackPlugin as default
338
+ };
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/marko-loader.ts
31
+ var marko_loader_exports = {};
32
+ __export(marko_loader_exports, {
33
+ default: () => markoLoader
34
+ });
35
+ module.exports = __toCommonJS(marko_loader_exports);
36
+ var import_node_fs = __toESM(require("fs"), 1);
37
+ var import_node_path = __toESM(require("path"), 1);
38
+ var import_node_url = require("url");
39
+ var bundledMarkoCompiler = __toESM(require("@marko/compiler"), 1);
40
+ var import_translator = __toESM(require("@marko/runtime-tags/translator"), 1);
41
+ function markoLoader(_source) {
42
+ const callback = this.async();
43
+ const options = this.getOptions() || {};
44
+ const filename = this.resourcePath;
45
+ const outputFormat = options.output || "dom";
46
+ const compilerPath = options.compiler;
47
+ const translator = options.translator || import_translator.default;
48
+ Promise.resolve().then(async () => {
49
+ if (!compilerPath) {
50
+ return bundledMarkoCompiler;
51
+ }
52
+ const compilerDir = import_node_path.default.dirname(compilerPath);
53
+ const traversePatchPath = import_node_path.default.join(compilerDir, "babel-types/traverse/patch.js");
54
+ await import((0, import_node_url.pathToFileURL)(traversePatchPath).href);
55
+ return import((0, import_node_url.pathToFileURL)(compilerPath).href);
56
+ }).then(
57
+ (markoCompiler) => markoCompiler.compileFile(filename, {
58
+ translator,
59
+ modules: options.modules || "esm",
60
+ output: outputFormat,
61
+ ...options.babelConfig ? { babelConfig: options.babelConfig } : {},
62
+ sourceMaps: options.sourceMaps ?? false,
63
+ writeVersionComment: false,
64
+ fileSystem: import_node_fs.default
65
+ })
66
+ ).then((result) => {
67
+ const map = result.map;
68
+ callback(null, result.code, map);
69
+ }).catch((err) => {
70
+ callback(err);
71
+ });
72
+ }
@@ -0,0 +1,14 @@
1
+ import { LoaderContext } from '@rspack/core';
2
+
3
+ interface MarkoLoaderOptions {
4
+ compiler?: string;
5
+ translator?: string;
6
+ modules?: 'esm' | 'cjs';
7
+ output?: 'html' | 'dom' | 'hydrate';
8
+ babelConfig?: Record<string, unknown>;
9
+ virtualFiles?: boolean;
10
+ sourceMaps?: boolean;
11
+ }
12
+ declare function markoLoader(this: LoaderContext<MarkoLoaderOptions>, _source: string): void;
13
+
14
+ export { markoLoader as default };
@@ -0,0 +1,14 @@
1
+ import { LoaderContext } from '@rspack/core';
2
+
3
+ interface MarkoLoaderOptions {
4
+ compiler?: string;
5
+ translator?: string;
6
+ modules?: 'esm' | 'cjs';
7
+ output?: 'html' | 'dom' | 'hydrate';
8
+ babelConfig?: Record<string, unknown>;
9
+ virtualFiles?: boolean;
10
+ sourceMaps?: boolean;
11
+ }
12
+ declare function markoLoader(this: LoaderContext<MarkoLoaderOptions>, _source: string): void;
13
+
14
+ export { markoLoader as default };
@@ -0,0 +1,41 @@
1
+ // src/marko-loader.ts
2
+ import fs from "fs";
3
+ import path from "path";
4
+ import { pathToFileURL } from "url";
5
+ import * as bundledMarkoCompiler from "@marko/compiler";
6
+ import bundledTranslator from "@marko/runtime-tags/translator";
7
+ function markoLoader(_source) {
8
+ const callback = this.async();
9
+ const options = this.getOptions() || {};
10
+ const filename = this.resourcePath;
11
+ const outputFormat = options.output || "dom";
12
+ const compilerPath = options.compiler;
13
+ const translator = options.translator || bundledTranslator;
14
+ Promise.resolve().then(async () => {
15
+ if (!compilerPath) {
16
+ return bundledMarkoCompiler;
17
+ }
18
+ const compilerDir = path.dirname(compilerPath);
19
+ const traversePatchPath = path.join(compilerDir, "babel-types/traverse/patch.js");
20
+ await import(pathToFileURL(traversePatchPath).href);
21
+ return import(pathToFileURL(compilerPath).href);
22
+ }).then(
23
+ (markoCompiler) => markoCompiler.compileFile(filename, {
24
+ translator,
25
+ modules: options.modules || "esm",
26
+ output: outputFormat,
27
+ ...options.babelConfig ? { babelConfig: options.babelConfig } : {},
28
+ sourceMaps: options.sourceMaps ?? false,
29
+ writeVersionComment: false,
30
+ fileSystem: fs
31
+ })
32
+ ).then((result) => {
33
+ const map = result.map;
34
+ callback(null, result.code, map);
35
+ }).catch((err) => {
36
+ callback(err);
37
+ });
38
+ }
39
+ export {
40
+ markoLoader as default
41
+ };
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@markopack/compiler",
3
+ "version": "0.1.0",
4
+ "description": "Marko compiler plugin for rspack (used by @markopack/rspack)",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/Priestch/markopack.git"
11
+ },
12
+ "keywords": ["marko", "rspack", "compiler", "loader"],
13
+ "engines": {
14
+ "node": ">=20.19.0 || >=22.12.0"
15
+ },
16
+ "main": "./dist/index.cjs",
17
+ "module": "./dist/index.js",
18
+ "types": "./dist/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js",
23
+ "require": "./dist/index.cjs",
24
+ "default": "./dist/index.js"
25
+ },
26
+ "./marko-loader": {
27
+ "types": "./dist/marko-loader.d.ts",
28
+ "import": "./dist/marko-loader.js",
29
+ "default": "./dist/marko-loader.js"
30
+ }
31
+ },
32
+ "files": [
33
+ "dist"
34
+ ],
35
+ "scripts": {
36
+ "build": "tsup"
37
+ },
38
+ "dependencies": {
39
+ "@marko/compiler": "^5.39.55",
40
+ "@marko/runtime-tags": "^6.0.145"
41
+ },
42
+ "peerDependencies": {
43
+ "@rspack/core": "^2.0.1",
44
+ "marko": "5 - 6"
45
+ },
46
+ "devDependencies": {
47
+ "@rspack/core": "^2.0.1",
48
+ "@types/node": "^24.0.13",
49
+ "tsup": "^8.3.0",
50
+ "typescript": "^5.9.3"
51
+ }
52
+ }