-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathprophet.ts
More file actions
352 lines (293 loc) · 9.83 KB
/
prophet.ts
File metadata and controls
352 lines (293 loc) · 9.83 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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
/*
* Copyright (c) 2025, Salesforce, Inc.
* SPDX-License-Identifier: Apache-2
* For full license text, see the license.txt file in the repo root or http://www.apache.org/licenses/LICENSE-2.0
*/
import * as fs from 'node:fs/promises';
import {existsSync} from 'node:fs';
import path from 'node:path';
import {Flags, ux} from '@oclif/core';
import {BaseCommand} from '@salesforce/b2c-tooling-sdk/cli';
import {withDocs} from '../../../i18n/index.js';
/**
* JSON output structure for setup ide prophet command.
*/
interface SetupIdeProphetResponse {
overwritten: boolean;
path: string;
}
/**
* Build the dw.js script for Prophet integration.
*/
function buildDwJsScript(inspectArgs: string[]): string {
return `/**
* Auto-generated by "b2c setup ide prophet".
* Purpose: Provide Prophet VS Code extension with dw.json-compatible configuration
* by exporting the resolved B2C CLI config as module.exports.
* support dwJson multi-config in prophet and other tools that support dw.js loading
* when this is present prophet will ignore dw.json and instead load the configuration exported
* This script shells out to: b2c setup inspect --json --unmask
*/
var childProcess = require('node:child_process');
var path = require('node:path');
var INSPECT_ARGS = ${JSON.stringify(inspectArgs)};
var dwJson = {};
function logProphetDw(message, error) {
var suffix = error && error.message ? ': ' + String(error.message) : '';
var line = '[b2c setup ide prophet] ' + message + suffix;
// Best-effort logging: this script is loaded by external tools (Prophet) where
// console may be redirected or unavailable. A failure to log a log message is
// not actionable and must not interfere with returning the resolved config.
try {
console.error(line);
} catch (logError) {
/* ignore */
}
try {
console.log(line);
} catch (logError) {
/* ignore */
}
}
function loadDotEnv() {
try {
require('dotenv').config({override: true});
} catch (error) {
// optional dependency
}
}
function getWorkspaceRoot() {
if (process.env.SFCC_PROJECT_DIRECTORY && process.env.SFCC_PROJECT_DIRECTORY.trim()) {
return process.env.SFCC_PROJECT_DIRECTORY.trim();
}
if (process.env.SFCC_WORKING_DIRECTORY && process.env.SFCC_WORKING_DIRECTORY.trim()) {
return process.env.SFCC_WORKING_DIRECTORY.trim();
}
if (process.env.SFCC_CONFIG && process.env.SFCC_CONFIG.trim()) {
return path.dirname(process.env.SFCC_CONFIG.trim());
}
if (typeof __dirname === 'string' && __dirname) {
return __dirname;
}
if (typeof module !== 'undefined' && module && module.filename) {
return path.dirname(module.filename);
}
if (typeof workspace !== 'undefined' && workspace && Array.isArray(workspace.workspaceFolders)) {
for (var i = 0; i < workspace.workspaceFolders.length; i += 1) {
var folder = workspace.workspaceFolders[i];
if (folder && folder.uri && typeof folder.uri.fsPath === 'string' && folder.uri.fsPath) {
return folder.uri.fsPath;
}
}
}
return process.cwd();
}
function withProjectDirectory(args, projectDirectory) {
if (!projectDirectory || args.indexOf('--project-directory') !== -1 || args.indexOf('--working-directory') !== -1) {
return args.slice();
}
return args.concat(['--project-directory', projectDirectory]);
}
function pickInspectConfig(parsed) {
if (!parsed || typeof parsed !== 'object') {
return {};
}
var root = parsed.result && typeof parsed.result === 'object' ? parsed.result : parsed;
if (root.config && typeof root.config === 'object') {
return root.config;
}
if (root.result && root.result.config && typeof root.result.config === 'object') {
return root.result.config;
}
return root;
}
function runSetupInspect(projectDirectory) {
var inspectArgs = withProjectDirectory(INSPECT_ARGS, projectDirectory);
var candidates = [];
if (process.env.B2C_CLI_BIN && process.env.B2C_CLI_BIN.trim()) {
candidates.push({cmd: process.env.B2C_CLI_BIN.trim(), args: inspectArgs});
}
candidates.push({cmd: 'b2c', args: inspectArgs});
candidates.push({cmd: 'npx', args: ['--yes', '@salesforce/b2c-cli'].concat(inspectArgs)});
var lastError;
for (var i = 0; i < candidates.length; i += 1) {
var candidate = candidates[i];
try {
var execOptions = {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
};
if (projectDirectory) {
execOptions.cwd = projectDirectory;
}
var stdout = childProcess.execFileSync(candidate.cmd, candidate.args, execOptions);
return pickInspectConfig(JSON.parse(stdout));
} catch (error) {
logProphetDw('setup inspect candidate failed (' + candidate.cmd + ')', error);
lastError = error;
}
}
throw lastError || new Error('No setup inspect candidate succeeded');
}
function resolveDwJsonConfig(raw) {
if (!raw || typeof raw !== 'object') {
return {};
}
var instanceName = process.env.SFCC_INSTANCE;
if (!instanceName || raw.name !== instanceName) {
if (instanceName && Array.isArray(raw.configs)) {
return raw.configs.find(function (item) {
return item && item.name === instanceName;
}) || raw;
}
if (Array.isArray(raw.configs) && raw.active !== true) {
return raw.configs.find(function (item) {
return item && item.active === true;
}) || raw;
}
}
return raw;
}
function loadDwJsonFallback(projectDirectory) {
try {
var dwJsonPath = process.env.SFCC_CONFIG ? process.env.SFCC_CONFIG : path.join(projectDirectory, 'dw.json');
if (!path.isAbsolute(dwJsonPath)) {
dwJsonPath = path.resolve(projectDirectory || process.cwd(), dwJsonPath);
}
return resolveDwJsonConfig(require(dwJsonPath));
} catch (error) {
logProphetDw('dw.json fallback failed', error);
return {};
}
}
function toProphetConfig(config) {
if (!config || typeof config !== 'object') {
return {};
}
var result = {};
var codeVersion = config['code-version'] || config.codeVersion || config.version;
if (config.hostname || config.server) {
result.hostname = config.hostname || config.server;
}
if (config.username) {
result.username = config.username;
}
if (config.password) {
result.password = config.password;
}
if (codeVersion) {
result['code-version'] = codeVersion;
result.version = codeVersion;
}
if (config.cartridgesPath !== undefined) {
result.cartridgesPath = config.cartridgesPath;
}
if (config.siteID !== undefined || config.siteId !== undefined) {
result.siteID = config.siteID || config.siteId;
}
if (config.storefrontPassword !== undefined) {
result.storefrontPassword = config.storefrontPassword;
}
if (config.cartridge !== undefined) {
result.cartridge = config.cartridge;
}
return result;
}
function loadDwConfig() {
loadDotEnv();
var projectDirectory = getWorkspaceRoot();
try {
var inspectConfig = runSetupInspect(projectDirectory);
var inspectMapped = toProphetConfig(inspectConfig);
if (inspectMapped.hostname) {
return inspectMapped;
}
logProphetDw('setup inspect returned no hostname; falling back to dw.json');
} catch (error) {
logProphetDw('setup inspect failed; falling back to dw.json', error);
}
try {
var fallbackMapped = toProphetConfig(loadDwJsonFallback(projectDirectory));
if (!fallbackMapped.hostname) {
logProphetDw('dw.json fallback returned no hostname');
}
return fallbackMapped;
} catch (error) {
logProphetDw('dw.json mapping failed; returning empty config', error);
return {};
}
}
try {
dwJson = loadDwConfig();
} catch (error) {
logProphetDw('unexpected dw.js error; returning empty config', error);
dwJson = {};
}
module.exports = dwJson;
`;
}
/**
* Create dw.js integration script for Prophet VS Code extension.
*/
export default class SetupIdeProphet extends BaseCommand<typeof SetupIdeProphet> {
static description = withDocs(
'Generate a dw.js script that exposes B2C CLI config for Prophet VS Code',
'/cli/setup.html#b2c-setup-ide-prophet',
);
static enableJsonFlag = true;
static examples = [
'<%= config.bin %> <%= command.id %>',
'<%= config.bin %> <%= command.id %> --force',
'<%= config.bin %> <%= command.id %> --output .vscode/dw.js',
'<%= config.bin %> <%= command.id %> --instance staging',
];
static flags = {
...BaseCommand.baseFlags,
output: Flags.string({
char: 'o',
description: 'Path for generated script file',
default: 'dw.js',
}),
force: Flags.boolean({
char: 'f',
description: 'Overwrite output file if it already exists',
default: false,
}),
};
async run(): Promise<SetupIdeProphetResponse> {
const outputPath = path.resolve(this.flags.output);
const alreadyExists = existsSync(outputPath);
if (alreadyExists && !this.flags.force) {
this.error(`File already exists at ${outputPath}. Use --force to overwrite.`);
}
const inspectArgs = this.buildInspectArgs();
const script = buildDwJsScript(inspectArgs);
await fs.mkdir(path.dirname(outputPath), {recursive: true});
await fs.writeFile(outputPath, script, 'utf8');
const result: SetupIdeProphetResponse = {
path: outputPath,
overwritten: alreadyExists,
};
if (!this.jsonEnabled()) {
ux.stdout(`Created ${outputPath}`);
}
return result;
}
/**
* Build setup inspect arguments for the generated script.
* Includes setup context flags so runtime resolution matches command intent.
*/
private buildInspectArgs(): string[] {
const args = ['setup', 'inspect', '--json', '--unmask'];
if (this.flags.instance) {
args.push('--instance', this.flags.instance);
}
if (this.flags.config) {
args.push('--config', this.flags.config);
}
if (this.flags['project-directory']) {
args.push('--project-directory', this.flags['project-directory']);
}
return args;
}
}