@meethive/vite 0.0.1

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 (72) hide show
  1. package/dist/index.d.ts +4 -0
  2. package/dist/index.d.ts.map +1 -0
  3. package/dist/index.js +2118 -0
  4. package/dist/index.mjs +2096 -0
  5. package/dist/src/federation/src/dev/expose-development.d.ts +5 -0
  6. package/dist/src/federation/src/dev/expose-development.d.ts.map +1 -0
  7. package/dist/src/federation/src/dev/remote-development.d.ts +5 -0
  8. package/dist/src/federation/src/dev/remote-development.d.ts.map +1 -0
  9. package/dist/src/federation/src/dev/shared-development.d.ts +5 -0
  10. package/dist/src/federation/src/dev/shared-development.d.ts.map +1 -0
  11. package/dist/src/federation/src/index.d.ts +7 -0
  12. package/dist/src/federation/src/index.d.ts.map +1 -0
  13. package/dist/src/federation/src/prod/expose-production.d.ts +5 -0
  14. package/dist/src/federation/src/prod/expose-production.d.ts.map +1 -0
  15. package/dist/src/federation/src/prod/remote-production.d.ts +7 -0
  16. package/dist/src/federation/src/prod/remote-production.d.ts.map +1 -0
  17. package/dist/src/federation/src/prod/shared-production.d.ts +5 -0
  18. package/dist/src/federation/src/prod/shared-production.d.ts.map +1 -0
  19. package/dist/src/federation/src/public.d.ts +40 -0
  20. package/dist/src/federation/src/public.d.ts.map +1 -0
  21. package/dist/src/federation/src/runtime/dynamic-remote.d.ts +79 -0
  22. package/dist/src/federation/src/runtime/dynamic-remote.d.ts.map +1 -0
  23. package/dist/src/federation/src/utils/html.d.ts +12 -0
  24. package/dist/src/federation/src/utils/html.d.ts.map +1 -0
  25. package/dist/src/federation/src/utils/index.d.ts +29 -0
  26. package/dist/src/federation/src/utils/index.d.ts.map +1 -0
  27. package/dist/src/federation/src/utils/semver/compare.d.ts +10 -0
  28. package/dist/src/federation/src/utils/semver/compare.d.ts.map +1 -0
  29. package/dist/src/federation/src/utils/semver/constants.d.ts +11 -0
  30. package/dist/src/federation/src/utils/semver/constants.d.ts.map +1 -0
  31. package/dist/src/federation/src/utils/semver/parser.d.ts +10 -0
  32. package/dist/src/federation/src/utils/semver/parser.d.ts.map +1 -0
  33. package/dist/src/federation/src/utils/semver/satisfy.d.ts +2 -0
  34. package/dist/src/federation/src/utils/semver/satisfy.d.ts.map +1 -0
  35. package/dist/src/federation/src/utils/semver/utils.d.ts +12 -0
  36. package/dist/src/federation/src/utils/semver/utils.d.ts.map +1 -0
  37. package/dist/src/monaco-editor/index.d.ts +35 -0
  38. package/dist/src/monaco-editor/index.d.ts.map +1 -0
  39. package/dist/src/monaco-editor/languageWork.d.ts +10 -0
  40. package/dist/src/monaco-editor/languageWork.d.ts.map +1 -0
  41. package/dist/src/monaco-editor/workerMiddleware.d.ts +9 -0
  42. package/dist/src/monaco-editor/workerMiddleware.d.ts.map +1 -0
  43. package/dist/src/sharp/index.d.ts +12 -0
  44. package/dist/src/sharp/index.d.ts.map +1 -0
  45. package/index.ts +3 -0
  46. package/package.json +48 -0
  47. package/src/federation/src/dev/expose-development.ts +29 -0
  48. package/src/federation/src/dev/remote-development.ts +435 -0
  49. package/src/federation/src/dev/shared-development.ts +29 -0
  50. package/src/federation/src/index.ts +242 -0
  51. package/src/federation/src/prod/expose-production.ts +333 -0
  52. package/src/federation/src/prod/federation_fn_import.js +75 -0
  53. package/src/federation/src/prod/remote-production.ts +658 -0
  54. package/src/federation/src/prod/shared-production.ts +268 -0
  55. package/src/federation/src/public.ts +54 -0
  56. package/src/federation/src/runtime/dynamic-remote.ts +247 -0
  57. package/src/federation/src/utils/html.ts +165 -0
  58. package/src/federation/src/utils/index.ts +255 -0
  59. package/src/federation/src/utils/semver/compare.ts +131 -0
  60. package/src/federation/src/utils/semver/constants.ts +46 -0
  61. package/src/federation/src/utils/semver/parser.ts +253 -0
  62. package/src/federation/src/utils/semver/satisfy.ts +151 -0
  63. package/src/federation/src/utils/semver/utils.ts +93 -0
  64. package/src/federation/types/dynamic-remote.d.ts +105 -0
  65. package/src/federation/types/index.d.ts +344 -0
  66. package/src/federation/types/pluginHooks.d.ts +4 -0
  67. package/src/federation/types/virtual-modules.d.ts +48 -0
  68. package/src/federation/types/viteDevServer.d.ts +22 -0
  69. package/src/monaco-editor/index.ts +205 -0
  70. package/src/monaco-editor/languageWork.ts +36 -0
  71. package/src/monaco-editor/workerMiddleware.ts +78 -0
  72. package/src/sharp/index.ts +93 -0
