-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuiBundleProjectUtils.ts
More file actions
206 lines (189 loc) · 7.08 KB
/
uiBundleProjectUtils.ts
File metadata and controls
206 lines (189 loc) · 7.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
/*
* Copyright 2026, Salesforce, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { execSync } from 'node:child_process';
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
import { homedir, tmpdir } from 'node:os';
import { join } from 'node:path';
import type { TestSession } from '@salesforce/cli-plugins-testkit';
import { UI_BUNDLES_FOLDER } from '../../../../src/config/uiBundleDiscovery.js';
/**
* Real home directory captured at module load, before TestSession overrides process.env.HOME.
* Used when running `sf ui-bundle generate` so the CLI finds linked plugin-templates
* (TestSession sets HOME to a temp dir, which hides linked plugins).
*/
export const REAL_HOME = homedir();
/**
* Relative path from project root to the uiBundles folder.
*/
const UI_BUNDLES_PATH = join('force-app', 'main', 'default', UI_BUNDLES_FOLDER);
/**
* Resolve the absolute path to a UI bundle directory within a project.
* If `uiBundleName` is omitted, returns the uiBundles folder itself.
*/
export function uiBundlePath(projectDir: string, uiBundleName?: string): string {
return uiBundleName ? join(projectDir, UI_BUNDLES_PATH, uiBundleName) : join(projectDir, UI_BUNDLES_PATH);
}
/**
* Verify the global `sf` CLI is available and has the required commands.
* Must be called after TestSession.create() since the session sets a valid HOME.
*/
export function ensureSfCli(): void {
try {
execSync('sf project generate --help', { stdio: 'pipe', timeout: 30_000 });
} catch {
throw new Error(
'Global sf CLI with plugin-templates not found.\n' +
'Install: npm install @salesforce/cli -g\n' +
'CI installs @salesforce/cli@nightly via nut.yml.'
);
}
}
/**
* Authenticate an org via TESTKIT_AUTH_URL without requiring DevHub.
* Returns the authenticated username.
*
* Must be called once per TestSession since each session has its own
* mock home directory where auth files are stored.
*/
export function authOrgViaUrl(): string {
const authUrl = process.env.TESTKIT_AUTH_URL;
if (!authUrl) {
throw new Error('TESTKIT_AUTH_URL environment variable is not set.');
}
// Use --sfdx-url-file for cross-platform reliability
const tmpFile = join(tmpdir(), `testkit-auth-${Date.now()}-${Math.random().toString(36).slice(2)}.txt`);
try {
writeFileSync(tmpFile, authUrl, 'utf8');
const output = execSync(`sf org login sfdx-url --sfdx-url-file "${tmpFile}" --json`, {
stdio: 'pipe',
timeout: 60_000,
}).toString();
const result = JSON.parse(output) as { result: { username: string } };
return result.result.username;
} finally {
rmSync(tmpFile, { force: true });
}
}
/**
* Run `sf project generate --name <name>` inside the session directory.
* Returns the absolute path to the generated project root.
*/
export function createProject(session: TestSession, name: string): string {
execSync(`sf project generate --name ${name}`, {
cwd: session.dir,
stdio: 'pipe',
});
return join(session.dir, name);
}
/**
* Run `sf project generate` then `sf ui-bundle generate --name <uiBundleName>` inside
* the project. Returns the absolute path to the generated project root.
*/
export function createProjectWithUiBundle(session: TestSession, projectName: string, uiBundleName: string): string {
const projectDir = createProject(session, projectName);
execSync(`sf ui-bundle generate --name ${uiBundleName}`, {
cwd: projectDir,
stdio: 'pipe',
env: { ...process.env, HOME: REAL_HOME, USERPROFILE: REAL_HOME },
});
return projectDir;
}
/**
* Create a project with multiple UI bundles. Used to test selection flows when
* more than one UI bundle exists in a single SFDX project.
*/
export function createProjectWithMultipleUiBundles(
session: TestSession,
projectName: string,
uiBundleNames: string[]
): string {
const projectDir = createProject(session, projectName);
for (const name of uiBundleNames) {
execSync(`sf ui-bundle generate --name ${name}`, {
cwd: projectDir,
stdio: 'pipe',
env: { ...process.env, HOME: REAL_HOME, USERPROFILE: REAL_HOME },
});
}
return projectDir;
}
/**
* Create the `uiBundles/` directory (empty — no UI bundles inside).
* Used to test "empty uiBundles folder" scenario.
*/
export function createEmptyUiBundlesDir(projectDir: string): void {
mkdirSync(uiBundlePath(projectDir), { recursive: true });
}
/**
* Create a UI bundle directory without the required `.uibundle-meta.xml`.
* Used to test "no metadata file" scenario.
*/
export function createUiBundleDirWithoutMeta(projectDir: string, name: string): void {
mkdirSync(uiBundlePath(projectDir, name), { recursive: true });
}
/**
* Overwrite the `ui-bundle.json` manifest for a given UI bundle.
*/
export function writeManifest(projectDir: string, uiBundleName: string, manifest: Record<string, unknown>): void {
writeFileSync(join(uiBundlePath(projectDir, uiBundleName), 'ui-bundle.json'), JSON.stringify(manifest, null, 2));
}
/**
* Write a tiny Node.js HTTP server script into the UI bundle directory.
* Returns the command string suitable for `dev.command` in the manifest.
*
* The script is CommonJS (.cjs) to avoid ESM/shell quoting issues.
*/
export function createDevServerScript(uiBundleDir: string, port: number): string {
const script = [
"const http = require('http');",
'const server = http.createServer((_, res) => {',
" res.writeHead(200, { 'Content-Type': 'text/html' });",
" res.end('<h1>Test Dev Server</h1>');",
'});',
`server.listen(${port}, () => {`,
` console.log('listening on port ${port}');`,
'});',
].join('\n');
writeFileSync(join(uiBundleDir, 'dev-server.cjs'), script);
return 'node dev-server.cjs';
}
/**
* Convenience: create a project with a UI bundle whose manifest includes a
* `dev.command` that starts a tiny HTTP server on `devPort`, and
* `dev.url` pointing to that port. Optionally sets `dev.port` (proxy port).
*
* Returns `{ projectDir, uiBundleDir }`.
*/
export function createProjectWithDevServer(
session: TestSession,
projectName: string,
uiBundleName: string,
devPort: number,
proxyPort?: number
): { projectDir: string; uiBundleDir: string } {
const projectDir = createProjectWithUiBundle(session, projectName, uiBundleName);
const uiBundleDir = uiBundlePath(projectDir, uiBundleName);
const devCommand = createDevServerScript(uiBundleDir, devPort);
const dev: Record<string, unknown> = {
url: `http://localhost:${devPort}`,
command: devCommand,
};
if (proxyPort !== undefined) {
dev.port = proxyPort;
}
writeManifest(projectDir, uiBundleName, { dev });
return { projectDir, uiBundleDir };
}