@salesforce/vite-plugin-ui-bundle 12.15.0 → 12.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -2,9 +2,11 @@ import { Plugin } from 'vite';
2
2
  import { CorePluginOptions } from './core/createCorePlugins';
3
3
  export type { BasePathResolver, Environment } from './core/env';
4
4
  export type { CorePluginOptions, CoreHooks } from './core/createCorePlugins';
5
+ export type { BuildManifestOptions, UiBundleBuildFile, UiBundleBuildManifest, } from './core/buildManifest';
6
+ export { BUILD_MANIFEST_FILE } from './core/buildManifest';
5
7
  /**
6
8
  * Options for the generic UI-bundle plugin: `orgAlias`, `debug`, `disableOrgProxy`,
7
- * `designMode`, and `designModeExcludePaths`.
9
+ * `designMode`, `designModeExcludePaths`, and `buildManifest`.
8
10
  */
9
11
  export type PluginOptions = CorePluginOptions;
10
12
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AACnC,OAAO,EAAqB,KAAK,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAErF,YAAY,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAChE,YAAY,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAE7E;;;GAGG;AACH,MAAM,MAAM,aAAa,GAAG,iBAAiB,CAAC;AAE9C;;;;;;GAMG;AACH,MAAM,CAAC,OAAO,UAAU,cAAc,CAAC,OAAO,GAAE,aAAkB,GAAG,MAAM,EAAE,CAG5E"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AACnC,OAAO,EAAqB,KAAK,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAErF,YAAY,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAChE,YAAY,EAAE,iBAAiB,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAC7E,YAAY,EACX,oBAAoB,EACpB,iBAAiB,EACjB,qBAAqB,GACrB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAE3D;;;GAGG;AACH,MAAM,MAAM,aAAa,GAAG,iBAAiB,CAAC;AAE9C;;;;;;GAMG;AACH,MAAM,CAAC,OAAO,UAAU,cAAc,CAAC,OAAO,GAAE,aAAkB,GAAG,MAAM,EAAE,CAG5E"}
package/dist/index.js CHANGED
@@ -1,7 +1,9 @@
1
- import { c as createCorePlugins } from "./createCorePlugins-CC0qwAbX.js";
1
+ import { c as createCorePlugins } from "./createCorePlugins-CDMGSlej.js";
2
+ import { B } from "./createCorePlugins-CDMGSlej.js";
2
3
  function uiBundlePlugin(options = {}) {
3
4
  return createCorePlugins(options);
4
5
  }
5
6
  export {
7
+ B as BUILD_MANIFEST_FILE,
6
8
  uiBundlePlugin as default
7
9
  };
@@ -1,4 +1,4 @@
1
- import { c as createCorePlugins } from "../createCorePlugins-CC0qwAbX.js";
1
+ import { c as createCorePlugins } from "../createCorePlugins-CDMGSlej.js";
2
2
  function resolveLanguageFromUrl(url, supported) {
3
3
  const [defaultLang, ...nonDefault] = supported;
4
4
  if (defaultLang === void 0) return void 0;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@salesforce/vite-plugin-ui-bundle",
3
3
  "description": "Vite plugin for Salesforce UI Bundles",
4
- "version": "12.15.0",
4
+ "version": "12.17.0",
5
5
  "license": "SEE LICENSE IN LICENSE.txt",
6
6
  "type": "module",
7
7
  "main": "./dist/index.js",
@@ -26,22 +26,27 @@
26
26
  "clean": "rm -rf dist",
27
27
  "dev": "vite build --watch",
28
28
  "test": "vitest run",
29
+ "test:e2e": "playwright test",
29
30
  "test:watch": "vitest",
30
31
  "test:coverage": "vitest run --coverage"
31
32
  },
32
33
  "dependencies": {
33
34
  "@babel/core": "^7.29.6",
34
- "@salesforce/ui-bundle": "^12.15.0",
35
- "@salesforce/ui-design-mode": "12.15.0"
35
+ "@salesforce/ui-bundle": "^12.17.0",
36
+ "@salesforce/ui-design-mode": "12.17.0"
36
37
  },