package/dist/index.js ADDED
@@ -0,0 +1,2118 @@
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 __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (let key of __getOwnPropNames(from))
11
+ if (!__hasOwnProp.call(to, key) && key !== except)
12
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ }
14
+ return to;
15
+ };
16
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
+ // If the importer is in node compatibility mode or this is not an ESM
18
+ // file that has been converted to a CommonJS file using a Babel-
19
+ // compatible transform (i.e. "__esModule" has not been set), then set
20
+ // "default" to the CommonJS "module.exports" for node compatibility.
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
25
+ const virtual = require("@rollup/plugin-virtual");
26
+ const path = require("path");
27
+ const estreeWalker = require("estree-walker");
28
+ const MagicString = require("magic-string");
29
+ const path$1 = require("node:path");
30
+ const fs = require("fs");
31
+ require("crypto");
32
+ const esbuild = require("esbuild");
33
+ const EXPOSES_MAP = /* @__PURE__ */ new Map();
34
+ const EXPOSES_KEY_MAP = /* @__PURE__ */ new Map();
35
+ const SHARED = "shared";
36
+ const DYNAMIC_LOADING_CSS = "dynamicLoadingCss";
37
+ const DYNAMIC_LOADING_CSS_PREFIX = "__v__css__";
38
+ const DEFAULT_ENTRY_FILENAME = "remoteEntry.js";
39
+ const builderInfo = {
40
+ builder: "rollup",
41
+ assetsDir: "",
42
+ isHost: false,
43
+ isRemote: false,
44
+ isShared: false
45
+ };
46
+ const parsedOptions = {
47
+ prodExpose: [],
48
+ prodRemote: [],
49
+ prodShared: [],
50
+ devShared: [],
51
+ devExpose: [],
52
+ devRemote: []
53
+ };
54
+ const devRemotes = [];
55
+ const prodRemotes = [];
56
+ const viteConfigResolved = {
57
+ config: void 0
58
+ };
59
+ const unaryTags = /* @__PURE__ */ new Set(["link", "meta", "base"]);
60
+ function serializeTag({ tag, attrs, children }, indent = "") {
61
+ if (unaryTags.has(tag)) {
62
+ return `<${tag}${serializeAttrs(attrs)}>`;
63
+ } else {
64
+ return `<${tag}${serializeAttrs(attrs)}>${serializeTags(
65
+ children,
66
+ incrementIndent(indent)
67
+ )}</${tag}>`;
68
+ }
69
+ }
70
+ function serializeTags(tags, indent = "") {
71
+ if (typeof tags === "string") {
72
+ return tags;
73
+ } else if (tags && tags.length) {
74
+ return tags.map((tag) => `${indent}${serializeTag(tag, indent)}
75
+ `).join("");
76
+ }
77
+ return "";
78
+ }
79
+ function serializeAttrs(attrs) {
80
+ let res = "";
81
+ for (const key in attrs) {
82
+ if (typeof attrs[key] === "boolean") {
83
+ res += attrs[key] ? ` ${key}` : ``;
84
+ } else {
85
+ res += ` ${key}="${escapeHtml(attrs[key])}"`;
86
+ }
87
+ }
88
+ return res;
89
+ }
90
+ function incrementIndent(indent = "") {
91
+ return `${indent}${indent[0] === " " ? " " : " "}`;
92
+ }
93
+ const matchHtmlRegExp = /["'&<>]/;
94
+ function escapeHtml(string) {
95
+ const str = "" + string;
96
+ const match = matchHtmlRegExp.exec(str);
97
+ if (!match) {
98
+ return str;
99
+ }
100
+ let escape;
101
+ let html = "";
102
+ let index = 0;
103
+ let lastIndex = 0;
104
+ for (index = match.index; index < str.length; index++) {
105
+ switch (str.charCodeAt(index)) {
106
+ case 34:
107
+ escape = "&quot;";
108
+ break;
109
+ case 38:
110
+ escape = "&amp;";
111
+ break;
112
+ case 39:
113
+ escape = "&#39;";
114
+ break;
115
+ case 60:
116
+ escape = "&lt;";
117
+ break;
118
+ case 62:
119
+ escape = "&gt;";
120
+ break;
121
+ default:
122
+ continue;
123
+ }
124
+ if (lastIndex !== index) {
125
+ html += str.substring(lastIndex, index);
126
+ }
127
+ lastIndex = index + 1;
128
+ html += escape;
129
+ }
130
+ return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
131
+ }
132
+ const headInjectRE = /([ \t]*)<\/head>/i;
133
+ const headPrependInjectRE = /([ \t]*)<head[^>]*>/i;
134
+ const htmlPrependInjectRE = /([ \t]*)<html[^>]*>/i;
135
+ const bodyPrependInjectRE = /([ \t]*)<body[^>]*>/i;
136
+ const doctypePrependInjectRE = /<!doctype html>/i;
137
+ const toPreloadTag = (href) => ({
138
+ tag: "link",
139
+ attrs: {
140
+ rel: "modulepreload",
141
+ crossorigin: true,
142
+ href
143
+ }
144
+ });
145
+ function injectToHead(html, tags, prepend = false) {
146
+ if (tags.length === 0) return html;
147
+ if (prepend) {
148
+ if (headPrependInjectRE.test(html)) {
149
+ return html.replace(
150
+ headPrependInjectRE,
151
+ (match, p1) => `${match}
152
+ ${serializeTags(tags, incrementIndent(p1))}`
153
+ );
154
+ }
155
+ } else {
156
+ if (headInjectRE.test(html)) {
157
+ return html.replace(
158
+ headInjectRE,
159
+ (match, p1) => `${serializeTags(tags, incrementIndent(p1))}${match}`
160
+ );
161
+ }
162
+ if (bodyPrependInjectRE.test(html)) {
163
+ return html.replace(
164
+ bodyPrependInjectRE,
165
+ (match, p1) => `${serializeTags(tags, p1)}
166
+ ${match}`
167
+ );
168
+ }
169
+ }
170
+ return prependInjectFallback(html, tags);
171
+ }
172
+ function prependInjectFallback(html, tags) {
173
+ if (htmlPrependInjectRE.test(html)) {
174
+ return html.replace(htmlPrependInjectRE, `$&
175
+ ${serializeTags(tags)}`);
176
+ }
177
+ if (doctypePrependInjectRE.test(html)) {
178
+ return html.replace(doctypePrependInjectRE, `$&
179
+ ${serializeTags(tags)}`);
180
+ }
181
+ return serializeTags(tags) + html;
182
+ }
183
+ function parseSharedOptions(options) {
184
+ return parseOptions(
185
+ options.shared || {},
186
+ (value, key) => ({
187
+ import: true,
188
+ shareScope: "default",
189
+ packagePath: key,
190
+ // Whether the path is set manually
191
+ manuallyPackagePathSetting: false,
192
+ generate: true,
193
+ modulePreload: false
194
+ }),
195
+ (value, key) => {
196
+ value.import = value.import ?? true;
197
+ value.shareScope = value.shareScope || "default";
198
+ value.packagePath = value.packagePath || key;
199
+ value.manuallyPackagePathSetting = value.packagePath !== key;
200
+ value.generate = value.generate ?? true;
201
+ value.modulePreload = value.modulePreload ?? false;
202
+ return value;
203
+ }
204
+ );
205
+ }
206
+ function parseExposeOptions(options) {
207
+ return parseOptions(
208
+ options.exposes,
209
+ (item) => {
210
+ return {
211
+ import: item,
212
+ name: void 0,
213
+ dontAppendStylesToHead: false
214
+ };
215
+ },
216
+ (item) => ({
217
+ import: item.import,
218
+ name: item.name || void 0,
219
+ dontAppendStylesToHead: item.dontAppendStylesToHead || false
220
+ })
221
+ );
222
+ }
223
+ function parseRemoteOptions(options) {
224
+ return parseOptions(
225
+ options.remotes ? options.remotes : {},
226
+ (item) => ({
227
+ external: Array.isArray(item) ? item : [item],
228
+ shareScope: options.shareScope || "default",
229
+ format: "esm",
230
+ from: "vite",
231
+ externalType: "url"
232
+ }),
233
+ (item) => ({
234
+ external: Array.isArray(item.external) ? item.external : [item.external],
235
+ shareScope: item.shareScope || options.shareScope || "default",
236
+ format: item.format || "esm",
237
+ from: item.from ?? "vite",
238
+ externalType: item.externalType || "url"
239
+ })
240
+ );
241
+ }
242
+ function parseOptions(options, normalizeSimple, normalizeOptions) {
243
+ if (!options) {
244
+ return [];
245
+ }
246
+ const list = [];
247
+ const array = (items) => {
248
+ for (const item of items) {
249
+ if (typeof item === "string") {
250
+ list.push([item, normalizeSimple(item, item)]);
251
+ } else if (item && typeof item === "object") {
252
+ object(item);
253
+ } else {
254
+ throw new Error("Unexpected options format");
255
+ }
256
+ }
257
+ };
258
+ const object = (obj) => {
259
+ for (const [key, value] of Object.entries(obj)) {
260
+ if (typeof value === "string" || Array.isArray(value)) {
261
+ list.push([key, normalizeSimple(value, key)]);
262
+ } else {
263
+ list.push([key, normalizeOptions(value, key)]);
264
+ }
265
+ }
266
+ };
267
+ if (Array.isArray(options)) {
268
+ array(options);
269
+ } else if (typeof options === "object") {
270
+ object(options);
271
+ } else {
272
+ throw new Error("Unexpected options format");
273
+ }
274
+ return list;
275
+ }
276
+ const letterReg = new RegExp("[0-9a-zA-Z]+");
277
+ function removeNonRegLetter(str, reg = letterReg) {
278
+ let needUpperCase = false;
279
+ let ret = "";
280
+ for (const c of str) {
281
+ if (reg.test(c)) {
282
+ ret += needUpperCase ? c.toUpperCase() : c;
283
+ needUpperCase = false;
284
+ } else {
285
+ needUpperCase = true;
286
+ }
287
+ }
288
+ return ret;
289
+ }
290
+ function getModuleMarker(value, type) {
291
+ return type ? `__rf_${type}__${value}` : `__rf_placeholder__${value}`;
292
+ }
293
+ function normalizePath(id) {
294
+ return path.posix.normalize(id.replace(/\\/g, "/"));
295
+ }
296
+ function createRemotesMap(remotes) {
297
+ const createUrl = (remote) => {
298
+ const external = remote.config.external[0];
299
+ const externalType = remote.config.externalType;
300
+ if (externalType === "promise") {
301
+ return `()=>${external}`;
302
+ } else {
303
+ return `'${external}'`;
304
+ }
305
+ };
306
+ return `const remotesMap = {
307
+ ${remotes.map(
308
+ (remote) => `'${remote.id}':{url:${createUrl(remote)},format:'${remote.config.format}',from:'${remote.config.from}'}`
309
+ ).join(",\n ")}
310
+ };`;
311
+ }
312
+ function getFileExtname(url) {
313
+ const fileNameAndParamArr = normalizePath(url).split("/");
314
+ const fileNameAndParam = fileNameAndParamArr[fileNameAndParamArr.length - 1];
315
+ const fileName = fileNameAndParam.split("?")[0];
316
+ return path.extname(fileName);
317
+ }
318
+ const REMOTE_FROM_PARAMETER = "remoteFrom";
319
+ const NAME_CHAR_REG = new RegExp("[0-9a-zA-Z@_-]+");
320
+ function joinUrlSegments(a, b) {
321
+ if (!a || !b) {
322
+ return a || b || "";
323
+ }
324
+ if (a[a.length - 1] === "/") {
325
+ a = a.substring(0, a.length - 1);
326
+ }
327
+ if (b[0] !== "/") {
328
+ b = "/" + b;
329
+ }
330
+ return a + b;
331
+ }
332
+ function toOutputFilePathWithoutRuntime(filename, type, hostId, hostType, config, toRelative) {
333
+ const { renderBuiltUrl } = config.experimental;
334
+ let relative = config.base === "" || config.base === "./";
335
+ if (renderBuiltUrl) {
336
+ const result = renderBuiltUrl(filename, {
337
+ hostId,
338
+ hostType,
339
+ type,
340
+ ssr: !!config.build.ssr
341
+ });
342
+ if (typeof result === "object") {
343
+ if (result.runtime) {
344
+ throw new Error(
345
+ `{ runtime: "${result.runtime}" } is not supported for assets in ${hostType} files: ${filename}`
346
+ );
347
+ }
348
+ if (typeof result.relative === "boolean") {
349
+ relative = result.relative;
350
+ }
351
+ } else if (result) {
352
+ return result;
353
+ }
354
+ }
355
+ if (relative && !config.build.ssr) {
356
+ return toRelative(filename, hostId);
357
+ } else {
358
+ return joinUrlSegments(config.base, filename);
359
+ }
360
+ }
361
+ function prodRemotePlugin(options) {
362
+ parsedOptions.prodRemote = parseRemoteOptions(options);
363
+ for (const item of parsedOptions.prodRemote) {
364
+ prodRemotes.push({
365
+ id: item[0],
366
+ regexp: new RegExp(`^${item[0]}/.+?`),
367
+ config: item[1]
368
+ });
369
+ }
370
+ const shareScope = options.shareScope || "default";
371
+ let resolvedConfig;
372
+ return {
373
+ name: "originjs:remote-production",
374
+ virtualFile: options.remotes || options.enableDynamicRemotes ? {
375
+ // language=JS
376
+ __federation__: `
377
+ ${createRemotesMap(prodRemotes)}
378
+ const currentImports = {}
379
+ const loadJS = async (url, fn) => {
380
+ const resolvedUrl = typeof url === 'function' ? await url() : url;
381
+ const script = document.createElement('script')
382
+ script.type = 'text/javascript';
383
+ script.onload = fn;
384
+ script.src = resolvedUrl;
385
+ document.getElementsByTagName('head')[0].appendChild(script);
386
+ }
387
+
388
+ function get(name, ${REMOTE_FROM_PARAMETER}) {
389
+ return __federation_import(name).then(module => () => {
390
+ if (${REMOTE_FROM_PARAMETER} === 'webpack') {
391
+ return Object.prototype.toString.call(module).indexOf('Module') > -1 && module.default ? module.default : module
392
+ }
393
+ return module
394
+ })
395
+ }
396
+
397
+ function merge(obj1, obj2) {
398
+ const mergedObj = Object.assign(obj1, obj2);
399
+ for (const key of Object.keys(mergedObj)) {
400
+ if (typeof mergedObj[key] === 'object' && typeof obj2[key] === 'object') {
401
+ mergedObj[key] = merge(mergedObj[key], obj2[key]);
402
+ }
403
+ }
404
+ return mergedObj;
405
+ }
406
+
407
+ const wrapShareModule = ${REMOTE_FROM_PARAMETER} => {
408
+ return merge({
409
+ ${getModuleMarker("shareScope")}
410
+ }, (globalThis.__federation_shared__ || {})['${shareScope}'] || {});
411
+ }
412
+
413
+ async function __federation_import(name) {
414
+ currentImports[name] ??= import(name)
415
+ return currentImports[name]
416
+ }
417
+
418
+ const initMap = Object.create(null);
419
+
420
+ async function __federation_method_ensure(remoteId) {
421
+ const remote = remotesMap[remoteId];
422
+ if (!remote.inited) {
423
+ if ('var' === remote.format) {
424
+ // loading js with script tag
425
+ return new Promise(resolve => {
426
+ const callback = () => {
427
+ if (!remote.inited) {
428
+ remote.lib = window[remoteId];
429
+ remote.lib.init(wrapShareModule(remote.from))
430
+ remote.inited = true;
431
+ }
432
+ resolve(remote.lib);
433
+ }
434
+ return loadJS(remote.url, callback);
435
+ });
436
+ } else if (['esm', 'systemjs'].includes(remote.format)) {
437
+ // loading js with import(...)
438
+ return new Promise((resolve, reject) => {
439
+ const getUrl = typeof remote.url === 'function' ? remote.url : () => Promise.resolve(remote.url);
440
+ getUrl().then(url => {
441
+ import(/* @vite-ignore */ url).then(lib => {
442
+ if (!remote.inited) {
443
+ const shareScope = wrapShareModule(remote.from);
444
+ lib.init(shareScope);
445
+ remote.lib = lib;
446
+ remote.lib.init(shareScope);
447
+ remote.inited = true;
448
+ }
449
+ resolve(remote.lib);
450
+ }).catch(reject)
451
+ })
452
+ })
453
+ }
454
+ } else {
455
+ return remote.lib;
456
+ }
457
+ }
458
+
459
+ function __federation_method_unwrapDefault(module) {
460
+ return (module?.__esModule || module?.[Symbol.toStringTag] === 'Module') ? module.default : module
461
+ }
462
+
463
+ function __federation_method_wrapDefault(module, need) {
464
+ if (!module?.default && need) {
465
+ let obj = Object.create(null);
466
+ obj.default = module;
467
+ obj.__esModule = true;
468
+ return obj;
469
+ }
470
+ return module;
471
+ }
472
+
473
+ function __federation_method_getRemote(remoteName, componentName) {
474
+ return __federation_method_ensure(remoteName).then((remote) => remote.get(componentName).then(factory => factory()));
475
+ }
476
+
477
+ function __federation_method_setRemote(remoteName, remoteConfig) {
478
+ remotesMap[remoteName] = remoteConfig;
479
+ }
480
+
481
+ async function __federation_method_add_origin_setRemote(remoteName, remoteUrl, options) {
482
+ const _options = options || {}
483
+ const _item = {
484
+ external: Array.isArray(_options.external) ? _options.external : [_options.external],
485
+ shareScope: _options.shareScope || 'default',
486
+ format: _options.format || 'esm',
487
+ from: _options.from ?? 'vite',
488
+ externalType: _options.externalType || 'url'
489
+ }
490
+
491
+ __federation_method_setRemote(remoteName, {
492
+ url: remoteUrl,
493
+ format: _item.format,
494
+ from: _item.from
495
+ })
496
+ }
497
+
498
+ export {
499
+ __federation_method_ensure,
500
+ __federation_method_getRemote,
501
+ __federation_method_setRemote,
502
+ __federation_method_add_origin_setRemote,
503
+ __federation_method_unwrapDefault,
504
+ __federation_method_wrapDefault
505
+ }
506
+ `
507
+ } : { __federation__: "" },
508
+ configResolved(config) {
509
+ resolvedConfig = config;
510
+ },
511
+ async transform(code, id) {
512
+ if (builderInfo.isShared) {
513
+ for (const sharedInfo of parsedOptions.prodShared) {
514
+ if (!sharedInfo[1].emitFile) {
515
+ sharedInfo[1].emitFile = this.emitFile({
516
+ type: "chunk",
517
+ id: sharedInfo[1].id ?? sharedInfo[1].packagePath,
518
+ preserveSignature: "strict",
519
+ name: `__federation_shared_${sharedInfo[0]}`
520
+ });
521
+ }
522
+ }
523
+ if (id === "\0virtual:__federation_fn_import") {
524
+ const moduleMapCode = parsedOptions.prodShared.filter((shareInfo) => shareInfo[1].generate).map(
525
+ (sharedInfo) => `'${sharedInfo[0]}':{get:()=>()=>__federation_import(import.meta.ROLLUP_FILE_URL_${sharedInfo[1].emitFile}),import:${sharedInfo[1].import}${sharedInfo[1].requiredVersion ? `,requiredVersion:'${sharedInfo[1].requiredVersion}'` : ""}}`
526
+ ).join(",");
527
+ return code.replace(
528
+ getModuleMarker("moduleMap", "var"),
529
+ `{${moduleMapCode}}`
530
+ );
531
+ }
532
+ }
533
+ if (builderInfo.isRemote) {
534
+ for (const expose of parsedOptions.prodExpose) {
535
+ if (!expose[1].emitFile) {
536
+ expose[1].emitFile = this.emitFile({
537
+ type: "chunk",
538
+ id: expose[1].id ?? expose[1].import,
539
+ name: EXPOSES_KEY_MAP.get(expose[0]),
540
+ preserveSignature: "allow-extension"
541
+ });
542
+ }
543
+ }
544
+ }
545
+ if (builderInfo.isHost) {
546
+ if (id === "\0virtual:__federation__") {
547
+ const res = [];
548
+ parsedOptions.prodShared.forEach((arr) => {
549
+ const obj = arr[1];
550
+ let str = "";
551
+ if (typeof obj === "object") {
552
+ const fileUrl = `import.meta.ROLLUP_FILE_URL_${obj.emitFile}`;
553
+ str += `get:()=>get(${fileUrl}, ${REMOTE_FROM_PARAMETER}), loaded:1`;
554
+ res.push(`'${arr[0]}':{'${obj.version}':{${str}}}`);
555
+ }
556
+ });
557
+ return code.replace(getModuleMarker("shareScope"), res.join(","));
558
+ }
559
+ } else {
560
+ if (id === "\0virtual:__federation__") {
561
+ return code.replace(getModuleMarker("shareScope"), "");
562
+ }
563
+ }
564
+ if (builderInfo.isHost || builderInfo.isShared) {
565
+ let ast = null;
566
+ try {
567
+ ast = this.parse(code);
568
+ } catch (err) {
569
+ console.error(err);
570
+ }
571
+ if (!ast) {
572
+ return null;
573
+ }
574
+ const magicString = new MagicString(code);
575
+ const hasStaticImported = /* @__PURE__ */ new Map();
576
+ let requiresRuntime = false;
577
+ let hasImportShared = false;
578
+ let modify = false;
579
+ let manualRequired = null;
580
+ estreeWalker.walk(ast, {
581
+ enter(node) {
582
+ if (node.type === "ImportDeclaration") {
583
+ const moduleName = node.source.value;
584
+ if (parsedOptions.prodShared.some(
585
+ (sharedInfo) => sharedInfo[0] === moduleName
586
+ )) {
587
+ const namedImportDeclaration = [];
588
+ let defaultImportDeclaration = null;
589
+ if (!node.specifiers?.length) {
590
+ magicString.remove(node.start, node.end);
591
+ modify = true;
592
+ } else {
593
+ node.specifiers.forEach((specify) => {
594
+ if (specify.imported?.name) {
595
+ namedImportDeclaration.push(
596
+ `${specify.imported.name === specify.local.name ? specify.imported.name : `${specify.imported.name}:${specify.local.name}`}`
597
+ );
598
+ } else {
599
+ defaultImportDeclaration = specify.local.name;
600
+ }
601
+ });
602
+ hasImportShared = true;
603
+ if (defaultImportDeclaration && namedImportDeclaration.length) {
604
+ const imports = namedImportDeclaration.join(",");
605
+ const line = `const ${defaultImportDeclaration} = await importShared('${moduleName}');
606
+ const {${imports}} = ${defaultImportDeclaration};
607
+ `;
608
+ magicString.overwrite(node.start, node.end, line);
609
+ } else if (defaultImportDeclaration) {
610
+ magicString.overwrite(
611
+ node.start,
612
+ node.end,
613
+ `const ${defaultImportDeclaration} = await importShared('${moduleName}');
614
+ `
615
+ );
616
+ } else if (namedImportDeclaration.length) {
617
+ magicString.overwrite(
618
+ node.start,
619
+ node.end,
620
+ `const {${namedImportDeclaration.join(
621
+ ","
622
+ )}} = await importShared('${moduleName}');
623
+ `
624
+ );
625
+ }
626
+ }
627
+ }
628
+ }
629
+ if (node.type === "ImportDeclaration" && node.source?.value === "virtual:__federation__") {
630
+ manualRequired = node;
631
+ }
632
+ if ((node.type === "ImportExpression" || node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration") && node.source?.value?.indexOf("/") > -1) {
633
+ const moduleId = node.source.value;
634
+ const remote = prodRemotes.find((r) => r.regexp.test(moduleId));
635
+ const needWrap = remote?.config.from === "vite";
636
+ if (remote) {
637
+ requiresRuntime = true;
638
+ const modName = `.${moduleId.slice(remote.id.length)}`;
639
+ switch (node.type) {
640
+ case "ImportExpression": {
641
+ magicString.overwrite(
642
+ node.start,
643
+ node.end,
644
+ `__federation_method_getRemote(${JSON.stringify(
645
+ remote.id
646
+ )} , ${JSON.stringify(
647
+ modName
648
+ )}).then(module=>__federation_method_wrapDefault(module, ${needWrap}))`
649
+ );
650
+ break;
651
+ }
652
+ case "ImportDeclaration": {
653
+ if (node.specifiers?.length) {
654
+ const afterImportName = `__federation_var_${moduleId.replace(
655
+ /[@/\\.-]/g,
656
+ ""
657
+ )}`;
658
+ if (!hasStaticImported.has(moduleId)) {
659
+ hasStaticImported.set(moduleId, afterImportName);
660
+ magicString.overwrite(
661
+ node.start,
662
+ node.end,
663
+ `const ${afterImportName} = await __federation_method_getRemote(${JSON.stringify(
664
+ remote.id
665
+ )} , ${JSON.stringify(modName)});`
666
+ );
667
+ }
668
+ let deconstructStr = "";
669
+ node.specifiers.forEach((spec) => {
670
+ if (spec.type === "ImportDefaultSpecifier") {
671
+ magicString.appendRight(
672
+ node.end,
673
+ `
674
+ let ${spec.local.name} = __federation_method_unwrapDefault(${afterImportName}) `
675
+ );
676
+ } else if (spec.type === "ImportSpecifier") {
677
+ const importedName = spec.imported.name;
678
+ const localName = spec.local.name;
679
+ deconstructStr += `${importedName === localName ? localName : `${importedName} : ${localName}`},`;
680
+ } else if (spec.type === "ImportNamespaceSpecifier") {
681
+ magicString.appendRight(
682
+ node.end,
683
+ `let {${spec.local.name}} = ${afterImportName}`
684
+ );
685
+ }
686
+ });
687
+ if (deconstructStr.length > 0) {
688
+ magicString.appendRight(
689
+ node.end,
690
+ `
691
+ let {${deconstructStr.slice(
692
+ 0,
693
+ -1
694
+ )}} = ${afterImportName}`
695
+ );
696
+ }
697
+ }
698
+ break;
699
+ }
700
+ case "ExportNamedDeclaration": {
701
+ const afterImportName = `__federation_var_${moduleId.replace(
702
+ /[@/\\.-]/g,
703
+ ""
704
+ )}`;
705
+ if (!hasStaticImported.has(moduleId)) {
706
+ hasStaticImported.set(moduleId, afterImportName);
707
+ magicString.overwrite(
708
+ node.start,
709
+ node.end,
710
+ `const ${afterImportName} = await __federation_method_getRemote(${JSON.stringify(
711
+ remote.id
712
+ )} , ${JSON.stringify(modName)});`
713
+ );
714
+ }
715
+ if (node.specifiers.length > 0) {
716
+ const specifiers = node.specifiers;
717
+ let exportContent = "";
718
+ let deconstructContent = "";
719
+ specifiers.forEach((spec) => {
720
+ const localName = spec.local.name;
721
+ const exportName = spec.exported.name;
722
+ const variableName = `${afterImportName}_${localName}`;
723
+ deconstructContent = deconstructContent.concat(
724
+ `${localName}:${variableName},`
725
+ );
726
+ exportContent = exportContent.concat(
727
+ `${variableName} as ${exportName},`
728
+ );
729
+ });
730
+ magicString.append(
731
+ `
732
+ const {${deconstructContent.slice(
733
+ 0,
734
+ deconstructContent.length - 1
735
+ )}} = ${afterImportName};
736
+ `
737
+ );
738
+ magicString.append(
739
+ `
740
+ export {${exportContent.slice(
741
+ 0,
742
+ exportContent.length - 1
743
+ )}}; `
744
+ );
745
+ }
746
+ break;
747
+ }
748
+ }
749
+ }
750
+ }
751
+ }
752
+ });
753
+ if (requiresRuntime) {
754
+ let requiresCode = `import {__federation_method_ensure, __federation_method_getRemote , __federation_method_wrapDefault , __federation_method_unwrapDefault, __federation_method_add_origin_setRemote} from '__federation__';
755
+
756
+ `;
757
+ if (manualRequired) {
758
+ requiresCode = `import {__federation_method_setRemote, __federation_method_ensure, __federation_method_getRemote , __federation_method_wrapDefault , __federation_method_unwrapDefault, __federation_method_add_origin_setRemote} from '__federation__';
759
+
760
+ `;
761
+ magicString.overwrite(manualRequired.start, manualRequired.end, ``);
762
+ }
763
+ magicString.prepend(requiresCode);
764
+ }
765
+ if (hasImportShared) {
766
+ magicString.prepend(
767
+ `import {importShared} from '\0virtual:__federation_fn_import';
768
+ `
769
+ );
770
+ }
771
+ if (requiresRuntime || hasImportShared || modify) {
772
+ return {
773
+ code: magicString.toString(),
774
+ map: magicString.generateMap({ hires: true })
775
+ };
776
+ }
777
+ }
778
+ },
779
+ generateBundle(options2, bundle) {
780
+ const preloadSharedReg = parsedOptions.prodShared.filter((shareInfo) => shareInfo[1].modulePreload).map(
781
+ (item) => new RegExp(`__federation_shared_${item[0]}-.{8}.js`, "g")
782
+ );
783
+ const getImportedChunks = (chunk, satisfy, seen = /* @__PURE__ */ new Set()) => {
784
+ const chunks = [];
785
+ chunk.imports.forEach((file) => {
786
+ const importee = bundle[file];
787
+ if (importee) {
788
+ if (importee.type === "chunk" && !seen.has(file)) {
789
+ if (satisfy(importee)) {
790
+ seen.add(file);
791
+ chunks.push(...getImportedChunks(importee, satisfy, seen));
792
+ chunks.push(importee);
793
+ }
794
+ }
795
+ }
796
+ });
797
+ return chunks;
798
+ };
799
+ const sharedFiles = [];
800
+ const entryChunk = {};
801
+ for (const fileName in bundle) {
802
+ const file = bundle[fileName];
803
+ if (file.type === "asset") {
804
+ if (fileName.endsWith(".html")) {
805
+ entryChunk[fileName] = file;
806
+ }
807
+ } else {
808
+ if (preloadSharedReg.some((item) => item.test(fileName))) {
809
+ sharedFiles.push(fileName);
810
+ }
811
+ }
812
+ }
813
+ if (!sharedFiles.length) return;
814
+ Object.keys(entryChunk).forEach((fileName) => {
815
+ let html = entryChunk[fileName].source;
816
+ const htmlPath = entryChunk[fileName].fileName;
817
+ const basePath = resolvedConfig.base === "./" || resolvedConfig.base === "" ? path$1.posix.join(
818
+ path$1.posix.relative(entryChunk[fileName].fileName, "").slice(0, -2),
819
+ "./"
820
+ ) : resolvedConfig.base;
821
+ const toOutputFilePath = (filename) => toOutputFilePathWithoutRuntime(
822
+ filename,
823
+ "asset",
824
+ htmlPath,
825
+ "html",
826
+ resolvedConfig,
827
+ (filename2) => basePath + filename2
828
+ );
829
+ const importFiles = sharedFiles.filter((item) => {
830
+ return !html.includes(toOutputFilePath(item));
831
+ }).flatMap((item) => {
832
+ const filepath = item;
833
+ const importFiles2 = getImportedChunks(
834
+ bundle[item],
835
+ (chunk) => !html.includes(toOutputFilePath(chunk.fileName))
836
+ ).map((item2) => item2.fileName);
837
+ return [filepath, ...importFiles2].map(
838
+ (item2) => toOutputFilePath(item2)
839
+ );
840
+ });
841
+ html = injectToHead(
842
+ html,
843
+ [...new Set(importFiles)].map((item) => toPreloadTag(item))
844
+ );
845
+ entryChunk[fileName].source = html;
846
+ });
847
+ }
848
+ };
849
+ }
850
+ const federation_fn_import = "import { satisfy } from '__federation_fn_satisfy'\r\n\r\nconst currentImports = {}\r\n\r\n// eslint-disable-next-line no-undef\r\nconst moduleMap = __rf_var__moduleMap\r\nconst moduleCache = Object.create(null)\r\nasync function importShared(name, shareScope = 'default') {\r\n return moduleCache[name]\r\n ? new Promise((r) => r(moduleCache[name]))\r\n : (await getSharedFromRuntime(name, shareScope)) || getSharedFromLocal(name)\r\n}\r\n// eslint-disable-next-line\r\nasync function __federation_import(name) {\r\n currentImports[name] ??= import(name)\r\n return currentImports[name]\r\n}\r\nasync function getSharedFromRuntime(name, shareScope) {\r\n let module = null\r\n if (globalThis?.__federation_shared__?.[shareScope]?.[name]) {\r\n const versionObj = globalThis.__federation_shared__[shareScope][name]\r\n const requiredVersion = moduleMap[name]?.requiredVersion\r\n const hasRequiredVersion = !!requiredVersion\r\n if (hasRequiredVersion) {\r\n const versionKey = Object.keys(versionObj).find((version) =>\r\n satisfy(version, requiredVersion)\r\n )\r\n if (versionKey) {\r\n const versionValue = versionObj[versionKey]\r\n module = await (await versionValue.get())()\r\n } else {\r\n console.log(\r\n `provider support ${name}(${versionKey}) is not satisfied requiredVersion(\\${moduleMap[name].requiredVersion})`\r\n )\r\n }\r\n } else {\r\n const versionKey = Object.keys(versionObj)[0]\r\n const versionValue = versionObj[versionKey]\r\n module = await (await versionValue.get())()\r\n }\r\n }\r\n if (module) {\r\n return flattenModule(module, name)\r\n }\r\n}\r\nasync function getSharedFromLocal(name) {\r\n if (moduleMap[name]?.import) {\r\n let module = await (await moduleMap[name].get())()\r\n return flattenModule(module, name)\r\n } else {\r\n console.error(\r\n `consumer config import=false,so cant use callback shared module`\r\n )\r\n }\r\n}\r\nfunction flattenModule(module, name) {\r\n // use a shared module which export default a function will getting error 'TypeError: xxx is not a function'\r\n if (typeof module.default === 'function') {\r\n Object.keys(module).forEach((key) => {\r\n if (key !== 'default') {\r\n module.default[key] = module[key]\r\n }\r\n })\r\n moduleCache[name] = module.default\r\n return module.default\r\n }\r\n if (module.default) module = Object.assign({}, module.default, module)\r\n moduleCache[name] = module\r\n return module\r\n}\r\nexport {\r\n importShared,\r\n getSharedFromRuntime as importSharedRuntime,\r\n getSharedFromLocal as importSharedLocal\r\n}\r\n";
851
+ const sharedFilePathReg = /__federation_shared_(.+)-.{8}\.js$/;
852
+ function prodSharedPlugin(options) {
853
+ parsedOptions.prodShared = parseSharedOptions(options);
854
+ const shareName2Prop = /* @__PURE__ */ new Map();
855
+ parsedOptions.prodShared.forEach(
856
+ (value) => shareName2Prop.set(removeNonRegLetter(value[0], NAME_CHAR_REG), value[1])
857
+ );
858
+ let isHost;
859
+ let isRemote;
860
+ const id2Prop = /* @__PURE__ */ new Map();
861
+ function negotiateManualChunksCompatibility(inputOptions) {
862
+ if (!inputOptions.output) return;
863
+ const outputs = Array.isArray(inputOptions.output) ? inputOptions.output : [inputOptions.output];
864
+ outputs.forEach((output) => {
865
+ if (!output.manualChunks) return;
866
+ const sharedModuleNames = [...shareName2Prop.keys()];
867
+ const conflictModules = /* @__PURE__ */ new Set();
868
+ if (typeof output.manualChunks === "object") {
869
+ Object.values(output.manualChunks).flat().forEach((mod) => {
870
+ if (sharedModuleNames.some((shared) => mod.includes(shared) || mod === shared)) {
871
+ conflictModules.add(mod);
872
+ }
873
+ });
874
+ }
875
+ if (conflictModules.size > 0) {
876
+ console.info(
877
+ `[Federation] 检测到模块 [${Array.from(conflictModules).join(", ")}] 同时配置在 shared 和 manualChunks 中,启用协商共存模式`
878
+ );
879
+ adaptSharedToManualChunks(conflictModules);
880
+ }
881
+ });
882
+ }
883
+ function adaptSharedToManualChunks(conflictModules) {
884
+ parsedOptions.prodShared.forEach((sharedItem, index) => {
885
+ const [moduleName, config] = sharedItem;
886
+ if (conflictModules.has(moduleName)) {
887
+ config.manualChunkCompat = true;
888
+ config.chunkLoading = "defer";
889
+ console.info(
890
+ `[Federation] 模块 "${moduleName}" 设置为兼容模式:manualChunks 负责分块,federation 负责运行时共享`
891
+ );
892
+ }
893
+ });
894
+ }
895
+ return {
896
+ name: "originjs:shared-production",
897
+ virtualFile: {
898
+ __federation_fn_import: federation_fn_import
899
+ },
900
+ options(inputOptions) {
901
+ isRemote = !!parsedOptions.prodExpose.length;
902
+ isHost = options.isHost;
903
+ if (shareName2Prop.size) {
904
+ inputOptions.external = inputOptions.external?.filter((item) => {
905
+ if (item instanceof RegExp)
906
+ return ![...shareName2Prop.keys()].some((key) => item.test(key));
907
+ return !shareName2Prop.has(removeNonRegLetter(item, NAME_CHAR_REG));
908
+ });
909
+ }
910
+ negotiateManualChunksCompatibility(inputOptions);
911
+ return inputOptions;
912
+ },
913
+ async buildStart() {
914
+ if (parsedOptions.prodShared.length && isRemote) {
915
+ this.emitFile({
916
+ name: "__federation_fn_import",
917
+ type: "chunk",
918
+ id: "__federation_fn_import",
919
+ preserveSignature: "strict"
920
+ });
921
+ }
922
+ const collectDirFn = (filePath, collect) => {
923
+ const files = fs.readdirSync(filePath);
924
+ files.forEach((name) => {
925
+ const tempPath = path.join(filePath, name);
926
+ const isDir = fs.statSync(tempPath).isDirectory();
927
+ if (isDir) {
928
+ collect.push(tempPath);
929
+ collectDirFn(tempPath, collect);
930
+ }
931
+ });
932
+ };
933
+ const monoRepos = [];
934
+ const dirPaths = [];
935
+ const currentDir = path.resolve();
936
+ for (const arr of parsedOptions.prodShared) {
937
+ if (isHost && !arr[1].version && !arr[1].manuallyPackagePathSetting) {
938
+ const packageJsonPath = (await this.resolve(`${arr[1].packagePath}/package.json`))?.id;
939
+ if (packageJsonPath) {
940
+ const packageJson = JSON.parse(
941
+ fs.readFileSync(packageJsonPath, { encoding: "utf-8" })
942
+ );
943
+ arr[1].version = packageJson.version;
944
+ } else {
945
+ arr[1].removed = true;
946
+ const dir = path.join(currentDir, "node_modules", arr[0]);
947
+ const dirStat = fs.statSync(dir);
948
+ if (dirStat.isDirectory()) {
949
+ collectDirFn(dir, dirPaths);
950
+ } else {
951
+ this.error(`cant resolve "${arr[1].packagePath}"`);
952
+ }
953
+ if (dirPaths.length > 0) {
954
+ monoRepos.push({ arr: dirPaths, root: arr });
955
+ }
956
+ }
957
+ if (!arr[1].removed && !arr[1].version) {
958
+ this.error(
959
+ `No description file or no version in description file (usually package.json) of ${arr[0]}. Add version to description file, or manually specify version in shared config.`
960
+ );
961
+ }
962
+ }
963
+ }
964
+ parsedOptions.prodShared = parsedOptions.prodShared.filter(
965
+ (item) => !item[1].removed
966
+ );
967
+ if (monoRepos.length > 0) {
968
+ for (const monoRepo of monoRepos) {
969
+ for (const id of monoRepo.arr) {
970
+ try {
971
+ const idResolve = await this.resolve(id);
972
+ if (idResolve?.id) {
973
+ parsedOptions.prodShared.push([
974
+ `${monoRepo.root[0]}/${path.basename(id)}`,
975
+ {
976
+ id: idResolve?.id,
977
+ import: monoRepo.root[1].import,
978
+ shareScope: monoRepo.root[1].shareScope,
979
+ root: monoRepo.root
980
+ }
981
+ ]);
982
+ }
983
+ } catch (e) {
984
+ }
985
+ }
986
+ }
987
+ }
988
+ if (parsedOptions.prodShared.length && isRemote) {
989
+ for (const prod of parsedOptions.prodShared) {
990
+ id2Prop.set(prod[1].id, prod[1]);
991
+ }
992
+ }
993
+ },
994
+ outputOptions: function(outputOption) {
995
+ outputOption.hoistTransitiveImports = false;
996
+ const manualChunkFunc = (id) => {
997
+ const find = parsedOptions.prodShared.find(
998
+ (arr) => arr[1].dependencies?.has(id)
999
+ );
1000
+ return find ? find[0] : void 0;
1001
+ };
1002
+ if (typeof outputOption.manualChunks === "function") {
1003
+ outputOption.manualChunks = new Proxy(outputOption.manualChunks, {
1004
+ apply(target, thisArg, argArray) {
1005
+ const result = manualChunkFunc(argArray[0]);
1006
+ return result ? result : target(argArray[0], argArray[1]);
1007
+ }
1008
+ });
1009
+ }
1010
+ if (outputOption.manualChunks === void 0) {
1011
+ outputOption.manualChunks = manualChunkFunc;
1012
+ }
1013
+ return outputOption;
1014
+ },
1015
+ generateBundle(options2, bundle) {
1016
+ if (!isRemote) {
1017
+ return;
1018
+ }
1019
+ const needRemoveShared = /* @__PURE__ */ new Set();
1020
+ for (const key in bundle) {
1021
+ const chunk = bundle[key];
1022
+ if (chunk.type === "chunk") {
1023
+ if (!isHost) {
1024
+ const regRst = sharedFilePathReg.exec(chunk.fileName);
1025
+ if (regRst && shareName2Prop.get(removeNonRegLetter(regRst[1], NAME_CHAR_REG))?.generate === false) {
1026
+ needRemoveShared.add(key);
1027
+ }
1028
+ }
1029
+ }
1030
+ }
1031
+ if (needRemoveShared.size !== 0) {
1032
+ for (const key of needRemoveShared) {
1033
+ delete bundle[key];
1034
+ }
1035
+ }
1036
+ }
1037
+ };
1038
+ }
1039
+ function prodExposePlugin(options) {
1040
+ let moduleMap = "";
1041
+ const hasOptions = parsedOptions.prodExpose.some((expose) => {
1042
+ return expose[0] === parseExposeOptions(options)[0]?.[0];
1043
+ });
1044
+ if (!hasOptions) {
1045
+ parsedOptions.prodExpose = Array.prototype.concat(
1046
+ parsedOptions.prodExpose,
1047
+ parseExposeOptions(options)
1048
+ );
1049
+ }
1050
+ for (const item of parseExposeOptions(options)) {
1051
+ getModuleMarker(`\${${item[0]}}`, SHARED);
1052
+ const exposeFilepath = normalizePath(path.resolve(item[1].import));
1053
+ EXPOSES_MAP.set(item[0], exposeFilepath);
1054
+ EXPOSES_KEY_MAP.set(
1055
+ item[0],
1056
+ `__federation_expose_${removeNonRegLetter(item[0], NAME_CHAR_REG)}`
1057
+ );
1058
+ moduleMap += `
1059
+ "${item[0]}":()=>{
1060
+ ${DYNAMIC_LOADING_CSS}('${DYNAMIC_LOADING_CSS_PREFIX}${exposeFilepath}', ${item[1].dontAppendStylesToHead}, '${item[0]}')
1061
+ return __federation_import('\${__federation_expose_${item[0]}}').then(module =>Object.keys(module).every(item => exportSet.has(item)) ? () => module.default : () => module)},`;
1062
+ }
1063
+ return {
1064
+ name: "originjs:expose-production",
1065
+ virtualFile: {
1066
+ // code generated for remote
1067
+ // language=JS
1068
+ [`__remoteEntryHelper__${options.filename}`]: `
1069
+ const currentImports = {}
1070
+ const exportSet = new Set(['Module', '__esModule', 'default', '_export_sfc']);
1071
+ let moduleMap = {${moduleMap}}
1072
+ const seen = {}
1073
+ export const ${DYNAMIC_LOADING_CSS} = (cssFilePaths, dontAppendStylesToHead, exposeItemName) => {
1074
+ const metaUrl = import.meta.url;
1075
+ if (typeof metaUrl === 'undefined') {
1076
+ console.warn('The remote style takes effect only when the build.target option in the vite.config.ts file is higher than that of "es2020".');
1077
+ return;
1078
+ }
1079
+
1080
+ const curUrl = metaUrl.substring(0, metaUrl.lastIndexOf('${options.filename}'));
1081
+ const base = __VITE_BASE_PLACEHOLDER__;
1082
+ const assetsDir = __VITE_ASSETS_DIR_PLACEHOLDER__;
1083
+
1084
+ cssFilePaths.forEach(cssPath => {
1085
+ let href = '';
1086
+ const baseUrl = base || curUrl;
1087
+ if (baseUrl) {
1088
+ const trimmer = {
1089
+ trailing: (path) => (path.endsWith('/') ? path.slice(0, -1) : path),
1090
+ leading: (path) => (path.startsWith('/') ? path.slice(1) : path)
1091
+ }
1092
+ const isAbsoluteUrl = (url) => url.startsWith('http') || url.startsWith('//');
1093
+
1094
+ const cleanBaseUrl = trimmer.trailing(baseUrl).replace('.', '');
1095
+ const cleanAssetsDir = trimmer.leading(assetsDir);
1096
+ const cleanCssPath = trimmer.leading(cssPath);
1097
+ const cleanCurUrl = trimmer.trailing(curUrl);
1098
+
1099
+ if (isAbsoluteUrl(baseUrl)) {
1100
+ href = [cleanBaseUrl, cleanAssetsDir, cleanCssPath].filter(Boolean).join('/');
1101
+ } else {
1102
+ // 当remoteEntry.js和CSS都在assets目录下时,使用相对路径
1103
+ const remoteEntryInAssets = cleanCurUrl.endsWith('/assets/') || cleanCurUrl.endsWith('/assets');
1104
+
1105
+ if (remoteEntryInAssets) {
1106
+ // 都在assets目录下,直接使用CSS文件名
1107
+ href = [cleanCurUrl, cleanCssPath].filter(Boolean).join('/');
1108
+ } else if (cleanCurUrl.includes(cleanBaseUrl)) {
1109
+ href = [cleanCurUrl, cleanAssetsDir, cleanCssPath].filter(Boolean).join('/');
1110
+ } else {
1111
+ href = [cleanCurUrl + cleanBaseUrl, cleanAssetsDir, cleanCssPath].filter(Boolean).join('/');
1112
+ }
1113
+ }
1114
+ } else {
1115
+ href = cssPath;
1116
+ }
1117
+
1118
+ if (dontAppendStylesToHead) {
1119
+ const key = 'css__${options.name}__' + exposeItemName;
1120
+ window[key] = window[key] || [];
1121
+ window[key].push(href);
1122
+ return;
1123
+ }
1124
+
1125
+ if (href in seen) return;
1126
+ seen[href] = true;
1127
+
1128
+ const element = document.createElement('link');
1129
+ element.rel = 'stylesheet';
1130
+ element.href = href;
1131
+ document.head.appendChild(element);
1132
+ });
1133
+ };
1134
+ async function __federation_import(name) {
1135
+ currentImports[name] ??= import(name)
1136
+ return currentImports[name]
1137
+ };
1138
+ export const get =(module) => {
1139
+ if(!moduleMap[module]) throw new Error('Can not find remote module ' + module)
1140
+ return moduleMap[module]();
1141
+ };
1142
+ export const init =(shareScope) => {
1143
+ globalThis.__federation_shared__= globalThis.__federation_shared__|| {};
1144
+ Object.entries(shareScope).forEach(([key, value]) => {
1145
+ for (const [versionKey, versionValue] of Object.entries(value)) {
1146
+ const scope = versionValue.scope || 'default'
1147
+ globalThis.__federation_shared__[scope] = globalThis.__federation_shared__[scope] || {};
1148
+ const shared= globalThis.__federation_shared__[scope];
1149
+ (shared[key] = shared[key]||{})[versionKey] = versionValue;
1150
+ }
1151
+ });
1152
+ }`
1153
+ },
1154
+ configResolved(config) {
1155
+ if (config) {
1156
+ viteConfigResolved.config = config;
1157
+ }
1158
+ },
1159
+ buildStart() {
1160
+ if (parsedOptions.prodExpose.length > 0) {
1161
+ const assetsDir = builderInfo.assetsDir;
1162
+ this.emitFile({
1163
+ fileName: assetsDir ? `${assetsDir}/${options.filename}` : options.filename,
1164
+ type: "chunk",
1165
+ id: `__remoteEntryHelper__${options.filename}`,
1166
+ preserveSignature: "strict"
1167
+ });
1168
+ }
1169
+ },
1170
+ generateBundle(_options, bundle) {
1171
+ let remoteEntryChunk;
1172
+ for (const file in bundle) {
1173
+ const chunk = bundle[file];
1174
+ if (chunk?.facadeModuleId === `\0virtual:__remoteEntryHelper__${options.filename}`) {
1175
+ remoteEntryChunk = chunk;
1176
+ break;
1177
+ }
1178
+ }
1179
+ if (remoteEntryChunk) {
1180
+ remoteEntryChunk.code = remoteEntryChunk.code.replace(
1181
+ "__VITE_BASE_PLACEHOLDER__",
1182
+ `'${viteConfigResolved.config?.base || ""}'`
1183
+ ).replace(
1184
+ "__VITE_ASSETS_DIR_PLACEHOLDER__",
1185
+ `'${builderInfo.assetsDir || ""}'`
1186
+ );
1187
+ const filepathMap = /* @__PURE__ */ new Map();
1188
+ const getFilename = (name) => path.parse(path.parse(name).name).name;
1189
+ const cssBundlesMap = Object.keys(bundle).filter((name) => path.extname(name) === ".css").reduce((res, name) => {
1190
+ const filename = getFilename(name);
1191
+ res.set(filename, bundle[name]);
1192
+ return res;
1193
+ }, /* @__PURE__ */ new Map());
1194
+ remoteEntryChunk.code = remoteEntryChunk.code.replace(
1195
+ new RegExp(`(["'])${DYNAMIC_LOADING_CSS_PREFIX}.*?\\1`, "g"),
1196
+ (str) => {
1197
+ if (viteConfigResolved.config && !viteConfigResolved.config.build.cssCodeSplit) {
1198
+ if (cssBundlesMap.size) {
1199
+ return `[${[...cssBundlesMap.values()].map(
1200
+ (cssBundle) => JSON.stringify(path.basename(cssBundle.fileName))
1201
+ ).join(",")}]`;
1202
+ } else {
1203
+ return "[]";
1204
+ }
1205
+ }
1206
+ const filepath = str.slice(
1207
+ (`'` + DYNAMIC_LOADING_CSS_PREFIX).length,
1208
+ -1
1209
+ );
1210
+ if (!filepath || !filepath.length) return str;
1211
+ let fileBundle = filepathMap.get(filepath);
1212
+ if (!fileBundle) {
1213
+ fileBundle = Object.values(bundle).find(
1214
+ (b) => "facadeModuleId" in b && b.facadeModuleId === filepath
1215
+ );
1216
+ if (fileBundle) filepathMap.set(filepath, fileBundle);
1217
+ else return str;
1218
+ }
1219
+ const depCssFiles = /* @__PURE__ */ new Set();
1220
+ const addDepCss = (bundleName) => {
1221
+ const theBundle = bundle[bundleName];
1222
+ if (theBundle && theBundle.viteMetadata) {
1223
+ for (const cssFileName of theBundle.viteMetadata.importedCss.values()) {
1224
+ const cssBundle = cssBundlesMap.get(getFilename(cssFileName));
1225
+ if (cssBundle) {
1226
+ depCssFiles.add(cssBundle.fileName);
1227
+ }
1228
+ }
1229
+ }
1230
+ if (theBundle && theBundle.imports && theBundle.imports.length) {
1231
+ theBundle.imports.forEach((name) => addDepCss(name));
1232
+ }
1233
+ };
1234
+ [fileBundle.fileName, ...fileBundle.imports].forEach(addDepCss);
1235
+ return `[${[...depCssFiles].map((d) => JSON.stringify(path.basename(d))).join(",")}]`;
1236
+ }
1237
+ );
1238
+ for (const expose of parseExposeOptions(options)) {
1239
+ const module2 = Object.keys(bundle).find((module22) => {
1240
+ const chunk = bundle[module22];
1241
+ return chunk.name === EXPOSES_KEY_MAP.get(expose[0]);
1242
+ });
1243
+ if (module2) {
1244
+ const chunk = bundle[module2];
1245
+ const fileRelativePath = path.relative(
1246
+ path.dirname(remoteEntryChunk.fileName),
1247
+ chunk.fileName
1248
+ );
1249
+ const slashPath = fileRelativePath.replace(/\\/g, "/");
1250
+ remoteEntryChunk.code = remoteEntryChunk.code.replace(
1251
+ `\${__federation_expose_${expose[0]}}`,
1252
+ viteConfigResolved.config?.base?.replace(/\/+$/, "") ? [
1253
+ viteConfigResolved.config.base.replace(/\/+$/, ""),
1254
+ slashPath
1255
+ ].filter(Boolean).join("/") : `./${slashPath}`
1256
+ );
1257
+ }
1258
+ }
1259
+ let ast = null;
1260
+ try {
1261
+ ast = this.parse(remoteEntryChunk.code);
1262
+ } catch (err) {
1263
+ console.error(err);
1264
+ }
1265
+ if (!ast) {
1266
+ return;
1267
+ }
1268
+ const magicString = new MagicString(remoteEntryChunk.code);
1269
+ estreeWalker.walk(ast, {
1270
+ enter(node) {
1271
+ if (node && node.type === "CallExpression" && typeof node.arguments[0]?.value === "string" && node.arguments[0]?.value.indexOf(
1272
+ `${DYNAMIC_LOADING_CSS_PREFIX}`
1273
+ ) > -1) {
1274
+ magicString.remove(node.start, node.end + 1);
1275
+ }
1276
+ }
1277
+ });
1278
+ remoteEntryChunk.code = magicString.toString();
1279
+ }
1280
+ }
1281
+ };
1282
+ }
1283
+ function devSharedPlugin(options) {
1284
+ parsedOptions.devShared = parseSharedOptions(options);
1285
+ return {
1286
+ name: "originjs:shared-development"
1287
+ };
1288
+ }
1289
+ function devRemotePlugin(options) {
1290
+ parsedOptions.devRemote = parseRemoteOptions(options);
1291
+ for (const item of parsedOptions.devRemote) {
1292
+ devRemotes.push({
1293
+ id: item[0],
1294
+ regexp: new RegExp(`^${item[0]}/.+?`),
1295
+ config: item[1]
1296
+ });
1297
+ }
1298
+ const needHandleFileType = [
1299
+ ".js",
1300
+ ".ts",
1301
+ ".jsx",
1302
+ ".tsx",
1303
+ ".mjs",
1304
+ ".cjs",
1305
+ ".vue",
1306
+ ".svelte"
1307
+ ];
1308
+ options.transformFileTypes = (options.transformFileTypes ?? []).concat(needHandleFileType).map((item) => item.toLowerCase());
1309
+ const transformFileTypeSet = new Set(options.transformFileTypes);
1310
+ let viteDevServer;
1311
+ return {
1312
+ name: "originjs:remote-development",
1313
+ virtualFile: options.remotes || options.enableDynamicRemotes ? {
1314
+ __federation__: `
1315
+ ${createRemotesMap(devRemotes)}
1316
+ const loadJS = async (url, fn) => {
1317
+ const resolvedUrl = typeof url === 'function' ? await url() : url;
1318
+ const script = document.createElement('script')
1319
+ script.type = 'text/javascript';
1320
+ script.onload = fn;
1321
+ script.src = resolvedUrl;
1322
+ document.getElementsByTagName('head')[0].appendChild(script);
1323
+ }
1324
+ function get(name, ${REMOTE_FROM_PARAMETER}){
1325
+ return import(/* @vite-ignore */ name).then(module => ()=> {
1326
+ if (${REMOTE_FROM_PARAMETER} === 'webpack') {
1327
+ return Object.prototype.toString.call(module).indexOf('Module') > -1 && module.default ? module.default : module
1328
+ }
1329
+ return module
1330
+ })
1331
+ }
1332
+ const wrapShareScope = ${REMOTE_FROM_PARAMETER} => {
1333
+ return {
1334
+ ${getModuleMarker("shareScope")}
1335
+ }
1336
+ }
1337
+
1338
+ const initMap = Object.create(null);
1339
+ async function __federation_method_ensure(remoteId) {
1340
+ const remote = remotesMap[remoteId];
1341
+ if (!remote.inited) {
1342
+ if ('var' === remote.format) {
1343
+ // loading js with script tag
1344
+ return new Promise(resolve => {
1345
+ const callback = () => {
1346
+ if (!remote.inited) {
1347
+ remote.lib = window[remoteId];
1348
+ remote.lib.init(wrapShareScope(remote.from))
1349
+ remote.inited = true;
1350
+ }
1351
+ resolve(remote.lib);
1352
+ }
1353
+ return loadJS(remote.url, callback);
1354
+ });
1355
+ } else if (['esm', 'systemjs'].includes(remote.format)) {
1356
+ // loading js with import(...)
1357
+ return new Promise((resolve, reject) => {
1358
+ const getUrl = typeof remote.url === 'function' ? remote.url : () => Promise.resolve(remote.url);
1359
+ getUrl().then(url => {
1360
+ import(/* @vite-ignore */ url).then(lib => {
1361
+ if (!remote.inited) {
1362
+ const shareScope = wrapShareScope(remote.from)
1363
+ lib.init(shareScope);
1364
+ remote.lib = lib;
1365
+ remote.lib.init(shareScope);
1366
+ remote.inited = true;
1367
+ }
1368
+ resolve(remote.lib);
1369
+ }).catch(reject)
1370
+ })
1371
+ })
1372
+ }
1373
+ } else {
1374
+ return remote.lib;
1375
+ }
1376
+ }
1377
+
1378
+ function __federation_method_unwrapDefault(module) {
1379
+ return (module?.__esModule || module?.[Symbol.toStringTag] === 'Module')?module.default:module
1380
+ }
1381
+
1382
+ function __federation_method_wrapDefault(module ,need){
1383
+ if (!module?.default && need) {
1384
+ let obj = Object.create(null);
1385
+ obj.default = module;
1386
+ obj.__esModule = true;
1387
+ return obj;
1388
+ }
1389
+ return module;
1390
+ }
1391
+
1392
+ function __federation_method_getRemote(remoteName, componentName){
1393
+ return __federation_method_ensure(remoteName).then((remote) => remote.get(componentName).then(factory => factory()));
1394
+ }
1395
+
1396
+ function __federation_method_setRemote(remoteName, remoteConfig) {
1397
+ remotesMap[remoteName] = remoteConfig;
1398
+ }
1399
+
1400
+ async function __federation_method_add_origin_setRemote(remoteName, remoteUrl, options) {
1401
+ const _options = options || {}
1402
+ const _item = {
1403
+ external: Array.isArray(_options.external) ? _options.external : [_options.external],
1404
+ shareScope: _options.shareScope || 'default',
1405
+ format: _options.format || 'esm',
1406
+ from: _options.from ?? 'vite',
1407
+ externalType: _options.externalType || 'url'
1408
+ }
1409
+
1410
+ __federation_method_setRemote(remoteName, {
1411
+ url: remoteUrl,
1412
+ format: _item.format,
1413
+ from: _item.from
1414
+ })
1415
+ }
1416
+
1417
+ export {__federation_method_ensure, __federation_method_getRemote , __federation_method_setRemote , __federation_method_unwrapDefault , __federation_method_wrapDefault, __federation_method_add_origin_setRemote}
1418
+ ;`
1419
+ } : { __federation__: "" },
1420
+ config(config) {
1421
+ if (parsedOptions.devRemote.length) {
1422
+ const excludeRemotes = [];
1423
+ parsedOptions.devRemote.forEach((item) => excludeRemotes.push(item[0]));
1424
+ let optimizeDeps = config.optimizeDeps;
1425
+ if (!optimizeDeps) {
1426
+ optimizeDeps = config.optimizeDeps = {};
1427
+ }
1428
+ if (!optimizeDeps.exclude) {
1429
+ optimizeDeps.exclude = [];
1430
+ }
1431
+ optimizeDeps.exclude = optimizeDeps.exclude.concat(excludeRemotes);
1432
+ }
1433
+ },
1434
+ configureServer(server) {
1435
+ viteDevServer = server;
1436
+ },
1437
+ async transform(code, id) {
1438
+ if (builderInfo.isHost && !builderInfo.isRemote) {
1439
+ for (const arr of parsedOptions.devShared) {
1440
+ if (!arr[1].version && !arr[1].manuallyPackagePathSetting) {
1441
+ const packageJsonPath = (await this.resolve(`${arr[0]}/package.json`))?.id;
1442
+ if (!packageJsonPath) {
1443
+ this.error(
1444
+ `No description file or no version in description file (usually package.json) of ${arr[0]}(${packageJsonPath}). Add version to description file, or manually specify version in shared config.`
1445
+ );
1446
+ } else {
1447
+ const json = JSON.parse(
1448
+ fs.readFileSync(packageJsonPath, { encoding: "utf-8" })
1449
+ );
1450
+ arr[1].version = json.version;
1451
+ }
1452
+ }
1453
+ }
1454
+ }
1455
+ if (id === "\0virtual:__federation__") {
1456
+ const scopeCode = await devSharedScopeCode.call(
1457
+ this,
1458
+ parsedOptions.devShared
1459
+ );
1460
+ return code.replace(getModuleMarker("shareScope"), scopeCode.join(","));
1461
+ }
1462
+ const fileExtname = getFileExtname(id);
1463
+ if (!transformFileTypeSet.has((fileExtname ?? "").toLowerCase())) {
1464
+ return;
1465
+ }
1466
+ let ast = null;
1467
+ try {
1468
+ ast = this.parse(code);
1469
+ } catch (err) {
1470
+ console.error(err);
1471
+ }
1472
+ if (!ast) {
1473
+ return null;
1474
+ }
1475
+ const magicString = new MagicString(code);
1476
+ const hasStaticImported = /* @__PURE__ */ new Map();
1477
+ let requiresRuntime = false;
1478
+ let manualRequired = null;
1479
+ estreeWalker.walk(ast, {
1480
+ enter(node) {
1481
+ if (node.type === "ImportDeclaration" && node.source?.value === "virtual:__federation__") {
1482
+ manualRequired = node;
1483
+ }
1484
+ if ((node.type === "ImportExpression" || node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration") && node.source?.value?.indexOf("/") > -1) {
1485
+ const moduleId = node.source.value;
1486
+ const remote = devRemotes.find((r) => r.regexp.test(moduleId));
1487
+ const needWrap = remote?.config.from === "vite";
1488
+ if (remote) {
1489
+ requiresRuntime = true;
1490
+ const modName = `.${moduleId.slice(remote.id.length)}`;
1491
+ switch (node.type) {
1492
+ case "ImportExpression": {
1493
+ magicString.overwrite(
1494
+ node.start,
1495
+ node.end,
1496
+ `__federation_method_getRemote(${JSON.stringify(
1497
+ remote.id
1498
+ )} , ${JSON.stringify(
1499
+ modName
1500
+ )}).then(module=>__federation_method_wrapDefault(module, ${needWrap}))`
1501
+ );
1502
+ break;
1503
+ }
1504
+ case "ImportDeclaration": {
1505
+ if (node.specifiers?.length) {
1506
+ const afterImportName = `__federation_var_${moduleId.replace(
1507
+ /[@/\\.-]/g,
1508
+ ""
1509
+ )}`;
1510
+ if (!hasStaticImported.has(moduleId)) {
1511
+ magicString.overwrite(
1512
+ node.start,
1513
+ node.end,
1514
+ `const ${afterImportName} = await __federation_method_getRemote(${JSON.stringify(
1515
+ remote.id
1516
+ )} , ${JSON.stringify(modName)});`
1517
+ );
1518
+ hasStaticImported.set(moduleId, afterImportName);
1519
+ }
1520
+ let deconstructStr = "";
1521
+ node.specifiers.forEach((spec) => {
1522
+ if (spec.type === "ImportDefaultSpecifier") {
1523
+ magicString.appendRight(
1524
+ node.end,
1525
+ `
1526
+ let ${spec.local.name} = __federation_method_unwrapDefault(${afterImportName}) `
1527
+ );
1528
+ } else if (spec.type === "ImportSpecifier") {
1529
+ const importedName = spec.imported.name;
1530
+ const localName = spec.local.name;
1531
+ deconstructStr += `${importedName === localName ? localName : `${importedName} : ${localName}`},`;
1532
+ } else if (spec.type === "ImportNamespaceSpecifier") {
1533
+ magicString.appendRight(
1534
+ node.end,
1535
+ `let {${spec.local.name}} = ${afterImportName}`
1536
+ );
1537
+ }
1538
+ });
1539
+ if (deconstructStr.length > 0) {
1540
+ magicString.appendRight(
1541
+ node.end,
1542
+ `
1543
+ let {${deconstructStr.slice(
1544
+ 0,
1545
+ -1
1546
+ )}} = ${afterImportName}`
1547
+ );
1548
+ }
1549
+ }
1550
+ break;
1551
+ }
1552
+ case "ExportNamedDeclaration": {
1553
+ const afterImportName = `__federation_var_${moduleId.replace(
1554
+ /[@/\\.-]/g,
1555
+ ""
1556
+ )}`;
1557
+ if (!hasStaticImported.has(moduleId)) {
1558
+ hasStaticImported.set(moduleId, afterImportName);
1559
+ magicString.overwrite(
1560
+ node.start,
1561
+ node.end,
1562
+ `const ${afterImportName} = await __federation_method_getRemote(${JSON.stringify(
1563
+ remote.id
1564
+ )} , ${JSON.stringify(modName)});`
1565
+ );
1566
+ }
1567
+ if (node.specifiers.length > 0) {
1568
+ const specifiers = node.specifiers;
1569
+ let exportContent = "";
1570
+ let deconstructContent = "";
1571
+ specifiers.forEach((spec) => {
1572
+ const localName = spec.local.name;
1573
+ const exportName = spec.exported.name;
1574
+ const variableName = `${afterImportName}_${localName}`;
1575
+ deconstructContent = deconstructContent.concat(
1576
+ `${localName}:${variableName},`
1577
+ );
1578
+ exportContent = exportContent.concat(
1579
+ `${variableName} as ${exportName},`
1580
+ );
1581
+ });
1582
+ magicString.append(
1583
+ `
1584
+ const {${deconstructContent.slice(
1585
+ 0,
1586
+ deconstructContent.length - 1
1587
+ )}} = ${afterImportName};
1588
+ `
1589
+ );
1590
+ magicString.append(
1591
+ `
1592
+ export {${exportContent.slice(
1593
+ 0,
1594
+ exportContent.length - 1
1595
+ )}}; `
1596
+ );
1597
+ }
1598
+ break;
1599
+ }
1600
+ }
1601
+ }
1602
+ }
1603
+ }
1604
+ });
1605
+ if (requiresRuntime) {
1606
+ let requiresCode = `import {__federation_method_ensure, __federation_method_getRemote , __federation_method_wrapDefault , __federation_method_unwrapDefault, __federation_method_add_origin_setRemote} from '__federation__';
1607
+
1608
+ `;
1609
+ if (manualRequired) {
1610
+ requiresCode = `import {__federation_method_setRemote, __federation_method_ensure, __federation_method_getRemote , __federation_method_wrapDefault , __federation_method_unwrapDefault, __federation_method_add_origin_setRemote} from '__federation__';
1611
+
1612
+ `;
1613
+ magicString.overwrite(manualRequired.start, manualRequired.end, ``);
1614
+ }
1615
+ magicString.prepend(requiresCode);
1616
+ }
1617
+ return magicString.toString();
1618
+ }
1619
+ };
1620
+ async function devSharedScopeCode(shared) {
1621
+ const res = [];
1622
+ if (shared.length) {
1623
+ const serverConfiguration = viteDevServer.config.server;
1624
+ const base = viteDevServer.config.base;
1625
+ const cwdPath = normalizePath(process.cwd());
1626
+ for (const item of shared) {
1627
+ const moduleInfo = await this.resolve(item[1].packagePath, void 0, {
1628
+ skipSelf: true
1629
+ });
1630
+ if (!moduleInfo) continue;
1631
+ const moduleFilePath = normalizePath(moduleInfo.id);
1632
+ const idx = moduleFilePath.indexOf(cwdPath);
1633
+ const relativePath = idx === 0 ? path.posix.join(base, moduleFilePath.slice(cwdPath.length)) : null;
1634
+ const sharedName = item[0];
1635
+ const obj = item[1];
1636
+ let str = "";
1637
+ if (typeof obj === "object") {
1638
+ const origin = serverConfiguration.origin;
1639
+ const pathname = relativePath ?? `/@fs/${moduleInfo.id}`;
1640
+ const url = origin ? `'${origin}${pathname}'` : `window.location.origin+'${pathname}'`;
1641
+ str += `get:()=> get(${url}, ${REMOTE_FROM_PARAMETER})`;
1642
+ res.push(`'${sharedName}':{'${obj.version}':{${str}}}`);
1643
+ }
1644
+ }
1645
+ }
1646
+ return res;
1647
+ }
1648
+ }
1649
+ function devExposePlugin(options) {
1650
+ parsedOptions.devExpose = parseExposeOptions(options);
1651
+ return {
1652
+ name: "originjs:expose-development"
1653
+ };
1654
+ }
1655
+ function isVueAvailable() {
1656
+ try {
1657
+ return typeof ref !== "undefined" && typeof onMounted !== "undefined";
1658
+ } catch {
1659
+ return false;
1660
+ }
1661
+ }
1662
+ let ref, onMounted, readonly;
1663
+ if (isVueAvailable()) {
1664
+ try {
1665
+ import("vue").then((vue) => {
1666
+ ref = vue.ref;
1667
+ onMounted = vue.onMounted;
1668
+ readonly = vue.readonly;
1669
+ }).catch(() => {
1670
+ console.warn("Vue not available for dynamic import");
1671
+ });
1672
+ } catch {
1673
+ }
1674
+ }
1675
+ const normalizeAssetsDir = (config) => {
1676
+ const configured = config?.build?.assetsDir ?? "assets";
1677
+ if (!configured) return "";
1678
+ if (!path.isAbsolute(configured)) return configured;
1679
+ const root = config?.root ? path.resolve(config.root) : process.cwd();
1680
+ const resolvedOutDir = config?.build?.outDir ? path.isAbsolute(config.build.outDir) ? config.build.outDir : path.resolve(root, config.build.outDir) : path.resolve(root, "dist");
1681
+ const normalized = path.relative(resolvedOutDir, configured).replace(/\\/g, "/");
1682
+ return normalized.startsWith("..") ? "" : normalized || "assets";
1683
+ };
1684
+ function federation(options) {
1685
+ options.filename = options.filename ? options.filename : DEFAULT_ENTRY_FILENAME;
1686
+ let pluginList = [];
1687
+ let virtualMod;
1688
+ let registerCount = 0;
1689
+ function registerPlugins(mode, command) {
1690
+ if (mode === "production" || command === "build") {
1691
+ pluginList = [
1692
+ prodSharedPlugin(options),
1693
+ prodExposePlugin(options),
1694
+ prodRemotePlugin(options)
1695
+ ];
1696
+ } else if (mode === "development" || command === "serve") {
1697
+ pluginList = [
1698
+ devSharedPlugin(options),
1699
+ devExposePlugin(options),
1700
+ devRemotePlugin(options)
1701
+ ];
1702
+ } else {
1703
+ pluginList = [];
1704
+ }
1705
+ builderInfo.isHost = options.isHost || !!(parsedOptions.prodRemote.length || parsedOptions.devRemote.length);
1706
+ builderInfo.isRemote = !!(parsedOptions.prodExpose.length || parsedOptions.devExpose.length);
1707
+ builderInfo.isShared = !!(parsedOptions.prodShared.length || parsedOptions.devShared.length);
1708
+ let virtualFiles = {};
1709
+ pluginList.forEach((plugin) => {
1710
+ if (plugin.virtualFile) {
1711
+ virtualFiles = Object.assign(virtualFiles, plugin.virtualFile);
1712
+ }
1713
+ });
1714
+ virtualMod = virtual(virtualFiles);
1715
+ }
1716
+ return {
1717
+ name: "originjs:federation",
1718
+ // for scenario vite.config.js build.cssCodeSplit: false
1719
+ // vite:css-post plugin will summarize all the styles in the style.xxxxxx.css file
1720
+ // so, this plugin need run after vite:css-post in post plugin list
1721
+ enforce: "post",
1722
+ // apply:'build',
1723
+ options(_options) {
1724
+ if (!registerCount++) {
1725
+ registerPlugins(options.mode = options.mode ?? "production", "");
1726
+ }
1727
+ if (typeof _options.input === "string") {
1728
+ _options.input = { index: _options.input };
1729
+ }
1730
+ _options.external = _options.external || [];
1731
+ if (!Array.isArray(_options.external)) {
1732
+ _options.external = [_options.external];
1733
+ }
1734
+ for (const pluginHook of pluginList) {
1735
+ pluginHook.options?.call(this, _options);
1736
+ }
1737
+ return _options;
1738
+ },
1739
+ config(config, env) {
1740
+ options.mode = options.mode ?? env.mode;
1741
+ registerPlugins(options.mode, env.command);
1742
+ registerCount++;
1743
+ for (const pluginHook of pluginList) {
1744
+ pluginHook.config?.call(this, config, env);
1745
+ }
1746
+ builderInfo.builder = "vite";
1747
+ builderInfo.assetsDir = normalizeAssetsDir(config) ?? "assets";
1748
+ },
1749
+ configureServer(server) {
1750
+ for (const pluginHook of pluginList) {
1751
+ pluginHook.configureServer?.call(this, server);
1752
+ }
1753
+ },
1754
+ configResolved(config) {
1755
+ for (const pluginHook of pluginList) {
1756
+ pluginHook.configResolved?.call(this, config);
1757
+ }
1758
+ },
1759
+ buildStart(inputOptions) {
1760
+ for (const pluginHook of pluginList) {
1761
+ pluginHook.buildStart?.call(this, inputOptions);
1762
+ }
1763
+ },
1764
+ async resolveId(...args) {
1765
+ const v = virtualMod.resolveId.call(this, ...args);
1766
+ if (v) {
1767
+ return v;
1768
+ }
1769
+ if (args[0] === "\0virtual:__federation_fn_import") {
1770
+ return {
1771
+ id: "\0virtual:__federation_fn_import",
1772
+ moduleSideEffects: true
1773
+ };
1774
+ }
1775
+ if (args[0] === "__federation_fn_satisfy") {
1776
+ const federationId = (await this.resolve("@meethive/vite"))?.id;
1777
+ if (federationId) {
1778
+ return await this.resolve(`${path.dirname(federationId)}/satisfy.mjs`);
1779
+ }
1780
+ return null;
1781
+ }
1782
+ if (args[0] === "virtual:__federation__") {
1783
+ return {
1784
+ id: "\0virtual:__federation__",
1785
+ moduleSideEffects: true
1786
+ };
1787
+ }
1788
+ return null;
1789
+ },
1790
+ load(...args) {
1791
+ const v = virtualMod.load.call(this, ...args);
1792
+ if (v) {
1793
+ return v;
1794
+ }
1795
+ return null;
1796
+ },
1797
+ transform(code, id) {
1798
+ for (const pluginHook of pluginList) {
1799
+ const result = pluginHook.transform?.call(this, code, id);
1800
+ if (result) {
1801
+ return result;
1802
+ }
1803
+ }
1804
+ return code;
1805
+ },
1806
+ moduleParsed(moduleInfo) {
1807
+ for (const pluginHook of pluginList) {
1808
+ pluginHook.moduleParsed?.call(this, moduleInfo);
1809
+ }
1810
+ },
1811
+ outputOptions(outputOptions) {
1812
+ for (const pluginHook of pluginList) {
1813
+ pluginHook.outputOptions?.call(this, outputOptions);
1814
+ }
1815
+ return outputOptions;
1816
+ },
1817
+ renderChunk(code, chunkInfo, _options) {
1818
+ for (const pluginHook of pluginList) {
1819
+ const result = pluginHook.renderChunk?.call(
1820
+ this,
1821
+ code,
1822
+ chunkInfo,
1823
+ _options
1824
+ );
1825
+ if (result) {
1826
+ return result;
1827
+ }
1828
+ }
1829
+ return null;
1830
+ },
1831
+ generateBundle: function(_options, bundle, isWrite) {
1832
+ for (const pluginHook of pluginList) {
1833
+ pluginHook.generateBundle?.call(this, _options, bundle, isWrite);
1834
+ }
1835
+ }
1836
+ };
1837
+ }
1838
+ const languageWorkAttr = [
1839
+ {
1840
+ label: "editorWorkerService",
1841
+ entry: "monaco-editor/esm/vs/editor/editor.worker"
1842
+ },
1843
+ {
1844
+ label: "css",
1845
+ entry: "monaco-editor/esm/vs/language/css/css.worker"
1846
+ },
1847
+ {
1848
+ label: "html",
1849
+ entry: "monaco-editor/esm/vs/language/html/html.worker"
1850
+ },
1851
+ {
1852
+ label: "json",
1853
+ entry: "monaco-editor/esm/vs/language/json/json.worker"
1854
+ },
1855
+ {
1856
+ label: "typescript",
1857
+ entry: "monaco-editor/esm/vs/language/typescript/ts.worker"
1858
+ }
1859
+ ];
1860
+ const languageWorksByLabel = {};
1861
+ languageWorkAttr.forEach(
1862
+ (languageWork) => languageWorksByLabel[languageWork.label] = languageWork
1863
+ );
1864
+ function getFilenameByEntry(entry) {
1865
+ entry = path.basename(entry, "js");
1866
+ return entry + ".bundle.js";
1867
+ }
1868
+ const cacheDir = "node_modules/.monaco/";
1869
+ function getWorkPath(works, options, config) {
1870
+ const workerPaths = {};
1871
+ for (const work of works) {
1872
+ if (isCDN(options.publicPath)) {
1873
+ workerPaths[work.label] = options.publicPath + "/" + getFilenameByEntry(work.entry);
1874
+ } else {
1875
+ workerPaths[work.label] = config.base + options.publicPath + "/" + getFilenameByEntry(work.entry);
1876
+ }
1877
+ }
1878
+ if (workerPaths["typescript"]) {
1879
+ workerPaths["javascript"] = workerPaths["typescript"];
1880
+ }
1881
+ if (workerPaths["css"]) {
1882
+ workerPaths["less"] = workerPaths["css"];
1883
+ workerPaths["scss"] = workerPaths["css"];
1884
+ }
1885
+ if (workerPaths["html"]) {
1886
+ workerPaths["handlebars"] = workerPaths["html"];
1887
+ workerPaths["razor"] = workerPaths["html"];
1888
+ }
1889
+ return workerPaths;
1890
+ }
1891
+ function workerMiddleware(middlewares, config, options) {
1892
+ const works = getWorks(options);
1893
+ if (fs.existsSync(cacheDir)) {
1894
+ fs.rmSync(cacheDir, { recursive: true, force: true });
1895
+ }
1896
+ for (const work of works) {
1897
+ middlewares.use(
1898
+ config.base + options.publicPath + "/" + getFilenameByEntry(work.entry),
1899
+ function(req, res, next) {
1900
+ if (!fs.existsSync(cacheDir + getFilenameByEntry(work.entry))) {
1901
+ esbuild.buildSync({
1902
+ entryPoints: [resolveMonacoPath(work.entry)],
1903
+ bundle: true,
1904
+ outfile: cacheDir + getFilenameByEntry(work.entry)
1905
+ });
1906
+ }
1907
+ const contentBuffer = fs.readFileSync(cacheDir + getFilenameByEntry(work.entry));
1908
+ res.setHeader("Content-Type", "text/javascript");
1909
+ res.end(contentBuffer);
1910
+ }
1911
+ );
1912
+ }
1913
+ }
1914
+ function resolveMonacoPath(filePath) {
1915
+ try {
1916
+ return path.resolve(path.join(process.cwd(), "node_modules", filePath));
1917
+ } catch (err) {
1918
+ return path.resolve(filePath);
1919
+ }
1920
+ }
1921
+ function getWorks(options) {
1922
+ let works = options.languageWorkers.map(
1923
+ (work) => languageWorksByLabel[work]
1924
+ );
1925
+ works.push(...options.customWorkers);
1926
+ return works;
1927
+ }
1928
+ const getFS = async () => {
1929
+ if (typeof process !== "undefined" && process.versions?.node) {
1930
+ const fs2 = await import("fs");
1931
+ return {
1932
+ existsSync: fs2.existsSync,
1933
+ mkdirSync: fs2.mkdirSync,
1934
+ readFileSync: fs2.readFileSync,
1935
+ writeFileSync: fs2.writeFileSync
1936
+ };
1937
+ }
1938
+ return null;
1939
+ };
1940
+ function monacoEditorPlugin(options) {
1941
+ const languageWorkers = options.languageWorkers || Object.keys(languageWorksByLabel);
1942
+ const publicPath = options.publicPath || "monacoeditorwork";
1943
+ const globalAPI = options.globalAPI || false;
1944
+ const customWorkers = options.customWorkers || [];
1945
+ const forceBuildCDN = options.forceBuildCDN || false;
1946
+ options = {
1947
+ ...options,
1948
+ languageWorkers,
1949
+ publicPath,
1950
+ globalAPI,
1951
+ customWorkers,
1952
+ forceBuildCDN
1953
+ };
1954
+ let resolvedConfig;
1955
+ return {
1956
+ name: "vite-plugin-monaco-editor",
1957
+ configResolved(getResolvedConfig) {
1958
+ resolvedConfig = getResolvedConfig;
1959
+ },
1960
+ configureServer(server) {
1961
+ if (isCDN(publicPath)) {
1962
+ return;
1963
+ }
1964
+ workerMiddleware(server.middlewares, resolvedConfig, options);
1965
+ },
1966
+ transformIndexHtml(html) {
1967
+ const works = getWorks(options);
1968
+ const workerPaths = getWorkPath(works, options, resolvedConfig);
1969
+ const globals = {
1970
+ MonacoEnvironment: `(function (paths) {
1971
+ return {
1972
+ globalAPI: ${globalAPI},
1973
+ getWorkerUrl : function (moduleId, label) {
1974
+ var result = paths[label];
1975
+ var _location = window.__MICRO_APP_ENVIRONMENT__ ? window.rawWindow.location : window.location;
1976
+ var currentUrl = String(_location);
1977
+ var currentOrigin = currentUrl.substr(0, currentUrl.length - _location.hash.length - _location.search.length - _location.pathname.length);
1978
+
1979
+ if (window.__MICRO_APP_ENVIRONMENT__) {
1980
+ result = currentOrigin + result.replace('./', '/')
1981
+ }
1982
+
1983
+ if (/^((http:)|(https:)|(file:)|(\\/\\/))/.test(result)) {
1984
+ if (result.substring(0, currentOrigin.length) !== currentOrigin) {
1985
+ var js = '/*' + label + '*/importScripts("' + result + '");';
1986
+ var blob = new Blob([js], { type: 'application/javascript' });
1987
+ return URL.createObjectURL(blob);
1988
+ }
1989
+ }
1990
+ console.log('result',result);
1991
+ return result;
1992
+ }
1993
+ };
1994
+ })(${JSON.stringify(workerPaths, null, 2)})`
1995
+ };
1996
+ const descriptor = [
1997
+ {
1998
+ tag: "script",
1999
+ children: Object.keys(globals).map((key) => `self[${JSON.stringify(key)}] = ${globals[key]};`).join("\n"),
2000
+ injectTo: "head-prepend"
2001
+ }
2002
+ ];
2003
+ return descriptor;
2004
+ },
2005
+ async writeBundle() {
2006
+ if (isCDN(publicPath) && !forceBuildCDN) {
2007
+ return;
2008
+ }
2009
+ const fs2 = await getFS();
2010
+ if (!fs2) {
2011
+ this.warn("File system operations not available in this environment");
2012
+ return;
2013
+ }
2014
+ const works = getWorks(options);
2015
+ const distPath = options.customDistPath ? options.customDistPath(
2016
+ resolvedConfig.root,
2017
+ resolvedConfig.build.outDir,
2018
+ resolvedConfig.base
2019
+ ) : path.join(
2020
+ resolvedConfig.root,
2021
+ resolvedConfig.build.outDir,
2022
+ resolvedConfig.base,
2023
+ options.publicPath
2024
+ );
2025
+ if (!fs2.existsSync(distPath)) {
2026
+ fs2.mkdirSync(distPath, {
2027
+ recursive: true
2028
+ });
2029
+ }
2030
+ for (const work of works) {
2031
+ if (!fs2.existsSync(cacheDir + getFilenameByEntry(work.entry))) {
2032
+ esbuild.buildSync({
2033
+ entryPoints: [resolveMonacoPath(work.entry)],
2034
+ bundle: true,
2035
+ outfile: cacheDir + getFilenameByEntry(work.entry)
2036
+ });
2037
+ }
2038
+ const contentBuffer = fs2.readFileSync(cacheDir + getFilenameByEntry(work.entry));
2039
+ const workDistPath = path.resolve(distPath, getFilenameByEntry(work.entry));
2040
+ fs2.writeFileSync(workDistPath, contentBuffer);
2041
+ }
2042
+ }
2043
+ };
2044
+ }
2045
+ function isCDN(publicPath) {
2046
+ if (/^((http:)|(https:)|(file:)|(\/\/))/.test(publicPath)) {
2047
+ return true;
2048
+ }
2049
+ return false;
2050
+ }
2051
+ function matches(filename, patterns) {
2052
+ if (!patterns || patterns.length === 0) return true;
2053
+ return patterns.some(
2054
+ (p) => typeof p === "string" ? filename.includes(p) : p.test(filename)
2055
+ );
2056
+ }
2057
+ function sharpOptimize(options = {}) {
2058
+ const {
2059
+ include,
2060
+ exclude,
2061
+ jpegQuality = 75,
2062
+ pngQuality = 75,
2063
+ webpQuality = 75,
2064
+ avifQuality = 50
2065
+ } = options;
2066
+ let _sharp = null;
2067
+ const getSharp = async () => {
2068
+ if (!_sharp) {
2069
+ const sharpModule = await import("sharp");
2070
+ _sharp = sharpModule.default ?? sharpModule;
2071
+ }
2072
+ return _sharp;
2073
+ };
2074
+ const imageExts = /* @__PURE__ */ new Set([".png", ".jpg", ".jpeg", ".webp", ".avif"]);
2075
+ return {
2076
+ name: "jetlinks-sharp-optimize",
2077
+ apply: "build",
2078
+ enforce: "post",
2079
+ async generateBundle(_opts, bundle) {
2080
+ for (const [fileName, asset] of Object.entries(bundle)) {
2081
+ if (asset.type !== "asset") continue;
2082
+ const ext = path$1.extname(fileName).toLowerCase();
2083
+ if (!imageExts.has(ext)) continue;
2084
+ if (exclude && matches(fileName, exclude)) continue;
2085
+ if (include && !matches(fileName, include)) continue;
2086
+ try {
2087
+ const sourceBuffer = Buffer.isBuffer(asset.source) ? asset.source : Buffer.from(String(asset.source));
2088
+ const sharp = await getSharp();
2089
+ let instance = sharp(sourceBuffer);
2090
+ switch (ext) {
2091
+ case ".jpg":
2092
+ case ".jpeg":
2093
+ instance = instance.jpeg({ quality: jpegQuality, mozjpeg: true });
2094
+ break;
2095
+ case ".png":
2096
+ instance = instance.png({ quality: pngQuality, compressionLevel: 9 });
2097
+ break;
2098
+ case ".webp":
2099
+ instance = instance.webp({ quality: webpQuality });
2100
+ break;
2101
+ case ".avif":
2102
+ instance = instance.avif({ quality: avifQuality });
2103
+ break;
2104
+ default:
2105
+ break;
2106
+ }
2107
+ const optimized = await instance.toBuffer();
2108
+ asset.source = optimized;
2109
+ } catch (err) {
2110
+ this.warn(`sharp optimize failed for ${fileName}: ${String(err)}`);
2111
+ }
2112
+ }
2113
+ }
2114
+ };
2115
+ }
2116
+ exports.federation = federation;
2117
+ exports.monacoEditorPlugin = monacoEditorPlugin;
2118
+ exports.sharpOptimize = sharpOptimize;