vite-plugin-zephyr 1.1.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +45 -1
  2. package/dist/index.d.mts +7 -0
  3. package/dist/index.d.ts +4 -0
  4. package/dist/index.js +44 -6
  5. package/dist/index.mjs +3 -0
  6. package/dist/lib/internal/extract/extract-entrypoint.d.mts +11 -0
  7. package/dist/lib/internal/extract/extract-entrypoint.d.ts +2 -1
  8. package/dist/lib/internal/extract/extract-entrypoint.js +53 -38
  9. package/dist/lib/internal/extract/extract-entrypoint.mjs +32 -0
  10. package/dist/lib/internal/extract/extract_mf_plugin.d.mts +10 -0
  11. package/dist/lib/internal/extract/extract_mf_plugin.d.ts +6 -2
  12. package/dist/lib/internal/extract/extract_mf_plugin.js +48 -5
  13. package/dist/lib/internal/extract/extract_mf_plugin.mjs +17 -0
  14. package/dist/lib/internal/extract/extract_vite_assets_map.d.mts +4 -0
  15. package/dist/lib/internal/extract/extract_vite_assets_map.d.ts +2 -1
  16. package/dist/lib/internal/extract/extract_vite_assets_map.js +65 -35
  17. package/dist/lib/internal/extract/extract_vite_assets_map.mjs +49 -0
  18. package/dist/lib/internal/extract/load_public_dir.d.mts +10 -0
  19. package/dist/lib/internal/extract/load_public_dir.d.ts +5 -2
  20. package/dist/lib/internal/extract/load_public_dir.js +57 -19
  21. package/dist/lib/internal/extract/load_public_dir.mjs +31 -0
  22. package/dist/lib/internal/extract/load_static_assets.d.mts +4 -0
  23. package/dist/lib/internal/extract/load_static_assets.d.ts +3 -2
  24. package/dist/lib/internal/extract/load_static_assets.js +60 -35
  25. package/dist/lib/internal/extract/load_static_assets.mjs +29 -0
  26. package/dist/lib/internal/extract/load_static_entries.d.mts +10 -0
  27. package/dist/lib/internal/extract/load_static_entries.d.ts +5 -2
  28. package/dist/lib/internal/extract/load_static_entries.js +56 -14
  29. package/dist/lib/internal/extract/load_static_entries.mjs +31 -0
  30. package/dist/lib/internal/extract/merge_vite_output_assets.d.mts +13 -0
  31. package/dist/lib/internal/extract/merge_vite_output_assets.d.ts +13 -0
  32. package/dist/lib/internal/extract/merge_vite_output_assets.js +68 -0
  33. package/dist/lib/internal/extract/merge_vite_output_assets.mjs +31 -0
  34. package/dist/lib/internal/mf-vite-etl/ensure_runtime_plugin.d.mts +31 -0
  35. package/dist/lib/internal/mf-vite-etl/ensure_runtime_plugin.d.ts +11 -0
  36. package/dist/lib/internal/mf-vite-etl/ensure_runtime_plugin.js +56 -15
  37. package/dist/lib/internal/mf-vite-etl/ensure_runtime_plugin.mjs +21 -0
  38. package/dist/lib/internal/mf-vite-etl/extract-mf-vite-remotes.d.mts +13 -0
  39. package/dist/lib/internal/mf-vite-etl/extract-mf-vite-remotes.d.ts +1 -0
  40. package/dist/lib/internal/mf-vite-etl/extract-mf-vite-remotes.js +55 -19
  41. package/dist/lib/internal/mf-vite-etl/extract-mf-vite-remotes.mjs +24 -0
  42. package/dist/lib/internal/mf-vite-etl/federation-metadata.d.mts +38 -0
  43. package/dist/lib/internal/mf-vite-etl/federation-metadata.d.ts +38 -0
  44. package/dist/lib/internal/mf-vite-etl/federation-metadata.js +154 -0
  45. package/dist/lib/internal/mf-vite-etl/federation-metadata.mjs +111 -0
  46. package/dist/lib/internal/mf-vite-etl/runtime_plugin.mjs +68 -159
  47. package/dist/lib/internal/partial-build-scope.d.mts +12 -0
  48. package/dist/lib/internal/partial-build-scope.d.ts +12 -0
  49. package/dist/lib/internal/partial-build-scope.js +83 -0
  50. package/dist/lib/internal/partial-build-scope.mjs +43 -0
  51. package/dist/lib/internal/types/zephyr-internal-options.d.mts +13 -0
  52. package/dist/lib/internal/types/zephyr-internal-options.d.ts +6 -2
  53. package/dist/lib/internal/types/zephyr-internal-options.js +18 -1
  54. package/dist/lib/internal/types/zephyr-internal-options.mjs +1 -0
  55. package/dist/lib/internal/types/zephyr-output.d.mts +23 -0
  56. package/dist/lib/internal/types/zephyr-output.d.ts +23 -0
  57. package/dist/lib/internal/types/zephyr-output.js +20 -0
  58. package/dist/lib/internal/types/zephyr-output.mjs +1 -0
  59. package/dist/lib/internal/utils/normalize-entrypoint.d.mts +11 -0
  60. package/dist/lib/internal/utils/normalize-entrypoint.d.ts +1 -0
  61. package/dist/lib/internal/utils/normalize-entrypoint.js +42 -24
  62. package/dist/lib/internal/utils/normalize-entrypoint.mjs +12 -0
  63. package/dist/lib/internal/utils/normalize-vite-path.d.mts +10 -0
  64. package/dist/lib/internal/utils/normalize-vite-path.d.ts +10 -0
  65. package/dist/lib/internal/utils/normalize-vite-path.js +51 -0
  66. package/dist/lib/internal/utils/normalize-vite-path.mjs +11 -0
  67. package/dist/lib/vite-plugin-zephyr-partial.d.mts +6 -0
  68. package/dist/lib/vite-plugin-zephyr-partial.d.ts +5 -8
  69. package/dist/lib/vite-plugin-zephyr-partial.js +75 -27
  70. package/dist/lib/vite-plugin-zephyr-partial.mjs +64 -0
  71. package/dist/lib/vite-plugin-zephyr.d.mts +21 -0
  72. package/dist/lib/vite-plugin-zephyr.d.ts +16 -3
  73. package/dist/lib/vite-plugin-zephyr.js +685 -239
  74. package/dist/lib/vite-plugin-zephyr.mjs +662 -0
  75. package/dist/rslib-runtime.mjs +21 -0
  76. package/package.json +53 -44
  77. package/dist/index.js.map +0 -1
  78. package/dist/lib/internal/extract/extract-entrypoint.js.map +0 -1
  79. package/dist/lib/internal/extract/extract_mf_plugin.js.map +0 -1
  80. package/dist/lib/internal/extract/extract_vite_assets_map.js.map +0 -1
  81. package/dist/lib/internal/extract/load_public_dir.js.map +0 -1
  82. package/dist/lib/internal/extract/load_static_assets.js.map +0 -1
  83. package/dist/lib/internal/extract/load_static_entries.js.map +0 -1
  84. package/dist/lib/internal/mf-vite-etl/ensure_runtime_plugin.js.map +0 -1
  85. package/dist/lib/internal/mf-vite-etl/extract-mf-vite-remotes.js.map +0 -1
  86. package/dist/lib/internal/types/zephyr-internal-options.js.map +0 -1
  87. package/dist/lib/internal/utils/normalize-entrypoint.js.map +0 -1
  88. package/dist/lib/vite-plugin-zephyr-partial.js.map +0 -1
  89. package/dist/lib/vite-plugin-zephyr.js.map +0 -1
  90. package/dist/package.json +0 -85
  91. package/dist/tsconfig.tsbuildinfo +0 -1
