@moostjs/vite 0.5.20 → 0.5.22

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.cjs CHANGED
@@ -1,329 +1,389 @@
1
- 'use strict';
1
+ "use strict";
2
+ //#region rolldown:runtime
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
2
23
 
3
- var vite = require('vite');
4
- var moost = require('moost');
5
- var node_fs = require('node:fs');
6
- var node_module = require('node:module');
24
+ //#endregion
25
+ const moost = __toESM(require("moost"));
26
+ const node_fs = __toESM(require("node:fs"));
27
+ const node_module = __toESM(require("node:module"));
7
28
 
29
+ //#region packages/vite/src/adapter-detector.ts
8
30
  function createAdapterDetector(adapter, onInit) {
9
- return {
10
- detected: false,
11
- regex: new RegExp(`from\\s+["'](@moostjs\\/event-${adapter})["']`),
12
- constructor: null,
13
- async init() {
14
- this.detected = true;
15
- const module = await import(`@moostjs/event-${adapter}`);
16
- this.constructor = module[`Moost${adapter.charAt(0).toUpperCase() + adapter.slice(1)}`];
17
- if (onInit) {
18
- onInit(this.constructor);
19
- }
20
- },
21
- compare(c) {
22
- if (this.detected && this.constructor) {
23
- return (this.constructor === c ||
24
- c instanceof this.constructor ||
25
- c.prototype instanceof this.constructor);
26
- }
27
- return false;
28
- },
29
- };
31
+ return {
32
+ detected: false,
33
+ regex: new RegExp(`from\\s+["'](@moostjs\\/event-${adapter})["']`),
34
+ constructor: null,
35
+ async init() {
36
+ this.detected = true;
37
+ const module$1 = await import(`@moostjs/event-${adapter}`);
38
+ this.constructor = module$1[`Moost${adapter.charAt(0).toUpperCase() + adapter.slice(1)}`];
39
+ if (onInit) onInit(this.constructor);
40
+ },
41
+ compare(c) {
42
+ if (this.detected && this.constructor) return this.constructor === c || c instanceof this.constructor || c.prototype instanceof this.constructor;
43
+ return false;
44
+ }
45
+ };
30
46
  }
31
47
 