37
38
  "devDependencies": {
39
+ "@playwright/test": "^1.63.0",
38
40
  "@types/babel__core": "^7.20.5",
39
- "vite": "^7.3.5",
41
+ "@vitejs/plugin-react": "^4.7.0",
42
+ "react": "^19.3.0",
43
+ "react-dom": "^19.3.0",
44
+ "vite": "^7.3.7",
40
45
  "vite-plugin-dts": "^4.5.4",
41
46
  "vitest": "^4.1.11"
42
47
  },
43
48
  "peerDependencies": {
44
- "vite": "^7.0.0"
49
+ "vite": "^7.0.0 || ^8.0.0"
45
50
  },
46
51
  "engines": {
47
52
  "node": ">=20.0.0"
@@ -1,592 +0,0 @@
1
- import { readFile } from "node:fs/promises";
2
- import path, { dirname, join, basename } from "node:path";
3
- import { loadManifest, getOrgInfo, loadDevProxyConfig } from "@salesforce/ui-bundle/app";
4
- import { injectLivePreviewScript, createProxyHandler } from "@salesforce/ui-bundle/proxy";
5
- import fs, { existsSync, readFileSync, readdirSync } from "node:fs";
6
- import { ASSETS_ROOT, resolveAssetRef, CSS_URL_TOKEN_SOURCE } from "@salesforce/ui-design-mode/authoring/host";
7
- import { getRuntimeScriptContent } from "@salesforce/ui-design-mode/runtime";
8
- import reactDesignTimeLocatorBabelPlugin from "@salesforce/ui-design-mode/source-locator/react";
9
- const DEFAULT_PORT = 5173;
10
- const DEFAULT_PREVIEW_PORT = 4173;
11
- const DEFAULT_API_VERSION = "65.0";
12
- const DEFAULT_NAMESPACE = "c";
13
- function getAppName(rootPath) {
14
- try {
15
- const files = readdirSync(rootPath);
16
- const metaFile = files.find((f) => f.endsWith(".uibundle-meta.xml"));
17
- if (metaFile) {
18
- return metaFile.replace(".uibundle-meta.xml", "");
19
- }
20
- } catch {
21
- }
22
- return basename(rootPath);
23
- }
24
- function getNamespace(startDir) {
25
- let dir = startDir;
26
- for (let parent = dirname(dir); ; dir = parent, parent = dirname(dir)) {
27
- const sfdxProjectPath = join(dir, "sfdx-project.json");
28
- if (existsSync(sfdxProjectPath)) {
29
- try {
30
- const namespace = JSON.parse(readFileSync(sfdxProjectPath, "utf-8")).namespace;
31
- if (typeof namespace === "string" && namespace.trim()) {
32
- return namespace.trim();
33
- }
34
- } catch {
35
- }
36
- return DEFAULT_NAMESPACE;
37
- }
38
- if (parent === dir) {
39
- break;
40
- }
41
- }
42
- return DEFAULT_NAMESPACE;
43
- }
44
- function getCodeBuilderBasePath(proxyUri, port) {
45
- try {
46
- const url = new URL(proxyUri.replace("{{port}}", port.toString()));
47
- return url.pathname;
48
- } catch (error) {
49
- console.error("Failed to parse CODE_BUILDER_FRAMEWORK_PROXY_URI:", error);
50
- return `/absproxy/${port}`;
51
- }
52
- }
53
- function getDevServerTarget(codeBuilderProxyUrl, port) {
54
- if (codeBuilderProxyUrl) {
55
- return getCodeBuilderBasePath(codeBuilderProxyUrl, port);
56
- }
57
- return `http://localhost:${port}`;
58
- }
59
- function getPort() {
60
- return parseInt(process.env.SF_UIBUNDLE_PORT || DEFAULT_PORT.toString(), 10);
61
- }
62
- const ASSET_ATTRS = /* @__PURE__ */ new Set(["src", "poster", "href", "srcSet", "srcset"]);
63
- const CSS_URL_TOKEN = new RegExp(CSS_URL_TOKEN_SOURCE, "gi");
64
- const escapeTemplateRaw = (s) => s.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/g, "\\${");
65
- const suffixOf = (raw) => raw.match(/[?#].*$/)?.[0] ?? "";
66
- function createTracerBabelPlugin(emit, onTouch) {
67
- return ({ types: t }) => {
68
- const fileUrlExpr = (referenceId) => t.memberExpression(
69
- t.metaProperty(t.identifier("import"), t.identifier("meta")),
70
- t.identifier(`ROLLUP_FILE_URL_${referenceId}`)
71
- );
72
- const withTail = (expr, tail) => tail ? t.templateLiteral(
73
- [
74
- t.templateElement({ raw: "", cooked: "" }, false),
75
- t.templateElement({ raw: escapeTemplateRaw(tail), cooked: tail }, true)
76
- ],
77
- [expr]
78
- ) : expr;
79
- const rewriteCssUrls = (raw) => {
80
- const quasis = [];
81
- const expressions = [];
82
- let buf = "";
83
- let cursor = 0;
84
- let matched = false;
85
- CSS_URL_TOKEN.lastIndex = 0;
86
- let m;
87
- while ((m = CSS_URL_TOKEN.exec(raw)) !== null) {
88
- const inner = m[2];
89
- if (!inner) continue;
90
- const resolved = resolveAssetRef(inner.trim());
91
- if (!resolved) continue;
92
- const referenceId = emit(resolved.assetPath);
93
- if (!referenceId) continue;
94
- matched = true;
95
- buf += raw.slice(cursor, m.index) + "url(";
96
- quasis.push(buf);
97
- expressions.push(fileUrlExpr(referenceId));
98
- buf = suffixOf(inner.trim()) + ")";
99
- cursor = m.index + m[0].length;
100
- }
101
- if (!matched) return null;
102
- buf += raw.slice(cursor);
103
- quasis.push(buf);
104
- return t.templateLiteral(
105
- quasis.map(
106
- (q, i) => t.templateElement({ raw: escapeTemplateRaw(q), cooked: q }, i === quasis.length - 1)
107
- ),
108
- expressions
109
- );
110
- };
111
- return {
112
- name: "asset-ref-tracer",
113
- visitor: {
114
- JSXAttribute(nodePath) {
115
- const nameNode = nodePath.node.name;
116
- if (!t.isJSXIdentifier(nameNode)) return;
117
- if (nameNode.name === "style") {
118
- const attrValue = nodePath.node.value;
119
- if (!t.isJSXExpressionContainer(attrValue)) return;
120
- const obj = attrValue.expression;
121
- if (!t.isObjectExpression(obj)) return;
122
- for (const prop of obj.properties) {
123
- if (!t.isObjectProperty(prop)) continue;
124
- const pv = prop.value;
125
- if (!t.isStringLiteral(pv) || !pv.value.includes("url(")) continue;
126
- const replacement = rewriteCssUrls(pv.value);
127
- if (replacement) {
128
- prop.value = replacement;
129
- onTouch();
130
- }
131
- }
132
- return;
133
- }
134
- if (!ASSET_ATTRS.has(nameNode.name)) return;
135
- const value = nodePath.node.value;
136
- if (!t.isStringLiteral(value)) return;
137
- const isSrcSet = nameNode.name === "srcSet" || nameNode.name === "srcset";
138
- if (isSrcSet) {
139
- if (value.value.includes(",")) return;
140
- const [url, ...descriptor] = value.value.trim().split(/\s+/);
141
- if (!url) return;
142
- const resolved2 = resolveAssetRef(url);
143
- if (!resolved2) return;
144
- const referenceId2 = emit(resolved2.assetPath);
145
- if (!referenceId2) return;
146
- const tail = suffixOf(url) + (descriptor.length ? ` ${descriptor.join(" ")}` : "");
147
- nodePath.node.value = t.jsxExpressionContainer(
148
- withTail(fileUrlExpr(referenceId2), tail)
149
- );
150
- onTouch();
151
- return;
152
- }
153
- const resolved = resolveAssetRef(value.value);
154
- if (!resolved) return;
155
- const referenceId = emit(resolved.assetPath);
156
- if (!referenceId) return;
157
- nodePath.node.value = t.jsxExpressionContainer(
158
- withTail(fileUrlExpr(referenceId), suffixOf(value.value))
159
- );
160
- onTouch();
161
- }
162
- }
163
- };
164
- };
165
- }
166
- function createAssetRefTracerPlugin() {
167
- let root = process.cwd();
168
- let emitted = /* @__PURE__ */ new Map();
169
- return {
170
- name: "@salesforce/vite-plugin-ui-bundle:asset-ref-tracer",
171
- apply: "build",
172
- enforce: "pre",
173
- configResolved(config) {
174
- root = config.root;
175
- },
176
- buildStart() {
177
- emitted = /* @__PURE__ */ new Map();
178
- },
179
- async transform(code, id) {
180
- if (!code.includes(ASSETS_ROOT)) return null;
181
- const filepath = id.split("?", 1)[0] ?? id;
182
- const isTsx = filepath.endsWith(".tsx");
183
- const isJsx = filepath.endsWith(".jsx");
184
- if (!isTsx && !isJsx) return null;
185
- if (filepath.includes("node_modules")) return null;
186
- const emit = (assetPath) => {
187
- const absPath = path.resolve(root, assetPath);
188
- if (emitted.has(absPath)) return emitted.get(absPath) ?? null;
189
- let source;
190
- try {
191
- source = fs.readFileSync(absPath);
192
- } catch {
193
- this.warn(
194
- `[asset-ref-tracer] referenced asset not found, leaving literal unchanged: ${assetPath}`
195
- );
196
- emitted.set(absPath, null);
197
- return null;
198
- }
199
- const referenceId = this.emitFile({
200
- type: "asset",
201
- name: path.basename(assetPath),
202
- source
203
- });
204
- emitted.set(absPath, referenceId);
205
- return referenceId;
206
- };
207
- const { transformAsync } = await import("@babel/core");
208
- let touched = false;
209
- const result = await transformAsync(code, {
210
- filename: filepath,
211
- babelrc: false,
212
- configFile: false,
213
- sourceMaps: true,
214
- parserOpts: {
215
- sourceType: "module",
216
- plugins: isTsx ? ["jsx", "typescript"] : ["jsx"]
217
- },
218
- plugins: [
219
- createTracerBabelPlugin(emit, () => {
220
- touched = true;
221
- })
222
- ]
223
- });
224
- if (!touched || !result?.code) return null;
225
- return { code: result.code, map: result.map };
226
- }
227
- };
228
- }
229
- function createDesignPlugin(options = {}) {
230
- let designModeEnabled = options.designMode ?? false;
231
- return {
232
- name: "@salesforce/vite-plugin-ui-bundle:design",
233
- enforce: "pre",
234
- config(_config, env) {
235
- designModeEnabled = options.designMode ?? env.mode === "design";
236
- },
237
- configureServer(server) {
238
- server.middlewares.use(async (req, res, next) => {
239
- if (!designModeEnabled) {
240
- next();
241
- return;
242
- }
243
- const urlPath = stripUrlQuery(req.url);
244
- if (urlPath.endsWith("/_sfdc/design-mode-interactions.js")) {
245
- try {
246
- const script = getRuntimeScriptContent();
247
- if (script !== null) {
248
- res.setHeader("Content-Type", "application/javascript");
249
- res.setHeader("Cache-Control", "no-cache");
250
- res.end(script);
251
- return;
252
- }
253
- console.error(
254
- `[ui-bundle-plugin] Design mode runtime script not found. Run 'npm run build' in @salesforce/ui-design-mode.`
255
- );
256
- res.writeHead(404);
257
- res.end("Design mode script not found");
258
- return;
259
- } catch (error) {
260
- console.error("[ui-bundle-plugin] Error serving design mode script:", error);
261
- res.writeHead(500);
262
- res.end("Error loading design mode script");
263
- return;
264
- }
265
- }
266
- next();
267
- });
268
- },
269
- async transform(code, id) {
270
- if (!designModeEnabled) return null;
271
- const filepath = id.split("?", 1)[0] ?? id;
272
- const isTsx = filepath.endsWith(".tsx");
273
- const isJsx = filepath.endsWith(".jsx");
274
- if (!isTsx && !isJsx) return null;
275
- if (filepath.includes("node_modules")) return null;
276
- const excludePaths = options.designModeExcludePaths ?? ["/components/ui/"];
277
- if (excludePaths.some((p) => filepath.includes(p))) return null;
278
- let originalSource;
279
- try {
280
- originalSource = fs.readFileSync(filepath, "utf-8");
281
- } catch {
282
- }
283
- const { transformAsync } = await import("@babel/core");
284
- const result = await transformAsync(code, {
285
- filename: filepath,
286
- babelrc: false,
287
- configFile: false,
288
- sourceMaps: true,
289
- parserOpts: {
290
- sourceType: "module",
291
- plugins: isTsx ? ["jsx", "typescript"] : ["jsx"]
292
- },
293
- plugins: [[reactDesignTimeLocatorBabelPlugin, { excludePaths, originalSource }]]
294
- });
295
- if (!result?.code) return null;
296
- return { code: result.code, map: result.map };
297
- },
298
- transformIndexHtml: {
299
- order: "pre",
300
- handler(html) {
301
- const tags = [];
302
- if (designModeEnabled) {
303
- tags.push({
304
- tag: "script",
305
- attrs: { src: "/_sfdc/design-mode-interactions.js" },
306
- injectTo: "body"
307
- });
308
- }
309
- return { html, tags };
310
- }
311
- }
312
- };
313
- }
314
- function stripUrlQuery(url) {
315
- if (!url) return "";
316
- const queryIndex = url.indexOf("?");
317
- return queryIndex === -1 ? url : url.slice(0, queryIndex);
318
- }
319
- const identityResolver = (_url, env) => ({ basePath: env.basePath });
320
- function buildEnvTags(html, env, originalUrl, resolveBasePath = identityResolver) {
321
- html = injectLivePreviewScript(html);
322
- const { basePath, language } = resolveBasePath(originalUrl, env);
323
- const tags = [];
324
- const baseHref = basePath.endsWith("/") ? basePath : `${basePath}/`;
325
- tags.push({
326
- tag: "base",
327
- attrs: { href: baseHref },
328
- injectTo: "head-prepend"
329
- });
330
- const sfdcEnv = {
331
- basePath,
332
- apiPath: env.apiPath
333
- };
334
- if (env.orgUrl) sfdcEnv.orgUrl = env.orgUrl;
335
- if (env.namespace) sfdcEnv.namespace = env.namespace;
336
- if (env.appName) sfdcEnv.appName = env.appName;
337
- if (language) sfdcEnv.language = language;
338
- const sfdcEnvLiteral = JSON.stringify(sfdcEnv).replace(/</g, "\\u003c");
339
- tags.push({
340
- tag: "script",
341
- children: `(function() { globalThis.SFDC_ENV = ${sfdcEnvLiteral}; })();`,
342
- injectTo: "body"
343
- });
344
- return { html, tags };
345
- }
346
- function injectEnvTags(html, env, originalUrl, resolveBasePath = identityResolver) {
347
- const { html: transformed, tags } = buildEnvTags(html, env, originalUrl, resolveBasePath);
348
- let headTags = "";
349
- let bodyTags = "";
350
- for (const tag of tags) {
351
- const rendered = tag.tag === "base" ? `<base href="${escapeAttr(String(tag.attrs.href))}">` : `<script>${String(tag.children)}<\/script>`;
352
- if (tag.injectTo === "head-prepend") headTags += rendered;
353
- else bodyTags += rendered;
354
- }
355
- let out = transformed.replace(/<head(\s[^>]*)?>/i, (open) => `${open}${headTags}`);
356
- out = /<\/body>/i.test(out) ? out.replace(/<\/body>/i, (close) => `${bodyTags}${close}`) : `${out}${bodyTags}`;
357
- return out;
358
- }
359
- function escapeAttr(value) {
360
- return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
361
- }
362
- function getAllowedHostsForCodeBuilder(proxyUrl) {
363
- const CODEBUILDER_WHITELISTED_HOSTS = ["localhost", "127.0.0.1"];
364
- if (proxyUrl) {
365
- try {
366
- const url = new URL(proxyUrl.replace("{{port}}", "0"));
367
- const hostname = url.hostname;
368
- const firstDot = hostname.indexOf(".");
369
- if (firstDot > 0) {
370
- CODEBUILDER_WHITELISTED_HOSTS.push(hostname.substring(firstDot));
371
- }
372
- } catch {
373
- }
374
- }
375
- return CODEBUILDER_WHITELISTED_HOSTS;
376
- }
377
- function createCorePlugins(options = {}, hooks = {}) {
378
- const resolveBasePath = hooks.resolveBasePath ?? identityResolver;
379
- const proxyOptions = {
380
- debug: options.debug ?? false,
381
- // UI-only preview: the handler itself 403s org-data routes (built with no
382
- // orgInfo). Org-route definitions stay centralized in the proxy handler.
383
- uiOnly: !!options.disableOrgProxy
384
- };
385
- let orgInfo;
386
- let manifest;
387
- let environment;
388
- let proxyHandler;
389
- let codeBuilderProxyUrl;
390
- async function applyDevProxyConfig(rootPath) {
391
- try {
392
- const devConfig = await loadDevProxyConfig(
393
- `${rootPath}/ui-bundle.dev.json`
394
- );
395
- if (devConfig) {
396
- proxyOptions.devPaths = { corePaths: devConfig.corePaths };
397
- }
398
- } catch (error) {
399
- console.error(`[ui-bundle-plugin] Failed to load ui-bundle.dev.json:`, error);
400
- }
401
- }
402
- function mountProxyMiddleware(server) {
403
- server.middlewares.use(async (req, res, next) => {
404
- if (proxyHandler) {
405
- try {
406
- await proxyHandler(req, res, next);
407
- } catch (error) {
408
- console.error("[ui-bundle-plugin] Proxy handler error:", error);
409
- next();
410
- }
411
- } else {
412
- if (req.url?.startsWith("/services")) {
413
- res.writeHead(503, { "Content-Type": "application/json" });
414
- res.end(
415
- JSON.stringify({
416
- error: "SERVICE_UNAVAILABLE",
417
- message: "Proxy not initialized."
418
- })
419
- );
420
- return;
421
- }
422
- next();
423
- }
424
- });
425
- }
426
- function createPreviewEnvMiddleware(server) {
427
- return async (req, res, next) => {
428
- if (!environment || req.method !== "GET" && req.method !== "HEAD") {
429
- next();
430
- return;
431
- }
432
- const base = environment.basePath.replace(/\/$/, "");
433
- let pathname;
434
- try {
435
- ({ pathname } = new URL(req.url ?? "/", "http://localhost"));
436
- pathname = decodeURIComponent(pathname);
437
- } catch {
438
- next();
439
- return;
440
- }
441
- const relPath = pathname.startsWith(base) ? pathname.slice(base.length) : pathname;
442
- if (!relPath.endsWith(".html") || req.headers["sec-fetch-dest"] === "script") {
443
- next();
444
- return;
445
- }
446
- const { root, build } = server.config;
447
- const outDir = path.resolve(root, build.outDir);
448
- const filePath = path.resolve(outDir, `.${relPath}`);
449
- if (!filePath.startsWith(outDir + path.sep)) {
450
- next();
451
- return;
452
- }
453
- try {
454
- const html = injectEnvTags(
455
- await readFile(filePath, "utf-8"),
456
- environment,
457
- req.originalUrl ?? req.url,
458
- resolveBasePath
459
- );
460
- res.writeHead(200, {
461
- "Content-Type": "text/html",
462
- "Content-Length": Buffer.byteLength(html)
463
- });
464
- res.end(req.method === "HEAD" ? void 0 : html);
465
- } catch (error) {
466
- if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) {
467
- console.error("[ui-bundle-plugin] Failed to serve preview HTML:", error);
468
- }
469
- next();
470
- }
471
- };
472
- }
473
- const corePlugin = {
474
- name: "@salesforce/vite-plugin-ui-bundle:core",
475
- enforce: "pre",
476
- async config(_config, env) {
477
- let version = DEFAULT_API_VERSION;
478
- if (!options.disableOrgProxy) {
479
- try {
480
- orgInfo = await getOrgInfo(options.orgAlias);
481
- version = orgInfo?.apiVersion || DEFAULT_API_VERSION;
482
- if (options.debug) {
483
- console.log(`[ui-bundle-plugin] Using Salesforce API version: ${version}`);
484
- }
485
- } catch {
486
- version = DEFAULT_API_VERSION;
487
- }
488
- }
489
- codeBuilderProxyUrl = process.env.CODE_BUILDER_FRAMEWORK_PROXY_URI;
490
- const isCodeBuilder = !!codeBuilderProxyUrl;
491
- const define = {
492
- __SF_API_VERSION__: JSON.stringify(version)
493
- };
494
- let base = "./";
495
- if (env.mode !== "production" || env.isPreview) {
496
- const port = env.isPreview ? _config.preview?.port ?? DEFAULT_PREVIEW_PORT : getPort();
497
- const basePath = isCodeBuilder ? getCodeBuilderBasePath(codeBuilderProxyUrl, port) : "/";
498
- environment = { basePath, apiPath: basePath, orgUrl: orgInfo?.instanceUrl };
499
- if (isCodeBuilder) {
500
- base = basePath;
501
- }
502
- }
503
- return {
504
- define,
505
- base,
506
- server: {
507
- port: getPort(),
508
- // Code Builder specific configuration
509
- ...isCodeBuilder && {
510
- allowedHosts: getAllowedHostsForCodeBuilder(codeBuilderProxyUrl),
511
- strictPort: true
512
- }
513
- }
514
- };
515
- },
516
- async configResolved(config) {
517
- try {
518
- const rootPath = config.root ?? process.cwd();
519
- if (environment) {
520
- environment.namespace = getNamespace(rootPath);
521
- environment.appName = getAppName(rootPath);
522
- }
523
- manifest = await loadManifest(`${rootPath}/ui-bundle.json`);
524
- if (!options.disableOrgProxy) {
525
- await applyDevProxyConfig(rootPath);
526
- }
527
- const target = getDevServerTarget(codeBuilderProxyUrl, config.server.port ?? DEFAULT_PORT);
528
- proxyHandler = createProxyHandler(
529
- manifest,
530
- orgInfo,
531
- target,
532
- environment?.basePath,
533
- proxyOptions
534
- );
535
- } catch (error) {
536
- console.error(`[ui-bundle-plugin] Initialization failed:`, error);
537
- }
538
- },
539
- configureServer(server) {
540
- mountProxyMiddleware(server);
541
- },
542
- // Mirror the proxy middleware onto `vite preview` so the built output in
543
- // static/dist/ can be tested against the org too — vite preview ignores the
544
- // dev server's middleware, so it must be mounted here as well.
545
- configurePreviewServer(server) {
546
- mountProxyMiddleware(server);
547
- const injectEnv = createPreviewEnvMiddleware(server);
548
- server.middlewares.use(injectEnv);
549
- return () => {
550
- server.middlewares.use(injectEnv);
551
- };
552
- },
553
- async handleHotUpdate({ file, server }) {
554
- if (file.endsWith("ui-bundle.json")) {
555
- const updatedManifest = await loadManifest(file);
556
- if (updatedManifest) {
557
- manifest = updatedManifest;
558
- const target = getDevServerTarget(
559
- codeBuilderProxyUrl,
560
- server.config.server.port ?? DEFAULT_PORT
561
- );
562
- proxyHandler = createProxyHandler(
563
- manifest,
564
- orgInfo,
565
- target,
566
- environment?.basePath,
567
- proxyOptions
568
- );
569
- server.ws.send({
570
- type: "full-reload",
571
- path: "*"
572
- });
573
- }
574
- }
575
- },
576
- transformIndexHtml: {
577
- order: "pre",
578
- handler(html, ctx) {
579
- if (!environment) {
580
- return { html, tags: [] };
581
- }
582
- return buildEnvTags(html, environment, ctx?.originalUrl, resolveBasePath);
583
- }
584
- }
585
- };
586
- const designPlugin = createDesignPlugin(options);
587
- const assetRefTracerPlugin = createAssetRefTracerPlugin();
588
- return [designPlugin, assetRefTracerPlugin, corePlugin];
589
- }
590
- export {
591
- createCorePlugins as c
592
- };