-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathllmo-onboarding.js
More file actions
1574 lines (1377 loc) · 52.4 KB
/
llmo-onboarding.js
File metadata and controls
1574 lines (1377 loc) · 52.4 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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2025 Adobe. All rights reserved.
* This file is licensed to you 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 REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import { Config } from '@adobe/spacecat-shared-data-access/src/models/site/config.js';
import { createFrom } from '@adobe/spacecat-helix-content-sdk';
import { Octokit } from '@octokit/rest';
import { Entitlement as EntitlementModel } from '@adobe/spacecat-shared-data-access/src/models/entitlement/index.js';
import TierClient from '@adobe/spacecat-shared-tier-client';
import { composeBaseURL, tracingFetch as fetch, isNonEmptyArray } from '@adobe/spacecat-shared-utils';
import AhrefsAPIClient from '@adobe/spacecat-shared-ahrefs-client';
import DrsClient from '@adobe/spacecat-shared-drs-client';
import { parse as parseDomain } from 'tldts';
import { postSlackMessage } from '../../utils/slack/base.js';
import {
readCustomerConfigV2FromPostgres,
writeCustomerConfigV2ToPostgres,
} from '../../support/customer-config-v2-storage.js';
import { convertV1ToV2, generateBrandId } from '../../support/customer-config-mapper.js';
import {
resolveLlmoOnboardingMode,
LLMO_ONBOARDING_MODE_V1,
LLMO_ONBOARDING_MODE_V2,
LLMO_FEATURE_FLAG_PRODUCT,
LLMO_BRANDALF_FLAG,
} from '../../support/llmo-onboarding-mode.js';
import { upsertFeatureFlag } from '../../support/feature-flags-storage.js';
import { upsertBrand } from '../../support/brands-storage.js';
// LLMO Constants
const LLMO_PRODUCT_CODE = EntitlementModel.PRODUCT_CODES.LLMO;
const LLMO_TIER = EntitlementModel.TIERS.FREE_TRIAL;
const SHAREPOINT_URL = 'https://adobe.sharepoint.com/:x:/r/sites/HelixProjects/Shared%20Documents/sites/elmo-ui-data';
// These audits don't depend on any additonal data being configured
export const BASIC_AUDITS = [
'scrape-top-pages',
'headings',
'llm-blocked',
'canonical',
'hreflang',
'summarization',
'prerender',
];
export const ASO_DEMO_ORG = '66331367-70e6-4a49-8445-4f6d9c265af9';
export const ASO_CRITICAL_SITES = [];
const LLMO_ONBOARDING_PUBLISH_TRIGGER = 'trigger:llmo-onboarding-publish';
function resolveUpdatedBy(context) {
return context.attributes?.authInfo?.profile?.email
|| context.attributes?.authInfo?.getProfile?.()?.email
|| 'system';
}
function buildOnboardingMetadata({
siteId, imsOrgId, brandName, onboardingMode, extra = {},
}) {
return {
site_id: siteId,
imsOrgId,
brand: brandName,
onboarding_mode: onboardingMode,
...extra,
};
}
function buildBrandalfMetadata({
organizationId,
siteId,
imsOrgId,
brandName,
companyWebsite,
onboardingMode,
}) {
const { hostname } = new URL(companyWebsite);
return buildOnboardingMetadata({
siteId,
imsOrgId,
brandName,
onboardingMode,
extra: {
site: hostname,
spaceCatId: organizationId,
company_website: companyWebsite,
},
});
}
export async function triggerBrandalfOnboardingJob({
drsClient,
organizationId,
siteId,
imsOrgId,
brandName,
companyWebsite,
onboardingMode,
log,
say = () => {},
}) {
const metadata = buildBrandalfMetadata({
organizationId,
siteId,
imsOrgId,
brandName,
companyWebsite,
onboardingMode,
});
const drsJob = await drsClient.submitJob({
provider_id: 'single_shot_prompt',
priority: 'HIGH',
source: 'onboarding',
parameters: {
prompt_type: 'brandalf',
name: brandName,
company_website: companyWebsite,
metadata,
},
});
log.info(`Started DRS Brandalf flow: job=${drsJob.job_id}`);
say(`:label: Started DRS Brandalf job: ${drsJob.job_id}`);
return drsJob;
}
function buildPromptGenerationMetadata({
siteId,
imsOrgId,
baseUrl,
brandName,
region,
onboardingMode,
}) {
return buildOnboardingMetadata({
siteId,
imsOrgId,
brandName,
onboardingMode,
extra: {
base_url: baseUrl,
region,
},
});
}
export async function submitOnboardingPromptGenerationJob({
drsClient,
baseUrl,
brandName,
audience,
region = 'US',
numPrompts = 50,
siteId,
imsOrgId,
onboardingMode,
}) {
return drsClient.submitJob({
provider_id: 'prompt_generation_base_url',
source: 'onboarding',
parameters: {
base_url: baseUrl,
brand: brandName,
audience,
region,
num_prompts: numPrompts,
model: 'gpt-5-nano',
metadata: buildPromptGenerationMetadata({
siteId,
imsOrgId,
baseUrl,
brandName,
region,
onboardingMode,
}),
},
});
}
export function buildInitialCustomerConfigV2({
brandName,
imsOrgId,
siteId,
baseURL,
overrideBaseURL,
updatedBy = 'system',
}) {
const primaryUrl = overrideBaseURL || baseURL;
const config = convertV1ToV2({
brands: {
aliases: [{
name: brandName,
regions: ['gl'],
status: 'active',
}],
},
competitors: { competitors: [] },
categories: {},
topics: {},
}, brandName, imsOrgId);
const [brand] = config.customer.brands;
const timestamp = new Date().toISOString();
brand.v1SiteId = siteId;
brand.baseUrl = primaryUrl;
brand.updatedAt = timestamp;
brand.updatedBy = updatedBy;
brand.urls = [{ value: primaryUrl, type: 'url' }];
brand.brandAliases = [{ name: brandName, regions: ['gl'] }];
config.customer.customerName = brandName;
return config;
}
export async function ensureInitialCustomerConfigV2({
organizationId,
brandName,
imsOrgId,
siteId,
baseURL,
overrideBaseURL,
context,
}) {
const postgrestClient = context.dataAccess?.services?.postgrestClient;
if (!postgrestClient?.from) {
throw new Error('V2 customer config requires Postgres (DATA_SERVICE_PROVIDER=postgres)');
}
const existingConfig = await readCustomerConfigV2FromPostgres(organizationId, postgrestClient);
if (existingConfig) {
if (!existingConfig.customer) {
existingConfig.customer = {};
}
if (!existingConfig.customer.brands) {
existingConfig.customer.brands = [];
}
const { brands } = existingConfig.customer;
const siteAlreadyRegistered = brands.some((b) => b.v1SiteId === siteId);
if (siteAlreadyRegistered) {
context.log.info(`V2 customer config already exists for organization ${organizationId} with site ${siteId}, skipping`);
return existingConfig;
}
// Add the new site as a brand to the existing config
const primaryUrl = overrideBaseURL || baseURL;
const timestamp = new Date().toISOString();
const trimmedName = brandName.trim();
let brandId = generateBrandId(trimmedName);
// Ensure brand ID is unique within the config
const existingIds = new Set(brands.map((b) => b.id));
if (existingIds.has(brandId)) {
brandId = `${brandId}-${siteId.slice(0, 8)}`;
}
brands.push({
id: brandId,
v1SiteId: siteId,
name: trimmedName,
baseUrl: primaryUrl,
status: 'active',
origin: 'system',
regions: ['gl'],
updatedAt: timestamp,
updatedBy: resolveUpdatedBy(context),
urls: [{ value: primaryUrl, type: 'url' }],
brandAliases: [{ name: trimmedName, regions: ['gl'] }],
});
await writeCustomerConfigV2ToPostgres(
organizationId,
existingConfig,
postgrestClient,
resolveUpdatedBy(context),
);
context.log.info(`Added site ${siteId} as brand "${brandName}" to existing V2 config for organization ${organizationId}`);
return existingConfig;
}
const config = buildInitialCustomerConfigV2({
brandName: brandName.trim(),
imsOrgId,
siteId,
baseURL,
overrideBaseURL,
updatedBy: resolveUpdatedBy(context),
});
await writeCustomerConfigV2ToPostgres(
organizationId,
config,
postgrestClient,
resolveUpdatedBy(context),
);
context.log.info(`Initialized V2 customer config for organization ${organizationId} during onboarding`);
return config;
}
/**
* Generates the data folder name from a domain.
* @param {string} domain - The domain name
* @param {string} env - The environment (prod, dev, etc.)
* @returns {string} The data folder name
*/
export function generateDataFolder(baseURL, env = 'dev') {
const { hostname } = new URL(baseURL);
const dataFolderName = hostname.replace(/[^a-zA-Z0-9]/g, '-').toLowerCase();
return env === 'prod' ? dataFolderName : `dev/${dataFolderName}`;
}
/**
* Posts an alert to the LLMO alerts Slack channel.
* Fails gracefully if channel/token not configured or if posting fails.
* @param {string} message - The message to post
* @param {object} context - The request context containing env and log
* @returns {Promise<void>}
*/
export async function postLlmoAlert(message, context) {
const { env, log } = context;
const slackChannel = env.SLACK_LLMO_ALERTS_CHANNEL_ID;
const slackToken = env.SLACK_BOT_TOKEN;
if (slackChannel && slackToken) {
try {
await postSlackMessage(slackChannel, message, slackToken);
} catch (slackError) {
log.error(`Failed to post LLMO alert to Slack: ${slackError.message}`);
}
}
}
/**
* Gets the IMS Org ID for a given organization ID.
* Used for enriching notification messages. Never throws - returns 'Unknown' on error.
* @param {string} organizationId - The SpaceCat organization ID
* @param {object} context - The request context containing dataAccess and log
* @returns {Promise<string>} The IMS Org ID or 'Unknown'
*/
async function getCurrentImsOrgIdForNotification(organizationId, context) {
const { dataAccess, log } = context;
const { Organization } = dataAccess;
try {
const organization = await Organization.findById(organizationId);
return organization ? organization.getImsOrgId() : 'Unknown';
} catch (error) {
log.warn(`Could not fetch IMS Org ID for notification: ${error.message}`);
return 'Unknown';
}
}
/**
* Gets the current IMS Org ID for a site by baseURL.
* Never throws - returns 'Unknown' on error.
* @param {string} baseURL - The site's base URL
* @param {object} context - The request context containing dataAccess and log
* @returns {Promise<string>} The IMS Org ID or 'Unknown'
*/
async function getCurrentImsOrgIdForSite(baseURL, context) {
const { dataAccess, log } = context;
const { Site } = dataAccess;
try {
const site = await Site.findByBaseURL(baseURL);
if (site) {
return await getCurrentImsOrgIdForNotification(
site.getOrganizationId(),
context,
);
}
return 'Unknown';
} catch (error) {
log.warn(`Could not fetch IMS Org ID for site: ${error.message}`);
return 'Unknown';
}
}
/**
* Creates a SharePoint client for LLMO operations.
* @param {object} env - Environment variables
* @returns {Promise<object>} SharePoint client
*/
export async function createSharePointClient(env) {
return createFrom({
clientId: env.SHAREPOINT_CLIENT_ID,
clientSecret: env.SHAREPOINT_CLIENT_SECRET,
authority: env.SHAREPOINT_AUTHORITY,
domainId: env.SHAREPOINT_DOMAIN_ID,
}, { url: SHAREPOINT_URL, type: 'onedrive' });
}
/**
* Validates that the site has not been onboarded yet by checking:
* 1. Site does not exist in SpaceCat API
* 2. SharePoint folder does not exist
* @param {string} baseURL - The base URL of the site
* @param {string} dataFolder - The data folder name
* @param {object} context - The request context
* @returns {Promise<{isValid: boolean, error?: string}>} Validation result
*/
export async function validateSiteNotOnboarded(baseURL, imsOrgId, dataFolder, context) {
const { log, dataAccess, env } = context;
const { Site, Organization } = dataAccess;
try {
// Check if SharePoint folder already exists
const sharepointClient = await createSharePointClient(env);
const folder = sharepointClient.getDocument(`/sites/elmo-ui-data/${dataFolder}/`);
const folderExists = await folder.exists();
if (folderExists) {
// Try to get current IMS Org if site exists (best effort - don't fail validation)
const currentImsOrgId = await getCurrentImsOrgIdForSite(baseURL, context);
await postLlmoAlert(
':warning: *Site is already onboarded* - Data folder already exists\n\n'
+ `• Site: \`${baseURL}\`\n`
+ `• Requested IMS Org: \`${imsOrgId}\`\n`
+ `• Current IMS Org: \`${currentImsOrgId}\`\n`
+ `• Data Folder: \`${dataFolder}`,
context,
);
return {
isValid: false,
error: `Data folder for site ${baseURL} already exists. The site is already onboarded.`,
};
}
// Check if site already exists in SpaceCat
const existingSite = await Site.findByBaseURL(baseURL);
// Get the organization id from the imsOrgId
const organization = await Organization.findByImsOrgId(imsOrgId);
// if the site doesn't exist, it means it's not onboarded yet and we are safe to onboard
// to either an existing or a new organization
if (!existingSite) {
return { isValid: true };
}
if (ASO_CRITICAL_SITES.includes(existingSite.getId())) {
return {
isValid: false,
error: `Site ${baseURL} is mission critical for ASO.`,
};
}
if (organization) {
// if the organization exists, we need to check if the site is assigned to the same
// organization, or the default organization (= not yet claimed)
// or AEM Demo Org (= not yet claimed)
if (existingSite.getOrganizationId() !== organization.getId()
&& existingSite.getOrganizationId() !== env.DEFAULT_ORGANIZATION_ID
&& existingSite.getOrganizationId() !== ASO_DEMO_ORG) {
// Get current organization's IMS Org ID (best effort - don't fail validation)
const currentImsOrgId = await getCurrentImsOrgIdForNotification(
existingSite.getOrganizationId(),
context,
);
await postLlmoAlert(
':warning: *Site is already onboarded* - Assigned to a different organization\n\n'
+ `• Site: \`${baseURL}\`\n`
+ `• Requested IMS Org: \`${imsOrgId}\`\n`
+ `• Current IMS Org: \`${currentImsOrgId}\`\n`
+ `• Requested Org ID: \`${organization.getId()}\n`
+ `• Current Org ID: \`${existingSite.getOrganizationId()}`,
context,
);
return {
isValid: false,
error: `Site ${baseURL} has already been assigned to a different organization.`,
};
}
} else if (existingSite.getOrganizationId() !== env.DEFAULT_ORGANIZATION_ID
&& existingSite.getOrganizationId() !== ASO_DEMO_ORG) {
// if the organization doesn't exist, but the site does, check that the site isn't claimed yet
// by another organization
// Get current organization's IMS Org ID (best effort - don't fail validation)
const currentImsOrgId = await getCurrentImsOrgIdForNotification(
existingSite.getOrganizationId(),
context,
);
await postLlmoAlert(
':warning: *Site is already onboarded* - Assigned to a different organization\n\n'
+ `• Site: \`${baseURL}\`\n`
+ `• Requested IMS Org: \`${imsOrgId}\`\n`
+ `• Current IMS Org: \`${currentImsOrgId}\`\n`
+ `• Current Org ID: \`${existingSite.getOrganizationId()}`,
context,
);
return {
isValid: false,
error: `Site ${baseURL} has already been assigned to a different organization.`,
};
}
return { isValid: true };
} catch (error) {
log.error(`Error validating site onboarding status: ${error.message}`);
// If we can't validate, we should fail safely and not allow onboarding
return {
isValid: false,
error: `Unable to validate onboarding status: ${error.message}`,
};
}
}
/**
* Starts a bulk status job for a given path.
* @param {string} path - The folder path to get status for
* @param {object} env - Environment variables
* @param {object} log - Logger instance
* @returns {Promise<string>} The job name
*/
export async function startBulkStatusJob(path, env, log) {
const org = 'adobe';
const site = 'project-elmo-ui-data';
const ref = 'main';
const headers = {
Cookie: `auth_token=${env.HLX_ONBOARDING_TOKEN}`,
'Content-Type': 'application/json',
};
if (!env.HLX_ONBOARDING_TOKEN) {
log.warn('LLMO offboarding: HLX_ONBOARDING_TOKEN is not set');
return null;
}
const baseUrl = 'https://admin.hlx.page';
const url = `${baseUrl}/status/${org}/${site}/${ref}/*`;
log.debug(`Starting bulk status job for path: ${path}`);
const response = await fetch(url, {
method: 'POST',
headers,
body: JSON.stringify({
paths: [`/${path}/*`],
}),
});
if (!response.ok) {
throw new Error(`Failed to start bulk status job: ${response.status} ${response.statusText}`);
}
const result = await response.json();
log.debug(`Bulk status job started: ${result.job?.name || result.name}`);
return result.job?.name || result.name;
}
/**
* Polls a job until it completes.
* @param {string} jobName - The job name to poll
* @param {object} env - Environment variables
* @param {object} log - Logger instance
* @returns {Promise<object>} The completed job data
*/
export async function pollJobStatus(jobName, env, log) {
const org = 'adobe';
const site = 'project-elmo-ui-data';
const ref = 'main';
const topic = 'status';
const headers = { Cookie: `auth_token=${env.HLX_ONBOARDING_TOKEN}` };
if (!env.HLX_ONBOARDING_TOKEN) {
log.warn('LLMO offboarding: HLX_ONBOARDING_TOKEN is not set');
return null;
}
const baseUrl = 'https://admin.hlx.page';
const url = `${baseUrl}/job/${org}/${site}/${ref}/${topic}/${jobName}/details`;
const pollInterval = 200; // 200ms as specified
const maxAttempts = 150; // 30 seconds timeout (150 * 200ms)
let attempts = 0;
log.debug(`Polling job status for: ${jobName}`);
// eslint-disable-next-line no-constant-condition
while (true) {
// eslint-disable-next-line no-await-in-loop
const response = await fetch(url, { method: 'GET', headers });
if (!response.ok) {
throw new Error(`Failed to get job status: ${response.status} ${response.statusText}`);
}
// eslint-disable-next-line no-await-in-loop
const jobData = await response.json();
if (jobData.state === 'stopped' && jobData.data?.phase === 'completed') {
log.debug(`Job ${jobName} completed successfully`);
return jobData;
}
attempts += 1;
if (attempts >= maxAttempts) {
throw new Error(`Job polling timed out after ${maxAttempts * pollInterval}ms`);
}
// eslint-disable-next-line no-await-in-loop
await new Promise((resolve) => {
setTimeout(resolve, pollInterval);
});
}
}
/**
* Performs bulk unpublish and un-preview for a list of paths.
* @param {Array<string>} paths - Array of paths to unpublish
* @param {string} dataFolder - Base data folder
* @param {object} env - Environment variables
* @param {object} log - Logger instance
*/
export async function bulkUnpublishPaths(paths, dataFolder, env, log) {
if (!paths || paths.length === 0) {
log.debug('No paths to unpublish');
return;
}
const org = 'adobe';
const site = 'project-elmo-ui-data';
const ref = 'main';
const headers = {
Cookie: `auth_token=${env.HLX_ONBOARDING_TOKEN}`,
'Content-Type': 'application/json',
};
if (!env.HLX_ONBOARDING_TOKEN) {
log.warn('LLMO offboarding: HLX_ONBOARDING_TOKEN is not set');
return;
}
const baseUrl = 'https://admin.hlx.page';
// Prepare paths in the format required by bulk APIs
const pathsPayload = paths.map((path) => ({ path }));
// Bulk unpublish (live)
const unpublishUrl = `${baseUrl}/live/${org}/${site}/${ref}/${dataFolder}/*`;
log.debug(`Starting bulk unpublish for ${paths.length} paths`);
try {
const unpublishResponse = await fetch(unpublishUrl, {
method: 'POST',
headers,
body: JSON.stringify({ paths: pathsPayload.map((o) => o.path), delete: true }),
});
if (!unpublishResponse.ok) {
log.error(`Bulk unpublish failed: ${unpublishResponse.status} ${unpublishResponse.statusText}`);
} else {
const unpublishResult = await unpublishResponse.json();
log.debug(`Bulk unpublish job started: ${unpublishResult.job?.name || unpublishResult.name}`);
}
} catch (error) {
log.error(`Error during bulk unpublish: ${error.message}`);
}
// Bulk un-preview
const unpreviewUrl = `${baseUrl}/preview/${org}/${site}/${ref}/${dataFolder}/*`;
log.debug(`Starting bulk un-preview for ${paths.length} paths`);
try {
const unpreviewResponse = await fetch(unpreviewUrl, {
method: 'POST',
headers,
body: JSON.stringify({ paths: pathsPayload.map((o) => o.path), delete: true }),
});
if (!unpreviewResponse.ok) {
log.error(`Bulk un-preview failed: ${unpreviewResponse.status} ${unpreviewResponse.statusText}`);
} else {
const unpreviewResult = await unpreviewResponse.json();
log.debug(`Bulk un-preview job started: ${unpreviewResult.job?.name || unpreviewResult.name}`);
}
} catch (error) {
log.error(`Error during bulk un-preview: ${error.message}`);
}
}
/**
* Unpublishes a file from admin.hlx.page.
* @param {string} dataFolder - The data folder to unpublish
* @param {object} env - Environment variables
* @param {object} log - Logger instance
*/
export async function unpublishFromAdminHlx(dataFolder, env, log) {
try {
// First, get bulk status of all files under the folder to know what needs to be unpublished
log.info(`Getting bulk status for folder: ${dataFolder}`);
const jobName = await startBulkStatusJob(dataFolder, env, log);
if (jobName) {
// Poll the job until it completes
const jobData = await pollJobStatus(jobName, env, log);
// Extract all paths from the resources
const paths = jobData?.data?.resources
?.filter((resource) => resource.path.startsWith(`/${dataFolder}`))
.map((resource) => resource.path) || [];
if (paths.length > 0) {
log.info(`Found ${paths.length} paths to unpublish under folder ${dataFolder}`);
// Bulk unpublish and un-preview all paths
await bulkUnpublishPaths(paths, dataFolder, env, log);
} else {
log.debug(`No published paths found under folder ${dataFolder}`);
}
}
} catch (error) {
log.error(`Error during bulk unpublish for folder ${dataFolder}: ${error.message}`);
// Don't throw - continue with folder deletion
}
}
/**
* Copies template files to SharePoint for a new LLMO onboarding.
* @param {string} dataFolder - The data folder name
* @param {object} context - The request context
* @param {Function} say - Optional function to send messages (e.g., Slack say function)
* @returns {Promise<void>}
*/
export async function copyFilesToSharepoint(dataFolder, context, say = () => {}) {
const { log, env } = context;
const sharepointClient = await createSharePointClient(env);
log.debug(`Copying query-index to ${dataFolder}`);
const folder = sharepointClient.getDocument(`/sites/elmo-ui-data/${dataFolder}/`);
const templateQueryIndex = sharepointClient.getDocument('/sites/elmo-ui-data/template/query-index.xlsx');
const newQueryIndex = sharepointClient.getDocument(`/sites/elmo-ui-data/${dataFolder}/query-index.xlsx`);
const folderExists = await folder.exists();
if (!folderExists) {
const base = dataFolder.startsWith('dev/') ? '/dev' : '/';
const folderName = dataFolder.startsWith('dev/') ? dataFolder.split('/')[1] : dataFolder;
await folder.createFolder(folderName, base);
} else {
log.warn(`Warning: Folder ${dataFolder} already exists. Skipping creation.`);
await say(`Folder ${dataFolder} already exists. Skipping creation.`);
}
const queryIndexExists = await newQueryIndex.exists();
if (!queryIndexExists) {
await templateQueryIndex.copy(`/${dataFolder}/query-index.xlsx`);
} else {
log.warn(`Warning: Query index at ${dataFolder} already exists. Skipping creation.`);
await say(`Query index in ${dataFolder} already exists. Skipping creation.`);
}
}
/**
* Updates the helix-query.yaml configuration in GitHub.
* @param {string} dataFolder - The data folder name
* @param {object} context - The request context
* @param {Function} say - Optional function to send messages (e.g., Slack say function)
* @returns {Promise<void>}
*/
export async function updateIndexConfig(dataFolder, context, say = () => {}) {
const { log, env } = context;
log.debug('Starting Git modification of helix query config');
const octokit = new Octokit({
auth: env.LLMO_ONBOARDING_GITHUB_TOKEN,
});
const owner = 'adobe';
const repo = 'project-elmo-ui-data';
const ref = env.ENV === 'prod' ? 'main' : 'onboarding-bot-dev';
const path = 'helix-query.yaml';
const { data: file } = await octokit.repos.getContent({
owner, repo, ref, path,
});
const content = Buffer.from(file.content, 'base64').toString('utf-8');
if (content.includes(dataFolder)) {
log.warn(`Helix query yaml already contains string ${dataFolder}. Skipping update.`);
await say(`Helix query yaml already contains string ${dataFolder}. Skipping GitHub update.`);
return;
}
// add new config to end of file
const modifiedContent = `${content}${content.endsWith('\n') ? '' : '\n'}
${dataFolder}:
<<: *default
include:
- '/${dataFolder}/**'
target: /${dataFolder}/query-index.xlsx
`;
await octokit.repos.createOrUpdateFileContents({
owner,
repo,
branch: ref,
path,
message: `Automation: Onboard ${dataFolder}`,
content: Buffer.from(modifiedContent).toString('base64'),
sha: file.sha,
});
}
/**
* Creates or finds an organization based on IMS Org ID.
* @param {string} imsOrgId - The IMS Organization ID
* @param {object} context - The request context
* @param {Function} [say] - Optional callback function for sending Slack messages
* @returns {Promise<object>} The organization object
*/
export async function createOrFindOrganization(imsOrgId, context, say = () => {}) {
const { dataAccess, log, imsClient } = context;
const { Organization } = dataAccess;
// Check if organization already exists
let organization = await Organization.findByImsOrgId(imsOrgId);
if (organization) {
log.debug(`Found existing organization for IMS Org ID: ${imsOrgId}`);
return organization;
}
// Fetch real org name from IMS if client available
let orgName = `Organization ${imsOrgId}`;
if (imsClient) {
try {
const imsOrgDetails = await imsClient.getImsOrganizationDetails(imsOrgId);
if (imsOrgDetails?.orgName) {
orgName = imsOrgDetails.orgName;
}
} catch (error) {
log.warn(`Could not fetch IMS org details for ${imsOrgId}: ${error.message}`);
}
}
// Create new organization
log.info(`Creating new organization for IMS Org ID: ${imsOrgId}`);
say(`Creating organization for IMS Org ID: ${imsOrgId}`);
organization = await Organization.create({
name: orgName,
imsOrgId,
});
log.info(`Created organization ${organization.getId()} for IMS Org ID: ${imsOrgId}`);
return organization;
}
/**
* Checks if a hostname has a non-www subdomain using the tldts library.
* This properly handles all TLDs including multi-part TLDs like .co.uk, .com.au, etc.
*
* @param {string} hostname - The hostname to check (e.g., "blog.example.com")
* @returns {boolean} - True if the hostname has a subdomain other than www
*
* @example
* hasNonWWWSubdomain('example.com') // false - apex domain
* hasNonWWWSubdomain('www.example.com') // false - only www subdomain
* hasNonWWWSubdomain('blog.example.com') // true - has subdomain
* hasNonWWWSubdomain('blog.example.co.uk') // true - has subdomain (multi-part TLD)
* hasNonWWWSubdomain('example.co.uk') // false - apex domain (multi-part TLD)
*/
function hasNonWWWSubdomain(hostname) {
const parsed = parseDomain(hostname);
// If parsing failed, be conservative and assume it's a subdomain
/* c8 ignore next 3 */
if (!parsed || !parsed.domain) {
return true;
}
const subdomain = parsed.subdomain || '';
return subdomain !== '' && subdomain !== 'www';
}
/**
* Toggles the www subdomain in a given URL.
* If the URL has www, it removes it. If it doesn't have www, it adds it.
* Only works for URLs without other subdomains (e.g., blog.example.com).
* For URLs with non-www subdomains, returns the original URL unchanged.
*
* @param {string} url - The URL to toggle (e.g., "https://example.com" or "https://www.example.com")
* @returns {string} - The URL with www toggled, or the original URL if it has a subdomain
*/
function toggleWWW(url) {
try {
const urlObj = new URL(url);
const { hostname } = urlObj;
if (hasNonWWWSubdomain(hostname)) {
return url;
}
// Safe to toggle www for apex domains
if (hostname.startsWith('www.')) {
urlObj.hostname = hostname.replace('www.', '');
} else {
urlObj.hostname = `www.${hostname}`;
}
// Preserve trailing slash consistency with the original URL
const result = urlObj.toString();
return result.endsWith('/') && !url.endsWith('/') ? result.slice(0, -1) : result;
/* c8 ignore next 3 */
} catch (error) {
return url;
}
}
/**
* Tests a URL against the Ahrefs top pages endpoint to see if it returns data.
* @param {string} url - The URL to test
* @param {object} ahrefsClient - The Ahrefs API client
* @param {object} log - Logger instance
* @returns {Promise<boolean>} - True if the URL returns top pages data, false otherwise
*/
async function testAhrefsTopPages(url, ahrefsClient, log) {
try {
const { result } = await ahrefsClient.getTopPages(url, 1);
const hasData = isNonEmptyArray(result?.pages);
log.debug(`Ahrefs top pages test for ${url}: ${hasData ? 'SUCCESS' : 'NO DATA'}`);
return hasData;
} catch (error) {
log.debug(`Ahrefs top pages test for ${url}: FAILED - ${error.message}`);
return false;
}
}
/**
* Determines if overrideBaseURL should be set based on Ahrefs top pages data.
* Tests both the base URL and its www-variant. If only the alternate variation succeeds,
* returns that variation as the overrideBaseURL.
*
* @param {string} baseURL - The site's base URL
* @param {object} context - The request context
* @returns {Promise<string|null>} - The overrideBaseURL if needed, null otherwise
*/
export async function determineOverrideBaseURL(baseURL, context) {
const { log } = context;
try {
log.info(`Determining overrideBaseURL for ${baseURL}`);
const ahrefsClient = AhrefsAPIClient.createFrom(context);
const alternateURL = toggleWWW(baseURL);
// If toggleWWW returns the same URL, it means the URL has a subdomain
// and we shouldn't try to toggle www (would create invalid nested subdomain)
if (alternateURL === baseURL) {
log.info(`Skipping overrideBaseURL detection for subdomain URL: ${baseURL}`);
return null;
}
log.debug(`Testing base URL: ${baseURL} and alternate: ${alternateURL}`);
const [baseURLSuccess, alternateURLSuccess] = await Promise.all([
testAhrefsTopPages(baseURL, ahrefsClient, log),
testAhrefsTopPages(alternateURL, ahrefsClient, log),
]);
if (!baseURLSuccess && alternateURLSuccess) {
log.info(`Setting overrideBaseURL to ${alternateURL} (base URL failed, alternate succeeded)`);
return alternateURL;
}
if (baseURLSuccess && alternateURLSuccess) {
log.debug('Both URLs succeeded, no overrideBaseURL needed');
} else if (baseURLSuccess && !alternateURLSuccess) {
log.debug('Base URL succeeded, no overrideBaseURL needed');
} else {
log.warn('Both URLs failed Ahrefs test, no overrideBaseURL set');
}
return null;
} catch (error) {
log.error(`Error determining overrideBaseURL: ${error.message}`, error);
// Don't fail onboarding if this check fails
return null;
}
}
/**