32
- function flattenItem(item) {
33
- return `${item.eventName}||${item.classConstructor.name}||${item.method}`;
48
+ //#endregion
49
+ //#region packages/vite/src/moost-logging.ts
50
+ function _define_property(obj, key, value) {
51
+ if (key in obj) Object.defineProperty(obj, key, {
52
+ value,
53
+ enumerable: true,
54
+ configurable: true,
55
+ writable: true
56
+ });
57
+ else obj[key] = value;
58
+ return obj;
34
59
  }
35
- class LogsStorage {
36
- constructor() {
37
- this.oldMap = new Map();
38
- this.newItems = [];
39
- this.isFirstRun = true;
40
- }
41
- startRecording() {
42
- this.newItems = [];
43
- }
44
- record(item) {
45
- const flat = flattenItem(item);
46
- this.newItems.push(item);
47
- return !this.oldMap.has(flat);
48
- }
49
- endRecording(logRemovedItem) {
50
- const newMap = new Map();
51
- for (const item of this.newItems) {
52
- const flat = flattenItem(item);
53
- newMap.set(flat, item);
54
- }
55
- for (const [flat, item] of this.oldMap.entries()) {
56
- if (!newMap.has(flat)) {
57
- logRemovedItem(item);
58
- }
59
- }
60
- this.oldMap = newMap;
61
- this.newItems = [];
62
- this.isFirstRun = false;
63
- }
60
+ /**
61
+ * Converts a TItem into a flattened string to uniquely identify it.
62
+ * @param {TItem} item - The handler registration item to flatten.
63
+ * @returns {string} A unique string key for the item.
64
+ */ function flattenItem(item) {
65
+ return `${item.eventName}||${item.classConstructor.name}||${item.method}`;
64
66
  }
65
- let logsStorage;
67
+ /**
68
+ * A storage mechanism to track old and new handler registrations
69
+ * across multiple initialization cycles. During each init:
70
+ * 1. Start recording newly encountered handlers.
71
+ * 2. Compare them against previously recorded handlers to detect
72
+ * which are newly added vs. removed.
73
+ * 3. Store the new state as the old map for the next cycle.
74
+ */ let LogsStorage = class LogsStorage$1 {
75
+ /**
76
+ * Called at the start of an init cycle to
77
+ * clear out the list of new items.
78
+ */ startRecording() {
79
+ this.newItems = [];
80
+ }
81
+ /**
82
+ * Records a newly encountered handler (via logMappedHandler).
83
+ *
84
+ * @param {TItem} item - The handler registration item to record.
85
+ * @returns {boolean} True if this item is newly added (not in oldMap),
86
+ * false if it existed already.
87
+ */ record(item) {
88
+ const flat = flattenItem(item);
89
+ this.newItems.push(item);
90
+ return !this.oldMap.has(flat);
91
+ }
92
+ /**
93
+ * Called at the end of an init cycle.
94
+ * 1. Builds a newMap of all newly encountered handlers.
95
+ * 2. Logs/strokes out any handlers that have disappeared compared
96
+ * to the previous cycle.
97
+ * 3. Updates oldMap so it becomes the baseline for the next cycle.
98
+ *
99
+ * @param {(item: TItem) => void} logRemovedItem - A callback that logs
100
+ * removed items (presumably by striking them out).
101
+ */ endRecording(logRemovedItem) {
102
+ const newMap = new Map();
103
+ for (const item of this.newItems) {
104
+ const flat = flattenItem(item);
105
+ newMap.set(flat, item);
106
+ }
107
+ for (const [flat, item] of this.oldMap.entries()) if (!newMap.has(flat)) logRemovedItem(item);
108
+ this.oldMap = newMap;
109
+ this.newItems = [];
110
+ this.isFirstRun = false;
111
+ }
112
+ constructor() {
113
+ /**
114
+ * A map of flattenItem() => TItem
115
+ * representing the previous cycle's known handlers.
116
+ */ _define_property(this, "oldMap", new Map());
117
+ /**
118
+ * The handlers discovered in the current cycle,
119
+ * awaiting finalization.
120
+ */ _define_property(this, "newItems", []);
121
+ _define_property(this, "isFirstRun", true);
122
+ }
123
+ };
124
+ /**
125
+ * A reference to a shared LogsStorage instance that persists
126
+ * across init cycles in dev mode.
127
+ */ let logsStorage;
66
128
  function patchMoostHandlerLogging() {
67
- const origInit = moost.Moost.prototype.init;
68
- moost.Moost.prototype.init = async function init() {
69
- if (!logsStorage) {
70
- logsStorage = new LogsStorage();
71
- }
72
- logsStorage.startRecording();
73
- await origInit.call(this);
74
- logsStorage.endRecording((item) => {
75
- origLogMappedHandler.call(this, item.eventName, item.classConstructor, item.method, true, '❌ ');
76
- });
77
- };
78
- const origLogMappedHandler = moost.Moost.prototype.logMappedHandler;
79
- moost.Moost.prototype.logMappedHandler = function logMappedHandler(eventName, classConstructor, method) {
80
- if (logsStorage.record({ eventName, classConstructor, method })) {
81
- origLogMappedHandler.call(this, eventName, classConstructor, method, false, logsStorage.isFirstRun ? '' : '✅ ');
82
- }
83
- };
129
+ const origInit = moost.Moost.prototype.init;
130
+ /**
131
+ * Monkey-patch Moost.init:
132
+ * 1. Start a new recording cycle in LogsStorage.
133
+ * 2. Call the real .init().
134
+ * 3. End the recording, logging any removed handlers.
135
+ */ moost.Moost.prototype.init = async function init() {
136
+ if (!logsStorage) logsStorage = new LogsStorage();
137
+ logsStorage.startRecording();
138
+ await origInit.call(this);
139
+ logsStorage.endRecording((item) => {
140
+ origLogMappedHandler.call(this, item.eventName, item.classConstructor, item.method, true, "❌ ");
141
+ });
142
+ };
143
+ const origLogMappedHandler = moost.Moost.prototype.logMappedHandler;
144
+ /**
145
+ * Monkey-patch Moost.logMappedHandler:
146
+ * If we haven’t seen this particular route+class+method combination
147
+ * in a previous cycle, call the original logger. Otherwise, skip it
148
+ * to avoid duplicate logs.
149
+ */ moost.Moost.prototype.logMappedHandler = function logMappedHandler(eventName, classConstructor, method) {
150
+ if (logsStorage.record({
151
+ eventName,
152
+ classConstructor,
153
+ method
154
+ })) origLogMappedHandler.call(this, eventName, classConstructor, method, false, logsStorage.isFirstRun ? "" : "✅ ");
155
+ };
84
156
  }
85
157
 
86
- const PLUGIN_NAME = 'moost-vite-dev';
158
+ //#endregion
159
+ //#region packages/vite/src/utils.ts
160
+ const PLUGIN_NAME = "moost-vite";
87
161
  function gatherAllImporters(moduleNode, visited = new Set()) {
88
- if (!moduleNode) {
89
- return visited;
90
- }
91
- if (visited.has(moduleNode)) {
92
- return visited;
93
- }
94
- visited.add(moduleNode);
95
- if (moduleNode.importers) {
96
- for (const importer of moduleNode.importers) {
97
- gatherAllImporters(importer, visited);
98
- }
99
- }
100
- return visited;
162
+ if (!moduleNode) return visited;
163
+ if (visited.has(moduleNode)) return visited;
164
+ visited.add(moduleNode);
165
+ if (moduleNode.importers) for (const importer of moduleNode.importers) gatherAllImporters(importer, visited);
166
+ return visited;
101
167
  }
102
- const logger = new moost.EventLogger('', { level: 99 }).createTopic('' + '' + PLUGIN_NAME);
168
+ const logger = new moost.EventLogger("", { level: 99 }).createTopic("\x1B[2m\x1B[36m" + PLUGIN_NAME);
103
169
  function getLogger() {
104
- return logger;
170
+ return logger;
105
171
  }
106
- function getExternals() {
107
- const pkg = JSON.parse(node_fs.readFileSync('package.json', 'utf8').toString());
108
- return [
109
- ...node_module.builtinModules,
110
- ...node_module.builtinModules.map(m => `node:${m}`),
111
- ...Object.keys(pkg.dependencies || {}),
112
- ];
172
+ function getExternals({ node, workspace }) {
173
+ const pkg = JSON.parse((0, node_fs.readFileSync)("package.json", "utf8").toString());
174
+ const externals = workspace ? Object.keys(pkg.dependencies || {}) : Object.entries(pkg.dependencies || {}).filter(([key, ver]) => !ver.startsWith("workspace:")).map((i) => i[0]);
175
+ if (node) externals.push(...node_module.builtinModules, ...node_module.builtinModules.map((m) => `node:${m}`));
176
+ return externals;
113
177
  }
114
178
 
179
+ //#endregion
180
+ //#region packages/vite/src/restart-cleanup.ts
115
181
  function moostRestartCleanup(adapters, onEject, cleanupInstances) {
116
- const logger = getLogger();
117
- const infact = moost.getMoostInfact();
118
- const { registry, scopes } = infact;
119
- const registries = [registry, ...Object.values(scopes)];
120
- infact._cleanup();
121
- const mate = moost.getMoostMate();
122
- if (cleanupInstances) {
123
- for (const reg of registries) {
124
- for (const key of Object.getOwnPropertySymbols(reg)) {
125
- const instance = reg[key];
126
- const viteId = mate.read(instance)?.__vite_id;
127
- if (viteId && cleanupInstances.has(viteId)) {
128
- logger.debug(`🔃 Replacing "${constructorName(instance)}"`);
129
- delete reg[key];
130
- }
131
- }
132
- for (const key of Object.getOwnPropertySymbols(reg)) {
133
- const instance = reg[key];
134
- scanParams(instance, (type) => {
135
- if ((type === moost.Moost || type instanceof moost.Moost || type.prototype instanceof moost.Moost) &&
136
- (!onEject || onEject(instance, type))) {
137
- delete reg[key];
138
- logger.debug(`✖️ Ejecting "${constructorName(instance)}" (depends on re-instantiated "Moost")`);
139
- return true;
140
- }
141
- for (const adapter of adapters) {
142
- if (adapter.compare(type) && (!onEject || onEject(instance, type))) {
143
- delete reg[key];
144
- logger.debug(`✖️ Ejecting "${constructorName(instance)}" (depends on re-instantiated "${adapter.constructor.name}")`);
145
- return true;
146
- }
147
- }
148
- });
149
- }
150
- clearDependantRegistry(reg, onEject);
151
- }
152
- infact.registry = registry;
153
- infact.scopes = scopes;
154
- }
155
- moost.getMoostMate()._cleanup();
156
- moost.clearGlobalWooks();
182
+ const logger$1 = getLogger();
183
+ const infact = (0, moost.getMoostInfact)();
184
+ const { registry, scopes } = infact;
185
+ const registries = [registry, ...Object.values(scopes)];
186
+ infact._cleanup();
187
+ const mate = (0, moost.getMoostMate)();
188
+ if (cleanupInstances) {
189
+ for (const reg of registries) {
190
+ for (const key of Object.getOwnPropertySymbols(reg)) {
191
+ const instance = reg[key];
192
+ const viteId = mate.read(instance)?.__vite_id;
193
+ if (viteId && cleanupInstances.has(viteId)) {
194
+ logger$1.debug(`🔃 Replacing "${constructorName(instance)}"`);
195
+ delete reg[key];
196
+ }
197
+ }
198
+ for (const key of Object.getOwnPropertySymbols(reg)) {
199
+ const instance = reg[key];
200
+ scanParams(instance, (type) => {
201
+ if ((type === moost.Moost || type instanceof moost.Moost || type.prototype instanceof moost.Moost) && (!onEject || onEject(instance, type))) {
202
+ delete reg[key];
203
+ logger$1.debug(`✖️ Ejecting "${constructorName(instance)}" (depends on re-instantiated "Moost")`);
204
+ return true;
205
+ }
206
+ for (const adapter of adapters) if (adapter.compare(type) && (!onEject || onEject(instance, type))) {
207
+ delete reg[key];
208
+ logger$1.debug(`✖️ Ejecting "${constructorName(instance)}" (depends on re-instantiated "${adapter.constructor.name}")`);
209
+ return true;
210
+ }
211
+ });
212
+ }
213
+ clearDependantRegistry(reg, onEject);
214
+ }
215
+ infact.registry = registry;
216
+ infact.scopes = scopes;
217
+ }
218
+ (0, moost.getMoostMate)()._cleanup();
219
+ (0, moost.clearGlobalWooks)();
157
220
  }
158
221
  function clearDependantRegistry(registry, onEject) {
159
- const logger = getLogger();
160
- const objSet = new Set();
161
- let somethingIsDeleted = true;
162
- while (somethingIsDeleted) {
163
- somethingIsDeleted = false;
164
- for (const key of Object.getOwnPropertySymbols(registry)) {
165
- const instance = registry[key];
166
- objSet.add(Object.getPrototypeOf(instance).constructor);
167
- }
168
- for (const key of Object.getOwnPropertySymbols(registry)) {
169
- const instance = registry[key];
170
- scanParams(instance, (type) => {
171
- if (!objSet.has(type) && (!onEject || onEject(instance, type))) {
172
- delete registry[key];
173
- logger.debug(`✖️ Ejecting "${constructorName(instance)}" (depends on "${type.name}" which is not in registry)`);
174
- somethingIsDeleted = true;
175
- return true;
176
- }
177
- });
178
- }
179
- }
222
+ const logger$1 = getLogger();
223
+ const objSet = new Set();
224
+ let somethingIsDeleted = true;
225
+ while (somethingIsDeleted) {
226
+ somethingIsDeleted = false;
227
+ for (const key of Object.getOwnPropertySymbols(registry)) {
228
+ const instance = registry[key];
229
+ objSet.add(Object.getPrototypeOf(instance).constructor);
230
+ }
231
+ for (const key of Object.getOwnPropertySymbols(registry)) {
232
+ const instance = registry[key];
233
+ scanParams(instance, (type) => {
234
+ if (!objSet.has(type) && (!onEject || onEject(instance, type))) {
235
+ delete registry[key];
236
+ logger$1.debug(`✖️ Ejecting "${constructorName(instance)}" (depends on "${type.name}" which is not in registry)`);
237
+ somethingIsDeleted = true;
238
+ return true;
239
+ }
240
+ });
241
+ }
242
+ }
180
243
  }
181
244
  function scanParams(instance, cb) {
182
- const mate = moost.getMoostMate();
183
- const params = mate.read(instance)?.params;
184
- if (params?.length) {
185
- for (const param of params) {
186
- if (param.type === undefined ||
187
- [Array, String, Number, Boolean, Object].includes(param.type)) {
188
- continue;
189
- }
190
- if (cb(param.type)) {
191
- break;
192
- }
193
- }
194
- }
245
+ const mate = (0, moost.getMoostMate)();
246
+ const params = mate.read(instance)?.params;
247
+ if (params?.length) for (const param of params) {
248
+ if (param.type === undefined || [
249
+ Array,
250
+ String,
251
+ Number,
252
+ Boolean,
253
+ Object
254
+ ].includes(param.type)) continue;
255
+ if (cb(param.type)) break;
256
+ }
195
257
  }
196
258
  function constructorName(i) {
197
- return Object.getPrototypeOf(i).constructor.name;
259
+ return Object.getPrototypeOf(i).constructor.name;
198
260
  }
199
261
 
200
- const REG_HAS_EXPORT_CLASS = /(^\s*@(Injectable|Controller)\()/m;
262
+ //#endregion
263
+ //#region packages/vite/src/moost-vite.ts
264
+ /** Regex checks */ const REG_HAS_EXPORT_CLASS = /(^\s*@(Injectable|Controller)\()/m;
201
265
  const REG_REPLACE_EXPORT_CLASS = /(^\s*@(Injectable|Controller)\()/gm;
202
266
  function moostVite(options) {
203
- let moostMiddleware = null;
204
- const adapters = [
205
- createAdapterDetector('http', MoostHttp => {
206
- MoostHttp.prototype.listen = function (...args) {
207
- moostMiddleware = this.getServerCb();
208
- setTimeout(() => {
209
- args.filter(a => typeof a === 'function').forEach(a => a());
210
- }, 1);
211
- return Promise.resolve();
212
- };
213
- }),
214
- createAdapterDetector('cli'),
215
- createAdapterDetector('wf'),
216
- ];
217
- const logger = getLogger();
218
- let reloadRequired = false;
219
- patchMoostHandlerLogging();
220
- return {
221
- name: PLUGIN_NAME,
222
- apply: 'serve',
223
- enforce: 'pre',
224
- config(cfg) {
225
- const entry = cfg.build?.rollupOptions?.input || options.entry;
226
- const outfile = typeof entry === 'string' ? entry.split('/').pop().replace(/\.ts$/, '.js') : undefined;
227
- const pluginConfig = {
228
- server: {
229
- port: cfg.server?.port || options.port || 3000,
230
- host: cfg.server?.host || options.host,
231
- },
232
- optimizeDeps: {
233
- noDiscovery: cfg.optimizeDeps?.noDiscovery === undefined ? true : cfg.optimizeDeps.noDiscovery,
234
- exclude: cfg.optimizeDeps?.exclude || ['@swc/core'],
235
- },
236
- build: {
237
- target: cfg.build?.target || 'node',
238
- outDir: cfg.build?.outDir || options.outDir || 'dist',
239
- ssr: cfg.build?.ssr ?? true,
240
- minify: cfg.build?.minify || false,
241
- rollupOptions: {
242
- external: cfg.build?.rollupOptions?.external || getExternals(),
243
- input: entry,
244
- output: {
245
- format: options.format,
246
- sourcemap: !!(options.sourcemap ?? true),
247
- entryFileNames: outfile,
248
- ...cfg.build?.rollupOptions?.output,
249
- },
250
- },
251
- },
252
- };
253
- return vite.mergeConfig(cfg, pluginConfig);
254
- },
255
- async transform(code, id) {
256
- if (!id.endsWith('.ts')) {
257
- return code;
258
- }
259
- for (const adapter of adapters) {
260
- if (!adapter.detected && adapter.regex.test(code)) {
261
- await adapter.init();
262
- }
263
- }
264
- if (REG_HAS_EXPORT_CLASS.test(code)) {
265
- code = code.replace(REG_REPLACE_EXPORT_CLASS, '\n@__VITE_ID(import.meta.filename)\n$1');
266
- code = `import { __VITE_ID } from 'virtual:vite-id'\n\n${code}`;
267
- }
268
- return code;
269
- },
270
- resolveId(id) {
271
- if (id === 'virtual:vite-id') {
272
- return '\0virtual:vite-id';
273
- }
274
- },
275
- load(id) {
276
- if (id === '\0virtual:vite-id') {
277
- return `
267
+ const isTest = process.env.NODE_ENV === "test";
268
+ const isProd = process.env.NODE_ENV === "production";
269
+ let moostMiddleware = null;
270
+ const adapters = isTest ? [] : [
271
+ createAdapterDetector("http", (MoostHttp) => {
272
+ MoostHttp.prototype.listen = function(...args) {
273
+ moostMiddleware = this.getServerCb();
274
+ setTimeout(() => {
275
+ args.filter((a) => typeof a === "function").forEach((a) => a());
276
+ }, 1);
277
+ return Promise.resolve();
278
+ };
279
+ }),
280
+ createAdapterDetector("cli"),
281
+ createAdapterDetector("wf")
282
+ ];
283
+ /** A logger instance for plugin debug output. */ const logger$1 = isTest ? console : getLogger();
284
+ let reloadRequired = false;
285
+ patchMoostHandlerLogging();
286
+ const pluginConfig = {
287
+ name: PLUGIN_NAME,
288
+ enforce: "pre",
289
+ config(cfg) {
290
+ const entry = cfg.build?.rollupOptions?.input || options.entry;
291
+ const outfile = typeof entry === "string" ? entry.split("/").pop().replace(/\.ts$/, ".js") : undefined;
292
+ return {
293
+ server: {
294
+ port: cfg.server?.port || options.port || 3e3,
295
+ host: cfg.server?.host || options.host
296
+ },
297
+ optimizeDeps: {
298
+ noDiscovery: cfg.optimizeDeps?.noDiscovery === undefined ? true : cfg.optimizeDeps.noDiscovery,
299
+ exclude: cfg.optimizeDeps?.exclude || ["@swc/core"]
300
+ },
301
+ build: {
302
+ target: cfg.build?.target || "node",
303
+ outDir: cfg.build?.outDir || options.outDir || "dist",
304
+ ssr: cfg.build?.ssr ?? true,
305
+ minify: cfg.build?.minify || false,
306
+ rollupOptions: {
307
+ external: isTest ? cfg.build?.rollupOptions?.external : cfg.build?.rollupOptions?.external || (options.externals === false ? [] : getExternals({
308
+ node: Boolean(options.externals === true || options.externals?.node),
309
+ workspace: Boolean(options.externals === true || options.externals?.workspace)
310
+ })),
311
+ input: entry,
312
+ output: {
313
+ format: options.format,
314
+ sourcemap: !!(options.sourcemap ?? true),
315
+ entryFileNames: outfile,
316
+ ...cfg.build?.rollupOptions?.output
317
+ }
318
+ }
319
+ }
320
+ };
321
+ },
322
+ async transform(code, id) {
323
+ if (!id.endsWith(".ts")) return code;
324
+ for (const adapter of adapters) if (!adapter.detected && adapter.regex.test(code)) await adapter.init();
325
+ if (REG_HAS_EXPORT_CLASS.test(code)) {
326
+ code = code.replace(REG_REPLACE_EXPORT_CLASS, "\n@__VITE_ID(import.meta.filename)\n$1");
327
+ code = `import { __VITE_ID } from 'virtual:vite-id'\n\n${code}`;
328
+ }
329
+ return code;
330
+ },
331
+ resolveId(id) {
332
+ if (id === "virtual:vite-id") return "\0virtual:vite-id";
333
+ },
334
+ load(id) {
335
+ if (id === "\0virtual:vite-id") return `
278
336
  import { getMoostMate } from "moost";
279
337
  const mate = getMoostMate();
280
338
  export function __VITE_ID(id) {
281
339
  return mate.decorate("__vite_id", id)
282
340
  }
283
341
  `;
284
- }
285
- },
286
- async configureServer(server) {
287
- moostRestartCleanup(adapters, options.onEject);
288
- await server.ssrLoadModule(options.entry);
289
- server.middlewares.use(async (req, res, next) => {
290
- if (reloadRequired) {
291
- reloadRequired = false;
292
- console.log();
293
- logger.debug('🚀 Reloading Moost App...');
294
- console.log();
295
- await server.ssrLoadModule(options.entry);
296
- await new Promise(resolve => setTimeout(resolve, 1));
297
- }
298
- if (moostMiddleware) {
299
- return moostMiddleware(req, res);
300
- }
301
- next();
302
- });
303
- },
304
- hotUpdate({ file }) {
305
- if (file.endsWith('.ts')) {
306
- const modules = this.environment.moduleGraph.getModulesByFile(file);
307
- if (modules) {
308
- logger.debug(`🔃 Hot update: ${file}`);
309
- const cleanupInstances = new Set();
310
- for (const mod of modules) {
311
- const allImporters = gatherAllImporters(mod);
312
- for (const impModule of allImporters) {
313
- if (impModule.id) {
314
- cleanupInstances.add(impModule.id);
315
- }
316
- }
317
- this.environment.moduleGraph.invalidateModule(mod);
318
- }
319
- moostMiddleware = null;
320
- moostRestartCleanup(adapters, options.onEject, cleanupInstances);
321
- reloadRequired = true;
322
- }
323
- return [];
324
- }
325
- },
326
- };
342
+ },
343
+ async configureServer(server) {
344
+ moostRestartCleanup(adapters, options.onEject);
345
+ await server.ssrLoadModule(options.entry);
346
+ server.middlewares.use(async (req, res, next) => {
347
+ if (reloadRequired) {
348
+ reloadRequired = false;
349
+ console.log();
350
+ logger$1.debug("🚀 Reloading Moost App...");
351
+ console.log();
352
+ await server.ssrLoadModule(options.entry);
353
+ await new Promise((resolve) => setTimeout(resolve, 1));
354
+ }
355
+ if (moostMiddleware) return moostMiddleware(req, res);
356
+ next();
357
+ });
358
+ },
359
+ hotUpdate({ file }) {
360
+ if (file.endsWith(".ts")) {
361
+ const modules = this.environment.moduleGraph.getModulesByFile(file);
362
+ if (modules) {
363
+ logger$1.debug(`🔃 Hot update: ${file}`);
364
+ const cleanupInstances = new Set();
365
+ for (const mod of modules) {
366
+ const allImporters = gatherAllImporters(mod);
367
+ for (const impModule of allImporters) if (impModule.id) cleanupInstances.add(impModule.id);
368
+ this.environment.moduleGraph.invalidateModule(mod);
369
+ }
370
+ moostMiddleware = null;
371
+ moostRestartCleanup(adapters, options.onEject, cleanupInstances);
372
+ reloadRequired = true;
373
+ }
374
+ return [];
375
+ }
376
+ }
377
+ };
378
+ if (isProd || isTest) {
379
+ delete pluginConfig.configureServer;
380
+ delete pluginConfig.resolveId;
381
+ delete pluginConfig.load;
382
+ delete pluginConfig.transform;
383
+ delete pluginConfig.hotUpdate;
384
+ }
385
+ return pluginConfig;
327
386
  }
328
387
 
329
- exports.moostVite = moostVite;
388
+ //#endregion
389
+ exports.moostVite = moostVite