@moostjs/vite 0.5.21 → 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,352 +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';
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
172
  function getExternals({ node, workspace }) {
107
- const pkg = JSON.parse(node_fs.readFileSync('package.json', 'utf8').toString());
108
- const externals = workspace
109
- ? Object.keys(pkg.dependencies || {})
110
- : Object.entries(pkg.dependencies || {})
111
- .filter(([key, ver]) => !ver.startsWith('workspace:'))
112
- .map(i => i[0]);
113
- if (node) {
114
- externals.push(...node_module.builtinModules, ...node_module.builtinModules.map(m => `node:${m}`));
115
- }
116
- return externals;
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;
117
177
  }
118
178
 
179
+ //#endregion
180
+ //#region packages/vite/src/restart-cleanup.ts
119
181
  function moostRestartCleanup(adapters, onEject, cleanupInstances) {
120
- const logger = getLogger();
121
- const infact = moost.getMoostInfact();
122
- const { registry, scopes } = infact;
123
- const registries = [registry, ...Object.values(scopes)];
124
- infact._cleanup();
125
- const mate = moost.getMoostMate();
126
- if (cleanupInstances) {
127
- for (const reg of registries) {
128
- for (const key of Object.getOwnPropertySymbols(reg)) {
129
- const instance = reg[key];
130
- const viteId = mate.read(instance)?.__vite_id;
131
- if (viteId && cleanupInstances.has(viteId)) {
132
- logger.debug(`🔃 Replacing "${constructorName(instance)}"`);
133
- delete reg[key];
134
- }
135
- }
136
- for (const key of Object.getOwnPropertySymbols(reg)) {
137
- const instance = reg[key];
138
- scanParams(instance, (type) => {
139
- if ((type === moost.Moost || type instanceof moost.Moost || type.prototype instanceof moost.Moost) &&
140
- (!onEject || onEject(instance, type))) {
141
- delete reg[key];
142
- logger.debug(`✖️ Ejecting "${constructorName(instance)}" (depends on re-instantiated "Moost")`);
143
- return true;
144
- }
145
- for (const adapter of adapters) {
146
- if (adapter.compare(type) && (!onEject || onEject(instance, type))) {
147
- delete reg[key];
148
- logger.debug(`✖️ Ejecting "${constructorName(instance)}" (depends on re-instantiated "${adapter.constructor.name}")`);
149
- return true;
150
- }
151
- }
152
- });
153
- }
154
- clearDependantRegistry(reg, onEject);
155
- }
156
- infact.registry = registry;
157
- infact.scopes = scopes;
158
- }
159
- moost.getMoostMate()._cleanup();
160
- 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)();
161
220
  }
162
221
  function clearDependantRegistry(registry, onEject) {
163
- const logger = getLogger();
164
- const objSet = new Set();
165
- let somethingIsDeleted = true;
166
- while (somethingIsDeleted) {
167
- somethingIsDeleted = false;
168
- for (const key of Object.getOwnPropertySymbols(registry)) {
169
- const instance = registry[key];
170
- objSet.add(Object.getPrototypeOf(instance).constructor);
171
- }
172
- for (const key of Object.getOwnPropertySymbols(registry)) {
173
- const instance = registry[key];
174
- scanParams(instance, (type) => {
175
- if (!objSet.has(type) && (!onEject || onEject(instance, type))) {
176
- delete registry[key];
177
- logger.debug(`✖️ Ejecting "${constructorName(instance)}" (depends on "${type.name}" which is not in registry)`);
178
- somethingIsDeleted = true;
179
- return true;
180
- }
181
- });
182
- }
183
- }
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
+ }
184
243
  }
185
244
  function scanParams(instance, cb) {
186
- const mate = moost.getMoostMate();
187
- const params = mate.read(instance)?.params;
188
- if (params?.length) {
189
- for (const param of params) {
190
- if (param.type === undefined ||
191
- [Array, String, Number, Boolean, Object].includes(param.type)) {
192
- continue;
193
- }
194
- if (cb(param.type)) {
195
- break;
196
- }
197
- }
198
- }
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
+ }
199
257
  }
200
258
  function constructorName(i) {
201
- return Object.getPrototypeOf(i).constructor.name;
259
+ return Object.getPrototypeOf(i).constructor.name;
202
260
  }
203
261
 