@@ -1,272 +1,718 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.withZephyr = withZephyr;
4
- const tslib_1 = require("tslib");
5
- const promises_1 = require("node:fs/promises");
6
- const magic_string_1 = tslib_1.__importDefault(require("magic-string"));
7
- const vite_1 = require("vite");
8
- const zephyr_agent_1 = require("zephyr-agent");
9
- const extract_entrypoint_1 = require("./internal/extract/extract-entrypoint");
10
- const extract_mf_plugin_1 = require("./internal/extract/extract_mf_plugin");
11
- const extract_vite_assets_map_1 = require("./internal/extract/extract_vite_assets_map");
12
- const ensure_runtime_plugin_1 = require("./internal/mf-vite-etl/ensure_runtime_plugin");
13
- const extract_mf_vite_remotes_1 = require("./internal/mf-vite-etl/extract-mf-vite-remotes");
14
- const DEFAULT_LIBRARY_TYPE = 'module';
15
- function loadModuleFederationPlugin() {
16
- let moduleFederation;
17
- try {
18
- moduleFederation = require('@module-federation/vite');
2
+ var __webpack_modules__ = {
3
+ "@module-federation/vite" (module) {
4
+ module.exports = require("@module-federation/vite");
19
5
  }
20
- catch (error) {
21
- throw new zephyr_agent_1.ZephyrError(zephyr_agent_1.ZeErrors.ERR_UNKNOWN, {
22
- message: `vite-plugin-zephyr: @module-federation/vite is required when mfConfig is provided. Install a compatible version of @module-federation/vite to use Module Federation with withZephyr().${error instanceof Error ? ` Original error: ${error.message}` : ''}`,
6
+ };
7
+ var __webpack_module_cache__ = {};
8
+ function __webpack_require__(moduleId) {
9
+ var cachedModule = __webpack_module_cache__[moduleId];
10
+ if (void 0 !== cachedModule) return cachedModule.exports;
11
+ var module = __webpack_module_cache__[moduleId] = {
12
+ exports: {}
13
+ };
14
+ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
15
+ return module.exports;
16
+ }
17
+ (()=>{
18
+ __webpack_require__.n = (module)=>{
19
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
20
+ __webpack_require__.d(getter, {
21
+ a: getter
23
22
  });
24
- }
25
- if (typeof moduleFederation.federation !== 'function') {
26
- throw new zephyr_agent_1.ZephyrError(zephyr_agent_1.ZeErrors.ERR_UNKNOWN, {
27
- message: 'vite-plugin-zephyr: failed to load @module-federation/vite federation plugin',
23
+ return getter;
24
+ };
25
+ })();
26
+ (()=>{
27
+ __webpack_require__.d = (exports1, getters, values)=>{
28
+ var define = (defs, kind)=>{
29
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
30
+ enumerable: true,
31
+ [kind]: defs[key]
32
+ });
33
+ };
34
+ define(getters, "get");
35
+ define(values, "value");
36
+ };
37
+ })();
38
+ (()=>{
39
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
40
+ })();
41
+ (()=>{
42
+ __webpack_require__.r = (exports1)=>{
43
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
44
+ value: 'Module'
28
45
  });
29
- }
30
- return moduleFederation.federation;
31
- }
32
- function withZephyrCore(options = {}) {
33
- const { zephyr_engine_defer, zephyr_defer_create } = zephyr_agent_1.ZephyrEngine.defer_create();
34
- const hooks = options.hooks;
35
- let resolve_vite_internal_options;
36
- const vite_internal_options_defer = new Promise((resolve) => {
37
- resolve_vite_internal_options = resolve;
46
+ Object.defineProperty(exports1, '__esModule', {
47
+ value: true
48
+ });
49
+ };
50
+ })();
51
+ var __webpack_exports__ = {};
52
+ (()=>{
53
+ __webpack_require__.r(__webpack_exports__);
54
+ __webpack_require__.d(__webpack_exports__, {
55
+ withZephyr: ()=>withZephyr
38
56
  });
39
- let cachedSpecifier;
40
- let entrypoint;
41
- let mfConfig = options.mfConfig;
42
- return {
43
- name: 'with-zephyr',
44
- // Run before Vite's env replacement so ZE_PUBLIC_* reads can be rewritten first.
45
- enforce: 'pre',
46
- config: (config) => {
47
- var _a, _b;
48
- // If MF was configured separately, inject the Zephyr runtime plugin before MF emits.
49
- const detectedMfConfig = (_b = (0, extract_mf_plugin_1.extract_mf_plugin)((_a = config.plugins) !== null && _a !== void 0 ? _a : [])) === null || _b === void 0 ? void 0 : _b._options;
50
- if (detectedMfConfig) {
51
- mfConfig = (0, ensure_runtime_plugin_1.ensureRuntimePlugin)(detectedMfConfig);
52
- }
57
+ const promises_namespaceObject = require("node:fs/promises");
58
+ const external_node_crypto_namespaceObject = require("node:crypto");
59
+ const external_node_path_namespaceObject = require("node:path");
60
+ const external_magic_string_namespaceObject = require("magic-string");
61
+ var external_magic_string_default = /*#__PURE__*/ __webpack_require__.n(external_magic_string_namespaceObject);
62
+ const external_zephyr_agent_namespaceObject = require("zephyr-agent");
63
+ const extract_entrypoint_js_namespaceObject = require("./internal/extract/extract-entrypoint.js");
64
+ const extract_mf_plugin_js_namespaceObject = require("./internal/extract/extract_mf_plugin.js");
65
+ const extract_vite_assets_map_js_namespaceObject = require("./internal/extract/extract_vite_assets_map.js");
66
+ const ensure_runtime_plugin_js_namespaceObject = require("./internal/mf-vite-etl/ensure_runtime_plugin.js");
67
+ const extract_mf_vite_remotes_js_namespaceObject = require("./internal/mf-vite-etl/extract-mf-vite-remotes.js");
68
+ const federation_metadata_js_namespaceObject = require("./internal/mf-vite-etl/federation-metadata.js");
69
+ const partial_build_scope_js_namespaceObject = require("./internal/partial-build-scope.js");
70
+ const DEFAULT_LIBRARY_TYPE = 'module';
71
+ const VITE_ENVIRONMENT_OUTPUT_PREFIX = 'vite-environment:';
72
+ function isOriginAbsoluteBase(base) {
73
+ return 'string' == typeof base && base.startsWith('/') && !base.startsWith('//');
74
+ }
75
+ function mergeClaimedPartialMaps(claims) {
76
+ const merged = {};
77
+ for (const claim of claims)for (const [partialKey, assetsMap] of Object.entries(claim.partialAssetMaps)){
78
+ if (Object.prototype.hasOwnProperty.call(merged, partialKey)) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_DEPLOY_LOCAL_BUILD, {
79
+ message: `Vite partial output "${partialKey}" was produced by multiple build scopes.`
80
+ });
81
+ merged[partialKey] = assetsMap;
82
+ }
83
+ return merged;
84
+ }
85
+ function mergeAssetMaps(maps) {
86
+ const merged = {};
87
+ const paths = new Map();
88
+ for (const assetsMap of maps)for (const [hash, asset] of Object.entries(assetsMap)){
89
+ const existingHash = paths.get(asset.path);
90
+ if (existingHash && existingHash !== hash) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_DEPLOY_LOCAL_BUILD, {
91
+ message: `Vite emitted conflicting partial assets for "${asset.path}".`
92
+ });
93
+ paths.set(asset.path, hash);
94
+ merged[hash] = asset;
95
+ }
96
+ return merged;
97
+ }
98
+ function viteEnvironmentOutputPrefix(environmentName) {
99
+ return `${VITE_ENVIRONMENT_OUTPUT_PREFIX}${encodeURIComponent(environmentName)}:`;
100
+ }
101
+ function viteEnvironmentOutputKey(environmentName, outputDirectory, outputFile, outputFormat, assetsMap) {
102
+ const destination = outputFile ? external_node_path_namespaceObject.join(outputDirectory, external_node_path_namespaceObject.basename(outputFile)) : outputDirectory;
103
+ const assets = Object.values(assetsMap).map((asset)=>[
104
+ asset.path.replace(/\\/g, '/'),
105
+ asset.hash,
106
+ asset.size
107
+ ]).sort(([leftPath, leftHash], [rightPath, rightHash])=>leftPath === rightPath ? leftHash.localeCompare(rightHash) : leftPath.localeCompare(rightPath));
108
+ const identity = (0, external_node_crypto_namespaceObject.createHash)('sha256').update(JSON.stringify({
109
+ destination: destination.replace(/\\/g, '/'),
110
+ format: outputFormat ?? null,
111
+ assets
112
+ })).digest('hex');
113
+ return `${viteEnvironmentOutputPrefix(environmentName)}${identity}`;
114
+ }
115
+ function parseViteEnvironmentOutputName(key) {
116
+ if (!key.startsWith(VITE_ENVIRONMENT_OUTPUT_PREFIX)) return null;
117
+ const outputIdentity = key.slice(VITE_ENVIRONMENT_OUTPUT_PREFIX.length);
118
+ const separator = outputIdentity.indexOf(':');
119
+ if (separator <= 0 || separator === outputIdentity.length - 1) return null;
120
+ try {
121
+ const environmentName = decodeURIComponent(outputIdentity.slice(0, separator));
122
+ return environmentName || null;
123
+ } catch {
53
124
  return null;
54
- },
55
- configResolved: async (config) => {
56
- var _a, _b, _c;
57
- const root = config.root;
58
- // Normalize the entrypoint early so uploads use the same path in serve/build.
59
- entrypoint = (0, extract_entrypoint_1.extractEntrypoint)(config);
60
- // Initialize the Zephyr engine in both serve and build flows.
61
- zephyr_defer_create({
62
- builder: 'vite',
63
- context: root,
125
+ }
126
+ }
127
+ function prefixAssetsMap(assetsMap, prefix) {
128
+ const normalized = prefix?.replace(/\\/g, '/').replace(/^\/+|\/+$/g, '');
129
+ if (!normalized) return assetsMap;
130
+ return Object.fromEntries(Object.values(assetsMap).map((asset)=>{
131
+ const assetPath = asset.path.replace(/\\/g, '/').replace(/^\/+/, '');
132
+ const prefixedPath = assetPath.startsWith(`${normalized}/`) ? assetPath : `${normalized}/${assetPath}`;
133
+ const prefixedAsset = (0, external_zephyr_agent_namespaceObject.zeBuildAssets)({
134
+ filepath: prefixedPath,
135
+ content: asset.buffer
64
136
  });
65
- resolve_vite_internal_options({
66
- root,
67
- outDir: (_a = config.build) === null || _a === void 0 ? void 0 : _a.outDir,
68
- publicDir: config.publicDir,
137
+ return [
138
+ prefixedAsset.hash,
139
+ prefixedAsset
140
+ ];
141
+ }));
142
+ }
143
+ function inferServerEntrypoint(partials, override, serverEnvironmentNames) {
144
+ if (override) return normalizeEntrypoint(override);
145
+ const allPaths = Object.values(partials).flatMap((assetsMap)=>Object.values(assetsMap).map((asset)=>asset.path));
146
+ const serverEnvironments = new Set(serverEnvironmentNames);
147
+ const serverPaths = Object.entries(partials).flatMap(([key, assetsMap])=>{
148
+ const environmentName = parseViteEnvironmentOutputName(key);
149
+ return environmentName && serverEnvironments.has(environmentName) ? Object.values(assetsMap).map((asset)=>asset.path) : [];
150
+ });
151
+ const paths = serverEnvironmentNames.length > 0 ? serverPaths : allPaths;
152
+ const preferred = [
153
+ 'server/index.js',
154
+ 'server/index.mjs',
155
+ 'server/index.cjs',
156
+ 'ssr/index.js',
157
+ 'ssr/index.mjs',
158
+ 'ssr/index.cjs',
159
+ 'rsc/index.js',
160
+ 'rsc/index.mjs',
161
+ 'rsc/index.cjs'
162
+ ];
163
+ return preferred.find((candidate)=>paths.includes(candidate)) ?? paths.find((candidate)=>/(^|\/)(server|index)\.(mjs|cjs|js)$/.test(candidate));
164
+ }
165
+ function commonDirectory(paths) {
166
+ if (0 === paths.length) return;
167
+ const resolvedPaths = paths.map((item)=>external_node_path_namespaceObject.resolve(item));
168
+ let candidate = resolvedPaths[0];
169
+ while(candidate && !resolvedPaths.every((item)=>{
170
+ const relative = external_node_path_namespaceObject.relative(candidate, item);
171
+ return !relative || !relative.startsWith(`..${external_node_path_namespaceObject.sep}`) && '..' !== relative;
172
+ })){
173
+ const parent = external_node_path_namespaceObject.dirname(candidate);
174
+ if (parent === candidate) return;
175
+ candidate = parent;
176
+ }
177
+ if (candidate === external_node_path_namespaceObject.parse(candidate).root && resolvedPaths.length > 1) return;
178
+ return candidate;
179
+ }
180
+ function normalizeEntrypoint(entrypoint) {
181
+ const normalized = entrypoint.replace(/\\/g, '/').replace(/^\.?\/+/, '');
182
+ const segments = normalized.split('/').filter((segment)=>segment && '.' !== segment);
183
+ if (!normalized || 0 === segments.length || segments.includes('..')) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_DEPLOY_LOCAL_BUILD, {
184
+ message: `Vite entrypoint must be a relative path inside the snapshot: "${entrypoint}".`
185
+ });
186
+ return segments.join('/');
187
+ }
188
+ function uniqueParticipant(base, reserved) {
189
+ let participant = base;
190
+ let suffix = 1;
191
+ const used = new Set(reserved);
192
+ while(used.has(participant))participant = `${base}-${suffix++}`;
193
+ return participant;
194
+ }
195
+ function toModuleFederationConfigArray(mfConfig) {
196
+ if (!mfConfig) return [];
197
+ return Array.isArray(mfConfig) ? mfConfig : [
198
+ mfConfig
199
+ ];
200
+ }
201
+ function attachViteFederationBuildStats(buildStats, federationMetadata) {
202
+ const federation = federationMetadata.federation;
203
+ if (!federation || 0 === federation.length) return buildStats;
204
+ const legacyFederation = 1 === federation.length ? federation[0] : void 0;
205
+ return {
206
+ ...buildStats,
207
+ federation,
208
+ ...legacyFederation ? {
209
+ remote: legacyFederation.remote,
210
+ mf_manifest: legacyFederation.mf_manifest,
211
+ library_type: legacyFederation.library_type,
212
+ exposes: legacyFederation.exposes,
213
+ shared: legacyFederation.shared
214
+ } : {
215
+ remote: void 0,
216
+ mf_manifest: void 0,
217
+ library_type: void 0,
218
+ exposes: void 0,
219
+ shared: void 0
220
+ }
221
+ };
222
+ }
223
+ function loadModuleFederationPlugin() {
224
+ let moduleFederation;
225
+ try {
226
+ moduleFederation = __webpack_require__("@module-federation/vite");
227
+ } catch (error) {
228
+ throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_UNKNOWN, {
229
+ message: `vite-plugin-zephyr: @module-federation/vite is required when mfConfig is provided. Install a compatible version of @module-federation/vite to use Module Federation with withZephyr().${error instanceof Error ? ` Original error: ${error.message}` : ''}`
69
230
  });
70
- const detectedMfConfig = (_c = (0, extract_mf_plugin_1.extract_mf_plugin)((_b = config.plugins) !== null && _b !== void 0 ? _b : [])) === null || _c === void 0 ? void 0 : _c._options;
71
- if (detectedMfConfig) {
72
- mfConfig = (0, ensure_runtime_plugin_1.ensureRuntimePlugin)(detectedMfConfig);
231
+ }
232
+ if ('function' != typeof moduleFederation.federation) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_UNKNOWN, {
233
+ message: 'vite-plugin-zephyr: failed to load @module-federation/vite federation plugin'
234
+ });
235
+ return moduleFederation.federation;
236
+ }
237
+ function withZephyrCore(options = {}) {
238
+ const { zephyr_engine_defer, zephyr_defer_create } = external_zephyr_agent_namespaceObject.ZephyrEngine.defer_create();
239
+ const hooks = options.hooks;
240
+ const preservesLockedArtifactPaths = 'tap-app' === options.target;
241
+ const buildInvocationId = `vite-${(0, external_node_crypto_namespaceObject.randomUUID)()}`;
242
+ const usesExternalPartialBuild = void 0 !== options.partialBuild || Boolean(process.env['ZE_BUILD_INVOCATION_ID']?.trim());
243
+ const externalPartialScope = usesExternalPartialBuild ? (0, partial_build_scope_js_namespaceObject.resolveVitePartialBuildScope)(options.partialBuild) : void 0;
244
+ let resolve_vite_internal_options;
245
+ const vite_internal_options_defer = new Promise((resolve)=>{
246
+ resolve_vite_internal_options = resolve;
247
+ });
248
+ let cachedSpecifier;
249
+ let entrypoint;
250
+ const configureModuleFederationRuntime = (config)=>preservesLockedArtifactPaths ? config : (0, ensure_runtime_plugin_js_namespaceObject.ensureRuntimePlugin)(config);
251
+ const mfConfigSources = toModuleFederationConfigArray(options.mfConfig).map(configureModuleFederationRuntime);
252
+ const ownedConfigIdentities = new Set(mfConfigSources.flatMap((config)=>(0, federation_metadata_js_namespaceObject.getConfigIdentities)(config)));
253
+ let environmentNames = [];
254
+ let environmentMetadata = new Map();
255
+ let sharedOutputRoot;
256
+ let isWatchMode = false;
257
+ let buildGeneration = 0;
258
+ let applicationContext;
259
+ let uploadMetadata;
260
+ let baseHref = '';
261
+ let supportsBuildApp = false;
262
+ const registerModuleFederationConfigs = (configs)=>{
263
+ for (const config of configs){
264
+ const identities = (0, federation_metadata_js_namespaceObject.getConfigIdentities)(config);
265
+ if (identities.some((identity)=>ownedConfigIdentities.has(identity))) continue;
266
+ const runtimeConfigured = configureModuleFederationRuntime(config);
267
+ if (!mfConfigSources.includes(runtimeConfigured)) {
268
+ mfConfigSources.push(runtimeConfigured);
269
+ for (const identity of (0, federation_metadata_js_namespaceObject.getConfigIdentities)(runtimeConfigured))ownedConfigIdentities.add(identity);
270
+ }
73
271
  }
74
- mfConfig !== null && mfConfig !== void 0 ? mfConfig : (mfConfig = detectedMfConfig);
75
- if (mfConfig) {
272
+ };
273
+ const getModuleFederationPublicationMetadata = ()=>(0, federation_metadata_js_namespaceObject.createViteModuleFederationPublicationMetadata)(mfConfigSources);
274
+ return {
275
+ name: 'with-zephyr',
276
+ enforce: 'pre',
277
+ config: (config, env)=>{
278
+ registerModuleFederationConfigs((0, extract_mf_plugin_js_namespaceObject.extract_mf_plugins)(config.plugins ?? []).map((plugin)=>plugin._options));
279
+ return preservesLockedArtifactPaths || 'build' !== env.command || null != config.base ? null : {
280
+ base: './'
281
+ };
282
+ },
283
+ configResolved: async (config)=>{
284
+ const vite = await import("vite");
285
+ supportsBuildApp = Number.parseInt(vite.version.split('.')[0] ?? '0', 10) >= 6;
286
+ const root = config.root;
287
+ baseHref = (0, external_zephyr_agent_namespaceObject.normalizeBasePath)(config.base);
288
+ entrypoint = normalizeEntrypoint(options.entrypoint ?? (0, extract_entrypoint_js_namespaceObject.extractEntrypoint)(config));
289
+ isWatchMode = Boolean(config.build?.watch);
290
+ const configuredEnvironments = config.environments ?? {};
291
+ environmentNames = Object.keys(configuredEnvironments);
292
+ environmentMetadata = new Map(Object.entries(configuredEnvironments).map(([name, environment])=>[
293
+ name,
294
+ {
295
+ consumer: environment.consumer,
296
+ outputDir: environment.build?.outDir ? external_node_path_namespaceObject.resolve(root, environment.build.outDir) : void 0
297
+ }
298
+ ]));
299
+ const outputDirectories = [
300
+ ...environmentMetadata.values()
301
+ ].map(({ outputDir })=>outputDir).filter((value)=>!!value);
302
+ sharedOutputRoot = preservesLockedArtifactPaths || outputDirectories.length !== environmentNames.length ? void 0 : commonDirectory(outputDirectories);
303
+ zephyr_defer_create({
304
+ builder: 'vite',
305
+ context: root,
306
+ target: options.target
307
+ });
76
308
  try {
77
- // Resolve remotes early so zephyr-manifest.json includes runtime dependencies.
78
- const dependencyPairs = (0, extract_mf_vite_remotes_1.extract_remotes_dependencies)(root, mfConfig);
79
- if (dependencyPairs) {
309
+ const zephyrEngine = await zephyr_engine_defer;
310
+ if ((0, external_zephyr_agent_namespaceObject.usesPathAddressing)(await zephyrEngine.application_configuration) && isOriginAbsoluteBase(config.base)) external_zephyr_agent_namespaceObject.ze_log.init(`The resolved Vite base '${config.base}' is still origin-absolute for a path-addressed target. A later config hook may have overridden Zephyr's relative base.`);
311
+ } catch (error) {
312
+ (0, external_zephyr_agent_namespaceObject.handleGlobalError)(error);
313
+ }
314
+ resolve_vite_internal_options({
315
+ root,
316
+ outDir: config.build?.outDir,
317
+ publicDir: config.publicDir,
318
+ target: options.target
319
+ });
320
+ registerModuleFederationConfigs((0, extract_mf_plugin_js_namespaceObject.extract_mf_plugins)(config.plugins ?? []).map((plugin)=>plugin._options));
321
+ const federationMetadata = getModuleFederationPublicationMetadata();
322
+ const mfConfigs = federationMetadata.mfConfigs ?? [];
323
+ if (mfConfigs.length > 0 && !preservesLockedArtifactPaths) try {
324
+ const dependencyPairs = [
325
+ ...new Map(mfConfigs.flatMap((mfConfig)=>(0, extract_mf_vite_remotes_js_namespaceObject.extract_remotes_dependencies)(root, mfConfig) ?? []).map((dependency)=>[
326
+ `${dependency.name}:${dependency.version}`,
327
+ dependency
328
+ ])).values()
329
+ ];
330
+ if (dependencyPairs.length > 0) {
80
331
  const zephyr_engine = await zephyr_engine_defer;
81
332
  await zephyr_engine.resolve_remote_dependencies(dependencyPairs, DEFAULT_LIBRARY_TYPE);
82
- zephyr_agent_1.ze_log.remotes(`Resolved ${dependencyPairs.length} remote dependencies in configResolved`);
333
+ external_zephyr_agent_namespaceObject.ze_log.remotes(`Resolved ${dependencyPairs.length} remote dependencies in configResolved`);
83
334
  }
335
+ } catch (error) {
336
+ (0, external_zephyr_agent_namespaceObject.handleGlobalError)(error);
84
337
  }
85
- catch (error) {
86
- (0, zephyr_agent_1.handleGlobalError)(error);
87
- }
88
- }
89
- try {
90
- // Mirror ZE_PUBLIC_* into process.env for agent-side manifest generation.
91
- const loaded = (0, vite_1.loadEnv)(config.mode || 'production', root, '');
92
- for (const [k, v] of Object.entries(loaded)) {
93
- if (k.startsWith('ZE_PUBLIC_') &&
94
- typeof v === 'string' &&
95
- !(k in process.env)) {
96
- process.env[k] = v;
97
- }
98
- }
99
- }
100
- catch (_d) {
101
- // ignore if loadEnv unavailable
102
- }
103
- },
104
- resolveId: async (source) => {
105
- if (source === ensure_runtime_plugin_1.ZEPHYR_MF_RUNTIME_PLUGIN_ID) {
106
- return ensure_runtime_plugin_1.RESOLVED_ZEPHYR_MF_RUNTIME_PLUGIN_ID;
107
- }
108
- try {
109
- const zephyr_engine = await zephyr_engine_defer;
110
- if (!cachedSpecifier) {
111
- cachedSpecifier = `env:vars:${zephyr_engine.application_uid}`;
112
- }
113
- if (source === cachedSpecifier) {
114
- if (process.env['NODE_ENV'] === 'development') {
115
- // Keep dev env imports aligned with the manifest JSON route used by other Zephyr plugins.
116
- return '/zephyr-manifest.json';
117
- }
118
- return { id: source, external: true };
119
- }
120
- }
121
- catch (_a) {
122
- // ignore
123
- }
124
- return null;
125
- },
126
- load: async (id) => {
127
- if (id === ensure_runtime_plugin_1.RESOLVED_ZEPHYR_MF_RUNTIME_PLUGIN_ID) {
128
- return (0, promises_1.readFile)((0, ensure_runtime_plugin_1.getRuntimePluginPath)(), 'utf8');
129
- }
130
- return null;
131
- },
132
- transform: {
133
- order: 'post',
134
- // Limit the hook to source-like files only.
135
- filter: {
136
- id: /\.(mjs|cjs|js|ts|jsx|tsx)/,
338
+ try {
339
+ const loaded = vite.loadEnv(config.mode || 'production', root, '');
340
+ for (const [k, v] of Object.entries(loaded))if (k.startsWith('ZE_PUBLIC_') && 'string' == typeof v && !(k in process.env)) process.env[k] = v;
341
+ } catch {}
137
342
  },
138
- handler: async (code, id) => {
343
+ resolveId: async (source)=>{
344
+ if (source === ensure_runtime_plugin_js_namespaceObject.ZEPHYR_MF_RUNTIME_PLUGIN_ID) return ensure_runtime_plugin_js_namespaceObject.RESOLVED_ZEPHYR_MF_RUNTIME_PLUGIN_ID;
139
345
  try {
140
- // Rewrite ZE_PUBLIC_* reads in app code; node_modules stay untouched.
141
- if (!id.includes('node_modules')) {
142
- const zephyr_engine = await zephyr_engine_defer;
143
- if (!cachedSpecifier) {
144
- cachedSpecifier = `env:vars:${zephyr_engine.application_uid}`;
145
- }
146
- const res = (0, zephyr_agent_1.rewriteEnvReadsToVirtualModule)(String(code), cachedSpecifier);
147
- if (res && typeof res.code === 'string' && res.code !== code) {
148
- code = res.code;
149
- return {
150
- code,
151
- map: new magic_string_1.default(code).generateMap({
152
- hires: true,
153
- }),
154
- };
155
- }
346
+ const zephyr_engine = await zephyr_engine_defer;
347
+ if (!cachedSpecifier) cachedSpecifier = `env:vars:${zephyr_engine.application_uid}`;
348
+ if (source === cachedSpecifier) {
349
+ if ('development' === process.env['NODE_ENV']) return '/zephyr-manifest.json';
350
+ return {
351
+ id: source,
352
+ external: true
353
+ };
156
354
  }
157
- return null;
158
- }
159
- catch (error) {
160
- (0, zephyr_agent_1.handleGlobalError)(error);
161
- return null;
162
- }
355
+ } catch {}
356
+ return null;
357
+ },
358
+ load: async (id)=>{
359
+ if (id === ensure_runtime_plugin_js_namespaceObject.RESOLVED_ZEPHYR_MF_RUNTIME_PLUGIN_ID) return (0, promises_namespaceObject.readFile)((0, ensure_runtime_plugin_js_namespaceObject.getRuntimePluginPath)(), 'utf8');
360
+ return null;
163
361
  },
164
- },
165
- generateBundle: async function (_outputOptions, bundle) {
166
- if (cachedSpecifier) {
167
- for (const [, chunk] of Object.entries(bundle)) {
168
- if (chunk &&
169
- typeof chunk === 'object' &&
170
- 'type' in chunk &&
171
- chunk.type === 'chunk' &&
172
- 'code' in chunk) {
173
- // Preserve JSON import assertions after bundling so runtime import maps still work.
174
- const importWithoutAssertion = new RegExp(`import\\s+([^\\s]+)\\s+from\\s*['"]${cachedSpecifier.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}['"]`, 'g');
175
- if (chunk.code.match(importWithoutAssertion)) {
176
- chunk.code = chunk.code.replace(importWithoutAssertion, `import $1 from '${cachedSpecifier}' with { type: 'json' }`);
362
+ transform: {
363
+ order: 'post',
364
+ filter: {
365
+ id: /\.(mjs|cjs|js|ts|jsx|tsx)/
366
+ },
367
+ handler: async (code, id)=>{
368
+ if (preservesLockedArtifactPaths) return null;
369
+ try {
370
+ if (!id.includes('node_modules')) {
371
+ const zephyr_engine = await zephyr_engine_defer;
372
+ if (!cachedSpecifier) cachedSpecifier = `env:vars:${zephyr_engine.application_uid}`;
373
+ const res = (0, external_zephyr_agent_namespaceObject.rewriteEnvReadsToVirtualModule)(String(code), cachedSpecifier);
374
+ if (res && 'string' == typeof res.code && res.code !== code) {
375
+ code = res.code;
376
+ return {
377
+ code,
378
+ map: new (external_magic_string_default())(code).generateMap({
379
+ hires: true
380
+ })
381
+ };
382
+ }
177
383
  }
384
+ return null;
385
+ } catch (error) {
386
+ (0, external_zephyr_agent_namespaceObject.handleGlobalError)(error);
387
+ return null;
178
388
  }
179
389
  }
180
- }
181
- try {
182
- const zephyr_engine = await zephyr_engine_defer;
183
- const dependencies = zephyr_engine.federated_dependencies || [];
184
- const manifestContent = (0, zephyr_agent_1.createManifestContent)(dependencies, true);
185
- this.emitFile({
186
- type: 'asset',
187
- fileName: 'zephyr-manifest.json',
188
- source: manifestContent,
189
- });
190
- }
191
- catch (error) {
192
- (0, zephyr_agent_1.handleGlobalError)(error);
193
- this.emitFile({
194
- type: 'asset',
195
- fileName: 'zephyr-manifest.json',
196
- source: JSON.stringify({
197
- version: '1.0.0',
198
- timestamp: new Date().toISOString(),
199
- dependencies: {},
200
- zeVars: {},
201
- }, null, 2),
202
- });
203
- }
204
- },
205
- configureServer: async (server) => {
206
- try {
207
- const zephyr_engine = await zephyr_engine_defer;
208
- if (!cachedSpecifier) {
209
- cachedSpecifier = `env:vars:${zephyr_engine.application_uid}`;
390
+ },
391
+ renderChunk: {
392
+ order: 'post',
393
+ handler (code) {
394
+ if (preservesLockedArtifactPaths || !cachedSpecifier) return null;
395
+ const importWithoutAttribute = new RegExp(`import\\s+([^\\s]+)\\s+from\\s*['"]${cachedSpecifier.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}['"]`, 'g');
396
+ const nextCode = code.replace(importWithoutAttribute, `import $1 from '${cachedSpecifier}' with { type: 'json' }`);
397
+ return nextCode === code ? null : {
398
+ code: nextCode,
399
+ map: null
400
+ };
210
401
  }
211
- server.middlewares.use((req, res, next) => {
212
- void (async () => {
213
- if (!req.url) {
214
- next();
215
- return;
216
- }
217
- const requestUrl = req.url.split('?')[0];
218
- if (requestUrl === '/zephyr-manifest.json') {
219
- try {
402
+ },
403
+ generateBundle: async function() {
404
+ if (preservesLockedArtifactPaths) return;
405
+ try {
406
+ const zephyr_engine = await zephyr_engine_defer;
407
+ const dependencies = zephyr_engine.federated_dependencies || [];
408
+ const manifestContent = (0, external_zephyr_agent_namespaceObject.createManifestContent)(dependencies, true);
409
+ this.emitFile({
410
+ type: 'asset',
411
+ fileName: 'zephyr-manifest.json',
412
+ source: manifestContent
413
+ });
414
+ } catch (error) {
415
+ (0, external_zephyr_agent_namespaceObject.handleGlobalError)(error);
416
+ this.emitFile({
417
+ type: 'asset',
418
+ fileName: 'zephyr-manifest.json',
419
+ source: JSON.stringify({
420
+ version: '1.0.0',
421
+ timestamp: new Date().toISOString(),
422
+ dependencies: {},
423
+ zeVars: {}
424
+ }, null, 2)
425
+ });
426
+ }
427
+ },
428
+ configureServer: async (server)=>{
429
+ try {
430
+ const zephyr_engine = await zephyr_engine_defer;
431
+ if (!cachedSpecifier) cachedSpecifier = `env:vars:${zephyr_engine.application_uid}`;
432
+ server.middlewares.use((req, res, next)=>{
433
+ (async ()=>{
434
+ if (!req.url) return void next();
435
+ const requestUrl = req.url.split('?')[0];
436
+ if ('/zephyr-manifest.json' === requestUrl) try {
220
437
  const dependencies = zephyr_engine.federated_dependencies || [];
221
- const manifestContent = (0, zephyr_agent_1.createManifestContent)(dependencies, true);
438
+ const manifestContent = (0, external_zephyr_agent_namespaceObject.createManifestContent)(dependencies, true);
222
439
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
223
440
  res.setHeader('Access-Control-Allow-Origin', '*');
224
441
  res.end(manifestContent);
225
442
  return;
443
+ } catch (error) {
444
+ (0, external_zephyr_agent_namespaceObject.handleGlobalError)(error);
226
445
  }
227
- catch (error) {
228
- (0, zephyr_agent_1.handleGlobalError)(error);
446
+ next();
447
+ })();
448
+ });
449
+ } catch {}
450
+ },
451
+ writeBundle: async function(outputOptions, bundle) {
452
+ const partialClaims = [];
453
+ try {
454
+ const [vite_internal_options, zephyr_engine] = await Promise.all([
455
+ vite_internal_options_defer,
456
+ zephyr_engine_defer
457
+ ]);
458
+ zephyr_engine.buildProperties.baseHref = baseHref;
459
+ const environmentName = this.environment?.name;
460
+ const isMultiEnvironment = environmentNames.length > 1;
461
+ if (isWatchMode && isMultiEnvironment) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_DEPLOY_LOCAL_BUILD, {
462
+ message: "Vite multi-environment watch publication is not supported because environment rebuilds do not expose an atomic application generation."
463
+ });
464
+ const outputDirectory = external_node_path_namespaceObject.resolve(vite_internal_options.root, outputOptions.dir ?? (outputOptions.file ? external_node_path_namespaceObject.dirname(outputOptions.file) : vite_internal_options.outDir));
465
+ const resolvedEnvironmentName = environmentName ?? [
466
+ ...environmentMetadata.entries()
467
+ ].find(([, metadata])=>metadata.outputDir === outputDirectory)?.[0] ?? (1 === environmentNames.length ? environmentNames[0] : void 0);
468
+ const coordinateWithBuildApp = supportsBuildApp && !isWatchMode;
469
+ if (coordinateWithBuildApp && !resolvedEnvironmentName) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_DEPLOY_LOCAL_BUILD, {
470
+ message: `Could not associate Vite output directory "${outputDirectory}" with an environment.`
471
+ });
472
+ let assetPrefix;
473
+ if (coordinateWithBuildApp && isMultiEnvironment && !preservesLockedArtifactPaths) {
474
+ if (!sharedOutputRoot) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_DEPLOY_LOCAL_BUILD, {
475
+ message: 'Could not determine a shared output root for Vite environments.'
476
+ });
477
+ const relativeOutput = external_node_path_namespaceObject.relative(sharedOutputRoot, outputDirectory);
478
+ if ('..' === relativeOutput || relativeOutput.startsWith(`..${external_node_path_namespaceObject.sep}`) || external_node_path_namespaceObject.isAbsolute(relativeOutput)) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_DEPLOY_LOCAL_BUILD, {
479
+ message: `Vite environment output "${outputDirectory}" is outside shared output root "${sharedOutputRoot}".`
480
+ });
481
+ assetPrefix = relativeOutput ? relativeOutput.split(external_node_path_namespaceObject.sep).join('/') : void 0;
482
+ }
483
+ const extractionOptions = {
484
+ ...vite_internal_options,
485
+ dir: outputOptions.dir,
486
+ outDir: outputDirectory,
487
+ assets: bundle,
488
+ publicDir: isMultiEnvironment && resolvedEnvironmentName && environmentMetadata.get(resolvedEnvironmentName)?.consumer === 'server' ? void 0 : vite_internal_options.publicDir
489
+ };
490
+ let assetsMap = await (0, extract_vite_assets_map_js_namespaceObject.extract_vite_assets_map)(zephyr_engine, extractionOptions);
491
+ if (coordinateWithBuildApp) {
492
+ if (!resolvedEnvironmentName) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_DEPLOY_LOCAL_BUILD, {
493
+ message: `Could not associate Vite output directory "${outputDirectory}" with an environment.`
494
+ });
495
+ const persistedAssetsMap = preservesLockedArtifactPaths ? assetsMap : prefixAssetsMap(assetsMap, assetPrefix);
496
+ await (0, external_zephyr_agent_namespaceObject.savePartialAssetMap)(zephyr_engine.application_uid, viteEnvironmentOutputKey(resolvedEnvironmentName, outputDirectory, outputOptions.file, outputOptions.format, persistedAssetsMap), persistedAssetsMap, {
497
+ invocationId: buildInvocationId,
498
+ generation: buildGeneration
499
+ });
500
+ return;
501
+ }
502
+ if (!isWatchMode && externalPartialScope) {
503
+ const batch = await (0, external_zephyr_agent_namespaceObject.claimPartialAssetMapBatch)(zephyr_engine.application_uid, [
504
+ externalPartialScope
505
+ ]);
506
+ if (!batch) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_DEPLOY_LOCAL_BUILD, {
507
+ message: 'Vite partialBuild was configured, but its external partial output was unavailable or already claimed.'
508
+ });
509
+ partialClaims.push(...batch.claims);
510
+ const partials = mergeClaimedPartialMaps(partialClaims);
511
+ assetsMap = mergeAssetMaps([
512
+ ...Object.values(partials),
513
+ assetsMap
514
+ ]);
515
+ }
516
+ if (!zephyr_engine.hasActiveBuild) await zephyr_engine.start_new_build();
517
+ const federationMetadata = getModuleFederationPublicationMetadata();
518
+ (0, external_zephyr_agent_namespaceObject.assertTapFederationPublicationMetadata)({
519
+ target: options.target,
520
+ mfConfigs: federationMetadata.mfConfigs,
521
+ federation: federationMetadata.federation
522
+ });
523
+ await zephyr_engine.upload_assets({
524
+ assetsMap,
525
+ buildStats: attachViteFederationBuildStats(await (0, external_zephyr_agent_namespaceObject.zeBuildDashData)(zephyr_engine), federationMetadata),
526
+ mfConfig: federationMetadata.mfConfig,
527
+ mfConfigs: federationMetadata.mfConfigs,
528
+ hooks,
529
+ entrypoint,
530
+ snapshotType: options.snapshotType ?? 'csr'
531
+ });
532
+ await zephyr_engine.build_finished();
533
+ await (0, external_zephyr_agent_namespaceObject.commitPartialAssetMapClaimBatch)(zephyr_engine.application_uid, partialClaims.map(({ claimId })=>claimId));
534
+ } catch (error) {
535
+ try {
536
+ const zephyr_engine = await zephyr_engine_defer;
537
+ zephyr_engine.build_failed();
538
+ } catch {}
539
+ if (partialClaims.length > 0) try {
540
+ const zephyr_engine = await zephyr_engine_defer;
541
+ await (0, external_zephyr_agent_namespaceObject.rollbackPartialAssetMapClaimBatch)(zephyr_engine.application_uid, partialClaims.map(({ claimId })=>claimId));
542
+ } catch (restoreError) {
543
+ (0, external_zephyr_agent_namespaceObject.handleGlobalError)(restoreError);
544
+ }
545
+ (0, external_zephyr_agent_namespaceObject.handleGlobalError)(error);
546
+ }
547
+ },
548
+ buildApp: {
549
+ order: 'post',
550
+ async handler (builder) {
551
+ if (!supportsBuildApp) return;
552
+ const environments = Object.entries(builder.environments);
553
+ if (isWatchMode) {
554
+ if (environments.length > 1) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_DEPLOY_LOCAL_BUILD, {
555
+ message: "Vite multi-environment watch publication is not supported because environment rebuilds do not expose an atomic application generation."
556
+ });
557
+ return;
558
+ }
559
+ if (0 === environments.length) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_DEPLOY_LOCAL_BUILD, {
560
+ message: 'Vite exposed no build environments for Zephyr publication.'
561
+ });
562
+ let incomplete = environments.filter(([, environment])=>!environment.isBuilt).map(([name])=>name);
563
+ if (incomplete.length === environments.length) {
564
+ for (const [, environment] of environments)await builder.build(environment);
565
+ incomplete = environments.filter(([, environment])=>!environment.isBuilt).map(([name])=>name);
566
+ }
567
+ if (incomplete.length > 0) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_DEPLOY_LOCAL_BUILD, {
568
+ message: `Vite completed without these environments: ${incomplete.join(', ')}. Zephyr will not publish partial compiler output.`
569
+ });
570
+ const partialClaims = [];
571
+ const generation = buildGeneration++;
572
+ try {
573
+ const zephyrEngine = await zephyr_engine_defer;
574
+ zephyrEngine.buildProperties.baseHref = baseHref;
575
+ const claimScopes = [
576
+ {
577
+ invocationId: buildInvocationId,
578
+ generation
579
+ },
580
+ ...externalPartialScope ? [
581
+ externalPartialScope
582
+ ] : []
583
+ ];
584
+ const batch = await (0, external_zephyr_agent_namespaceObject.claimPartialAssetMapBatch)(zephyrEngine.application_uid, claimScopes);
585
+ if (!batch) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_DEPLOY_LOCAL_BUILD, {
586
+ message: externalPartialScope ? 'Vite could not atomically claim both environment and configured external partial output.' : 'Vite environment output was unavailable or already claimed.'
587
+ });
588
+ partialClaims.push(...batch.claims);
589
+ const claimedPartials = mergeClaimedPartialMaps(partialClaims);
590
+ if (0 === Object.keys(claimedPartials).length) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_DEPLOY_LOCAL_BUILD, {
591
+ message: 'Vite produced no environment assets for Zephyr publication.'
592
+ });
593
+ const expectedEnvironmentNames = new Set(environments.map(([name])=>name));
594
+ const environmentOutputCounts = new Map(environments.map(([name])=>[
595
+ name,
596
+ 0
597
+ ]));
598
+ const unexpectedEnvironmentOutputs = [];
599
+ for (const key of Object.keys(claimedPartials)){
600
+ if (!key.startsWith(VITE_ENVIRONMENT_OUTPUT_PREFIX)) continue;
601
+ const environmentName = parseViteEnvironmentOutputName(key);
602
+ if (!environmentName || !expectedEnvironmentNames.has(environmentName)) {
603
+ unexpectedEnvironmentOutputs.push(key);
604
+ continue;
229
605
  }
606
+ environmentOutputCounts.set(environmentName, (environmentOutputCounts.get(environmentName) ?? 0) + 1);
230
607
  }
231
- next();
232
- })();
233
- });
234
- }
235
- catch (_a) {
236
- // ignore
237
- }
238
- },
239
- writeBundle: async function (options, bundle) {
240
- try {
241
- const [vite_internal_options, zephyr_engine] = await Promise.all([
242
- vite_internal_options_defer,
243
- zephyr_engine_defer,
244
- ]);
245
- vite_internal_options.dir = options.dir;
246
- vite_internal_options.assets = bundle;
247
- const assetsMap = await (0, extract_vite_assets_map_1.extract_vite_assets_map)(zephyr_engine, vite_internal_options);
248
- await zephyr_engine.upload_assets({
249
- assetsMap,
250
- buildStats: await (0, zephyr_agent_1.zeBuildDashData)(zephyr_engine),
251
- hooks,
252
- entrypoint,
253
- snapshotType: 'csr',
254
- });
255
- await zephyr_engine.build_finished();
256
- }
257
- catch (error) {
258
- (0, zephyr_agent_1.handleGlobalError)(error);
608
+ const missingEnvironmentOutputs = environments.map(([name])=>name).filter((name)=>0 === environmentOutputCounts.get(name)).map(viteEnvironmentOutputPrefix);
609
+ if (missingEnvironmentOutputs.length > 0) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_DEPLOY_LOCAL_BUILD, {
610
+ message: `Vite did not produce Zephyr output for: ${missingEnvironmentOutputs.join(', ')}`
611
+ });
612
+ if (unexpectedEnvironmentOutputs.length > 0) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_DEPLOY_LOCAL_BUILD, {
613
+ message: 'Vite found stale or unexpected environment output for: ' + unexpectedEnvironmentOutputs.join(', ')
614
+ });
615
+ const serverEnvironmentNames = environments.filter(([name, environment])=>environment.config?.consumer === 'server' || environmentMetadata.get(name)?.consumer === 'server').map(([name])=>name);
616
+ const inferredSsr = serverEnvironmentNames.length > 0;
617
+ const snapshotType = options.snapshotType ?? (!preservesLockedArtifactPaths && inferredSsr ? 'ssr' : 'csr');
618
+ const finalEntrypoint = 'ssr' === snapshotType ? inferServerEntrypoint(claimedPartials, options.entrypoint, serverEnvironmentNames) : preservesLockedArtifactPaths ? void 0 : options.entrypoint ?? entrypoint;
619
+ if ('ssr' === snapshotType && !finalEntrypoint) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_DEPLOY_LOCAL_BUILD, {
620
+ message: 'Could not infer a Vite server entrypoint. Set withZephyr({ entrypoint }).'
621
+ });
622
+ if ('ssr' === snapshotType && finalEntrypoint && !Object.values(claimedPartials).some((assetsMap)=>Object.values(assetsMap).some((asset)=>asset.path === finalEntrypoint))) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_DEPLOY_LOCAL_BUILD, {
623
+ message: `Vite server entrypoint "${finalEntrypoint}" was not emitted in the coordinated snapshot.`
624
+ });
625
+ uploadMetadata = {
626
+ snapshotType,
627
+ entrypoint: finalEntrypoint
628
+ };
629
+ applicationContext ??= new external_zephyr_agent_namespaceObject.ApplicationContext({
630
+ applicationUid: zephyrEngine.application_uid,
631
+ prepare: ()=>zephyrEngine.hasActiveBuild ? void 0 : zephyrEngine.start_new_build(),
632
+ publish: async ({ assetsMap })=>{
633
+ if (!uploadMetadata) throw new external_zephyr_agent_namespaceObject.ZephyrError(external_zephyr_agent_namespaceObject.ZeErrors.ERR_DEPLOY_LOCAL_BUILD, {
634
+ message: 'Vite upload metadata was not prepared.'
635
+ });
636
+ const federationMetadata = getModuleFederationPublicationMetadata();
637
+ (0, external_zephyr_agent_namespaceObject.assertTapFederationPublicationMetadata)({
638
+ target: options.target,
639
+ mfConfigs: federationMetadata.mfConfigs,
640
+ federation: federationMetadata.federation
641
+ });
642
+ await zephyrEngine.upload_assets({
643
+ assetsMap,
644
+ buildStats: attachViteFederationBuildStats(await (0, external_zephyr_agent_namespaceObject.zeBuildDashData)(zephyrEngine), federationMetadata),
645
+ mfConfig: federationMetadata.mfConfig,
646
+ mfConfigs: federationMetadata.mfConfigs,
647
+ hooks,
648
+ snapshotType: uploadMetadata.snapshotType,
649
+ entrypoint: uploadMetadata.entrypoint
650
+ });
651
+ },
652
+ finish: ()=>zephyrEngine.build_finished(),
653
+ onFailure: ()=>zephyrEngine.build_failed()
654
+ });
655
+ const outputParticipant = uniqueParticipant('vite-output', environments.map(([name])=>name));
656
+ const session = applicationContext.beginBuild({
657
+ invocationId: `${buildInvocationId}:${generation}`,
658
+ generation,
659
+ strictAssetPaths: preservesLockedArtifactPaths,
660
+ participants: [
661
+ ...environments.map(([name, environment])=>({
662
+ name,
663
+ role: environment.config?.consumer ?? environmentMetadata.get(name)?.consumer ?? name
664
+ })),
665
+ {
666
+ name: outputParticipant,
667
+ role: snapshotType
668
+ }
669
+ ]
670
+ });
671
+ for (const [name] of environments)session.completeParticipant(name);
672
+ for (const [key, assetsMap] of Object.entries(claimedPartials))session.contribute({
673
+ participant: outputParticipant,
674
+ key,
675
+ assetsMap
676
+ });
677
+ session.completeParticipant(outputParticipant);
678
+ await session.publish();
679
+ await (0, external_zephyr_agent_namespaceObject.commitPartialAssetMapClaimBatch)(zephyrEngine.application_uid, partialClaims.map(({ claimId })=>claimId));
680
+ } catch (error) {
681
+ try {
682
+ const zephyrEngine = await zephyr_engine_defer;
683
+ zephyrEngine.build_failed();
684
+ } catch {}
685
+ if (partialClaims.length > 0) try {
686
+ const zephyrEngine = await zephyr_engine_defer;
687
+ await (0, external_zephyr_agent_namespaceObject.rollbackPartialAssetMapClaimBatch)(zephyrEngine.application_uid, partialClaims.map(({ claimId })=>claimId));
688
+ } catch (restoreError) {
689
+ (0, external_zephyr_agent_namespaceObject.handleGlobalError)(restoreError);
690
+ }
691
+ (0, external_zephyr_agent_namespaceObject.handleGlobalError)(error);
692
+ }
693
+ }
259
694
  }
260
- },
261
- };
262
- }
263
- function withZephyr(options = {}) {
264
- const plugins = [];
265
- if (options.mfConfig) {
266
- const federation = loadModuleFederationPlugin();
267
- plugins.push(...federation((0, ensure_runtime_plugin_1.ensureRuntimePlugin)(options.mfConfig)));
695
+ };
268
696
  }
269
- plugins.push(withZephyrCore(options));
270
- return plugins;
271
- }
697
+ function withZephyr(options = {}) {
698
+ if (void 0 !== options.target) (0, external_zephyr_agent_namespaceObject.assertZephyrBuildTarget)(options.target, 'withZephyr({ target })');
699
+ const plugins = [];
700
+ const mfConfigs = toModuleFederationConfigArray(options.mfConfig);
701
+ if (mfConfigs.length > 0) {
702
+ const federation = loadModuleFederationPlugin();
703
+ const preservesLockedArtifactPaths = 'tap-app' === options.target;
704
+ for (const mfConfig of mfConfigs)plugins.push(...federation(preservesLockedArtifactPaths ? mfConfig : (0, ensure_runtime_plugin_js_namespaceObject.ensureRuntimePlugin)(mfConfig)));
705
+ }
706
+ plugins.push(withZephyrCore(options));
707
+ return plugins;
708
+ }
709
+ })();
710
+ exports.withZephyr = __webpack_exports__.withZephyr;
711
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
712
+ "withZephyr"
713
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
714
+ Object.defineProperty(exports, '__esModule', {
715
+ value: true
716
+ });
717
+
272
718
  //# sourceMappingURL=vite-plugin-zephyr.js.map