@salesforce/vite-plugin-ui-bundle 12.16.0 → 12.18.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/README.md +185 -0
- package/dist/core/assetRefTracer.d.ts +10 -1
- package/dist/core/assetRefTracer.d.ts.map +1 -1
- package/dist/core/buildManifest.d.ts +221 -0
- package/dist/core/buildManifest.d.ts.map +1 -0
- package/dist/core/createCorePlugins.d.ts +21 -0
- package/dist/core/createCorePlugins.d.ts.map +1 -1
- package/dist/createCorePlugins-C2hhY3Xv.js +1192 -0
- package/dist/index.d.ts +4 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/site/index.js +1 -1
- package/package.json +17 -5
- package/dist/createCorePlugins-CC0qwAbX.js +0 -592
|
@@ -0,0 +1,1192 @@
|
|
|
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 { singleFilePlugins } from "@salesforce/ui-bundle/vite";
|
|
6
|
+
import fs, { existsSync, readFileSync, readdirSync, rmSync, realpathSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { ASSETS_ROOT, resolveAssetRef, CSS_URL_TOKEN_SOURCE } from "@salesforce/ui-design-mode/authoring/host";
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
9
|
+
import { normalizePath, parseAst } from "vite";
|
|
10
|
+
import { getRuntimeScriptContent } from "@salesforce/ui-design-mode/runtime";
|
|
11
|
+
import reactDesignTimeLocatorBabelPlugin from "@salesforce/ui-design-mode/source-locator/react";
|
|
12
|
+
const DEFAULT_PORT = 5173;
|
|
13
|
+
const DEFAULT_PREVIEW_PORT = 4173;
|
|
14
|
+
const DEFAULT_API_VERSION = "65.0";
|
|
15
|
+
const DEFAULT_NAMESPACE = "c";
|
|
16
|
+
function getAppName(rootPath) {
|
|
17
|
+
try {
|
|
18
|
+
const files = readdirSync(rootPath);
|
|
19
|
+
const metaFile = files.find((f) => f.endsWith(".uibundle-meta.xml"));
|
|
20
|
+
if (metaFile) {
|
|
21
|
+
return metaFile.replace(".uibundle-meta.xml", "");
|
|
22
|
+
}
|
|
23
|
+
} catch {
|
|
24
|
+
}
|
|
25
|
+
return basename(rootPath);
|
|
26
|
+
}
|
|
27
|
+
function getNamespace(startDir) {
|
|
28
|
+
let dir = startDir;
|
|
29
|
+
for (let parent = dirname(dir); ; dir = parent, parent = dirname(dir)) {
|
|
30
|
+
const sfdxProjectPath = join(dir, "sfdx-project.json");
|
|
31
|
+
if (existsSync(sfdxProjectPath)) {
|
|
32
|
+
try {
|
|
33
|
+
const namespace = JSON.parse(readFileSync(sfdxProjectPath, "utf-8")).namespace;
|
|
34
|
+
if (typeof namespace === "string" && namespace.trim()) {
|
|
35
|
+
return namespace.trim();
|
|
36
|
+
}
|
|
37
|
+
} catch {
|
|
38
|
+
}
|
|
39
|
+
return DEFAULT_NAMESPACE;
|
|
40
|
+
}
|
|
41
|
+
if (parent === dir) {
|
|
42
|
+
break;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return DEFAULT_NAMESPACE;
|
|
46
|
+
}
|
|
47
|
+
function getCodeBuilderBasePath(proxyUri, port) {
|
|
48
|
+
try {
|
|
49
|
+
const url = new URL(proxyUri.replace("{{port}}", port.toString()));
|
|
50
|
+
return url.pathname;
|
|
51
|
+
} catch (error) {
|
|
52
|
+
console.error("Failed to parse CODE_BUILDER_FRAMEWORK_PROXY_URI:", error);
|
|
53
|
+
return `/absproxy/${port}`;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function getDevServerTarget(codeBuilderProxyUrl, port) {
|
|
57
|
+
if (codeBuilderProxyUrl) {
|
|
58
|
+
return getCodeBuilderBasePath(codeBuilderProxyUrl, port);
|
|
59
|
+
}
|
|
60
|
+
return `http://localhost:${port}`;
|
|
61
|
+
}
|
|
62
|
+
function getPort() {
|
|
63
|
+
return parseInt(process.env.SF_UIBUNDLE_PORT || DEFAULT_PORT.toString(), 10);
|
|
64
|
+
}
|
|
65
|
+
const ASSET_ATTRS = /* @__PURE__ */ new Set(["src", "poster", "href", "srcSet", "srcset"]);
|
|
66
|
+
const CSS_URL_TOKEN = new RegExp(CSS_URL_TOKEN_SOURCE, "gi");
|
|
67
|
+
const escapeTemplateRaw = (s) => s.replace(/\\/g, "\\\\").replace(/`/g, "\\`").replace(/\$\{/g, "\\${");
|
|
68
|
+
const suffixOf = (raw) => raw.match(/[?#].*$/)?.[0] ?? "";
|
|
69
|
+
const suffixFor = (url, raw) => "importPath" in url ? raw.match(/#.*$/)?.[0] ?? "" : suffixOf(raw);
|
|
70
|
+
function createTracerBabelPlugin(emit, onTouch) {
|
|
71
|
+
return ({ types: t }) => {
|
|
72
|
+
let program;
|
|
73
|
+
const imports = /* @__PURE__ */ new Map();
|
|
74
|
+
const fileUrlExpr = (url) => {
|
|
75
|
+
if ("importPath" in url) {
|
|
76
|
+
let name = imports.get(url.importPath);
|
|
77
|
+
if (!name) {
|
|
78
|
+
name = program.scope.generateUidIdentifier("sfAsset").name;
|
|
79
|
+
imports.set(url.importPath, name);
|
|
80
|
+
}
|
|
81
|
+
return t.identifier(name);
|
|
82
|
+
}
|
|
83
|
+
return t.memberExpression(
|
|
84
|
+
t.metaProperty(t.identifier("import"), t.identifier("meta")),
|
|
85
|
+
t.identifier(`ROLLUP_FILE_URL_${url.referenceId}`)
|
|
86
|
+
);
|
|
87
|
+
};
|
|
88
|
+
const withTail = (expr, tail) => tail ? t.templateLiteral(
|
|
89
|
+
[
|
|
90
|
+
t.templateElement({ raw: "", cooked: "" }, false),
|
|
91
|
+
t.templateElement({ raw: escapeTemplateRaw(tail), cooked: tail }, true)
|
|
92
|
+
],
|
|
93
|
+
[expr]
|
|
94
|
+
) : expr;
|
|
95
|
+
const rewriteCssUrls = (raw) => {
|
|
96
|
+
const quasis = [];
|
|
97
|
+
const expressions = [];
|
|
98
|
+
let buf = "";
|
|
99
|
+
let cursor = 0;
|
|
100
|
+
let matched = false;
|
|
101
|
+
CSS_URL_TOKEN.lastIndex = 0;
|
|
102
|
+
let m;
|
|
103
|
+
while ((m = CSS_URL_TOKEN.exec(raw)) !== null) {
|
|
104
|
+
const inner = m[2];
|
|
105
|
+
if (!inner) continue;
|
|
106
|
+
const resolved = resolveAssetRef(inner.trim());
|
|
107
|
+
if (!resolved) continue;
|
|
108
|
+
const assetUrl = emit(resolved.assetPath, inner.trim());
|
|
109
|
+
if (!assetUrl) continue;
|
|
110
|
+
matched = true;
|
|
111
|
+
buf += raw.slice(cursor, m.index) + 'url("';
|
|
112
|
+
quasis.push(buf);
|
|
113
|
+
expressions.push(fileUrlExpr(assetUrl));
|
|
114
|
+
buf = suffixFor(assetUrl, inner.trim()) + '")';
|
|
115
|
+
cursor = m.index + m[0].length;
|
|
116
|
+
}
|
|
117
|
+
if (!matched) return null;
|
|
118
|
+
buf += raw.slice(cursor);
|
|
119
|
+
quasis.push(buf);
|
|
120
|
+
return t.templateLiteral(
|
|
121
|
+
quasis.map(
|
|
122
|
+
(q, i) => t.templateElement({ raw: escapeTemplateRaw(q), cooked: q }, i === quasis.length - 1)
|
|
123
|
+
),
|
|
124
|
+
expressions
|
|
125
|
+
);
|
|
126
|
+
};
|
|
127
|
+
return {
|
|
128
|
+
name: "asset-ref-tracer",
|
|
129
|
+
visitor: {
|
|
130
|
+
Program: {
|
|
131
|
+
enter(nodePath) {
|
|
132
|
+
program = nodePath;
|
|
133
|
+
imports.clear();
|
|
134
|
+
},
|
|
135
|
+
// Single-file builds: one `import <binding> from "<asset>"` per distinct asset.
|
|
136
|
+
exit(nodePath) {
|
|
137
|
+
if (!imports.size) return;
|
|
138
|
+
nodePath.unshiftContainer(
|
|
139
|
+
"body",
|
|
140
|
+
[...imports].map(
|
|
141
|
+
([specifier, name]) => t.importDeclaration(
|
|
142
|
+
[t.importDefaultSpecifier(t.identifier(name))],
|
|
143
|
+
t.stringLiteral(specifier)
|
|
144
|
+
)
|
|
145
|
+
)
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
},
|
|
149
|
+
JSXAttribute(nodePath) {
|
|
150
|
+
const nameNode = nodePath.node.name;
|
|
151
|
+
if (!t.isJSXIdentifier(nameNode)) return;
|
|
152
|
+
if (nameNode.name === "style") {
|
|
153
|
+
const attrValue = nodePath.node.value;
|
|
154
|
+
if (!t.isJSXExpressionContainer(attrValue)) return;
|
|
155
|
+
const obj = attrValue.expression;
|
|
156
|
+
if (!t.isObjectExpression(obj)) return;
|
|
157
|
+
for (const prop of obj.properties) {
|
|
158
|
+
if (!t.isObjectProperty(prop)) continue;
|
|
159
|
+
const pv = prop.value;
|
|
160
|
+
if (!t.isStringLiteral(pv) || !pv.value.includes("url(")) continue;
|
|
161
|
+
const replacement = rewriteCssUrls(pv.value);
|
|
162
|
+
if (replacement) {
|
|
163
|
+
prop.value = replacement;
|
|
164
|
+
onTouch();
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
if (!ASSET_ATTRS.has(nameNode.name)) return;
|
|
170
|
+
const value = nodePath.node.value;
|
|
171
|
+
if (!t.isStringLiteral(value)) return;
|
|
172
|
+
const isSrcSet = nameNode.name === "srcSet" || nameNode.name === "srcset";
|
|
173
|
+
if (isSrcSet) {
|
|
174
|
+
if (value.value.includes(",")) return;
|
|
175
|
+
const [url, ...descriptor] = value.value.trim().split(/\s+/);
|
|
176
|
+
if (!url) return;
|
|
177
|
+
const resolved2 = resolveAssetRef(url);
|
|
178
|
+
if (!resolved2) return;
|
|
179
|
+
const assetUrl2 = emit(resolved2.assetPath, url);
|
|
180
|
+
if (!assetUrl2) return;
|
|
181
|
+
const tail = suffixFor(assetUrl2, url) + (descriptor.length ? ` ${descriptor.join(" ")}` : "");
|
|
182
|
+
nodePath.node.value = t.jsxExpressionContainer(withTail(fileUrlExpr(assetUrl2), tail));
|
|
183
|
+
onTouch();
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
const resolved = resolveAssetRef(value.value);
|
|
187
|
+
if (!resolved) return;
|
|
188
|
+
const assetUrl = emit(resolved.assetPath, value.value);
|
|
189
|
+
if (!assetUrl) return;
|
|
190
|
+
nodePath.node.value = t.jsxExpressionContainer(
|
|
191
|
+
withTail(fileUrlExpr(assetUrl), suffixFor(assetUrl, value.value))
|
|
192
|
+
);
|
|
193
|
+
onTouch();
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
function createAssetRefTracerPlugin({ inline = false } = {}) {
|
|
200
|
+
let root = process.cwd();
|
|
201
|
+
let emitted = /* @__PURE__ */ new Map();
|
|
202
|
+
return {
|
|
203
|
+
name: "@salesforce/vite-plugin-ui-bundle:asset-ref-tracer",
|
|
204
|
+
apply: "build",
|
|
205
|
+
enforce: "pre",
|
|
206
|
+
configResolved(config) {
|
|
207
|
+
root = config.root;
|
|
208
|
+
},
|
|
209
|
+
buildStart() {
|
|
210
|
+
emitted = /* @__PURE__ */ new Map();
|
|
211
|
+
},
|
|
212
|
+
async transform(code, id) {
|
|
213
|
+
if (!code.includes(ASSETS_ROOT)) return null;
|
|
214
|
+
const filepath = id.split("?", 1)[0] ?? id;
|
|
215
|
+
const isTsx = filepath.endsWith(".tsx");
|
|
216
|
+
const isJsx = filepath.endsWith(".jsx");
|
|
217
|
+
if (!isTsx && !isJsx) return null;
|
|
218
|
+
if (filepath.includes("node_modules")) return null;
|
|
219
|
+
const emit = (assetPath, raw) => {
|
|
220
|
+
const absPath = path.resolve(root, assetPath);
|
|
221
|
+
const isSvgFragment = inline && /\.svg$/i.test(absPath) && suffixOf(raw).includes("#");
|
|
222
|
+
const key = isSvgFragment ? `${absPath}#` : absPath;
|
|
223
|
+
let referenceId = emitted.get(key);
|
|
224
|
+
if (referenceId === void 0) {
|
|
225
|
+
let source;
|
|
226
|
+
try {
|
|
227
|
+
source = fs.readFileSync(absPath);
|
|
228
|
+
} catch {
|
|
229
|
+
this.warn(
|
|
230
|
+
`[asset-ref-tracer] referenced asset not found, leaving literal unchanged: ${assetPath}`
|
|
231
|
+
);
|
|
232
|
+
}
|
|
233
|
+
if (source && (!inline || isSvgFragment)) {
|
|
234
|
+
this.addWatchFile(absPath);
|
|
235
|
+
referenceId = this.emitFile({ type: "asset", name: path.basename(assetPath), source });
|
|
236
|
+
} else {
|
|
237
|
+
referenceId = source ? "" : null;
|
|
238
|
+
}
|
|
239
|
+
emitted.set(key, referenceId);
|
|
240
|
+
}
|
|
241
|
+
if (referenceId === null) return null;
|
|
242
|
+
if (isSvgFragment) {
|
|
243
|
+
this.warn(
|
|
244
|
+
`[asset-ref-tracer] SVG fragment refs can't be inlined in single-file builds; "${raw}" is emitted as a separate file, so the build isn't fully self-contained. Inline the <symbol> markup or import the SVG as a component.`
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
if (!inline || isSvgFragment) return { referenceId };
|
|
248
|
+
const rel = path.relative(path.dirname(filepath), absPath).split(path.sep).join("/");
|
|
249
|
+
return { importPath: rel.startsWith(".") ? rel : `./${rel}` };
|
|
250
|
+
};
|
|
251
|
+
const { transformAsync } = await import("@babel/core");
|
|
252
|
+
let touched = false;
|
|
253
|
+
const result = await transformAsync(code, {
|
|
254
|
+
filename: filepath,
|
|
255
|
+
babelrc: false,
|
|
256
|
+
configFile: false,
|
|
257
|
+
sourceMaps: true,
|
|
258
|
+
parserOpts: {
|
|
259
|
+
sourceType: "module",
|
|
260
|
+
plugins: isTsx ? ["jsx", "typescript"] : ["jsx"]
|
|
261
|
+
},
|
|
262
|
+
plugins: [
|
|
263
|
+
createTracerBabelPlugin(emit, () => {
|
|
264
|
+
touched = true;
|
|
265
|
+
})
|
|
266
|
+
]
|
|
267
|
+
});
|
|
268
|
+
if (!touched || !result?.code) return null;
|
|
269
|
+
return { code: result.code, map: result.map };
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
const BUILD_MANIFEST_FILE = "ui-bundle.build.json";
|
|
274
|
+
const REQUIRE_PREFIX = "\0ui-bundle-shared-require:";
|
|
275
|
+
const BUNDLE_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_]*\/[A-Za-z][A-Za-z0-9_]*$/;
|
|
276
|
+
const VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
277
|
+
const ACCESS_CHECK_PATTERN = /^(?:Gater(?:\.[A-Za-z][A-Za-z0-9_]*)+|[A-Za-z][A-Za-z0-9_]*\.[A-Za-z][A-Za-z0-9_]*)$/;
|
|
278
|
+
const COMPOSITION_KEYS = ["screens", "screenDependencies"];
|
|
279
|
+
const SCREEN_KEYS = ["mount", "section", "label", "order", "icon", "access"];
|
|
280
|
+
const INT32 = { min: -2147483648, max: 2 ** 31 - 1 };
|
|
281
|
+
const BUILD_MANIFEST_VERSION = 1;
|
|
282
|
+
const LOG_PREFIX = "[ui-bundle-build-manifest]";
|
|
283
|
+
function readJson(file) {
|
|
284
|
+
try {
|
|
285
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
286
|
+
} catch (e) {
|
|
287
|
+
throw new Error(`${LOG_PREFIX} ${file} is not valid JSON: ${e.message}`, {
|
|
288
|
+
cause: e
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
function readJsonIfPresent(file) {
|
|
293
|
+
return existsSync(file) ? readJson(file) : void 0;
|
|
294
|
+
}
|
|
295
|
+
function findSharedAllowlist(root) {
|
|
296
|
+
for (let dir = path.resolve(root); ; dir = path.dirname(dir)) {
|
|
297
|
+
const shared = readJsonIfPresent(path.join(dir, "package.json"))?.uiBundleShared;
|
|
298
|
+
if (shared !== void 0) {
|
|
299
|
+
if (!Array.isArray(shared) || !shared.every((s) => typeof s === "string")) {
|
|
300
|
+
throw new Error(
|
|
301
|
+
`${LOG_PREFIX} ${path.join(dir, "package.json")}: "uiBundleShared" must be an array of strings`
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
return shared;
|
|
305
|
+
}
|
|
306
|
+
if (path.dirname(dir) === dir) return void 0;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
function packageRootExport(pkg) {
|
|
310
|
+
let target = pkg.exports;
|
|
311
|
+
if (target && typeof target === "object" && !Array.isArray(target)) {
|
|
312
|
+
const map = target;
|
|
313
|
+
if (Object.keys(map).some((k) => k.startsWith("."))) target = map["."];
|
|
314
|
+
}
|
|
315
|
+
while (target && typeof target === "object" && !Array.isArray(target)) {
|
|
316
|
+
const conditions = target;
|
|
317
|
+
target = conditions.import ?? conditions.default;
|
|
318
|
+
}
|
|
319
|
+
return typeof target === "string" ? target : void 0;
|
|
320
|
+
}
|
|
321
|
+
function packageName(specifier) {
|
|
322
|
+
const parts = specifier.split("/");
|
|
323
|
+
return parts.slice(0, specifier.startsWith("@") ? 2 : 1).join("/");
|
|
324
|
+
}
|
|
325
|
+
const RANGE_VERSION = /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:\+.*)?$/;
|
|
326
|
+
function isCoreRange(range) {
|
|
327
|
+
const isVersion = (v) => RANGE_VERSION.test(v) && (v.match(/\d+/g) ?? []).every((n) => Number(n) <= INT32.max);
|
|
328
|
+
return range.split("||").every((alternative) => {
|
|
329
|
+
const trimmed = alternative.trim();
|
|
330
|
+
const hyphen = /^(\S+)\s+-\s+(\S+)$/.exec(trimmed);
|
|
331
|
+
if (hyphen) return isVersion(hyphen[1]) && isVersion(hyphen[2]);
|
|
332
|
+
const comparators = trimmed.replace(/(<=|>=|<|>|=|\^|~)\s+/g, "$1").split(/\s+/);
|
|
333
|
+
return comparators.every((c) => !c || isVersion(c.replace(/^(<=|>=|<|>|=|\^|~)/, "")));
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
function editDistance(a, b) {
|
|
337
|
+
let row = Array.from({ length: b.length + 1 }, (_, j) => j);
|
|
338
|
+
for (let i = 1; i <= a.length; i++) {
|
|
339
|
+
const next = [i];
|
|
340
|
+
for (let j = 1; j <= b.length; j++) {
|
|
341
|
+
next[j] = Math.min(
|
|
342
|
+
row[j] + 1,
|
|
343
|
+
next[j - 1] + 1,
|
|
344
|
+
row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)
|
|
345
|
+
);
|
|
346
|
+
}
|
|
347
|
+
row = next;
|
|
348
|
+
}
|
|
349
|
+
return row[b.length];
|
|
350
|
+
}
|
|
351
|
+
function closeKey(key, known) {
|
|
352
|
+
const lower = key.toLowerCase();
|
|
353
|
+
return known.find((k) => editDistance(lower, k.toLowerCase()) <= 2);
|
|
354
|
+
}
|
|
355
|
+
function unknownKeys(object, known, at) {
|
|
356
|
+
return Object.keys(object).filter((key) => !known.includes(key)).map((key) => {
|
|
357
|
+
const hint = closeKey(key, known);
|
|
358
|
+
return `${at} has unknown key "${key}"${hint ? `; did you mean "${hint}"?` : ""}`;
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
function nodeModulesPackage(id) {
|
|
362
|
+
return id.match(/\/node_modules\/((?:@[^/]+\/)?[^/]+)(?=\/)/g)?.pop()?.slice("/node_modules/".length);
|
|
363
|
+
}
|
|
364
|
+
function isMount(mount) {
|
|
365
|
+
return /^(\/[A-Za-z0-9._~!$&'()+,;=@-]+)+$/.test(mount) && mount.slice(1).split("/").every((seg) => seg !== "." && seg !== "..");
|
|
366
|
+
}
|
|
367
|
+
function mountsOverlap(a, b) {
|
|
368
|
+
return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
|
|
369
|
+
}
|
|
370
|
+
const isStringArray = (v) => Array.isArray(v) && v.every((s) => typeof s === "string");
|
|
371
|
+
function validateScreens(screens) {
|
|
372
|
+
if (!Array.isArray(screens)) return ['"screens" must be an array'];
|
|
373
|
+
const problems = [];
|
|
374
|
+
const claimed = [];
|
|
375
|
+
screens.forEach((s, i) => {
|
|
376
|
+
const at = `screens[${i}]`;
|
|
377
|
+
if (typeof s !== "object" || s === null || Array.isArray(s)) {
|
|
378
|
+
problems.push(`${at} must be an object`);
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
problems.push(...unknownKeys(s, SCREEN_KEYS, at));
|
|
382
|
+
if (typeof s.mount !== "string" || !s.mount) {
|
|
383
|
+
problems.push(`${at} has no "mount"`);
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
if (!isMount(s.mount)) {
|
|
387
|
+
problems.push(
|
|
388
|
+
`${at}.mount "${s.mount}" must be "/" then literal segments, with no trailing "/"`
|
|
389
|
+
);
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
if (s.access !== void 0) {
|
|
393
|
+
if (!isStringArray(s.access)) {
|
|
394
|
+
problems.push(`${at}.access must be an array of strings`);
|
|
395
|
+
} else {
|
|
396
|
+
for (const check of s.access) {
|
|
397
|
+
if (!ACCESS_CHECK_PATTERN.test(check)) {
|
|
398
|
+
problems.push(
|
|
399
|
+
`${at}.access "${check}" must be an access check name, Namespace.checkName or Gater.<gate>`
|
|
400
|
+
);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
if (s.order !== void 0 && !(Number.isInteger(s.order) && s.order >= INT32.min && s.order <= INT32.max)) {
|
|
406
|
+
problems.push(`${at}.order must be an integer from ${INT32.min} to ${INT32.max}`);
|
|
407
|
+
}
|
|
408
|
+
for (const key of ["section", "label", "icon"]) {
|
|
409
|
+
if (s[key] !== void 0 && typeof s[key] !== "string") {
|
|
410
|
+
problems.push(`${at}.${key} must be a string`);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
const overlap = claimed.find((c) => mountsOverlap(c, s.mount));
|
|
414
|
+
if (overlap !== void 0) {
|
|
415
|
+
problems.push(`${at}.mount "${s.mount}" overlaps an earlier screen's "${overlap}"`);
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
claimed.push(s.mount);
|
|
419
|
+
});
|
|
420
|
+
return problems;
|
|
421
|
+
}
|
|
422
|
+
function validateComposition(composition, self) {
|
|
423
|
+
if (typeof composition !== "object" || composition === null || Array.isArray(composition)) {
|
|
424
|
+
return ["composition must be an object"];
|
|
425
|
+
}
|
|
426
|
+
const { screens, screenDependencies } = composition;
|
|
427
|
+
const problems = unknownKeys(
|
|
428
|
+
composition,
|
|
429
|
+
COMPOSITION_KEYS,
|
|
430
|
+
"composition"
|
|
431
|
+
);
|
|
432
|
+
if (screens !== void 0) {
|
|
433
|
+
problems.push(
|
|
434
|
+
...Array.isArray(screens) ? validateScreens(screens).map((p) => `composition.${p}`) : ["composition.screens must be an array"]
|
|
435
|
+
);
|
|
436
|
+
}
|
|
437
|
+
if (screenDependencies !== void 0) {
|
|
438
|
+
if (!isStringArray(screenDependencies)) {
|
|
439
|
+
problems.push("composition.screenDependencies must be an array of strings");
|
|
440
|
+
} else {
|
|
441
|
+
const seen = /* @__PURE__ */ new Set();
|
|
442
|
+
screenDependencies.forEach((name, i) => {
|
|
443
|
+
const at = `composition.screenDependencies[${i}]`;
|
|
444
|
+
if (!BUNDLE_NAME_PATTERN.test(name)) {
|
|
445
|
+
problems.push(`${at} "${name}" must be namespace/name`);
|
|
446
|
+
} else if (self !== void 0 && name.toLowerCase() === self.toLowerCase()) {
|
|
447
|
+
problems.push(`${at} "${name}" is this bundle; a bundle can't list itself`);
|
|
448
|
+
} else if (seen.has(name.toLowerCase())) {
|
|
449
|
+
problems.push(`${at} "${name}" is listed twice; names ignore case`);
|
|
450
|
+
}
|
|
451
|
+
seen.add(name.toLowerCase());
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
return problems;
|
|
456
|
+
}
|
|
457
|
+
function importedSpecifiers(code) {
|
|
458
|
+
const found = [];
|
|
459
|
+
const visit = (node) => {
|
|
460
|
+
if (typeof node !== "object" || node === null) return;
|
|
461
|
+
if (Array.isArray(node)) {
|
|
462
|
+
node.forEach(visit);
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
const { source } = node;
|
|
466
|
+
if (source?.type === "Literal" && typeof source.value === "string") found.push(source.value);
|
|
467
|
+
Object.values(node).forEach(visit);
|
|
468
|
+
};
|
|
469
|
+
visit(parseAst(code));
|
|
470
|
+
return found;
|
|
471
|
+
}
|
|
472
|
+
function entryCss(entry, chunks) {
|
|
473
|
+
const byFile = new Map(chunks.map((c) => [c.fileName, c]));
|
|
474
|
+
const css = /* @__PURE__ */ new Set();
|
|
475
|
+
const seen = /* @__PURE__ */ new Set();
|
|
476
|
+
const visit = (chunk) => {
|
|
477
|
+
if (seen.has(chunk.fileName)) return;
|
|
478
|
+
seen.add(chunk.fileName);
|
|
479
|
+
for (const file of chunk.imports) {
|
|
480
|
+
const imported = byFile.get(file);
|
|
481
|
+
if (imported) visit(imported);
|
|
482
|
+
}
|
|
483
|
+
for (const file of chunk.viteMetadata?.importedCss ?? []) css.add(file);
|
|
484
|
+
};
|
|
485
|
+
visit(entry);
|
|
486
|
+
return [...css];
|
|
487
|
+
}
|
|
488
|
+
const DEFAULT_ASSET_FILE_NAMES = "assets/[name]-[hash][extname]";
|
|
489
|
+
const HASH_PLACEHOLDER = /\[hash(?::\d+)?\]/;
|
|
490
|
+
const md5Of = (source) => createHash("md5").update(source).digest("hex");
|
|
491
|
+
function trackAssetNames(output, named) {
|
|
492
|
+
const original = output.assetFileNames ?? DEFAULT_ASSET_FILE_NAMES;
|
|
493
|
+
return {
|
|
494
|
+
...output,
|
|
495
|
+
assetFileNames(info) {
|
|
496
|
+
const pattern = typeof original === "function" ? original(info) : original;
|
|
497
|
+
const digest = md5Of(info.source);
|
|
498
|
+
named.set(digest, (named.get(digest) ?? true) && HASH_PLACEHOLDER.test(pattern));
|
|
499
|
+
return pattern;
|
|
500
|
+
}
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
function hashedFiles(bundle, namedAssets) {
|
|
504
|
+
const hashed = /* @__PURE__ */ new Set();
|
|
505
|
+
const files = Object.values(bundle);
|
|
506
|
+
const copies = /* @__PURE__ */ new Map();
|
|
507
|
+
for (const file of files) {
|
|
508
|
+
if (file.type === "asset") {
|
|
509
|
+
const digest = md5Of(file.source);
|
|
510
|
+
copies.set(digest, (copies.get(digest) ?? 0) + 1);
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
for (const file of files) {
|
|
514
|
+
if (file.type === "chunk") {
|
|
515
|
+
const preliminary = file.preliminaryFileName;
|
|
516
|
+
if (typeof preliminary === "string" && preliminary !== file.fileName) {
|
|
517
|
+
hashed.add(file.fileName);
|
|
518
|
+
}
|
|
519
|
+
} else {
|
|
520
|
+
const digest = md5Of(file.source);
|
|
521
|
+
if (copies.get(digest) === 1 && namedAssets.get(digest)) hashed.add(file.fileName);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
return hashed;
|
|
525
|
+
}
|
|
526
|
+
const isHtml = (file) => /\.html?$/i.test(file);
|
|
527
|
+
function isInside(dir, file) {
|
|
528
|
+
const rel = path.relative(dir, file);
|
|
529
|
+
return !rel.startsWith("..") && !path.isAbsolute(rel);
|
|
530
|
+
}
|
|
531
|
+
function listFiles(dir, skipped, prefix = "") {
|
|
532
|
+
return readdirSync(path.join(dir, prefix), { withFileTypes: true }).flatMap((d) => {
|
|
533
|
+
const rel = prefix ? `${prefix}/${d.name}` : d.name;
|
|
534
|
+
if (d.isDirectory()) return listFiles(dir, skipped, rel);
|
|
535
|
+
if (d.isFile()) return [rel];
|
|
536
|
+
skipped.push(rel);
|
|
537
|
+
return [];
|
|
538
|
+
}).sort();
|
|
539
|
+
}
|
|
540
|
+
function createBuildManifestPlugin(options = {}) {
|
|
541
|
+
let root = process.cwd();
|
|
542
|
+
let outDir = "";
|
|
543
|
+
let entryPath = "";
|
|
544
|
+
let hasEntry = false;
|
|
545
|
+
let shared = /* @__PURE__ */ new Set();
|
|
546
|
+
let sharedPackages = /* @__PURE__ */ new Set();
|
|
547
|
+
let emptiesOutDir = true;
|
|
548
|
+
const namedAssets = /* @__PURE__ */ new Map();
|
|
549
|
+
let pending;
|
|
550
|
+
return {
|
|
551
|
+
name: "@salesforce/vite-plugin-ui-bundle:build-manifest",
|
|
552
|
+
// The dev server serves source, not a build, so there's nothing to describe.
|
|
553
|
+
// An SSR build isn't what Core serves either. `env.isSsrBuild` reflects only
|
|
554
|
+
// `--ssr` (Vite computes it before loading vite.config), so check `build.ssr` too.
|
|
555
|
+
apply: (config, env) => env.command === "build" && !env.isSsrBuild && !config.build?.ssr,
|
|
556
|
+
// Run before Vite's own resolver, which would otherwise resolve shared
|
|
557
|
+
// specifiers into node_modules and bundle them.
|
|
558
|
+
enforce: "pre",
|
|
559
|
+
configResolved(config) {
|
|
560
|
+
root = config.root;
|
|
561
|
+
outDir = path.resolve(root, config.build.outDir);
|
|
562
|
+
emptiesOutDir = config.build.emptyOutDir ?? isInside(root, outDir);
|
|
563
|
+
const pkgFile = path.join(root, "package.json");
|
|
564
|
+
const entry = options.entry ?? packageRootExport(readJsonIfPresent(pkgFile) ?? {});
|
|
565
|
+
const from = options.entry !== void 0 ? "entry" : `${pkgFile} exports["."]`;
|
|
566
|
+
if (entry !== void 0) {
|
|
567
|
+
entryPath = path.resolve(root, entry);
|
|
568
|
+
hasEntry = true;
|
|
569
|
+
if (!existsSync(entryPath)) {
|
|
570
|
+
throw new Error(`${LOG_PREFIX} ${from} ${entry} does not exist under ${root}`);
|
|
571
|
+
}
|
|
572
|
+
if (isInside(outDir, entryPath)) {
|
|
573
|
+
throw new Error(
|
|
574
|
+
`${LOG_PREFIX} ${from} ${entry} is in the build output; point it at the source module`
|
|
575
|
+
);
|
|
576
|
+
}
|
|
577
|
+
if (!config.build.cssCodeSplit) {
|
|
578
|
+
throw new Error(
|
|
579
|
+
`${LOG_PREFIX} build.cssCodeSplit is false, so the entry's CSS can't be listed in entryCss; set build.cssCodeSplit: true`
|
|
580
|
+
);
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
const list = options.shared ?? findSharedAllowlist(root);
|
|
584
|
+
if (!list) {
|
|
585
|
+
throw new Error(
|
|
586
|
+
`${LOG_PREFIX} No package.json at or above ${root} declares "uiBundleShared"; pass the \`shared\` option.`
|
|
587
|
+
);
|
|
588
|
+
}
|
|
589
|
+
shared = new Set(list);
|
|
590
|
+
sharedPackages = new Set(list.map(packageName));
|
|
591
|
+
},
|
|
592
|
+
// Make the route module an entry and keep its exports: a Vite app build
|
|
593
|
+
// otherwise only builds index.html and strips entry exports.
|
|
594
|
+
options(inputOptions) {
|
|
595
|
+
if (!hasEntry) return null;
|
|
596
|
+
const { input } = inputOptions;
|
|
597
|
+
const inputs = typeof input === "string" ? [input] : input ?? [];
|
|
598
|
+
const listed = Object.values(inputs).some((i) => path.resolve(root, i) === entryPath);
|
|
599
|
+
let nextInput = input;
|
|
600
|
+
if (!listed) {
|
|
601
|
+
if (Array.isArray(inputs)) {
|
|
602
|
+
nextInput = [...inputs, entryPath];
|
|
603
|
+
} else {
|
|
604
|
+
let name = path.parse(entryPath).name;
|
|
605
|
+
while (name in inputs) name = `_${name}`;
|
|
606
|
+
nextInput = { ...inputs, [name]: entryPath };
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
return {
|
|
610
|
+
...inputOptions,
|
|
611
|
+
input: nextInput,
|
|
612
|
+
// "exports-only" keeps the exports of entries that have them (the route
|
|
613
|
+
// module) without forcing a facade chunk for ones that don't (index.html's
|
|
614
|
+
// script). Vite's app-build default is `false`, which strips exports, so
|
|
615
|
+
// that is replaced; any other setting in the config wins.
|
|
616
|
+
preserveEntrySignatures: inputOptions.preserveEntrySignatures || "exports-only"
|
|
617
|
+
};
|
|
618
|
+
},
|
|
619
|
+
buildStart() {
|
|
620
|
+
this.addWatchFile(path.join(root, "package.json"));
|
|
621
|
+
this.addWatchFile(path.join(root, "ui-bundle.json"));
|
|
622
|
+
if (!emptiesOutDir) {
|
|
623
|
+
this.warn(
|
|
624
|
+
`${LOG_PREFIX} Vite won't empty ${outDir}, so files left from an earlier build are listed in ${BUILD_MANIFEST_FILE}; set build.emptyOutDir: true`
|
|
625
|
+
);
|
|
626
|
+
}
|
|
627
|
+
},
|
|
628
|
+
// Watch how assetFileNames names the assets, to tell hashed ones from fixed names.
|
|
629
|
+
outputOptions(output) {
|
|
630
|
+
namedAssets.clear();
|
|
631
|
+
return trackAssetNames(output, namedAssets);
|
|
632
|
+
},
|
|
633
|
+
// Remove the previous build's manifest before anything is written, so a build
|
|
634
|
+
// that fails never leaves one next to its output.
|
|
635
|
+
renderStart(outputOptions) {
|
|
636
|
+
rmSync(
|
|
637
|
+
path.join(
|
|
638
|
+
outputOptions.dir ? path.resolve(outputOptions.dir) : outDir,
|
|
639
|
+
BUILD_MANIFEST_FILE
|
|
640
|
+
),
|
|
641
|
+
{
|
|
642
|
+
force: true
|
|
643
|
+
}
|
|
644
|
+
);
|
|
645
|
+
},
|
|
646
|
+
resolveId(id, importer, resolveOptions) {
|
|
647
|
+
if (!shared.has(id) || importer === void 0) return null;
|
|
648
|
+
if (resolveOptions.kind === "require-call") return REQUIRE_PREFIX + id;
|
|
649
|
+
return { id, external: true };
|
|
650
|
+
},
|
|
651
|
+
load(id) {
|
|
652
|
+
if (!id.startsWith(REQUIRE_PREFIX)) return null;
|
|
653
|
+
const specifier = JSON.stringify(id.slice(REQUIRE_PREFIX.length));
|
|
654
|
+
return `import * as m from ${specifier};
|
|
655
|
+
const exports = "default" in m ? m.default : m;
|
|
656
|
+
export { exports as "module.exports" };
|
|
657
|
+
`;
|
|
658
|
+
},
|
|
659
|
+
generateBundle(_outputOptions, bundle) {
|
|
660
|
+
const chunks = Object.values(bundle).filter(
|
|
661
|
+
(c) => c.type === "chunk"
|
|
662
|
+
);
|
|
663
|
+
const entryIds = new Set(
|
|
664
|
+
hasEntry ? [entryPath, realpathSync(entryPath)].map(normalizePath) : []
|
|
665
|
+
);
|
|
666
|
+
const imported = new Set(chunks.flatMap((c) => importedSpecifiers(c.code)));
|
|
667
|
+
const bundled = /* @__PURE__ */ new Map();
|
|
668
|
+
for (const id of chunks.flatMap((c) => c.moduleIds)) {
|
|
669
|
+
const file = normalizePath(id);
|
|
670
|
+
const name = nodeModulesPackage(file);
|
|
671
|
+
if (name === "react" && sharedPackages.has("react") && /\/jsx-dev-runtime\.|\/react-jsx-dev-runtime\./.test(file)) {
|
|
672
|
+
this.error(
|
|
673
|
+
`${LOG_PREFIX} React's dev JSX runtime is bundled, which crashes on Core's production React; build with NODE_ENV=production (NODE_ENV is ${JSON.stringify(process.env.NODE_ENV)})`
|
|
674
|
+
);
|
|
675
|
+
}
|
|
676
|
+
if (name && sharedPackages.has(name) && !bundled.has(name)) bundled.set(name, id);
|
|
677
|
+
}
|
|
678
|
+
for (const [name, id] of bundled) {
|
|
679
|
+
const specifiers = [...shared].filter((s) => packageName(s) === name).join(", ");
|
|
680
|
+
this.warn(
|
|
681
|
+
`${LOG_PREFIX} ${path.relative(root, id)} from shared package ${name} is bundled; import ${name} only through ${specifiers}, or share the specifier it's imported by`
|
|
682
|
+
);
|
|
683
|
+
}
|
|
684
|
+
const entry = chunks.find(
|
|
685
|
+
(c) => c.isEntry && entryIds.has((c.facadeModuleId ?? "").replace(/\?commonjs-entry$/, ""))
|
|
686
|
+
);
|
|
687
|
+
const hashed = hashedFiles(bundle, namedAssets);
|
|
688
|
+
pending = {
|
|
689
|
+
entry: entry?.fileName,
|
|
690
|
+
entryCss: entry && entryCss(entry, chunks),
|
|
691
|
+
// `imported` also holds the bundle's own chunks; keep only shared specifiers.
|
|
692
|
+
externals: [...imported].filter((id) => shared.has(id)).sort(),
|
|
693
|
+
hashed
|
|
694
|
+
};
|
|
695
|
+
},
|
|
696
|
+
// Ordered "post", so files Vite and earlier plugins write are listed too.
|
|
697
|
+
writeBundle: {
|
|
698
|
+
order: "post",
|
|
699
|
+
sequential: true,
|
|
700
|
+
handler(outputOptions) {
|
|
701
|
+
if (!pending) return;
|
|
702
|
+
const { entry, entryCss: entryCss2, externals, hashed } = pending;
|
|
703
|
+
pending = void 0;
|
|
704
|
+
const dir = outputOptions.dir ? path.resolve(outputOptions.dir) : outDir;
|
|
705
|
+
const pkg = readJsonIfPresent(path.join(root, "package.json")) ?? {};
|
|
706
|
+
const problems = [];
|
|
707
|
+
let peers = pkg.peerDependencies ?? {};
|
|
708
|
+
if (typeof peers !== "object" || peers === null || Array.isArray(peers)) {
|
|
709
|
+
problems.push("package.json peerDependencies must be an object");
|
|
710
|
+
peers = {};
|
|
711
|
+
}
|
|
712
|
+
const peerDependencies = {};
|
|
713
|
+
for (const [name, range] of Object.entries(peers)) {
|
|
714
|
+
if (!sharedPackages.has(name)) continue;
|
|
715
|
+
if (typeof range !== "string") {
|
|
716
|
+
problems.push(`package.json peerDependencies.${name} must be a string`);
|
|
717
|
+
} else if (!isCoreRange(range)) {
|
|
718
|
+
problems.push(
|
|
719
|
+
`package.json peerDependencies.${name} "${range}" isn't a range Core reads; use ^, ~, comparators, x-ranges or a hyphen range, without pre-release versions`
|
|
720
|
+
);
|
|
721
|
+
} else {
|
|
722
|
+
peerDependencies[name] = range;
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
const uiBundleFile = path.join(root, "ui-bundle.json");
|
|
726
|
+
const uiBundle = readJsonIfPresent(uiBundleFile);
|
|
727
|
+
const isObject = typeof uiBundle === "object" && uiBundle !== null && !Array.isArray(uiBundle);
|
|
728
|
+
if (uiBundle !== void 0 && !isObject) {
|
|
729
|
+
problems.push(`${uiBundleFile} must be a JSON object`);
|
|
730
|
+
}
|
|
731
|
+
const config = isObject ? uiBundle : {};
|
|
732
|
+
for (const key of Object.keys(config)) {
|
|
733
|
+
if (key !== "composition" && closeKey(key, ["composition"])) {
|
|
734
|
+
problems.push(`${uiBundleFile} has unknown key "${key}"; did you mean "composition"?`);
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
const { composition, appNamespace, appName } = config;
|
|
738
|
+
const self = typeof appNamespace === "string" && typeof appName === "string" ? `${appNamespace}/${appName}` : void 0;
|
|
739
|
+
if (composition !== void 0) {
|
|
740
|
+
problems.push(
|
|
741
|
+
...validateComposition(composition, self).map((p) => `${uiBundleFile}: ${p}`)
|
|
742
|
+
);
|
|
743
|
+
const screens = composition?.screens;
|
|
744
|
+
if (Array.isArray(screens) && screens.length > 0 && entry === void 0) {
|
|
745
|
+
problems.push(
|
|
746
|
+
hasEntry ? (
|
|
747
|
+
// Configured, but no output chunk is the route module's: something
|
|
748
|
+
// else in the config replaced or renamed the entry.
|
|
749
|
+
`${uiBundleFile} lists composition.screens but no output chunk is the entry ${path.relative(root, entryPath)}; check build.rollupOptions.input and plugins that change entries`
|
|
750
|
+
) : `${uiBundleFile} lists composition.screens but the bundle has no entry; set package.json exports["."] or the entry option`
|
|
751
|
+
);
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
for (const spec of externals) {
|
|
755
|
+
if (typeof peers[packageName(spec)] !== "string") {
|
|
756
|
+
problems.push(
|
|
757
|
+
`${spec} is external but package.json has no peerDependencies range for ${packageName(spec)}`
|
|
758
|
+
);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
const version = options.version ?? pkg.version;
|
|
762
|
+
if (version !== void 0 && (typeof version !== "string" || !VERSION_PATTERN.test(version))) {
|
|
763
|
+
problems.push(
|
|
764
|
+
`version ${JSON.stringify(version)} must be a string matching ${VERSION_PATTERN}, so no +build metadata`
|
|
765
|
+
);
|
|
766
|
+
}
|
|
767
|
+
const html = path.join(dir, "index.html");
|
|
768
|
+
if (existsSync(html) && /<script[^>]*\btype\s*=\s*["']?importmap/i.test(readFileSync(html, "utf8"))) {
|
|
769
|
+
problems.push(
|
|
770
|
+
`index.html has its own <script type="importmap">; Core adds the page's import map, and composes nothing when there already is one`
|
|
771
|
+
);
|
|
772
|
+
}
|
|
773
|
+
if (problems.length) {
|
|
774
|
+
this.error(`${LOG_PREFIX} ${problems.join("\n")}`);
|
|
775
|
+
}
|
|
776
|
+
const skipped = [];
|
|
777
|
+
const files = listFiles(dir, skipped).filter((file) => file !== BUILD_MANIFEST_FILE).map((file) => {
|
|
778
|
+
const bytes = readFileSync(path.join(dir, file));
|
|
779
|
+
return {
|
|
780
|
+
path: file,
|
|
781
|
+
md5: createHash("md5").update(bytes).digest("hex"),
|
|
782
|
+
size: bytes.length,
|
|
783
|
+
// Files that aren't in the bundle (public/, other plugins', an
|
|
784
|
+
// earlier build's) aren't hashed by Rollup, so they're marked too.
|
|
785
|
+
...!isHtml(file) && !hashed.has(file) && { cache: "revalidate" }
|
|
786
|
+
};
|
|
787
|
+
});
|
|
788
|
+
if (skipped.length) {
|
|
789
|
+
this.warn(
|
|
790
|
+
`${LOG_PREFIX} ${BUILD_MANIFEST_FILE} doesn't list ${skipped.join(", ")}: it lists only regular files, not symlinks`
|
|
791
|
+
);
|
|
792
|
+
}
|
|
793
|
+
const manifest = {
|
|
794
|
+
manifestVersion: BUILD_MANIFEST_VERSION,
|
|
795
|
+
entry,
|
|
796
|
+
entryCss: entryCss2,
|
|
797
|
+
externals,
|
|
798
|
+
peerDependencies,
|
|
799
|
+
// An object, or the build failed above.
|
|
800
|
+
uiBundle,
|
|
801
|
+
// A string, or the build failed above.
|
|
802
|
+
version,
|
|
803
|
+
files
|
|
804
|
+
};
|
|
805
|
+
writeFileSync(
|
|
806
|
+
path.join(dir, BUILD_MANIFEST_FILE),
|
|
807
|
+
`${JSON.stringify(manifest, null, 2)}
|
|
808
|
+
`
|
|
809
|
+
);
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
};
|
|
813
|
+
}
|
|
814
|
+
function createDesignPlugin(options = {}) {
|
|
815
|
+
let designModeEnabled = options.designMode ?? false;
|
|
816
|
+
return {
|
|
817
|
+
name: "@salesforce/vite-plugin-ui-bundle:design",
|
|
818
|
+
enforce: "pre",
|
|
819
|
+
config(_config, env) {
|
|
820
|
+
designModeEnabled = options.designMode ?? env.mode === "design";
|
|
821
|
+
},
|
|
822
|
+
configureServer(server) {
|
|
823
|
+
server.middlewares.use(async (req, res, next) => {
|
|
824
|
+
if (!designModeEnabled) {
|
|
825
|
+
next();
|
|
826
|
+
return;
|
|
827
|
+
}
|
|
828
|
+
const urlPath = stripUrlQuery(req.url);
|
|
829
|
+
if (urlPath.endsWith("/_sfdc/design-mode-interactions.js")) {
|
|
830
|
+
try {
|
|
831
|
+
const script = getRuntimeScriptContent();
|
|
832
|
+
if (script !== null) {
|
|
833
|
+
res.setHeader("Content-Type", "application/javascript");
|
|
834
|
+
res.setHeader("Cache-Control", "no-cache");
|
|
835
|
+
res.end(script);
|
|
836
|
+
return;
|
|
837
|
+
}
|
|
838
|
+
console.error(
|
|
839
|
+
`[ui-bundle-plugin] Design mode runtime script not found. Run 'npm run build' in @salesforce/ui-design-mode.`
|
|
840
|
+
);
|
|
841
|
+
res.writeHead(404);
|
|
842
|
+
res.end("Design mode script not found");
|
|
843
|
+
return;
|
|
844
|
+
} catch (error) {
|
|
845
|
+
console.error("[ui-bundle-plugin] Error serving design mode script:", error);
|
|
846
|
+
res.writeHead(500);
|
|
847
|
+
res.end("Error loading design mode script");
|
|
848
|
+
return;
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
next();
|
|
852
|
+
});
|
|
853
|
+
},
|
|
854
|
+
async transform(code, id) {
|
|
855
|
+
if (!designModeEnabled) return null;
|
|
856
|
+
const filepath = id.split("?", 1)[0] ?? id;
|
|
857
|
+
const isTsx = filepath.endsWith(".tsx");
|
|
858
|
+
const isJsx = filepath.endsWith(".jsx");
|
|
859
|
+
if (!isTsx && !isJsx) return null;
|
|
860
|
+
if (filepath.includes("node_modules")) return null;
|
|
861
|
+
const excludePaths = options.designModeExcludePaths ?? ["/components/ui/"];
|
|
862
|
+
if (excludePaths.some((p) => filepath.includes(p))) return null;
|
|
863
|
+
let originalSource;
|
|
864
|
+
try {
|
|
865
|
+
originalSource = fs.readFileSync(filepath, "utf-8");
|
|
866
|
+
} catch {
|
|
867
|
+
}
|
|
868
|
+
const { transformAsync } = await import("@babel/core");
|
|
869
|
+
const result = await transformAsync(code, {
|
|
870
|
+
filename: filepath,
|
|
871
|
+
babelrc: false,
|
|
872
|
+
configFile: false,
|
|
873
|
+
sourceMaps: true,
|
|
874
|
+
parserOpts: {
|
|
875
|
+
sourceType: "module",
|
|
876
|
+
plugins: isTsx ? ["jsx", "typescript"] : ["jsx"]
|
|
877
|
+
},
|
|
878
|
+
plugins: [[reactDesignTimeLocatorBabelPlugin, { excludePaths, originalSource }]]
|
|
879
|
+
});
|
|
880
|
+
if (!result?.code) return null;
|
|
881
|
+
return { code: result.code, map: result.map };
|
|
882
|
+
},
|
|
883
|
+
transformIndexHtml: {
|
|
884
|
+
order: "pre",
|
|
885
|
+
handler(html) {
|
|
886
|
+
const tags = [];
|
|
887
|
+
if (designModeEnabled) {
|
|
888
|
+
tags.push({
|
|
889
|
+
tag: "script",
|
|
890
|
+
attrs: { src: "/_sfdc/design-mode-interactions.js" },
|
|
891
|
+
injectTo: "body"
|
|
892
|
+
});
|
|
893
|
+
}
|
|
894
|
+
return { html, tags };
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
};
|
|
898
|
+
}
|
|
899
|
+
function stripUrlQuery(url) {
|
|
900
|
+
if (!url) return "";
|
|
901
|
+
const queryIndex = url.indexOf("?");
|
|
902
|
+
return queryIndex === -1 ? url : url.slice(0, queryIndex);
|
|
903
|
+
}
|
|
904
|
+
const identityResolver = (_url, env) => ({ basePath: env.basePath });
|
|
905
|
+
function buildEnvTags(html, env, originalUrl, resolveBasePath = identityResolver) {
|
|
906
|
+
html = injectLivePreviewScript(html);
|
|
907
|
+
const { basePath, language } = resolveBasePath(originalUrl, env);
|
|
908
|
+
const tags = [];
|
|
909
|
+
const baseHref = basePath.endsWith("/") ? basePath : `${basePath}/`;
|
|
910
|
+
tags.push({
|
|
911
|
+
tag: "base",
|
|
912
|
+
attrs: { href: baseHref },
|
|
913
|
+
injectTo: "head-prepend"
|
|
914
|
+
});
|
|
915
|
+
const sfdcEnv = {
|
|
916
|
+
basePath,
|
|
917
|
+
apiPath: env.apiPath
|
|
918
|
+
};
|
|
919
|
+
if (env.orgUrl) sfdcEnv.orgUrl = env.orgUrl;
|
|
920
|
+
if (env.namespace) sfdcEnv.namespace = env.namespace;
|
|
921
|
+
if (env.appName) sfdcEnv.appName = env.appName;
|
|
922
|
+
if (language) sfdcEnv.language = language;
|
|
923
|
+
const sfdcEnvLiteral = JSON.stringify(sfdcEnv).replace(/</g, "\\u003c");
|
|
924
|
+
tags.push({
|
|
925
|
+
tag: "script",
|
|
926
|
+
children: `(function() { globalThis.SFDC_ENV = ${sfdcEnvLiteral}; })();`,
|
|
927
|
+
injectTo: "body"
|
|
928
|
+
});
|
|
929
|
+
return { html, tags };
|
|
930
|
+
}
|
|
931
|
+
function injectEnvTags(html, env, originalUrl, resolveBasePath = identityResolver) {
|
|
932
|
+
const { html: transformed, tags } = buildEnvTags(html, env, originalUrl, resolveBasePath);
|
|
933
|
+
let headTags = "";
|
|
934
|
+
let bodyTags = "";
|
|
935
|
+
for (const tag of tags) {
|
|
936
|
+
const rendered = tag.tag === "base" ? `<base href="${escapeAttr(String(tag.attrs.href))}">` : `<script>${String(tag.children)}<\/script>`;
|
|
937
|
+
if (tag.injectTo === "head-prepend") headTags += rendered;
|
|
938
|
+
else bodyTags += rendered;
|
|
939
|
+
}
|
|
940
|
+
let out = transformed.replace(/<head(\s[^>]*)?>/i, (open) => `${open}${headTags}`);
|
|
941
|
+
out = /<\/body>/i.test(out) ? out.replace(/<\/body>/i, (close) => `${bodyTags}${close}`) : `${out}${bodyTags}`;
|
|
942
|
+
return out;
|
|
943
|
+
}
|
|
944
|
+
function escapeAttr(value) {
|
|
945
|
+
return value.replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<");
|
|
946
|
+
}
|
|
947
|
+
function getAllowedHostsForCodeBuilder(proxyUrl) {
|
|
948
|
+
const CODEBUILDER_WHITELISTED_HOSTS = ["localhost", "127.0.0.1"];
|
|
949
|
+
if (proxyUrl) {
|
|
950
|
+
try {
|
|
951
|
+
const url = new URL(proxyUrl.replace("{{port}}", "0"));
|
|
952
|
+
const hostname = url.hostname;
|
|
953
|
+
const firstDot = hostname.indexOf(".");
|
|
954
|
+
if (firstDot > 0) {
|
|
955
|
+
CODEBUILDER_WHITELISTED_HOSTS.push(hostname.substring(firstDot));
|
|
956
|
+
}
|
|
957
|
+
} catch {
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
return CODEBUILDER_WHITELISTED_HOSTS;
|
|
961
|
+
}
|
|
962
|
+
function createCorePlugins(options = {}, hooks = {}) {
|
|
963
|
+
const resolveBasePath = hooks.resolveBasePath ?? identityResolver;
|
|
964
|
+
const proxyOptions = {
|
|
965
|
+
debug: options.debug ?? false,
|
|
966
|
+
// UI-only preview: the handler itself 403s org-data routes (built with no
|
|
967
|
+
// orgInfo). Org-route definitions stay centralized in the proxy handler.
|
|
968
|
+
uiOnly: !!options.disableOrgProxy
|
|
969
|
+
};
|
|
970
|
+
let orgInfo;
|
|
971
|
+
let manifest;
|
|
972
|
+
let environment;
|
|
973
|
+
let proxyHandler;
|
|
974
|
+
let codeBuilderProxyUrl;
|
|
975
|
+
async function applyDevProxyConfig(rootPath) {
|
|
976
|
+
try {
|
|
977
|
+
const devConfig = await loadDevProxyConfig(
|
|
978
|
+
`${rootPath}/ui-bundle.dev.json`
|
|
979
|
+
);
|
|
980
|
+
if (devConfig) {
|
|
981
|
+
proxyOptions.devPaths = { corePaths: devConfig.corePaths };
|
|
982
|
+
}
|
|
983
|
+
} catch (error) {
|
|
984
|
+
console.error(`[ui-bundle-plugin] Failed to load ui-bundle.dev.json:`, error);
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
function mountProxyMiddleware(server) {
|
|
988
|
+
server.middlewares.use(async (req, res, next) => {
|
|
989
|
+
if (proxyHandler) {
|
|
990
|
+
try {
|
|
991
|
+
await proxyHandler(req, res, next);
|
|
992
|
+
} catch (error) {
|
|
993
|
+
console.error("[ui-bundle-plugin] Proxy handler error:", error);
|
|
994
|
+
next();
|
|
995
|
+
}
|
|
996
|
+
} else {
|
|
997
|
+
if (req.url?.startsWith("/services")) {
|
|
998
|
+
res.writeHead(503, { "Content-Type": "application/json" });
|
|
999
|
+
res.end(
|
|
1000
|
+
JSON.stringify({
|
|
1001
|
+
error: "SERVICE_UNAVAILABLE",
|
|
1002
|
+
message: "Proxy not initialized."
|
|
1003
|
+
})
|
|
1004
|
+
);
|
|
1005
|
+
return;
|
|
1006
|
+
}
|
|
1007
|
+
next();
|
|
1008
|
+
}
|
|
1009
|
+
});
|
|
1010
|
+
}
|
|
1011
|
+
function createPreviewEnvMiddleware(server) {
|
|
1012
|
+
return async (req, res, next) => {
|
|
1013
|
+
if (!environment || req.method !== "GET" && req.method !== "HEAD") {
|
|
1014
|
+
next();
|
|
1015
|
+
return;
|
|
1016
|
+
}
|
|
1017
|
+
const base = environment.basePath.replace(/\/$/, "");
|
|
1018
|
+
let pathname;
|
|
1019
|
+
try {
|
|
1020
|
+
({ pathname } = new URL(req.url ?? "/", "http://localhost"));
|
|
1021
|
+
pathname = decodeURIComponent(pathname);
|
|
1022
|
+
} catch {
|
|
1023
|
+
next();
|
|
1024
|
+
return;
|
|
1025
|
+
}
|
|
1026
|
+
const relPath = pathname.startsWith(base) ? pathname.slice(base.length) : pathname;
|
|
1027
|
+
if (!relPath.endsWith(".html") || req.headers["sec-fetch-dest"] === "script") {
|
|
1028
|
+
next();
|
|
1029
|
+
return;
|
|
1030
|
+
}
|
|
1031
|
+
const { root, build } = server.config;
|
|
1032
|
+
const outDir = path.resolve(root, build.outDir);
|
|
1033
|
+
const filePath = path.resolve(outDir, `.${relPath}`);
|
|
1034
|
+
if (!filePath.startsWith(outDir + path.sep)) {
|
|
1035
|
+
next();
|
|
1036
|
+
return;
|
|
1037
|
+
}
|
|
1038
|
+
try {
|
|
1039
|
+
const html = injectEnvTags(
|
|
1040
|
+
await readFile(filePath, "utf-8"),
|
|
1041
|
+
environment,
|
|
1042
|
+
req.originalUrl ?? req.url,
|
|
1043
|
+
resolveBasePath
|
|
1044
|
+
);
|
|
1045
|
+
res.writeHead(200, {
|
|
1046
|
+
"Content-Type": "text/html",
|
|
1047
|
+
"Content-Length": Buffer.byteLength(html)
|
|
1048
|
+
});
|
|
1049
|
+
res.end(req.method === "HEAD" ? void 0 : html);
|
|
1050
|
+
} catch (error) {
|
|
1051
|
+
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) {
|
|
1052
|
+
console.error("[ui-bundle-plugin] Failed to serve preview HTML:", error);
|
|
1053
|
+
}
|
|
1054
|
+
next();
|
|
1055
|
+
}
|
|
1056
|
+
};
|
|
1057
|
+
}
|
|
1058
|
+
const corePlugin = {
|
|
1059
|
+
name: "@salesforce/vite-plugin-ui-bundle:core",
|
|
1060
|
+
enforce: "pre",
|
|
1061
|
+
async config(_config, env) {
|
|
1062
|
+
let version = DEFAULT_API_VERSION;
|
|
1063
|
+
if (!options.disableOrgProxy) {
|
|
1064
|
+
try {
|
|
1065
|
+
orgInfo = await getOrgInfo(options.orgAlias);
|
|
1066
|
+
version = orgInfo?.apiVersion || DEFAULT_API_VERSION;
|
|
1067
|
+
if (options.debug) {
|
|
1068
|
+
console.log(`[ui-bundle-plugin] Using Salesforce API version: ${version}`);
|
|
1069
|
+
}
|
|
1070
|
+
} catch {
|
|
1071
|
+
version = DEFAULT_API_VERSION;
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
codeBuilderProxyUrl = process.env.CODE_BUILDER_FRAMEWORK_PROXY_URI;
|
|
1075
|
+
const isCodeBuilder = !!codeBuilderProxyUrl;
|
|
1076
|
+
const define = {
|
|
1077
|
+
__SF_API_VERSION__: JSON.stringify(version)
|
|
1078
|
+
};
|
|
1079
|
+
let base = "./";
|
|
1080
|
+
if (env.mode !== "production" || env.isPreview) {
|
|
1081
|
+
const port = env.isPreview ? _config.preview?.port ?? DEFAULT_PREVIEW_PORT : getPort();
|
|
1082
|
+
const basePath = isCodeBuilder ? getCodeBuilderBasePath(codeBuilderProxyUrl, port) : "/";
|
|
1083
|
+
environment = { basePath, apiPath: basePath, orgUrl: orgInfo?.instanceUrl };
|
|
1084
|
+
if (isCodeBuilder) {
|
|
1085
|
+
base = basePath;
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
return {
|
|
1089
|
+
define,
|
|
1090
|
+
base,
|
|
1091
|
+
server: {
|
|
1092
|
+
port: getPort(),
|
|
1093
|
+
// Code Builder specific configuration
|
|
1094
|
+
...isCodeBuilder && {
|
|
1095
|
+
allowedHosts: getAllowedHostsForCodeBuilder(codeBuilderProxyUrl),
|
|
1096
|
+
strictPort: true
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
};
|
|
1100
|
+
},
|
|
1101
|
+
async configResolved(config) {
|
|
1102
|
+
try {
|
|
1103
|
+
const rootPath = config.root ?? process.cwd();
|
|
1104
|
+
if (environment) {
|
|
1105
|
+
environment.namespace = getNamespace(rootPath);
|
|
1106
|
+
environment.appName = getAppName(rootPath);
|
|
1107
|
+
}
|
|
1108
|
+
manifest = await loadManifest(`${rootPath}/ui-bundle.json`);
|
|
1109
|
+
if (!options.disableOrgProxy) {
|
|
1110
|
+
await applyDevProxyConfig(rootPath);
|
|
1111
|
+
}
|
|
1112
|
+
const target = getDevServerTarget(codeBuilderProxyUrl, config.server.port ?? DEFAULT_PORT);
|
|
1113
|
+
proxyHandler = createProxyHandler(
|
|
1114
|
+
manifest,
|
|
1115
|
+
orgInfo,
|
|
1116
|
+
target,
|
|
1117
|
+
environment?.basePath,
|
|
1118
|
+
proxyOptions
|
|
1119
|
+
);
|
|
1120
|
+
} catch (error) {
|
|
1121
|
+
console.error(`[ui-bundle-plugin] Initialization failed:`, error);
|
|
1122
|
+
}
|
|
1123
|
+
},
|
|
1124
|
+
configureServer(server) {
|
|
1125
|
+
mountProxyMiddleware(server);
|
|
1126
|
+
},
|
|
1127
|
+
// Mirror the proxy middleware onto `vite preview` so the built output in
|
|
1128
|
+
// static/dist/ can be tested against the org too — vite preview ignores the
|
|
1129
|
+
// dev server's middleware, so it must be mounted here as well.
|
|
1130
|
+
configurePreviewServer(server) {
|
|
1131
|
+
mountProxyMiddleware(server);
|
|
1132
|
+
const injectEnv = createPreviewEnvMiddleware(server);
|
|
1133
|
+
server.middlewares.use(injectEnv);
|
|
1134
|
+
return () => {
|
|
1135
|
+
server.middlewares.use(injectEnv);
|
|
1136
|
+
};
|
|
1137
|
+
},
|
|
1138
|
+
async handleHotUpdate({ file, server }) {
|
|
1139
|
+
if (file.endsWith("ui-bundle.json")) {
|
|
1140
|
+
const updatedManifest = await loadManifest(file);
|
|
1141
|
+
if (updatedManifest) {
|
|
1142
|
+
manifest = updatedManifest;
|
|
1143
|
+
const target = getDevServerTarget(
|
|
1144
|
+
codeBuilderProxyUrl,
|
|
1145
|
+
server.config.server.port ?? DEFAULT_PORT
|
|
1146
|
+
);
|
|
1147
|
+
proxyHandler = createProxyHandler(
|
|
1148
|
+
manifest,
|
|
1149
|
+
orgInfo,
|
|
1150
|
+
target,
|
|
1151
|
+
environment?.basePath,
|
|
1152
|
+
proxyOptions
|
|
1153
|
+
);
|
|
1154
|
+
server.ws.send({
|
|
1155
|
+
type: "full-reload",
|
|
1156
|
+
path: "*"
|
|
1157
|
+
});
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
},
|
|
1161
|
+
transformIndexHtml: {
|
|
1162
|
+
order: "pre",
|
|
1163
|
+
handler(html, ctx) {
|
|
1164
|
+
if (!environment) {
|
|
1165
|
+
return { html, tags: [] };
|
|
1166
|
+
}
|
|
1167
|
+
return buildEnvTags(html, environment, ctx?.originalUrl, resolveBasePath);
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
};
|
|
1171
|
+
const designPlugin = createDesignPlugin(options);
|
|
1172
|
+
const assetRefTracerPlugin = createAssetRefTracerPlugin({ inline: !!options.singleFile });
|
|
1173
|
+
const plugins = [designPlugin, assetRefTracerPlugin, corePlugin];
|
|
1174
|
+
if (options.buildManifest) {
|
|
1175
|
+
plugins.push(
|
|
1176
|
+
createBuildManifestPlugin(options.buildManifest === true ? {} : options.buildManifest)
|
|
1177
|
+
);
|
|
1178
|
+
}
|
|
1179
|
+
if (options.singleFile) {
|
|
1180
|
+
plugins.push(
|
|
1181
|
+
...singleFilePlugins({
|
|
1182
|
+
owner: "@salesforce/vite-plugin-ui-bundle",
|
|
1183
|
+
option: "singleFile: true"
|
|
1184
|
+
})
|
|
1185
|
+
);
|
|
1186
|
+
}
|
|
1187
|
+
return plugins;
|
|
1188
|
+
}
|
|
1189
|
+
export {
|
|
1190
|
+
BUILD_MANIFEST_FILE as B,
|
|
1191
|
+
createCorePlugins as c
|
|
1192
|
+
};
|