204
- 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;
205
265
  const REG_REPLACE_EXPORT_CLASS = /(^\s*@(Injectable|Controller)\()/gm;
206
266
  function moostVite(options) {
207
- const isTest = process.env.NODE_ENV === 'test';
208
- const isProd = process.env.NODE_ENV === 'production';
209
- let moostMiddleware = null;
210
- const adapters = isTest
211
- ? []
212
- : [
213
- createAdapterDetector('http', MoostHttp => {
214
- MoostHttp.prototype.listen = function (...args) {
215
- moostMiddleware = this.getServerCb();
216
- setTimeout(() => {
217
- args.filter(a => typeof a === 'function').forEach(a => a());
218
- }, 1);
219
- return Promise.resolve();
220
- };
221
- }),
222
- createAdapterDetector('cli'),
223
- createAdapterDetector('wf'),
224
- ];
225
- const logger = isTest ? console : getLogger();
226
- let reloadRequired = false;
227
- patchMoostHandlerLogging();
228
- const pluginConfig = {
229
- name: PLUGIN_NAME,
230
- enforce: 'pre',
231
- config(cfg) {
232
- const entry = cfg.build?.rollupOptions?.input || options.entry;
233
- const outfile = typeof entry === 'string' ? entry.split('/').pop().replace(/\.ts$/, '.js') : undefined;
234
- const pluginConfig = {
235
- server: {
236
- port: cfg.server?.port || options.port || 3000,
237
- host: cfg.server?.host || options.host,
238
- },
239
- optimizeDeps: {
240
- noDiscovery: cfg.optimizeDeps?.noDiscovery === undefined ? true : cfg.optimizeDeps.noDiscovery,
241
- exclude: cfg.optimizeDeps?.exclude || ['@swc/core'],
242
- },
243
- build: {
244
- target: cfg.build?.target || 'node',
245
- outDir: cfg.build?.outDir || options.outDir || 'dist',
246
- ssr: cfg.build?.ssr ?? true,
247
- minify: cfg.build?.minify || false,
248
- rollupOptions: {
249
- external: isTest
250
- ? cfg.build?.rollupOptions?.external
251
- : cfg.build?.rollupOptions?.external ||
252
- (options.externals === false
253
- ? []
254
- : getExternals({
255
- node: Boolean(options.externals === true || options.externals?.node),
256
- workspace: Boolean(options.externals === true || options.externals?.workspace),
257
- })),
258
- input: entry,
259
- output: {
260
- format: options.format,
261
- sourcemap: !!(options.sourcemap ?? true),
262
- entryFileNames: outfile,
263
- ...cfg.build?.rollupOptions?.output,
264
- },
265
- },
266
- },
267
- };
268
- return vite.mergeConfig(cfg, pluginConfig);
269
- },
270
- async transform(code, id) {
271
- if (!id.endsWith('.ts')) {
272
- return code;
273
- }
274
- for (const adapter of adapters) {
275
- if (!adapter.detected && adapter.regex.test(code)) {
276
- await adapter.init();
277
- }
278
- }
279
- if (REG_HAS_EXPORT_CLASS.test(code)) {
280
- code = code.replace(REG_REPLACE_EXPORT_CLASS, '\n@__VITE_ID(import.meta.filename)\n$1');
281
- code = `import { __VITE_ID } from 'virtual:vite-id'\n\n${code}`;
282
- }
283
- return code;
284
- },
285
- resolveId(id) {
286
- if (id === 'virtual:vite-id') {
287
- return '\0virtual:vite-id';
288
- }
289
- },
290
- load(id) {
291
- if (id === '\0virtual:vite-id') {
292
- 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 `
293
336
  import { getMoostMate } from "moost";
294
337
  const mate = getMoostMate();
295
338
  export function __VITE_ID(id) {
296
339
  return mate.decorate("__vite_id", id)
297
340
  }
298
341
  `;
299
- }
300
- },
301
- async configureServer(server) {
302
- moostRestartCleanup(adapters, options.onEject);
303
- await server.ssrLoadModule(options.entry);
304
- server.middlewares.use(async (req, res, next) => {
305
- if (reloadRequired) {
306
- reloadRequired = false;
307
- console.log();
308
- logger.debug('🚀 Reloading Moost App...');
309
- console.log();
310
- await server.ssrLoadModule(options.entry);
311
- await new Promise(resolve => setTimeout(resolve, 1));
312
- }
313
- if (moostMiddleware) {
314
- return moostMiddleware(req, res);
315
- }
316
- next();
317
- });
318
- },
319
- hotUpdate({ file }) {
320
- if (file.endsWith('.ts')) {
321
- const modules = this.environment.moduleGraph.getModulesByFile(file);
322
- if (modules) {
323
- logger.debug(`🔃 Hot update: ${file}`);
324
- const cleanupInstances = new Set();
325
- for (const mod of modules) {
326
- const allImporters = gatherAllImporters(mod);
327
- for (const impModule of allImporters) {
328
- if (impModule.id) {
329
- cleanupInstances.add(impModule.id);
330
- }
331
- }
332
- this.environment.moduleGraph.invalidateModule(mod);
333
- }
334
- moostMiddleware = null;
335
- moostRestartCleanup(adapters, options.onEject, cleanupInstances);
336
- reloadRequired = true;
337
- }
338
- return [];
339
- }
340
- },
341
- };
342
- if (isProd || isTest) {
343
- delete pluginConfig.configureServer;
344
- delete pluginConfig.resolveId;
345
- delete pluginConfig.load;
346
- delete pluginConfig.transform;
347
- delete pluginConfig.hotUpdate;
348
- }
349
- return pluginConfig;
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;
350
386
  }
351
387
 
352
- exports.moostVite = moostVite;
388
+ //#endregion
389
+ exports.moostVite = moostVite