Skip to content

Commit 94108b3

Browse files
committed
feat: add getLatest flag / delete unused code
1 parent ee0a3dc commit 94108b3

File tree

2 files changed

+49
-100
lines changed

2 files changed

+49
-100
lines changed

src/commands/lightning/dev/site.ts

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ export default class LightningDevSite extends SfCommand<void> {
3939

4040
try {
4141
const org = flags['target-org'];
42+
const getLatest = flags['get-latest'];
4243
let siteName = flags.name;
4344

4445
const connection = org.getConnection(undefined);
@@ -59,26 +60,23 @@ export default class LightningDevSite extends SfCommand<void> {
5960
const selectedSite = new ExperienceSite(org, siteName);
6061
let siteZip: string | undefined;
6162

62-
if (!selectedSite.isSiteSetup()) {
63-
this.log(`[local-dev] initializing: ${siteName}`);
63+
// TODO if locally cached site is 252 site, we should trigger an update also
64+
if (!selectedSite.isSiteSetup() || getLatest) {
65+
this.log(`[local-dev] initializing: '${siteName}'`);
66+
this.spinner.start('[local-dev] Downloading site (this may take a few minutes)');
6467
siteZip = await selectedSite.downloadSite();
65-
} else {
66-
// If local-dev is already setup, check if an updated site has been published to download
67-
const updateAvailable = await selectedSite.isUpdateAvailable();
68-
if (updateAvailable) {
69-
const shouldUpdate = await PromptUtils.promptUserToConfirmUpdate(siteName);
70-
if (shouldUpdate) {
71-
this.log(`[local-dev] updating: ${siteName}`);
72-
siteZip = await selectedSite.downloadSite();
73-
// delete oldSitePath recursive
74-
const oldSitePath = selectedSite.getExtractDirectory();
75-
if (fs.existsSync(oldSitePath)) {
76-
fs.rmSync(oldSitePath, { recursive: true });
77-
}
78-
}
68+
69+
// delete oldSitePath recursive
70+
this.spinner.status = '[local-dev] cleaning up site cache';
71+
const oldSitePath = selectedSite.getExtractDirectory();
72+
if (fs.existsSync(oldSitePath)) {
73+
fs.rmSync(oldSitePath, { recursive: true });
7974
}
75+
this.spinner.stop('[local-dev] setup complete');
8076
}
8177

78+
this.log(`[local-dev] launching browser preview for: ${siteName}`);
79+
8280
// Establish a valid access token for this site
8381
const authToken = await selectedSite.setupAuth();
8482

@@ -100,6 +98,7 @@ export default class LightningDevSite extends SfCommand<void> {
10098
await setupDev(startupParams);
10199
} else {
102100
await expDev(startupParams);
101+
this.log('[local-dev] watching for file changes... (CTRL-C to stop)');
103102
}
104103
} catch (e) {
105104
this.log('Local Development setup failed', e);

src/shared/experience/expSite.ts

Lines changed: 34 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -41,44 +41,6 @@ export class ExperienceSite {
4141
this.siteName = this.siteName.replace(/[^a-zA-Z0-9]/g, '_');
4242
}
4343

44-
/**
45-
* Get an experience site bundle by site name.
46-
*
47-
* @param conn - Salesforce connection object.
48-
* @param siteName - The name of the experience site.
49-
* @returns - The experience site.
50-
*
51-
* @param siteName
52-
* @returns
53-
*/
54-
public static getLocalExpSite(siteName: string): ExperienceSite {
55-
const siteJsonPath = path.join('.localdev', siteName.trim().replace(' ', '_'), 'site.json');
56-
const siteJson = fs.readFileSync(siteJsonPath, 'utf8');
57-
const site = JSON.parse(siteJson) as ExperienceSite;
58-
return site;
59-
}
60-
61-
/**
62-
* Fetches all experience site bundles that are published to MRT.
63-
*
64-
* @param {Connection} conn - Salesforce connection object.
65-
* @returns {Promise<ExperienceSite[]>} - List of experience sites.
66-
*/
67-
public static async getAllPublishedExpSites(org: Org): Promise<ExperienceSite[]> {
68-
const result = await org
69-
.getConnection()
70-
.query<{ Id: string; Name: string; LastModifiedDate: string }>(
71-
"SELECT Id, Name, LastModifiedDate FROM StaticResource WHERE Name LIKE 'MRT%_'"
72-
);
73-
74-
// Example of creating ExperienceSite instances
75-
const experienceSites: ExperienceSite[] = result.records.map(
76-
(record) => new ExperienceSite(org, getSiteNameFromStaticResource(record.Name))
77-
);
78-
79-
return experienceSites;
80-
}
81-
8244
/**
8345
* Fetches all current experience sites
8446
*
@@ -227,32 +189,12 @@ export class ExperienceSite {
227189
*/
228190
public async downloadSite(): Promise<string> {
229191
if (process.env.STATIC_MODE !== 'true') {
230-
const retVal = await this.downloadSiteV2();
192+
// Use sites API to download the site bundle on demand
193+
const retVal = await this.downloadSiteApi();
231194
return retVal;
232195
} else {
233-
const remoteMetadata = await this.getRemoteMetadata();
234-
if (!remoteMetadata) {
235-
throw new SfError(`No published site found for: ${this.siteDisplayName}`);
236-
}
237-
238-
// Download the site from static resources
239-
// eslint-disable-next-line no-console
240-
console.log('[local-dev] Downloading site...'); // TODO spinner
241-
const resourcePath = this.getSiteZipPath(remoteMetadata);
242-
const staticresource = await this.org.getConnection().metadata.read('StaticResource', remoteMetadata.bundleName);
243-
if (staticresource?.content) {
244-
// Save the static resource
245-
fs.mkdirSync(this.getSiteDirectory(), { recursive: true });
246-
const buffer = Buffer.from(staticresource.content, 'base64');
247-
fs.writeFileSync(resourcePath, buffer);
248-
249-
// Save the site's metadata
250-
this.saveMetadata(remoteMetadata);
251-
} else {
252-
throw new SfError(`Error occurred downloading your site: ${this.siteDisplayName}`);
253-
}
254-
255-
return resourcePath;
196+
const retVal = await this.downloadSiteStaticResources();
197+
return retVal;
256198
}
257199
}
258200

@@ -261,7 +203,7 @@ export class ExperienceSite {
261203
*
262204
* @returns path of downloaded site zip
263205
*/
264-
public async downloadSiteV2(): Promise<string> {
206+
public async downloadSiteApi(): Promise<string> {
265207
const remoteMetadata = await this.org
266208
.getConnection()
267209
.query<{ Id: string; Name: string; LastModifiedDate: string; MasterLabel: string }>(
@@ -273,8 +215,6 @@ export class ExperienceSite {
273215
const theSite = remoteMetadata.records[0];
274216

275217
// Download the site via API
276-
// eslint-disable-next-line no-console
277-
console.log('[local-dev] Downloading site...'); // TODO spinner
278218
const conn = this.org.getConnection();
279219
const metadata = {
280220
bundleName: theSite.Name,
@@ -290,8 +230,8 @@ export class ExperienceSite {
290230
const resourcePath = this.getSiteZipPath(metadata);
291231
try {
292232
// Limit API to published sites for now until we have a patch for the issues with unpublished sites
293-
// TODO set the api version dynamically based on CLI input
294-
const apiUrl = `${instanceUrl}/services/data/v63.0/sites/${siteIdMinus3}/preview?published`;
233+
// TODO use preview api when fixed
234+
const apiUrl = `${instanceUrl}/services/data/v63.0/sites/${siteIdMinus3}/preview`;
295235
const response = await axios.get(apiUrl, {
296236
headers: {
297237
Authorization: `Bearer ${accessToken}`,
@@ -318,6 +258,32 @@ export class ExperienceSite {
318258
return resourcePath;
319259
}
320260

261+
// Deprecated. Only used internally now for testing. Customer sites will no longer be stored in static resources
262+
// and are only available via the API.
263+
public async downloadSiteStaticResources(): Promise<string> {
264+
// This is for testing purposes only now - not an officially supported external path
265+
const remoteMetadata = await this.getRemoteMetadata();
266+
if (!remoteMetadata) {
267+
throw new SfError(`No published site found for: ${this.siteDisplayName}`);
268+
}
269+
270+
// Download the site from static resources
271+
const resourcePath = this.getSiteZipPath(remoteMetadata);
272+
const staticresource = await this.org.getConnection().metadata.read('StaticResource', remoteMetadata.bundleName);
273+
if (staticresource?.content) {
274+
// Save the static resource
275+
fs.mkdirSync(this.getSiteDirectory(), { recursive: true });
276+
const buffer = Buffer.from(staticresource.content, 'base64');
277+
fs.writeFileSync(resourcePath, buffer);
278+
279+
// Save the site's metadata
280+
this.saveMetadata(remoteMetadata);
281+
} else {
282+
throw new SfError(`Error occurred downloading your site: ${this.siteDisplayName}`);
283+
}
284+
return resourcePath;
285+
}
286+
321287
private async getNetworkId(): Promise<string> {
322288
const conn = this.org.getConnection();
323289
// Query the Network object for the network with the given site name
@@ -334,6 +300,7 @@ export class ExperienceSite {
334300
}
335301
}
336302

303+
// TODO
337304
private async getNewSidToken(networkId: string): Promise<string> {
338305
// Get the connection and access token from the org
339306
const conn = this.org.getConnection();
@@ -346,9 +313,6 @@ export class ExperienceSite {
346313

347314
// Make the GET request without following redirects
348315
if (accessToken) {
349-
// TODO should we try and refresh auth here?
350-
// await conn.refreshAuth();
351-
352316
// Call out to the switcher servlet to establish a session
353317
const switchUrl = `${instanceUrl}/servlet/networks/switch?networkId=${networkId}`;
354318
const cookies = [`sid=${accessToken}`, `oid=${orgIdMinus3}`].join('; ').trim();
@@ -411,17 +375,3 @@ export class ExperienceSite {
411375
return '';
412376
}
413377
}
414-
415-
/**
416-
* Return the site name given the name of its static resource bundle
417-
*
418-
* @param staticResourceName the static resource bundle name
419-
* @returns the name of the site
420-
*/
421-
function getSiteNameFromStaticResource(staticResourceName: string): string {
422-
const parts = staticResourceName.split('_');
423-
if (parts.length < 5) {
424-
throw new Error(`Unexpected static resource name: ${staticResourceName}`);
425-
}
426-
return parts.slice(4).join(' ');
427-
}

0 commit comments

Comments
 (0)