@salesforce/ui-bundle-template-feature-react-customer-web-client-chat 11.52.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.
Files changed (107) hide show
  1. package/LICENSE.txt +82 -0
  2. package/README.md +63 -0
  3. package/dist/.forceignore +15 -0
  4. package/dist/.husky/pre-commit +4 -0
  5. package/dist/.prettierignore +11 -0
  6. package/dist/.prettierrc +17 -0
  7. package/dist/CHANGELOG.md +4553 -0
  8. package/dist/README.md +77 -0
  9. package/dist/config/project-scratch-def.json +13 -0
  10. package/dist/eslint.config.js +7 -0
  11. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/.forceignore +15 -0
  12. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/.graphqlrc.yml +2 -0
  13. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/.prettierignore +9 -0
  14. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/.prettierrc +11 -0
  15. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/CHANGELOG.md +10 -0
  16. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/README.md +75 -0
  17. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/codegen.yml +95 -0
  18. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/components.json +18 -0
  19. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/e2e/app.spec.ts +17 -0
  20. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/eslint.config.js +169 -0
  21. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/feature-react-customer-web-client-chat.uibundle-meta.xml +7 -0
  22. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/index.html +12 -0
  23. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/package.json +76 -0
  24. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/playwright.config.ts +24 -0
  25. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/scripts/get-graphql-schema.mjs +71 -0
  26. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/scripts/rewrite-e2e-assets.mjs +23 -0
  27. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/api/graphqlClient.ts +44 -0
  28. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/app.tsx +17 -0
  29. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/appLayout.tsx +83 -0
  30. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/assets/icons/book.svg +3 -0
  31. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/assets/icons/copy.svg +4 -0
  32. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/assets/icons/rocket.svg +3 -0
  33. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/assets/icons/star.svg +3 -0
  34. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/assets/images/codey-1.png +0 -0
  35. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/assets/images/codey-2.png +0 -0
  36. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/assets/images/codey-3.png +0 -0
  37. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/assets/images/vibe-codey.svg +194 -0
  38. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/CustomerWebClientChat.tsx +74 -0
  39. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/alerts/status-alert.tsx +52 -0
  40. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/layouts/card-layout.tsx +29 -0
  41. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/alert.tsx +76 -0
  42. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/avatar.tsx +109 -0
  43. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/badge.tsx +48 -0
  44. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/breadcrumb.tsx +109 -0
  45. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/button.tsx +67 -0
  46. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/calendar.tsx +232 -0
  47. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/card.tsx +103 -0
  48. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/checkbox.tsx +32 -0
  49. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/collapsible.tsx +33 -0
  50. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/datePicker.tsx +127 -0
  51. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/dialog.tsx +162 -0
  52. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/dropdown-menu.tsx +257 -0
  53. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/field.tsx +237 -0
  54. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/index.ts +109 -0
  55. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/input.tsx +19 -0
  56. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/label.tsx +22 -0
  57. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/pagination.tsx +132 -0
  58. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/popover.tsx +89 -0
  59. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/select.tsx +193 -0
  60. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/separator.tsx +26 -0
  61. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/skeleton.tsx +14 -0
  62. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/sonner.tsx +20 -0
  63. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/spinner.tsx +16 -0
  64. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/table.tsx +121 -0
  65. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/ui/tabs.tsx +88 -0
  66. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/hooks/useAsyncData.ts +67 -0
  67. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/index.ts +6 -0
  68. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/lib/utils.ts +6 -0
  69. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/navigationMenu.tsx +80 -0
  70. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/pages/Home.tsx +12 -0
  71. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/pages/NotFound.tsx +18 -0
  72. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/pages/TestChatPage.tsx +26 -0
  73. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/router-utils.tsx +35 -0
  74. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/routes.tsx +28 -0
  75. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/styles/global.css +135 -0
  76. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/types/chat.ts +36 -0
  77. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/tsconfig.json +45 -0
  78. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/tsconfig.node.json +13 -0
  79. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/tsconfig.tsbuildinfo +1 -0
  80. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/ui-bundle.json +7 -0
  81. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/vite-env.d.ts +4 -0
  82. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/vite.config.ts +106 -0
  83. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/vitest-env.d.ts +2 -0
  84. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/vitest.config.ts +11 -0
  85. package/dist/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/vitest.setup.ts +1 -0
  86. package/dist/jest.config.js +6 -0
  87. package/dist/package-lock.json +10066 -0
  88. package/dist/package.json +46 -0
  89. package/dist/scripts/apex/hello.apex +10 -0
  90. package/dist/scripts/gitignore-templates.json +4 -0
  91. package/dist/scripts/graphql-search.sh +191 -0
  92. package/dist/scripts/org-setup-config-schema.mjs +120 -0
  93. package/dist/scripts/org-setup-dev.mjs +87 -0
  94. package/dist/scripts/org-setup-utils.mjs +569 -0
  95. package/dist/scripts/org-setup-xml.mjs +182 -0
  96. package/dist/scripts/org-setup.config.json +5 -0
  97. package/dist/scripts/org-setup.mjs +2345 -0
  98. package/dist/scripts/sf-project-setup.mjs +103 -0
  99. package/dist/scripts/soql/account.soql +6 -0
  100. package/dist/scripts/validate-org-setup-config.mjs +38 -0
  101. package/dist/sfdx-project.json +12 -0
  102. package/package.json +51 -0
  103. package/src/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/components/CustomerWebClientChat.tsx +74 -0
  104. package/src/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/index.ts +6 -0
  105. package/src/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/pages/TestChatPage.tsx +26 -0
  106. package/src/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/routes.tsx +23 -0
  107. package/src/force-app/main/default/uiBundles/feature-react-customer-web-client-chat/src/types/chat.ts +36 -0
@@ -0,0 +1,2345 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * One-command setup: login, deploy, optional permset/data, GraphQL schema/codegen, UI bundle build.
4
+ * Use this script to make setup easier for each app generated from this template.
5
+ *
6
+ * Usage:
7
+ * node scripts/org-setup.mjs --target-org <alias> # interactive step picker (all selected)
8
+ * node scripts/org-setup.mjs # prompt to pick an authenticated org
9
+ * node scripts/org-setup.mjs --target-org <alias> --yes # skip picker, run all steps
10
+ * node scripts/org-setup.mjs --target-org afv5 --skip-data --skip-ui-bundle-build
11
+ * node scripts/org-setup.mjs --target-org myorg --ui-bundle-name my-app
12
+ *
13
+ * Login is an unconditional precondition (not a toggleable step); the dev server
14
+ * is launched separately via `npm run dev:preview` (scripts/org-setup-dev.mjs).
15
+ *
16
+ * Steps (in order):
17
+ * login (precondition) — sf org login web only if org not already connected; always runs before deploy
18
+ * 1. uiBundle — (all UI bundles) npm install && npm run build so dist exists for deploy (skip with --skip-ui-bundle-build)
19
+ * 2. deploy — sf project deploy start --target-org <alias> (requires dist for entity deployment)
20
+ * 3. permset — assign permsets per org-setup.config.json (skip with --skip-permset; override via --permset-name)
21
+ * 4. data — prepare unique fields + sf data import tree (skipped if no data dir/plan)
22
+ * 5. graphql — (in UI bundle) npm run graphql:schema then npm run graphql:codegen
23
+ *
24
+ * Permset assignment config (scripts/org-setup.config.json):
25
+ * {
26
+ * "permsetAssignments": {
27
+ * "defaultAssignee": "skip",
28
+ * "assignments": {
29
+ * "My_Permset": { "assignee": "currentUser" },
30
+ * "Guest_Permset": { "assignee": "guestUser" },
31
+ * "Internal_Only": { "assignee": "skip" }
32
+ * }
33
+ * }
34
+ * }
35
+ * Assignee values: "currentUser", "guestUser", or "skip". For "guestUser" the
36
+ * site is derived from the single networks/<siteName>.network-meta.xml the app
37
+ * ships — it is not restated per assignment.
38
+ * Unlisted permsets resolve to "defaultAssignee" (default "skip").
39
+ */
40
+
41
+ import { spawnSync, spawn as nodeSpawn } from 'node:child_process';
42
+ import { resolve, dirname, join } from 'node:path';
43
+ import { fileURLToPath } from 'node:url';
44
+ import {
45
+ readdirSync,
46
+ existsSync,
47
+ readFileSync,
48
+ writeFileSync,
49
+ mkdirSync,
50
+ mkdtempSync,
51
+ rmSync,
52
+ openSync,
53
+ closeSync,
54
+ } from 'node:fs';
55
+ import { tmpdir } from 'node:os';
56
+
57
+ import { validateConfig } from './org-setup-config-schema.mjs';
58
+ import {
59
+ addProfileToMemberGroups,
60
+ enableSelfRegInXml,
61
+ NetworkXmlError,
62
+ } from './org-setup-xml.mjs';
63
+ import {
64
+ discoverAllUIBundleDirs as discoverAllUIBundleDirsIn,
65
+ discoverUIBundleDir as discoverUIBundleDirIn,
66
+ resolveTargetOrg,
67
+ evaluateLicenseRows,
68
+ validateProfileNameForSoql,
69
+ validateSoqlName,
70
+ validateApiName,
71
+ escapeSoqlString,
72
+ parseApexInsertResults,
73
+ planApexBatches,
74
+ } from './org-setup-utils.mjs';
75
+
76
+ const __dirname = dirname(fileURLToPath(import.meta.url));
77
+ const ROOT = resolve(__dirname, '..');
78
+
79
+ /**
80
+ * Thrown by step runners (run/runAsync) when a subprocess fails. The per-step
81
+ * orchestration in main() catches it, records the failure in the result ledger,
82
+ * and either aborts (fail-fast steps) or continues (skippable steps).
83
+ */
84
+ class StepError extends Error {}
85
+
86
+ const APEX_TMP_PREFIX = 'org-setup-';
87
+ // Legacy fixed-name temp files that older versions of this script wrote to ROOT
88
+ // and could leave behind on a hard kill. Swept at startup for backward cleanup.
89
+ const LEGACY_ROOT_TMP_FILES = ['.tmp-setup-selfreg.apex', '.tmp-setup-delete.apex'];
90
+
91
+ /**
92
+ * Remove leftover Apex temp artifacts from a prior hard-killed run (cleanup AT
93
+ * START). Two sources: per-run dirs under os.tmpdir() created by
94
+ * withApexTempDir, and legacy fixed-name files this script used to write to
95
+ * ROOT. Best-effort: a failure to remove one entry never blocks setup.
96
+ *
97
+ * Scoped to DIRECTORY entries only: the per-run artifacts are dirs created by
98
+ * withApexTempDir via mkdtempSync, whereas the per-org lock files share the same
99
+ * `org-setup-` prefix but are plain files (`org-setup-lock-<org>.lock`). Sweeping
100
+ * files too would delete a live run's lock before acquireOrgLock could see it,
101
+ * defeating the concurrency guard. The dir sweep is still intentionally broad
102
+ * across PIDs; the per-target-org lock acquired in main() is what makes that
103
+ * safe — only one live run per org.
104
+ */
105
+ function sweepStaleApexTempDirs() {
106
+ const base = tmpdir();
107
+ let entries = [];
108
+ try {
109
+ entries = readdirSync(base, { withFileTypes: true });
110
+ } catch {
111
+ /* tmpdir unreadable — nothing to sweep */
112
+ }
113
+ for (const entry of entries) {
114
+ if (entry.isDirectory() && entry.name.startsWith(APEX_TMP_PREFIX)) {
115
+ try {
116
+ rmSync(join(base, entry.name), { recursive: true, force: true });
117
+ } catch {
118
+ /* best effort */
119
+ }
120
+ }
121
+ }
122
+ for (const legacy of LEGACY_ROOT_TMP_FILES) {
123
+ const p = resolve(ROOT, legacy);
124
+ if (existsSync(p)) {
125
+ try {
126
+ rmSync(p, { force: true });
127
+ } catch {
128
+ /* best effort */
129
+ }
130
+ }
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Run `fn(writeApex)` with a private temp dir under os.tmpdir() that is ALWAYS
136
+ * removed afterwards (cleanup IN FINALLY), even when fn throws or
137
+ * the spawned Apex step fails. `writeApex(basename, contents)` writes a file in
138
+ * that dir and returns its absolute path. Replaces the old fixed-name
139
+ * `.tmp-setup-*.apex` files in ROOT, which collided across concurrent runs and
140
+ * leaked on throw.
141
+ */
142
+ function withApexTempDir(fn) {
143
+ const dir = mkdtempSync(join(tmpdir(), APEX_TMP_PREFIX));
144
+ try {
145
+ return fn((basename, contents) => {
146
+ const p = join(dir, basename);
147
+ writeFileSync(p, contents);
148
+ return p;
149
+ });
150
+ } finally {
151
+ try {
152
+ rmSync(dir, { recursive: true, force: true });
153
+ } catch {
154
+ /* best effort */
155
+ }
156
+ }
157
+ }
158
+
159
+ /** Filesystem-safe lock path for a target org. */
160
+ function orgLockPath(targetOrg) {
161
+ const safe = String(targetOrg).replace(/[^a-zA-Z0-9._-]/g, '_');
162
+ return join(tmpdir(), `org-setup-lock-${safe}.lock`);
163
+ }
164
+
165
+ /**
166
+ * Liveness probe: signal 0 throws ESRCH if the pid is gone, EPERM if it exists
167
+ * but we can't signal it (still alive, owned by another user).
168
+ */
169
+ function isProcessAlive(pid) {
170
+ try {
171
+ process.kill(pid, 0);
172
+ return true;
173
+ } catch (e) {
174
+ return e.code === 'EPERM';
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Acquire a single-host advisory per-target-org lock. If a LIVE
180
+ * run already holds it, exit early with a clear message rather than interleaving
181
+ * destructive Apex (deletes/imports) against the same org. A lock left by a
182
+ * hard-killed run (dead pid) is reclaimed. Different-org runs use different lock
183
+ * files and proceed in parallel.
184
+ *
185
+ * Released via process.on('exit') — NOT a finally block — because main() exits
186
+ * through process.exit() (the runStep fail-fast path, the end-of-run summary,
187
+ * and the top-level .catch), and process.exit() does not run finally blocks.
188
+ */
189
+ function acquireOrgLock(targetOrg) {
190
+ const lockPath = orgLockPath(targetOrg);
191
+ if (existsSync(lockPath)) {
192
+ const holder = Number(readFileSync(lockPath, 'utf8').trim());
193
+ if (holder && isProcessAlive(holder)) {
194
+ console.error(
195
+ `\nAnother org-setup run (pid ${holder}) is already targeting "${targetOrg}".\n` +
196
+ `Wait for it to finish, or if it was killed, remove ${lockPath} and retry.`,
197
+ );
198
+ process.exit(1);
199
+ }
200
+ // Stale lock (holder dead / hard-killed) — reclaim it.
201
+ rmSync(lockPath, { force: true });
202
+ }
203
+ // O_EXCL ('wx') create closes the check-then-write race between two
204
+ // near-simultaneous runs: the loser gets EEXIST.
205
+ let fd;
206
+ try {
207
+ fd = openSync(lockPath, 'wx');
208
+ } catch (e) {
209
+ if (e.code === 'EEXIST') {
210
+ console.error(
211
+ `\nAnother org-setup run just acquired the lock for "${targetOrg}". Retry shortly.`,
212
+ );
213
+ process.exit(1);
214
+ }
215
+ throw e;
216
+ }
217
+ writeFileSync(fd, String(process.pid));
218
+ closeSync(fd);
219
+
220
+ process.on('exit', () => {
221
+ try {
222
+ rmSync(lockPath, { force: true });
223
+ } catch {
224
+ /* best effort */
225
+ }
226
+ });
227
+ }
228
+
229
+ /**
230
+ * npm strips .gitignore from published packages — generate them on first run.
231
+ * Templates are stored in scripts/gitignore-templates.json (generated at build
232
+ * time from the actual .gitignore files) so the content lives in one place.
233
+ * The JSON may not exist in git-cloned distributions where .gitignore is
234
+ * already present, so loading is best-effort.
235
+ */
236
+ function loadGitignoreTemplates() {
237
+ const templatesPath = resolve(__dirname, 'gitignore-templates.json');
238
+ if (!existsSync(templatesPath)) return null;
239
+ try {
240
+ return JSON.parse(readFileSync(templatesPath, 'utf8'));
241
+ } catch {
242
+ return null;
243
+ }
244
+ }
245
+
246
+ function ensureGitignore(dir, content) {
247
+ if (!content) return;
248
+ const gitignorePath = resolve(dir, '.gitignore');
249
+ if (!existsSync(gitignorePath)) {
250
+ writeFileSync(gitignorePath, content, 'utf8');
251
+ console.log(`Created .gitignore in ${dir}`);
252
+ }
253
+ }
254
+
255
+ function resolveSfdxSource() {
256
+ const sfdxPath = resolve(ROOT, 'sfdx-project.json');
257
+ if (!existsSync(sfdxPath)) {
258
+ console.error('Error: sfdx-project.json not found at project root.');
259
+ process.exit(1);
260
+ }
261
+ const sfdxProject = JSON.parse(readFileSync(sfdxPath, 'utf8'));
262
+ const pkgDir = sfdxProject?.packageDirectories?.[0]?.path;
263
+ if (!pkgDir) {
264
+ console.error('Error: No packageDirectories[].path found in sfdx-project.json.');
265
+ process.exit(1);
266
+ }
267
+ return resolve(ROOT, pkgDir, 'main', 'default');
268
+ }
269
+
270
+ const SFDX_SOURCE = resolveSfdxSource();
271
+ const UIBUNDLES_DIR = resolve(SFDX_SOURCE, 'uiBundles');
272
+ const DATA_DIR = resolve(SFDX_SOURCE, 'data');
273
+ const DATA_PLAN = resolve(SFDX_SOURCE, 'data/data-plan.json');
274
+
275
+ function parseArgs() {
276
+ const args = process.argv.slice(2);
277
+ let targetOrg = null;
278
+ let uiBundleName = null;
279
+ /** If non-empty, only these names are assigned; otherwise all discovered from the project. */
280
+ const permsetNamesExplicit = [];
281
+ let yes = false;
282
+ const flags = {
283
+ skipDeploy: false,
284
+ skipPermset: false,
285
+ skipRole: false,
286
+ skipData: false,
287
+ skipGraphql: false,
288
+ skipUIBundleBuild: false,
289
+ skipSelfReg: false,
290
+ skipSocialLogin: false,
291
+ };
292
+ for (let i = 0; i < args.length; i++) {
293
+ if (args[i] === '--target-org' && args[i + 1]) {
294
+ targetOrg = args[++i];
295
+ } else if (args[i] === '--ui-bundle-name' && args[i + 1]) {
296
+ uiBundleName = args[++i];
297
+ } else if (args[i] === '--permset-name' && args[i + 1]) {
298
+ permsetNamesExplicit.push(args[++i]);
299
+ } else if (args[i] === '--skip-deploy') flags.skipDeploy = true;
300
+ else if (args[i] === '--skip-permset') flags.skipPermset = true;
301
+ else if (args[i] === '--skip-role') flags.skipRole = true;
302
+ else if (args[i] === '--skip-data') flags.skipData = true;
303
+ else if (args[i] === '--skip-self-reg') flags.skipSelfReg = true;
304
+ else if (args[i] === '--skip-social-login') flags.skipSocialLogin = true;
305
+ else if (args[i] === '--skip-graphql') flags.skipGraphql = true;
306
+ else if (args[i] === '--skip-ui-bundle-build') flags.skipUIBundleBuild = true;
307
+ // --skip-login and --skip-dev are retired: login is now an unconditional
308
+ // precondition and the dev step moved to `npm run dev:preview`.
309
+ // Accept them silently as no-ops so existing invocations don't hard-error.
310
+ else if (args[i] === '--skip-login' || args[i] === '--skip-dev') {
311
+ /* no-op (retired flag) */
312
+ } else if (args[i] === '--yes' || args[i] === '-y') yes = true;
313
+ else if (args[i] === '--help' || args[i] === '-h') {
314
+ console.log(`
315
+ Setup CLI — one-command setup for apps in this project
316
+
317
+ Usage:
318
+ node scripts/org-setup.mjs [--target-org <alias>] [options]
319
+
320
+ Options:
321
+ --target-org <alias> Target Salesforce org alias (e.g. myorg). If omitted, you
322
+ are prompted to pick from authenticated orgs (or the
323
+ default org is used when not running interactively).
324
+ --ui-bundle-name <name> UI bundle folder name under uiBundles/ (default: auto-detect)
325
+ --permset-name <name> Assign only this permission set (repeatable). Default: all sets under permissionsets/
326
+ --skip-deploy Do not deploy metadata
327
+ --skip-permset Do not assign permission set
328
+ --skip-social-login Do not enable social login (auth providers + community profile)
329
+ --skip-data Do not prepare data or run data import
330
+ --skip-graphql Do not fetch schema or run GraphQL codegen
331
+ --skip-ui-bundle-build Do not npm install / build the UI bundle
332
+ -y, --yes Skip interactive step picker; run all enabled steps immediately
333
+ -h, --help Show this help
334
+
335
+ To launch the dev server after setup, run: npm run dev:preview
336
+
337
+ Permset config (scripts/org-setup.config.json):
338
+ Control per-permset assignment via a config file. Example:
339
+ {
340
+ "permsetAssignments": {
341
+ "defaultAssignee": "skip",
342
+ "assignments": {
343
+ "My_Permset": { "assignee": "currentUser" },
344
+ "Guest_Permset": { "assignee": "guestUser" },
345
+ "Internal_Only": { "assignee": "skip" }
346
+ }
347
+ }
348
+ }
349
+ Assignee values: "currentUser", "guestUser", or "skip". For "guestUser" the site
350
+ is derived from the single networks/<siteName>.network-meta.xml the app ships.
351
+ Unlisted permsets resolve to "defaultAssignee" (default "skip").
352
+ `);
353
+ process.exit(0);
354
+ }
355
+ }
356
+ // NOTE: no hard-exit on a missing --target-org here. Resolution is
357
+ // deferred to resolveTargetOrg(), which either prompts (TTY) or falls back to
358
+ // the default org / exits with a clear message (non-TTY).
359
+ return { targetOrg, uiBundleName, permsetNamesExplicit, yes, ...flags };
360
+ }
361
+
362
+ // Bundle discovery lives in org-setup-utils.mjs so org-setup-dev.mjs shares it verbatim.
363
+ // These thin wrappers bind the shared helpers to this script's UIBUNDLES_DIR and
364
+ // keep the existing call-site signatures. discoverUIBundleDir carries the
365
+ // multi-bundle acknowledgment (TTY picker / non-TTY warning).
366
+ function discoverAllUIBundleDirs(uiBundleName) {
367
+ return discoverAllUIBundleDirsIn(UIBUNDLES_DIR, uiBundleName);
368
+ }
369
+
370
+ function discoverUIBundleDir(uiBundleName) {
371
+ return discoverUIBundleDirIn(UIBUNDLES_DIR, uiBundleName);
372
+ }
373
+
374
+ /** API names from permissionsets/*.permissionset-meta.xml in the first package directory. */
375
+ function discoverPermissionSetNames() {
376
+ const dir = resolve(SFDX_SOURCE, 'permissionsets');
377
+ if (!existsSync(dir)) return [];
378
+ const names = [];
379
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
380
+ if (!entry.isFile()) continue;
381
+ const m = entry.name.match(/^(.+)\.permissionset-meta\.xml$/);
382
+ if (m) names.push(m[1]);
383
+ }
384
+ return names.sort();
385
+ }
386
+
387
+ const CONFIG_PATH = resolve(__dirname, 'org-setup.config.json');
388
+
389
+ /**
390
+ * Read + validate org-setup.config.json ONCE, against the shared zod schema
391
+ * (the same `validateConfig` the build/CI gate uses). Exits non-zero with the
392
+ * precise zod issues if the config is invalid — before any step runs.
393
+ *
394
+ * Returns the validated config object (zod defaults applied), or an empty
395
+ * object when the file is absent (every section is optional).
396
+ *
397
+ * This is the single source of truth: loadPermsetConfig / loadRoleConfig /
398
+ * loadSelfRegConfig all read from the object it returns, so they no longer
399
+ * parse or defensively swallow errors.
400
+ */
401
+ function loadValidatedConfig() {
402
+ if (!existsSync(CONFIG_PATH)) return {};
403
+ const result = validateConfig(readFileSync(CONFIG_PATH, 'utf8'), CONFIG_PATH);
404
+ if (!result.ok) {
405
+ console.error('Invalid org-setup.config.json:');
406
+ for (const err of result.errors) console.error(` - ${err}`);
407
+ process.exit(1);
408
+ }
409
+ return result.data;
410
+ }
411
+
412
+ /**
413
+ * Derive the site name from the single networks/<siteName>.network-meta.xml the
414
+ * app ships. An app ships exactly one site, so the site name is derivable from
415
+ * deployed metadata rather than restated per-assignment. Returns
416
+ * null when there is no networks dir or no .network-meta.xml file.
417
+ */
418
+ function deriveSiteName() {
419
+ const networksDir = resolve(SFDX_SOURCE, 'networks');
420
+ if (!existsSync(networksDir)) return null;
421
+ const files = readdirSync(networksDir)
422
+ .filter((f) => f.endsWith('.network-meta.xml'))
423
+ .sort();
424
+ if (files.length === 0) return null;
425
+ // An app ships exactly one site; if a developer added a second, derivation is
426
+ // ambiguous — fail loudly rather than silently bind to an arbitrary site.
427
+ if (files.length > 1) {
428
+ throw new StepError(
429
+ `cannot derive guest site: multiple network metadata files found in ${networksDir} (${files.join(', ')}); guestUser assignment requires exactly one`,
430
+ );
431
+ }
432
+ const siteName = files[0].replace(/\.network-meta\.xml$/, '');
433
+ // The site name is interpolated into SOQL (Network lookup, guest-user lookup),
434
+ // so validate it here — the single chokepoint both callers pass through. Its
435
+ // source is the metadata filename, not org-setup.config.json, so point the fix
436
+ // there.
437
+ validateSoqlName(siteName, 'site name', {
438
+ remediation: `the networks/<siteName>.network-meta.xml filename (currently "${files[0]}")`,
439
+ });
440
+ return siteName;
441
+ }
442
+
443
+ /**
444
+ * Permset assignment configuration, read from the already-validated config.
445
+ *
446
+ * Config shape:
447
+ * {
448
+ * "permsetAssignments": {
449
+ * "defaultAssignee": "skip",
450
+ * "assignments": {
451
+ * "My_Permset": { "assignee": "currentUser" },
452
+ * "My_Guest_Permset": { "assignee": "guestUser" },
453
+ * "Internal_Only": { "assignee": "skip" }
454
+ * }
455
+ * }
456
+ * }
457
+ *
458
+ * Assignee values:
459
+ * "currentUser" — assign to the user running the script
460
+ * "skip" — do not assign this permset
461
+ * "guestUser" — resolve the site guest user automatically (site derived from
462
+ * the single networks/<siteName>.network-meta.xml the app ships)
463
+ *
464
+ * Unlisted permsets resolve to `defaultAssignee` (default "skip").
465
+ *
466
+ * Returns { defaultAssignee: string, assignments: Record<string, { assignee: string }> }
467
+ */
468
+ function loadPermsetConfig(config) {
469
+ const section = config.permsetAssignments;
470
+ if (!section) return { defaultAssignee: 'skip', assignments: {} };
471
+ return {
472
+ defaultAssignee: section.defaultAssignee,
473
+ assignments: section.assignments,
474
+ };
475
+ }
476
+
477
+ /** Resolve the effective assignment config for a given permset name. */
478
+ function resolveAssignment(permsetName, permsetConfig) {
479
+ const override = permsetConfig.assignments[permsetName];
480
+ if (!override) return { assignee: permsetConfig.defaultAssignee };
481
+ return { assignee: override.assignee };
482
+ }
483
+
484
+ /**
485
+ * Role assignment config, read from the already-validated config.
486
+ *
487
+ * Config shape:
488
+ * { "role": { "assignee": "currentUser", "roleName": "Admin" } }
489
+ *
490
+ * Returns null if no "role" section exists in config (the step is hidden).
491
+ */
492
+ function loadRoleConfig(config) {
493
+ const section = config.role;
494
+ if (!section) return null;
495
+ return {
496
+ assignee: section.assignee,
497
+ roleName: section.roleName,
498
+ };
499
+ }
500
+
501
+ /**
502
+ * Self-registration config, read from the already-validated config. The site is
503
+ * NOT stored here — it is derived from the single
504
+ * networks/<siteName>.network-meta.xml the app ships, exactly like
505
+ * the guestUser permset path. deriveSiteName() is called lazily inside the
506
+ * selfReg step body so its "multiple network files" StepError is recorded in
507
+ * the ledger rather than escaping config load.
508
+ *
509
+ * Config shape:
510
+ * {
511
+ * "selfRegistration": {
512
+ * "selfRegProfile": "myapp Profile",
513
+ * "accountName": "My Self-Reg Account"
514
+ * }
515
+ * }
516
+ *
517
+ * Returns null if no "selfRegistration" section exists in config (the step is hidden).
518
+ */
519
+ function loadSelfRegConfig(config) {
520
+ const section = config.selfRegistration;
521
+ if (!section) return null;
522
+ return {
523
+ selfRegProfile: section.selfRegProfile,
524
+ accountName: section.accountName,
525
+ };
526
+ }
527
+
528
+ /**
529
+ * Social login config, read from the already-validated config.
530
+ *
531
+ * Config shape:
532
+ * {
533
+ * "socialLogin": {
534
+ * "communityMemberProfile": "Customer Community User",
535
+ * "authProviderNames": ["Google", "Facebook", "My_SAML_Provider"],
536
+ * "communityUserPermset": "myapp_Guest_User_Api_Access" // optional
537
+ * }
538
+ * }
539
+ *
540
+ * - communityMemberProfile: profile added to NetworkMemberGroup (required for access)
541
+ * - authProviderNames: DeveloperNames of AuthProvider (OAuth) or SamlSsoConfig (SAML) records to link to site
542
+ * - communityUserPermset: permset assigned to community users so getCurrentUser()
543
+ * works (requires PermissionsApiEnabled for /chatter/users/me via /sf/api/)
544
+ *
545
+ * Returns null if no "socialLogin" section exists in config (the step is hidden).
546
+ */
547
+ function loadSocialLoginConfig(config) {
548
+ const section = config.socialLogin;
549
+ if (!section) return null;
550
+ return {
551
+ communityMemberProfile: section.communityMemberProfile,
552
+ authProviderNames: section.authProviderNames,
553
+ communityUserPermset: section.communityUserPermset || null,
554
+ };
555
+ }
556
+
557
+ /**
558
+ * Enable the "Allow using standard external profiles for self-registration,
559
+ * user creation, and login" org setting via Metadata API deploy.
560
+ *
561
+ * This setting is required for SSO registration handlers to create users with
562
+ * standard community profiles (e.g. "Customer Community User"). Without it,
563
+ * auth providers return FIELD_INTEGRITY_EXCEPTION on user insert.
564
+ *
565
+ * The correct metadata field is `enableOotbProfExtUserOpsEnable` in
566
+ * CommunitiesSettings. The REST/Tooling API approaches also fail on many
567
+ * org types. Deploying via Metadata API is the most reliable method.
568
+ */
569
+ function enableExternalProfiles(targetOrg) {
570
+ const dir = mkdtempSync(join(tmpdir(), APEX_TMP_PREFIX));
571
+ try {
572
+ // Create a minimal sfdx project with just the Communities setting
573
+ const settingsDir = join(dir, 'force-app', 'main', 'default', 'settings');
574
+ mkdirSync(settingsDir, { recursive: true });
575
+
576
+ writeFileSync(join(dir, 'sfdx-project.json'), JSON.stringify({
577
+ packageDirectories: [{ path: 'force-app', default: true }],
578
+ sourceApiVersion: '68.0',
579
+ }));
580
+
581
+ writeFileSync(join(settingsDir, 'Communities.settings-meta.xml'), [
582
+ '<?xml version="1.0" encoding="UTF-8"?>',
583
+ '<CommunitiesSettings xmlns="http://soap.sforce.com/2006/04/metadata">',
584
+ ' <enableOotbProfExtUserOpsEnable>true</enableOotbProfExtUserOpsEnable>',
585
+ '</CommunitiesSettings>',
586
+ ].join('\n'));
587
+
588
+ const result = spawnSync('sf', [
589
+ 'project', 'deploy', 'start',
590
+ '--target-org', targetOrg,
591
+ '--source-dir', join(dir, 'force-app'),
592
+ '--json',
593
+ ], { cwd: dir, stdio: 'pipe', shell: true, timeout: 120000 });
594
+
595
+ const out = result.stdout?.toString() || '';
596
+ let deployResult;
597
+ try { deployResult = JSON.parse(out); } catch { deployResult = null; }
598
+
599
+ if (deployResult?.status === 0 || deployResult?.result?.status === 'Succeeded') {
600
+ console.log(' Enabled "Allow using standard external profiles" org setting.');
601
+ } else {
602
+ // Check if it failed because the setting is already enabled or not deployable
603
+ const errMsg = deployResult?.message || deployResult?.result?.details?.componentFailures?.[0]?.problem || '';
604
+ if (errMsg.includes('already') || errMsg.includes('enableOotbProfExtUserOpsEnable')) {
605
+ console.log(' Warning: could not deploy "Allow standard external profiles" setting.');
606
+ console.log(` Detail: ${errMsg}`);
607
+ console.log(' The setting may already be active. Enable manually via Setup > Digital Experiences > Settings if needed.');
608
+ } else {
609
+ console.log(' Warning: could not enable "Allow standard external profiles".');
610
+ console.log(` Deploy result: ${errMsg || 'unknown error'}`);
611
+ console.log(' Enable manually via Setup > Digital Experiences > Settings.');
612
+ }
613
+ }
614
+ } finally {
615
+ try { rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ }
616
+ }
617
+ }
618
+
619
+ /**
620
+ * Enable Auth Providers for a community by creating AuthConfigProviders junction
621
+ * records via Anonymous Apex + REST API callouts.
622
+ *
623
+ * React (Site Container) sites intentionally hide SSO configuration in the Admin
624
+ * UI, so this must be done programmatically. The approach:
625
+ * 1. Query the AuthConfig record for the site (one per community).
626
+ * 2. Query AuthProvider records by DeveloperName.
627
+ * 3. Query SamlSsoConfig records by DeveloperName (for SAML providers).
628
+ * 4. Check existing AuthConfigProviders to avoid duplicates.
629
+ * 5. Create missing AuthConfigProviders via REST API (DML is not allowed on this object).
630
+ *
631
+ * AuthConfig.AuthOptionsAuthProvider auto-flips to true when AuthConfigProviders
632
+ * are inserted — no separate update needed.
633
+ *
634
+ * @param {string[]} authProviderNames - DeveloperNames of AuthProvider or SamlSsoConfig records
635
+ * @param {string} siteName - Name of the Network/community
636
+ * @param {string} targetOrg - Target org alias
637
+ */
638
+ function enableAuthProvidersForSite(authProviderNames, siteName, targetOrg) {
639
+ // DML is not allowed on AuthConfigProviders, so we use Anonymous Apex with
640
+ // HTTP callouts to the REST API to create the junction records.
641
+ // Whitelist each DeveloperName before it is interpolated into the generated
642
+ // Apex `DeveloperName IN (…)` literal — same call-site guard the data-import
643
+ // path applies with validateApiName, and defense-in-depth alongside the
644
+ // up-front socialLogin validation in main(). loadSocialLoginConfig already
645
+ // rejects an empty list, so the resulting literal is never empty here.
646
+ const providerNamesLiteral = authProviderNames
647
+ .map((n) => `'${validateSoqlName(n, 'socialLogin.authProviderNames entry')}'`)
648
+ .join(', ');
649
+
650
+ const apex = `
651
+ // Enable Auth Providers (OAuth + SAML) for community "${siteName}"
652
+ Http http = new Http();
653
+ String baseUrl = Url.getOrgDomainUrl().toExternalForm();
654
+ String token = UserInfo.getSessionId();
655
+
656
+ // Step 1: Find the AuthConfig for this site
657
+ List<AuthConfig> authConfigs = [
658
+ SELECT Id, Url
659
+ FROM AuthConfig
660
+ WHERE Url LIKE '%${siteName}%'
661
+ LIMIT 1
662
+ ];
663
+ if (authConfigs.isEmpty()) {
664
+ System.debug('ERROR_NO_AUTHCONFIG');
665
+ return;
666
+ }
667
+ AuthConfig ac = authConfigs[0];
668
+ System.debug('AUTHCONFIG_FOUND:' + ac.Id + ':' + ac.Url);
669
+
670
+ // Step 2: Query AuthProvider records by DeveloperName (OAuth providers)
671
+ List<AuthProvider> oauthProviders = [
672
+ SELECT Id, DeveloperName, FriendlyName
673
+ FROM AuthProvider
674
+ WHERE DeveloperName IN (${providerNamesLiteral})
675
+ ];
676
+ System.debug('OAUTH_PROVIDERS_FOUND:' + oauthProviders.size());
677
+
678
+ // Step 3: Query SamlSsoConfig records by DeveloperName (SAML providers)
679
+ List<SamlSsoConfig> samlProviders = [
680
+ SELECT Id, DeveloperName
681
+ FROM SamlSsoConfig
682
+ WHERE DeveloperName IN (${providerNamesLiteral})
683
+ ];
684
+ System.debug('SAML_PROVIDERS_FOUND:' + samlProviders.size());
685
+
686
+ // Combine both into a unified list with (Id, DeveloperName, Type)
687
+ List<Map<String, String>> allProviders = new List<Map<String, String>>();
688
+ for (AuthProvider ap : oauthProviders) {
689
+ allProviders.add(new Map<String, String>{
690
+ 'Id' => ap.Id,
691
+ 'DeveloperName' => ap.DeveloperName,
692
+ 'Type' => 'OAuth'
693
+ });
694
+ }
695
+ for (SamlSsoConfig sp : samlProviders) {
696
+ allProviders.add(new Map<String, String>{
697
+ 'Id' => sp.Id,
698
+ 'DeveloperName' => sp.DeveloperName,
699
+ 'Type' => 'SAML'
700
+ });
701
+ }
702
+
703
+ if (allProviders.isEmpty()) {
704
+ System.debug('ERROR_NO_PROVIDERS');
705
+ return;
706
+ }
707
+ System.debug('TOTAL_PROVIDERS_FOUND:' + allProviders.size());
708
+
709
+ // Step 4: Check existing AuthConfigProviders to avoid duplicates
710
+ Set<Id> existingProviderIds = new Set<Id>();
711
+ for (AuthConfigProviders acp : [
712
+ SELECT AuthProviderId FROM AuthConfigProviders WHERE AuthConfigId = :ac.Id
713
+ ]) {
714
+ existingProviderIds.add(acp.AuthProviderId);
715
+ }
716
+
717
+ // Step 5: Create missing junction records via REST API
718
+ Integer inserted = 0;
719
+ for (Map<String, String> provider : allProviders) {
720
+ String providerId = provider.get('Id');
721
+ String providerName = provider.get('DeveloperName');
722
+ String providerType = provider.get('Type');
723
+
724
+ if (existingProviderIds.contains(providerId)) {
725
+ System.debug('ALREADY_LINKED:' + providerName + ':' + providerType);
726
+ continue;
727
+ }
728
+ HttpRequest req = new HttpRequest();
729
+ req.setEndpoint(baseUrl + '/services/data/v62.0/sobjects/AuthConfigProviders');
730
+ req.setMethod('POST');
731
+ req.setHeader('Authorization', 'Bearer ' + token);
732
+ req.setHeader('Content-Type', 'application/json');
733
+ req.setBody('{"AuthConfigId":"' + ac.Id + '","AuthProviderId":"' + providerId + '"}');
734
+ HttpResponse res = http.send(req);
735
+ if (res.getStatusCode() == 201 || res.getStatusCode() == 200) {
736
+ System.debug('INSERTED:' + providerName + ':' + providerType);
737
+ inserted++;
738
+ } else {
739
+ System.debug('INSERT_FAILED:' + providerName + ':' + providerType + ':' + res.getStatusCode() + ':' + res.getBody());
740
+ }
741
+ }
742
+ if (inserted == 0 && existingProviderIds.size() >= allProviders.size()) {
743
+ System.debug('ALL_ALREADY_LINKED');
744
+ } else {
745
+ System.debug('TOTAL_INSERTED:' + inserted);
746
+ }
747
+ `;
748
+
749
+ const apexOut = withApexTempDir((writeApex) => {
750
+ const tmpApex = writeApex('auth-providers.apex', apex);
751
+ const result = spawnSync('sf', [
752
+ 'apex', 'run', '--target-org', targetOrg, '--file', tmpApex,
753
+ ], { cwd: ROOT, stdio: 'pipe', shell: true, timeout: 60000 });
754
+ const out = result.stdout?.toString() || '';
755
+ const err = result.stderr?.toString() || '';
756
+ if (result.status !== 0 && !out.includes('Compiled successfully')) {
757
+ process.stderr.write(err || out);
758
+ throw new StepError('failed to execute AuthConfigProviders apex');
759
+ }
760
+ return out;
761
+ });
762
+
763
+ // Parse output for status — match only |DEBUG| lines to avoid false positives
764
+ // from the "Execute Anonymous:" source echo that sf apex run always prints.
765
+ if (apexOut.match(/\|DEBUG\|ERROR_NO_AUTHCONFIG/)) {
766
+ throw new StepError(`no AuthConfig found for site "${siteName}" — ensure the site is published/active`);
767
+ }
768
+ if (apexOut.match(/\|DEBUG\|ERROR_NO_PROVIDERS/)) {
769
+ throw new StepError(`no AuthProvider or SamlSsoConfig records found for names: ${authProviderNames.join(', ')} — create them in Setup first`);
770
+ }
771
+
772
+ // Check for insert failures
773
+ const insertFails = [...apexOut.matchAll(/\|DEBUG\|INSERT_FAILED:([^:]+):(OAuth|SAML):(\d+):([^\n]+)/g)];
774
+ if (insertFails.length > 0) {
775
+ for (const m of insertFails) {
776
+ console.error(` ✖ ${m[1]} (${m[2]}) — HTTP ${m[3]}: ${m[4].trim()}`);
777
+ }
778
+ throw new StepError(`failed to link ${insertFails.length} Auth Provider(s) to site AuthConfig`);
779
+ }
780
+
781
+ const totalMatch = apexOut.match(/\|DEBUG\|TOTAL_INSERTED:(\d+)/);
782
+ if (totalMatch) {
783
+ console.log(` Linked ${totalMatch[1]} Auth Provider(s) to site "${siteName}".`);
784
+ } else if (apexOut.match(/\|DEBUG\|ALL_ALREADY_LINKED/)) {
785
+ console.log(` All Auth Provider(s) already linked to site "${siteName}"; no changes needed.`);
786
+ }
787
+
788
+ // Log individual provider statuses
789
+ const alreadyLinked = [...apexOut.matchAll(/\|DEBUG\|ALREADY_LINKED:([^:]+):(OAuth|SAML)/g)];
790
+ for (const m of alreadyLinked) {
791
+ console.log(` ✔ ${m[1]} (${m[2]}, already linked)`);
792
+ }
793
+ const inserted = [...apexOut.matchAll(/\|DEBUG\|INSERTED:([^:]+):(OAuth|SAML)/g)];
794
+ for (const m of inserted) {
795
+ console.log(` + ${m[1]} (${m[2]}, newly linked)`);
796
+ }
797
+ }
798
+
799
+ /**
800
+ * Add a community user profile to the NetworkMemberGroup so that SSO-registered
801
+ * users (who get assigned this profile by the registration handler) can access
802
+ * the community.
803
+ *
804
+ * Without this, users created by the SSO registration handler get
805
+ * "NO_ACCESS: User was not authorized for the community".
806
+ *
807
+ * @param {string} profileName - Profile name to add (e.g. "Customer Community User")
808
+ * @param {string} siteName - Name of the Network/community
809
+ * @param {string} targetOrg - Target org alias
810
+ */
811
+ function addCommunityMemberProfile(profileName, siteName, targetOrg) {
812
+ // Query Network Id
813
+ const netQuery = `SELECT Id FROM Network WHERE Name = '${siteName}'`;
814
+ const netResult = spawnSync('sf', [
815
+ 'data', 'query', '--query', netQuery, '--target-org', targetOrg, '--json',
816
+ ], { cwd: ROOT, encoding: 'utf8' });
817
+ let networkId = null;
818
+ if (netResult.status === 0) {
819
+ try {
820
+ const json = JSON.parse(netResult.stdout);
821
+ networkId = json.result?.records?.[0]?.Id || null;
822
+ } catch { /* fall through */ }
823
+ }
824
+ if (!networkId) {
825
+ throw new StepError(`could not find Network "${siteName}" in org`);
826
+ }
827
+
828
+ // Query Profile Id
829
+ const profQuery = `SELECT Id FROM Profile WHERE Name = '${profileName}'`;
830
+ const profResult = spawnSync('sf', [
831
+ 'data', 'query', '--query', profQuery, '--target-org', targetOrg, '--json',
832
+ ], { cwd: ROOT, encoding: 'utf8' });
833
+ let profileId = null;
834
+ if (profResult.status === 0) {
835
+ try {
836
+ const json = JSON.parse(profResult.stdout);
837
+ profileId = json.result?.records?.[0]?.Id || null;
838
+ } catch { /* fall through */ }
839
+ }
840
+ if (!profileId) {
841
+ throw new StepError(`could not find Profile "${profileName}" in org`);
842
+ }
843
+
844
+ // Check if already a member
845
+ const memberQuery = `SELECT Id FROM NetworkMemberGroup WHERE NetworkId = '${networkId}' AND ParentId = '${profileId}'`;
846
+ const memberResult = spawnSync('sf', [
847
+ 'data', 'query', '--query', memberQuery, '--target-org', targetOrg, '--json',
848
+ ], { cwd: ROOT, encoding: 'utf8' });
849
+ let alreadyExists = false;
850
+ if (memberResult.status === 0) {
851
+ try {
852
+ const json = JSON.parse(memberResult.stdout);
853
+ alreadyExists = (json.result?.records?.length || 0) > 0;
854
+ } catch { /* proceed to create */ }
855
+ }
856
+ if (alreadyExists) {
857
+ console.log(` Profile "${profileName}" is already a member of community "${siteName}"; skipping.`);
858
+ return;
859
+ }
860
+
861
+ // Create NetworkMemberGroup record
862
+ const createResult = spawnSync('sf', [
863
+ 'data', 'create', 'record',
864
+ '--sobject', 'NetworkMemberGroup',
865
+ '--values', `NetworkId='${networkId}' ParentId='${profileId}'`,
866
+ '--target-org', targetOrg,
867
+ '--json',
868
+ ], { cwd: ROOT, encoding: 'utf8' });
869
+ if (createResult.status !== 0) {
870
+ const out = (createResult.stderr || '') + (createResult.stdout || '');
871
+ if (out) process.stderr.write(out);
872
+ throw new StepError(`failed to add profile "${profileName}" to NetworkMemberGroup for "${siteName}"`);
873
+ }
874
+ try {
875
+ const json = JSON.parse(createResult.stdout);
876
+ const id = json.result?.id;
877
+ console.log(` Added profile "${profileName}" to community "${siteName}" (NetworkMemberGroup: ${id}).`);
878
+ } catch {
879
+ console.log(` Added profile "${profileName}" to community "${siteName}".`);
880
+ }
881
+ }
882
+
883
+ /**
884
+ * Assign a permission set to all existing community users with a given profile.
885
+ *
886
+ * After SSO login, community users need the app's API-enabled permset so that
887
+ * getCurrentUser() (which calls /chatter/users/me via the /sf/api/ proxy) works.
888
+ * Without PermissionsApiEnabled the proxy returns API_DISABLED_FOR_ORG and the
889
+ * React app treats the user as unauthenticated.
890
+ *
891
+ * This is idempotent: already-assigned users are skipped.
892
+ */
893
+ function assignPermsetToCommunityUsers(permsetName, profileName, targetOrg) {
894
+ // Resolve PermissionSet Id
895
+ const psQuery = `SELECT Id FROM PermissionSet WHERE Name = '${permsetName}'`;
896
+ const psResult = spawnSync('sf', [
897
+ 'data', 'query', '--query', psQuery, '--target-org', targetOrg, '--json',
898
+ ], { cwd: ROOT, encoding: 'utf8' });
899
+ let permsetId = null;
900
+ if (psResult.status === 0) {
901
+ try {
902
+ const json = JSON.parse(psResult.stdout);
903
+ permsetId = json.result?.records?.[0]?.Id || null;
904
+ } catch { /* fall through */ }
905
+ }
906
+ if (!permsetId) {
907
+ throw new StepError(`could not find PermissionSet "${permsetName}" in org`);
908
+ }
909
+
910
+ // Find community users on the given profile who do NOT already have the permset
911
+ const usersQuery = [
912
+ `SELECT Id, Username FROM User`,
913
+ `WHERE Profile.Name = '${profileName}'`,
914
+ `AND IsActive = true`,
915
+ `AND UserType IN ('CspLitePortal', 'CustomerSuccess', 'PowerCustomerSuccess')`,
916
+ `AND Id NOT IN (SELECT AssigneeId FROM PermissionSetAssignment WHERE PermissionSetId = '${permsetId}')`,
917
+ ].join(' ');
918
+ const usersResult = spawnSync('sf', [
919
+ 'data', 'query', '--query', usersQuery, '--target-org', targetOrg, '--json',
920
+ ], { cwd: ROOT, encoding: 'utf8' });
921
+ let users = [];
922
+ if (usersResult.status === 0) {
923
+ try {
924
+ const json = JSON.parse(usersResult.stdout);
925
+ users = json.result?.records || [];
926
+ } catch { /* empty list */ }
927
+ }
928
+
929
+ if (users.length === 0) {
930
+ console.log(` No community users on profile "${profileName}" need permset "${permsetName}"; skipping.`);
931
+ return;
932
+ }
933
+
934
+ // Assign the permset to each user
935
+ let assigned = 0;
936
+ for (const user of users) {
937
+ const createResult = spawnSync('sf', [
938
+ 'data', 'create', 'record',
939
+ '--sobject', 'PermissionSetAssignment',
940
+ '--values', `PermissionSetId='${permsetId}' AssigneeId='${user.Id}'`,
941
+ '--target-org', targetOrg,
942
+ '--json',
943
+ ], { cwd: ROOT, encoding: 'utf8' });
944
+ if (createResult.status === 0) {
945
+ assigned++;
946
+ } else {
947
+ // Log but don't fail — user might already have it via race condition
948
+ const out = (createResult.stdout || '') + (createResult.stderr || '');
949
+ if (!out.includes('DUPLICATE_VALUE')) {
950
+ console.warn(` Warning: could not assign "${permsetName}" to ${user.Username}: ${out.slice(0, 120)}`);
951
+ }
952
+ }
953
+ }
954
+ console.log(` Assigned permset "${permsetName}" to ${assigned}/${users.length} community user(s).`);
955
+ }
956
+
957
+ /**
958
+ * Ensure the self-registration profile is listed in networkMemberGroups.
959
+ * This must happen BEFORE the initial deploy so that the profile is a recognised
960
+ * site member when subsequent steps (selfRegProfile, selfRegistration=true) are deployed.
961
+ */
962
+ function ensureNetworkMemberProfile(selfRegConfig, siteName) {
963
+ const { selfRegProfile } = selfRegConfig;
964
+ if (!siteName || !selfRegProfile) return;
965
+
966
+ const networkXmlPath = resolve(SFDX_SOURCE, 'networks', `${siteName}.network-meta.xml`);
967
+ if (!existsSync(networkXmlPath)) {
968
+ console.log(` Network metadata not found: ${networkXmlPath}; skipping member group update.`);
969
+ return;
970
+ }
971
+ const xml = readFileSync(networkXmlPath, 'utf8');
972
+
973
+ // Parse + assert the target node exists, then mutate via a targeted edit.
974
+ // This is the BEST-EFFORT pre-deploy prep (not inside runStep, see lines
975
+ // ~1050): on a missing <networkMemberGroups> node we surface a LOUD
976
+ // console.error but do NOT throw — a bare throw here aborts before deploy and
977
+ // bypasses the ledger. The authoritative failure is recorded later by the
978
+ // post-deploy selfReg step.
979
+ let result;
980
+ try {
981
+ result = addProfileToMemberGroups(xml, selfRegProfile);
982
+ } catch (e) {
983
+ if (e instanceof NetworkXmlError) {
984
+ console.error(
985
+ ` ERROR: cannot add self-reg profile to ${siteName}.network-meta.xml — ${e.message}. ` +
986
+ `Continuing pre-deploy; the self-registration step will record the authoritative failure.`,
987
+ );
988
+ return;
989
+ }
990
+ throw e;
991
+ }
992
+
993
+ if (!result.changed) {
994
+ console.log(` Profile "${selfRegProfile}" already in networkMemberGroups; no update needed.`);
995
+ return;
996
+ }
997
+ writeFileSync(networkXmlPath, result.xml);
998
+ console.log(` Added profile "${selfRegProfile}" to networkMemberGroups in ${siteName}.network-meta.xml`);
999
+ }
1000
+
1001
+ /**
1002
+ * Enable self-registration for an Experience Cloud network.
1003
+ *
1004
+ * 1. Modify the network metadata XML to set selfRegistration=true and add selfRegProfile.
1005
+ * 2. Re-deploy the modified network metadata.
1006
+ * 3. Create an Account record (idempotent).
1007
+ * 4. Create a NetworkSelfRegistration record linking the Account to the Network (idempotent).
1008
+ */
1009
+ function enableSelfRegistration(selfRegConfig, siteName, targetOrg) {
1010
+ const { selfRegProfile, accountName } = selfRegConfig;
1011
+
1012
+ // 1. Modify network metadata XML
1013
+ const networkXmlPath = resolve(SFDX_SOURCE, 'networks', `${siteName}.network-meta.xml`);
1014
+ if (!existsSync(networkXmlPath)) {
1015
+ throw new StepError(`network metadata not found: ${networkXmlPath}`);
1016
+ }
1017
+ const xml = readFileSync(networkXmlPath, 'utf8');
1018
+
1019
+ // Parse + assert the <selfRegistration> node exists, then mutate via a
1020
+ // targeted edit. This runs inside
1021
+ // runStep(selfReg, failFast:false) (line ~1211), so a missing node must throw
1022
+ // a StepError — caught, recorded `failed`, non-zero exit — rather than the
1023
+ // old silent no-op. The helper's idempotency check
1024
+ // (already true / selfRegProfile present) yields changed:false here.
1025
+ let result;
1026
+ try {
1027
+ result = enableSelfRegInXml(xml, selfRegProfile);
1028
+ } catch (e) {
1029
+ if (e instanceof NetworkXmlError) {
1030
+ throw new StepError(`${siteName}.network-meta.xml: ${e.message}`);
1031
+ }
1032
+ throw e;
1033
+ }
1034
+
1035
+ if (!result.changed) {
1036
+ console.log(` Network "${siteName}" already has self-registration configured; skipping metadata update and deploy.`);
1037
+ } else {
1038
+ writeFileSync(networkXmlPath, result.xml);
1039
+ console.log(` Updated ${siteName}.network-meta.xml: selfRegistration=true, selfRegProfile=${selfRegProfile}`);
1040
+
1041
+ // Re-deploy only the network file
1042
+ const deployResult = spawnSync('sf', [
1043
+ 'project', 'deploy', 'start',
1044
+ '--target-org', targetOrg,
1045
+ '--source-dir', networkXmlPath,
1046
+ ], { cwd: ROOT, stdio: 'inherit', shell: true, timeout: 120000 });
1047
+ if (deployResult.status !== 0) {
1048
+ throw new StepError(`failed to deploy updated network metadata (exit ${deployResult.status ?? 1})`);
1049
+ }
1050
+ }
1051
+
1052
+ // 3. Create Account (idempotent).
1053
+ // accountName is a free-form display value (e.g. "O'Brien Rentals & Co.") that
1054
+ // legitimately contains punctuation, so it is ESCAPED rather than whitelisted:
1055
+ // escape it for the SOQL read here, and create it via Apex below
1056
+ // (apexLiteral-escaped) rather than the `--values Name='...'` CLI arg, whose
1057
+ // space-separated key=value parsing an escaped name cannot safely satisfy.
1058
+ const acctQuery = `SELECT Id FROM Account WHERE Name = '${escapeSoqlString(accountName)}' LIMIT 1`;
1059
+ const acctQueryResult = spawnSync('sf', [
1060
+ 'data', 'query',
1061
+ '--query', acctQuery,
1062
+ '--target-org', targetOrg,
1063
+ '--json',
1064
+ ], { cwd: ROOT, encoding: 'utf8' });
1065
+ let accountId = null;
1066
+ if (acctQueryResult.status === 0) {
1067
+ try {
1068
+ const json = JSON.parse(acctQueryResult.stdout);
1069
+ accountId = json.result?.records?.[0]?.Id || null;
1070
+ } catch { /* proceed to create */ }
1071
+ }
1072
+ if (accountId) {
1073
+ console.log(` Account "${accountName}" already exists (${accountId}); skipping creation.`);
1074
+ } else {
1075
+ // Create via Anonymous Apex (apexLiteral escapes the name) instead of
1076
+ // `sf data create record --values`: the CLI parses --values as
1077
+ // space-separated key=value pairs, so a name with a space, quote, or `&`
1078
+ // either mis-parses or opens a field-injection surface. Apex string
1079
+ // escaping closes that off and mirrors the NSR create just below.
1080
+ const apex = [
1081
+ `Account acct = new Account(Name = ${apexLiteral(accountName)});`,
1082
+ `insert acct;`,
1083
+ `System.debug('ACCOUNT_CREATED:' + acct.Id);`,
1084
+ ].join('\n');
1085
+ const apexOut = withApexTempDir((writeApex) => {
1086
+ const tmpApex = writeApex('account.apex', apex);
1087
+ const apexResult = spawnSync('sf', [
1088
+ 'apex', 'run', '--target-org', targetOrg, '--file', tmpApex,
1089
+ ], { cwd: ROOT, stdio: 'pipe', shell: true, timeout: 60000 });
1090
+ const out = apexResult.stdout?.toString() || '';
1091
+ if (apexResult.status !== 0 && !out.includes('Compiled successfully')) {
1092
+ process.stderr.write(apexResult.stderr?.toString() || out);
1093
+ throw new StepError(`failed to create Account "${accountName}"`);
1094
+ }
1095
+ return out;
1096
+ });
1097
+ const acctMatch = apexOut.match(/ACCOUNT_CREATED:(\w+)/);
1098
+ if (!acctMatch) {
1099
+ throw new StepError('failed to parse Account creation result');
1100
+ }
1101
+ accountId = acctMatch[1];
1102
+ console.log(` Created Account "${accountName}" (${accountId}).`);
1103
+ }
1104
+
1105
+ // 4. Query Network Id
1106
+ const netQuery = `SELECT Id FROM Network WHERE Name = '${siteName}'`;
1107
+ const netResult = spawnSync('sf', [
1108
+ 'data', 'query',
1109
+ '--query', netQuery,
1110
+ '--target-org', targetOrg,
1111
+ '--json',
1112
+ ], { cwd: ROOT, encoding: 'utf8' });
1113
+ let networkId = null;
1114
+ if (netResult.status === 0) {
1115
+ try {
1116
+ const json = JSON.parse(netResult.stdout);
1117
+ networkId = json.result?.records?.[0]?.Id || null;
1118
+ } catch { /* fall through */ }
1119
+ }
1120
+ if (!networkId) {
1121
+ throw new StepError(`could not find Network "${siteName}" in org`);
1122
+ }
1123
+ console.log(` Found Network "${siteName}" (${networkId}).`);
1124
+
1125
+ // 5. Create NetworkSelfRegistration (idempotent)
1126
+ const nsrQuery = `SELECT Id FROM NetworkSelfRegistration WHERE NetworkId = '${networkId}'`;
1127
+ const nsrResult = spawnSync('sf', [
1128
+ 'data', 'query',
1129
+ '--query', nsrQuery,
1130
+ '--target-org', targetOrg,
1131
+ '--json',
1132
+ ], { cwd: ROOT, encoding: 'utf8' });
1133
+ let nsrExists = false;
1134
+ if (nsrResult.status === 0) {
1135
+ try {
1136
+ const json = JSON.parse(nsrResult.stdout);
1137
+ nsrExists = (json.result?.records?.length || 0) > 0;
1138
+ } catch { /* proceed to create */ }
1139
+ }
1140
+ if (nsrExists) {
1141
+ console.log(' NetworkSelfRegistration record already exists; skipping.');
1142
+ } else {
1143
+ const apex = [
1144
+ `Account acct = [SELECT Id FROM Account WHERE Id = '${accountId}' LIMIT 1];`,
1145
+ `NetworkSelfRegistration nsr = new NetworkSelfRegistration();`,
1146
+ `nsr.AccountId = acct.Id;`,
1147
+ `nsr.NetworkId = '${networkId}';`,
1148
+ `insert nsr;`,
1149
+ `System.debug('NSR_CREATED:' + nsr.Id);`,
1150
+ ].join('\n');
1151
+ const apexOut = withApexTempDir((writeApex) => {
1152
+ const tmpApex = writeApex('selfreg.apex', apex);
1153
+ const apexResult = spawnSync('sf', [
1154
+ 'apex', 'run', '--target-org', targetOrg, '--file', tmpApex,
1155
+ ], { cwd: ROOT, stdio: 'pipe', shell: true, timeout: 60000 });
1156
+ const out = apexResult.stdout?.toString() || '';
1157
+ if (apexResult.status !== 0 && !out.includes('Compiled successfully')) {
1158
+ process.stderr.write(apexResult.stderr?.toString() || out);
1159
+ throw new StepError('failed to create NetworkSelfRegistration record');
1160
+ }
1161
+ return out;
1162
+ });
1163
+ const nsrMatch = apexOut.match(/NSR_CREATED:(\w+)/);
1164
+ if (nsrMatch) {
1165
+ console.log(` Created NetworkSelfRegistration (${nsrMatch[1]}).`);
1166
+ } else {
1167
+ console.log(' NetworkSelfRegistration creation executed.');
1168
+ }
1169
+ }
1170
+ }
1171
+
1172
+ /**
1173
+ * Assign a role to the current user so that Experience Cloud self-registration
1174
+ * works correctly.
1175
+ */
1176
+ function assignRoleToCurrentUser(roleName, targetOrg) {
1177
+ validateSoqlName(roleName, 'role name');
1178
+ const roleQuery = `SELECT Id FROM UserRole WHERE Name = '${roleName}'`;
1179
+ const roleResult = spawnSync('sf', [
1180
+ 'data', 'query',
1181
+ '--query', roleQuery,
1182
+ '--target-org', targetOrg,
1183
+ '--json',
1184
+ ], { cwd: ROOT, encoding: 'utf8' });
1185
+ if (roleResult.status !== 0) {
1186
+ if (roleResult.stderr) console.error(roleResult.stderr);
1187
+ throw new StepError(`failed to query role "${roleName}" in org`);
1188
+ }
1189
+ let roleId;
1190
+ try {
1191
+ const json = JSON.parse(roleResult.stdout);
1192
+ const records = json.result?.records;
1193
+ if (!records || records.length === 0) {
1194
+ throw new StepError(`role "${roleName}" not found in org`);
1195
+ }
1196
+ roleId = records[0].Id;
1197
+ } catch (err) {
1198
+ if (err instanceof StepError) throw err;
1199
+ throw new StepError(`failed to parse role query result for "${roleName}"`);
1200
+ }
1201
+
1202
+ const orgResult = spawnSync('sf', [
1203
+ 'org', 'display',
1204
+ '--target-org', targetOrg,
1205
+ '--json',
1206
+ ], { cwd: ROOT, encoding: 'utf8' });
1207
+ if (orgResult.status !== 0) {
1208
+ throw new StepError('failed to resolve current user from org');
1209
+ }
1210
+ let username;
1211
+ try {
1212
+ const json = JSON.parse(orgResult.stdout);
1213
+ username = json.result?.username;
1214
+ if (!username) {
1215
+ throw new StepError('could not determine current username from org display');
1216
+ }
1217
+ } catch (err) {
1218
+ if (err instanceof StepError) throw err;
1219
+ throw new StepError('failed to parse org display result');
1220
+ }
1221
+
1222
+ const userQuery = `SELECT Id, UserRoleId FROM User WHERE Username = '${username}'`;
1223
+ const userResult = spawnSync('sf', [
1224
+ 'data', 'query',
1225
+ '--query', userQuery,
1226
+ '--target-org', targetOrg,
1227
+ '--json',
1228
+ ], { cwd: ROOT, encoding: 'utf8' });
1229
+ if (userResult.status === 0) {
1230
+ try {
1231
+ const json = JSON.parse(userResult.stdout);
1232
+ const userRecord = json.result?.records?.[0];
1233
+ if (userRecord?.UserRoleId) {
1234
+ console.log(` User ${username} already has a role assigned; skipping to avoid overriding.`);
1235
+ return;
1236
+ }
1237
+ } catch { /* continue */ }
1238
+ }
1239
+
1240
+ const updateResult = spawnSync('sf', [
1241
+ 'data', 'update', 'record',
1242
+ '--sobject', 'User',
1243
+ '--where', `Username='${username}'`,
1244
+ '--values', `UserRoleId='${roleId}'`,
1245
+ '--target-org', targetOrg,
1246
+ '--json',
1247
+ ], { cwd: ROOT, encoding: 'utf8' });
1248
+ if (updateResult.status === 0) {
1249
+ console.log(` Role "${roleName}" assigned to ${username}.`);
1250
+ } else {
1251
+ const out = (updateResult.stderr?.toString() || '') + (updateResult.stdout?.toString() || '');
1252
+ if (out) console.error(out);
1253
+ throw new StepError(`failed to assign role "${roleName}" to ${username}`);
1254
+ }
1255
+ }
1256
+
1257
+ /**
1258
+ * Query the org for the guest user of the given site.
1259
+ *
1260
+ * Salesforce auto-creates a guest profile named "<Site> Profile" for each
1261
+ * Experience Cloud site. The old `Profile.Name LIKE '%<siteName>%'` substring
1262
+ * match collided across sites — e.g. site "shop" also matched "shop-admin"'s
1263
+ * guest profile — and then blindly took records[0]. This uses an exact match on
1264
+ * the profile name instead. SOQL string equality on a text field is
1265
+ * case-insensitive by default (it wraps both sides in UPPER()), so a site whose
1266
+ * label casing differs from the derived name still matches without explicit
1267
+ * normalization. siteName is whitelist-validated at the deriveSiteName()
1268
+ * chokepoint, so it is safe to interpolate here.
1269
+ *
1270
+ * Residual limitation: on a non-English org the auto-generated " Profile" suffix
1271
+ * may be localized, in which case no row matches and the assignment soft-skips
1272
+ * (returned null) with a clear message — the caller records that as a skip, not
1273
+ * a crash.
1274
+ *
1275
+ * Returns the guest Username, or null (with a logged reason) when the query
1276
+ * fails, no guest user exists, or the match is ambiguous.
1277
+ */
1278
+ function resolveGuestUsername(siteName, targetOrg) {
1279
+ const query =
1280
+ `SELECT Username FROM User ` +
1281
+ `WHERE Profile.Name = '${siteName} Profile' AND UserType = 'Guest'`;
1282
+ const result = spawnSync('sf', [
1283
+ 'data', 'query',
1284
+ '--query', query,
1285
+ '--target-org', targetOrg,
1286
+ '--json',
1287
+ ], { cwd: ROOT, encoding: 'utf8' });
1288
+ if (result.status !== 0) {
1289
+ console.error(` Failed to query guest user for site "${siteName}".`);
1290
+ if (result.stderr) console.error(result.stderr);
1291
+ return null;
1292
+ }
1293
+ try {
1294
+ const json = JSON.parse(result.stdout);
1295
+ const records = json.result?.records;
1296
+ if (!records || records.length === 0) {
1297
+ console.error(` No guest user found for site "${siteName}" (looked for profile "${siteName} Profile").`);
1298
+ return null;
1299
+ }
1300
+ if (records.length > 1) {
1301
+ const names = records.map((r) => r.Username).join(', ');
1302
+ console.error(
1303
+ ` Ambiguous guest user for site "${siteName}": ${records.length} guest users share ` +
1304
+ `profile "${siteName} Profile" (${names}); refusing to guess.`,
1305
+ );
1306
+ return null;
1307
+ }
1308
+ return records[0].Username;
1309
+ } catch {
1310
+ console.error(` Failed to parse guest user query result for site "${siteName}".`);
1311
+ return null;
1312
+ }
1313
+ }
1314
+
1315
+ /**
1316
+ * License pre-check for self-registration. Query the UserLicense that the
1317
+ * selfRegProfile belongs to and decide whether self-registration can proceed.
1318
+ * The profile name is validate-and-fail: a SOQL-special character throws a config
1319
+ * error rather than being escaped — profile names are developer-authored config,
1320
+ * not user input, so a `'` / `\` / control char is a mistake to surface loudly.
1321
+ *
1322
+ * Selection is on the stable LicenseDefinitionKey; the seat math lives in JS
1323
+ * (evaluateLicenseRows) because SOQL cannot compare two fields. A query failure
1324
+ * or 0 rows is treated as "not satisfied" (soft skip), not a hard error.
1325
+ *
1326
+ * @returns {{ satisfied: boolean, reason: string|null }}
1327
+ */
1328
+ function checkSelfRegLicense(selfRegConfig, targetOrg) {
1329
+ const profileName = validateProfileNameForSoql(selfRegConfig.selfRegProfile);
1330
+ const query =
1331
+ `SELECT UserLicense.LicenseDefinitionKey, UserLicense.Name, UserLicense.Status, ` +
1332
+ `UserLicense.TotalLicenses, UserLicense.UsedLicenses ` +
1333
+ `FROM Profile WHERE Name = '${profileName}'`;
1334
+ const result = spawnSync('sf', [
1335
+ 'data', 'query',
1336
+ '--query', query,
1337
+ '--target-org', targetOrg,
1338
+ '--json',
1339
+ ], { cwd: ROOT, encoding: 'utf8' });
1340
+
1341
+ if (result.status !== 0) {
1342
+ if (result.stderr) console.error(result.stderr);
1343
+ return {
1344
+ satisfied: false,
1345
+ reason: `could not query the UserLicense for profile "${profileName}" (sf data query failed)`,
1346
+ };
1347
+ }
1348
+ let rows;
1349
+ try {
1350
+ rows = JSON.parse(result.stdout).result?.records ?? [];
1351
+ } catch {
1352
+ return {
1353
+ satisfied: false,
1354
+ reason: `could not parse the UserLicense query result for profile "${profileName}"`,
1355
+ };
1356
+ }
1357
+ const { satisfied, reason } = evaluateLicenseRows(rows, profileName);
1358
+ return { satisfied, reason };
1359
+ }
1360
+
1361
+ /**
1362
+ * Read the UserLicense the selfRegProfile requires straight from the local
1363
+ * profile metadata's <userLicense> element. The deploy pre-check runs BEFORE
1364
+ * the profile is deployed, so querying the org's Profile table returns 0 rows
1365
+ * and can only report "profile missing" — which never tells the user which
1366
+ * license to add. The profile source we are about to deploy is the
1367
+ * authoritative declaration of the required license.
1368
+ *
1369
+ * @returns {string|null} the license name, or null if the file / field is absent
1370
+ */
1371
+ function readProfileUserLicense(selfRegProfile) {
1372
+ const profilePath = resolve(SFDX_SOURCE, 'profiles', `${selfRegProfile}.profile-meta.xml`);
1373
+ if (!existsSync(profilePath)) return null;
1374
+ const xml = readFileSync(profilePath, 'utf8');
1375
+ const m = xml.match(/<userLicense>\s*([^<]+?)\s*<\/userLicense>/);
1376
+ return m ? m[1].trim() : null;
1377
+ }
1378
+
1379
+ /**
1380
+ * Deploy license pre-check. `sf project deploy start` fails with a
1381
+ * cryptic error when the org lacks the UserLicense the selfRegProfile's metadata
1382
+ * declares. Resolve the required license NAME from the local profile source, then
1383
+ * query the org's UserLicense by that name so a miss names the actual license the
1384
+ * admin must add — not the not-yet-deployed profile. Seat/status math is shared
1385
+ * with the self-reg gate via evaluateLicenseRows.
1386
+ *
1387
+ * @returns {{ satisfied: boolean, reason: string|null }}
1388
+ */
1389
+ function checkDeployLicense(selfRegConfig, targetOrg) {
1390
+ const licenseName = readProfileUserLicense(selfRegConfig.selfRegProfile);
1391
+ // No <userLicense> in the profile source (or profile file absent) — nothing to
1392
+ // gate on; let deploy proceed and surface any real error on its own.
1393
+ if (!licenseName) return { satisfied: true, reason: null };
1394
+
1395
+ const query =
1396
+ `SELECT LicenseDefinitionKey, Name, Status, TotalLicenses, UsedLicenses ` +
1397
+ `FROM UserLicense WHERE Name = '${escapeSoqlString(licenseName)}'`;
1398
+ const result = spawnSync('sf', [
1399
+ 'data', 'query',
1400
+ '--query', query,
1401
+ '--target-org', targetOrg,
1402
+ '--json',
1403
+ ], { cwd: ROOT, encoding: 'utf8' });
1404
+
1405
+ if (result.status !== 0) {
1406
+ if (result.stderr) console.error(result.stderr);
1407
+ return { satisfied: false, reason: `could not query UserLicense "${licenseName}" (sf data query failed)` };
1408
+ }
1409
+ let rows;
1410
+ try {
1411
+ rows = JSON.parse(result.stdout).result?.records ?? [];
1412
+ } catch {
1413
+ return { satisfied: false, reason: `could not parse the UserLicense query result for "${licenseName}"` };
1414
+ }
1415
+ if (rows.length === 0) {
1416
+ return {
1417
+ satisfied: false,
1418
+ reason: `required license "${licenseName}" is not present in the org — add it before deploying`,
1419
+ };
1420
+ }
1421
+ // evaluateLicenseRows expects the license nested under `.UserLicense` (its
1422
+ // Profile-query shape); reshape the direct UserLicense rows to match so the
1423
+ // seat/status logic — and its license-named messages — stay shared.
1424
+ return evaluateLicenseRows(rows.map((r) => ({ UserLicense: r })), selfRegConfig.selfRegProfile);
1425
+ }
1426
+
1427
+ function isOrgConnected(targetOrg) {
1428
+ const result = spawnSync('sf', ['org', 'display', '--target-org', targetOrg, '--json'], {
1429
+ cwd: ROOT,
1430
+ stdio: 'pipe',
1431
+ shell: true,
1432
+ });
1433
+ return result.status === 0;
1434
+ }
1435
+
1436
+ function apexLiteral(value) {
1437
+ if (value === null || value === undefined) return 'null';
1438
+ if (typeof value === 'boolean') return String(value);
1439
+ if (typeof value === 'number') return String(value);
1440
+ const s = String(value);
1441
+ if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return `Date.valueOf('${s}')`;
1442
+ if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(s)) {
1443
+ const dt = s.replace('T', ' ').replace(/\.\d+/, '').replace('Z', '');
1444
+ return `DateTime.valueOf('${dt}')`;
1445
+ }
1446
+ return "'" + s.replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'";
1447
+ }
1448
+
1449
+ function buildApexInsert(sobject, records, refIds) {
1450
+ // The sobject type and every field key land as bare identifiers inside the
1451
+ // generated Apex (`new ${sobject}()`, `r.put('${key}', …)`), where they can't
1452
+ // be quoted-and-escaped like a value — so they get the strict API-name
1453
+ // whitelist. refIds are the record referenceIds echoed back through a JSON
1454
+ // marker; they carry no Apex-identifier role, so escaping (not whitelisting)
1455
+ // is the right treatment for their single-quoted literal. All three come from
1456
+ // app-shipped seed fixtures, so a violation is a fixture bug surfaced loudly.
1457
+ validateApiName(sobject, 'sobject type');
1458
+ const lines = [
1459
+ 'Database.DMLOptions dmlOpts = new Database.DMLOptions();',
1460
+ // Intentional: bypass duplicate rules for seed-data import. These are
1461
+ // controlled fixtures the app ships, not user input, and duplicate-rule
1462
+ // blocks (plus matching-service timeouts the REST Sforce-Duplicate-Rule-Action
1463
+ // header can't override) would abort an otherwise-valid setup.
1464
+ 'dmlOpts.DuplicateRuleHeader.allowSave = true;',
1465
+ `List<${sobject}> recs = new List<${sobject}>();`,
1466
+ ];
1467
+ for (const rec of records) {
1468
+ lines.push(`{ ${sobject} r = new ${sobject}();`);
1469
+ for (const [key, val] of Object.entries(rec)) {
1470
+ if (key === 'attributes') continue;
1471
+ validateApiName(key, `field API name on ${sobject}`);
1472
+ lines.push(`r.put('${key}', ${apexLiteral(val)});`);
1473
+ }
1474
+ lines.push('recs.add(r); }');
1475
+ }
1476
+ lines.push('Database.SaveResult[] results = Database.insert(recs, dmlOpts);');
1477
+ const refArray = refIds.map((r) => `'${escapeSoqlString(r)}'`).join(',');
1478
+ lines.push(`String[] refs = new String[]{${refArray}};`);
1479
+ // Emit ONE machine-readable line instead of one System.debug per record: a
1480
+ // JSON array of {ref, id?|err?}. The Node side parses this with
1481
+ // parseApexInsertResults and treats a missing/unparseable marker as a hard
1482
+ // batch failure (a truncated debug line must not read as "0 errors"). Measured
1483
+ // batching keeps each batch — and thus this payload — well under the log line
1484
+ // size.
1485
+ lines.push('List<Object> setupOut = new List<Object>();');
1486
+ lines.push('for (Integer i = 0; i < results.size(); i++) {');
1487
+ lines.push(' Map<String,Object> m = new Map<String,Object>{ \'ref\' => refs[i] };');
1488
+ lines.push(' if (results[i].isSuccess()) { m.put(\'id\', results[i].getId()); }');
1489
+ lines.push(' else { m.put(\'err\', results[i].getErrors()[0].getMessage()); }');
1490
+ lines.push(' setupOut.add(m);');
1491
+ lines.push('}');
1492
+ // Use LoggingLevel.ERROR to ensure this critical line appears near the end of
1493
+ // the debug log and isn't truncated by excessive DEBUG-level noise from DML
1494
+ // operations, workflow rules, or process builders that fire during insert.
1495
+ lines.push("System.debug(LoggingLevel.ERROR, 'SETUP_RESULT_JSON:' + JSON.serialize(setupOut));");
1496
+ return lines.join('\n');
1497
+ }
1498
+
1499
+ /**
1500
+ * Interactive multi-select: arrow keys navigate, space toggles, 'a' toggles all, enter confirms.
1501
+ * Returns a boolean[] matching the input order. Falls through immediately when stdin is not a TTY.
1502
+ */
1503
+ async function promptSteps(steps) {
1504
+ if (!process.stdin.isTTY) return steps.map((s) => s.enabled);
1505
+
1506
+ // `selected` stays indexed by ORIGINAL step order (so the caller's
1507
+ // selections[i] → stepDefs[i] mapping is unchanged); unavailable steps remain
1508
+ // false. Only available steps are shown and navigable — unavailable steps are
1509
+ // hidden entirely rather than rendered greyed-out.
1510
+ const selected = steps.map((s) => s.enabled);
1511
+ const visible = steps.map((s, i) => ({ step: s, index: i })).filter(({ step }) => step.available);
1512
+ let cursor = 0;
1513
+ const RST = '\x1B[0m';
1514
+ const CYAN = '\x1B[36m';
1515
+ const GREEN = '\x1B[32m';
1516
+
1517
+ /** Strip ANSI escape sequences to get visible character count. */
1518
+ function visibleLength(str) {
1519
+ return str.replace(/\x1B\[[0-9;]*m/g, '').length;
1520
+ }
1521
+
1522
+ /** Count how many terminal rows a set of lines occupies (accounting for wrapping). */
1523
+ function terminalRows(lines) {
1524
+ const cols = process.stdout.columns || 80;
1525
+ let rows = 0;
1526
+ for (const line of lines) {
1527
+ const len = visibleLength(line);
1528
+ rows += len === 0 ? 1 : Math.ceil(len / cols);
1529
+ }
1530
+ return rows;
1531
+ }
1532
+
1533
+ function render() {
1534
+ return visible.map(({ step, index }, row) => {
1535
+ const ptr = row === cursor ? `${CYAN}❯${RST}` : ' ';
1536
+ const chk = selected[index] ? `${GREEN}●${RST}` : '○';
1537
+ return `${ptr} ${chk} ${step.label}`;
1538
+ });
1539
+ }
1540
+
1541
+ let prevRows = 0;
1542
+
1543
+ return new Promise((resolve) => {
1544
+ process.stdin.setRawMode(true);
1545
+ process.stdin.resume();
1546
+ process.stdin.setEncoding('utf8');
1547
+ process.stdout.write('\x1B[?25l');
1548
+ console.log('\nSelect steps (↑↓ move, space toggle, a all, enter confirm):\n');
1549
+ const initialLines = render();
1550
+ prevRows = terminalRows(initialLines);
1551
+ process.stdout.write(initialLines.join('\n') + '\n');
1552
+
1553
+ function redraw() {
1554
+ process.stdout.write(`\x1B[${prevRows}A`);
1555
+ const lines = render();
1556
+ for (const line of lines) process.stdout.write(`\x1B[2K${line}\n`);
1557
+ prevRows = terminalRows(lines);
1558
+ }
1559
+
1560
+ process.stdin.on('data', (key) => {
1561
+ if (key === '\x03') {
1562
+ process.stdout.write('\x1B[?25h\n');
1563
+ process.exit(0);
1564
+ }
1565
+ if (key === '\r' || key === '\n') {
1566
+ process.stdout.write('\x1B[?25h');
1567
+ process.stdin.setRawMode(false);
1568
+ process.stdin.pause();
1569
+ process.stdin.removeAllListeners('data');
1570
+ console.log();
1571
+ resolve(selected);
1572
+ return;
1573
+ }
1574
+ // Note: `cursor` indexes `visible`; `selected` is indexed by ORIGINAL step
1575
+ // order. Map through visible[cursor].index before touching `selected`.
1576
+ if (key === ' ') {
1577
+ const { index } = visible[cursor];
1578
+ selected[index] = !selected[index];
1579
+ redraw();
1580
+ return;
1581
+ }
1582
+ if (key === 'a') {
1583
+ const allOn = visible.every(({ index }) => selected[index]);
1584
+ for (const { index } of visible) selected[index] = !allOn;
1585
+ redraw();
1586
+ return;
1587
+ }
1588
+ if (key === '\x1B[A' || key === 'k') {
1589
+ cursor = Math.max(0, cursor - 1);
1590
+ redraw();
1591
+ } else if (key === '\x1B[B' || key === 'j') {
1592
+ cursor = Math.min(visible.length - 1, cursor + 1);
1593
+ redraw();
1594
+ }
1595
+ });
1596
+ });
1597
+ }
1598
+
1599
+ function run(name, cmd, args, opts = {}) {
1600
+ const { cwd = ROOT, optional = false } = opts;
1601
+ console.log('\n---', name, '---');
1602
+ const result = spawnSync(cmd, args, {
1603
+ cwd,
1604
+ stdio: 'inherit',
1605
+ shell: true,
1606
+ ...(opts.env && { env: opts.env }),
1607
+ ...(opts.timeout && { timeout: opts.timeout }),
1608
+ });
1609
+ if (result.status !== 0 && !optional) {
1610
+ throw new StepError(`${name} (exit ${result.status ?? 1})`);
1611
+ }
1612
+ return result;
1613
+ }
1614
+
1615
+ /** Promise-based spawn for parallel execution. Always uses stdio: 'pipe'. */
1616
+ function spawnAsync(cmd, args, opts = {}) {
1617
+ return new Promise((resolve, reject) => {
1618
+ const proc = nodeSpawn(cmd, args, {
1619
+ cwd: opts.cwd || ROOT,
1620
+ stdio: 'pipe',
1621
+ shell: true,
1622
+ ...(opts.timeout && { timeout: opts.timeout }),
1623
+ });
1624
+ let stdout = '';
1625
+ let stderr = '';
1626
+ proc.stdout.on('data', (d) => { stdout += d.toString(); });
1627
+ proc.stderr.on('data', (d) => { stderr += d.toString(); });
1628
+ proc.on('close', (code) => resolve({ status: code, stdout, stderr }));
1629
+ proc.on('error', reject);
1630
+ });
1631
+ }
1632
+
1633
+ /** Async version of run() for parallel steps. Captures output and prints on failure. */
1634
+ async function runAsync(name, cmd, args, opts = {}) {
1635
+ const { cwd = ROOT, optional = false } = opts;
1636
+ const result = await spawnAsync(cmd, args, { cwd, ...(opts.timeout && { timeout: opts.timeout }) });
1637
+ if (result.status !== 0 && !optional) {
1638
+ if (result.stdout) process.stdout.write(result.stdout);
1639
+ if (result.stderr) process.stderr.write(result.stderr);
1640
+ throw new StepError(`${name} (exit ${result.status ?? 1})`);
1641
+ }
1642
+ return result;
1643
+ }
1644
+
1645
+ /**
1646
+ * In-memory result ledger. Each selected step records exactly one outcome:
1647
+ * ok — the step ran and succeeded
1648
+ * skipped — the step was not selected, or had no config section (intentional)
1649
+ * failed — the step ran and failed (with a human-readable reason)
1650
+ * The end-of-run summary is rendered from this ledger and the process exits
1651
+ * non-zero whenever any step is `failed` (fail-fast or skippable alike).
1652
+ *
1653
+ * @typedef {{ key: string, label: string, status: 'ok'|'skipped'|'failed', reason?: string, failFast?: boolean }} StepResult
1654
+ */
1655
+ const results = [];
1656
+ function recordOk(step) {
1657
+ results.push({ key: step.key, label: step.label, status: 'ok', failFast: step.failFast });
1658
+ }
1659
+ function recordSkipped(step, reason) {
1660
+ results.push({ key: step.key, label: step.label, status: 'skipped', reason, failFast: step.failFast });
1661
+ }
1662
+ function recordFailed(step, reason) {
1663
+ results.push({ key: step.key, label: step.label, status: 'failed', reason, failFast: step.failFast });
1664
+ }
1665
+
1666
+ /** True if any step in the ledger failed. */
1667
+ function finalExitCode() {
1668
+ return results.some((r) => r.status === 'failed') ? 1 : 0;
1669
+ }
1670
+
1671
+ const SUMMARY_GLYPH = { ok: '✔', skipped: '–', failed: '✖' };
1672
+
1673
+ /**
1674
+ * Render the end-of-run summary. Always called — on success, on a fail-fast
1675
+ * abort (partial: only steps reached so far are present), and on a clean finish
1676
+ * that had skippable failures. Failed rows are listed last so the real problem
1677
+ * is the last thing the developer sees.
1678
+ */
1679
+ function printSummary(targetOrg) {
1680
+ const ordered = [
1681
+ ...results.filter((r) => r.status !== 'failed'),
1682
+ ...results.filter((r) => r.status === 'failed'),
1683
+ ];
1684
+ const pad = Math.max(0, ...ordered.map((r) => r.key.length));
1685
+ console.log(`\nSetup summary (target org: ${targetOrg})`);
1686
+ for (const r of ordered) {
1687
+ const glyph = SUMMARY_GLYPH[r.status] ?? ' ';
1688
+ const key = r.key.padEnd(pad);
1689
+ let line = ` ${glyph} ${key} ${r.status}`;
1690
+ if (r.reason) line += ` (${r.reason})`;
1691
+ if (r.status === 'failed') line += r.failFast ? ' [fail-fast — aborted]' : ' [skippable — continued]';
1692
+ console.log(line);
1693
+ }
1694
+ const failures = results.filter((r) => r.status === 'failed').length;
1695
+ if (failures > 0) {
1696
+ console.log(`Setup completed with ${failures} failure(s). Exiting 1.`);
1697
+ } else {
1698
+ console.log('Setup complete.');
1699
+ }
1700
+ }
1701
+
1702
+ /**
1703
+ * Run one step body, recording its outcome in the ledger and honoring the
1704
+ * step's fixed `failFast` classification. The body either completes (→ ok),
1705
+ * throws a StepError (→ failed), or throws something unexpected (→ failed,
1706
+ * with the raw message). On a fail-fast failure this prints the partial
1707
+ * summary and exits non-zero immediately; on a skippable failure it records
1708
+ * and returns so the run continues.
1709
+ */
1710
+ async function runStep(step, targetOrg, body) {
1711
+ try {
1712
+ await body();
1713
+ recordOk(step);
1714
+ } catch (err) {
1715
+ const reason = err instanceof StepError ? err.message : (err?.message ?? String(err));
1716
+ recordFailed(step, reason);
1717
+ console.error(`\nStep "${step.key}" failed: ${reason}`);
1718
+ if (step.failFast) {
1719
+ printSummary(targetOrg);
1720
+ process.exit(1);
1721
+ }
1722
+ }
1723
+ }
1724
+
1725
+ async function main() {
1726
+ // Cleanup AT START: remove Apex temp artifacts left by a prior hard-killed run.
1727
+ // Safe to run before the per-org lock is acquired because it only removes
1728
+ // org-setup-* temp DIRECTORIES and legacy ROOT temp files — never the
1729
+ // org-setup-lock-<org>.lock files (plain files), so it cannot clobber a
1730
+ // concurrent run's live lock.
1731
+ sweepStaleApexTempDirs();
1732
+
1733
+ // Ensure .gitignore files exist (npm strips them from published packages).
1734
+ const gitignoreTemplates = loadGitignoreTemplates();
1735
+ if (gitignoreTemplates) {
1736
+ ensureGitignore(ROOT, gitignoreTemplates.sfdx);
1737
+ if (existsSync(UIBUNDLES_DIR)) {
1738
+ for (const entry of readdirSync(UIBUNDLES_DIR, { withFileTypes: true })) {
1739
+ if (entry.isDirectory() && !entry.name.startsWith('.')) {
1740
+ ensureGitignore(resolve(UIBUNDLES_DIR, entry.name), gitignoreTemplates.webapp);
1741
+ }
1742
+ }
1743
+ }
1744
+ }
1745
+
1746
+ const parsed = parseArgs();
1747
+ const {
1748
+ uiBundleName,
1749
+ permsetNamesExplicit,
1750
+ yes,
1751
+ skipDeploy: argSkipDeploy,
1752
+ skipPermset: argSkipPermset,
1753
+ skipRole: argSkipRole,
1754
+ skipSelfReg: argSkipSelfReg,
1755
+ skipSocialLogin: argSkipSocialLogin,
1756
+ skipData: argSkipData,
1757
+ skipGraphql: argSkipGraphql,
1758
+ skipUIBundleBuild: argSkipUIBundleBuild,
1759
+ } = parsed;
1760
+
1761
+ // Resolve the target org up front: explicit --target-org is used verbatim;
1762
+ // otherwise prompt (TTY) or fall back to the default org / exit.
1763
+ const targetOrg = await resolveTargetOrg(parsed);
1764
+
1765
+ // Per-target-org lock: acquired right after the start-of-run
1766
+ // sweep and before any step runs, so two runs against the same org cannot
1767
+ // interleave destructive Apex. The startup sweep above deliberately skips lock
1768
+ // files, so it never races this. Released on process exit.
1769
+ acquireOrgLock(targetOrg);
1770
+
1771
+ const permsetNames =
1772
+ permsetNamesExplicit.length > 0 ? permsetNamesExplicit : discoverPermissionSetNames();
1773
+ const permsetStepLabel =
1774
+ permsetNames.length === 0
1775
+ ? 'Permset — (none under permissionsets/)'
1776
+ : permsetNames.length <= 3
1777
+ ? `Permset — assign ${permsetNames.join(', ')}`
1778
+ : `Permset — assign ${permsetNames.length} permission sets`;
1779
+
1780
+ // Validate org-setup.config.json ONCE, before any step runs. The three
1781
+ // load*Config helpers read from this already-validated object.
1782
+ const config = loadValidatedConfig();
1783
+
1784
+ const hasDataPlan = existsSync(DATA_PLAN) && existsSync(DATA_DIR);
1785
+ const roleConfig = loadRoleConfig(config);
1786
+ const hasRoleConfig = roleConfig !== null;
1787
+ const selfRegConfig = loadSelfRegConfig(config);
1788
+ const hasSelfRegConfig = selfRegConfig !== null;
1789
+ const socialLoginConfig = loadSocialLoginConfig(config);
1790
+ const hasSocialLoginConfig = socialLoginConfig !== null;
1791
+
1792
+ // Validate the selfRegProfile name for SOQL-safety up front, alongside the
1793
+ // config validation and BEFORE any org mutation (login/deploy). A quote /
1794
+ // backslash / control char is a config mistake, not a runtime value to
1795
+ // escape — fail fast here with a clean, actionable message rather than
1796
+ // letting the license gate throw a raw stack trace deep in the run after deploy.
1797
+ if (hasSelfRegConfig) {
1798
+ try {
1799
+ validateProfileNameForSoql(selfRegConfig.selfRegProfile);
1800
+ } catch (err) {
1801
+ console.error(`Invalid org-setup.config.json:\n - ${err.message}`);
1802
+ process.exit(1);
1803
+ }
1804
+ }
1805
+
1806
+ // Same fail-fast treatment for the socialLogin identifiers, alongside the
1807
+ // self-reg guard above and BEFORE any org mutation. communityMemberProfile,
1808
+ // every authProviderNames entry, and the optional communityUserPermset are all
1809
+ // interpolated into generated SOQL / CLI value strings — the Profile and
1810
+ // PermissionSet `WHERE Name = '…'` lookups, the AuthProvider/SamlSsoConfig
1811
+ // `DeveloperName IN (…)` list, and the NetworkMemberGroup/User queries. These
1812
+ // are developer-authored identifiers the app ships, so a quote / backslash /
1813
+ // control char is a config mistake to surface loudly here rather than a value
1814
+ // to silently escape (same rationale as validateSoqlName's self-reg use).
1815
+ if (hasSocialLoginConfig) {
1816
+ try {
1817
+ validateSoqlName(socialLoginConfig.communityMemberProfile, 'socialLogin.communityMemberProfile');
1818
+ for (const providerName of socialLoginConfig.authProviderNames ?? []) {
1819
+ validateSoqlName(providerName, 'socialLogin.authProviderNames entry');
1820
+ }
1821
+ if (socialLoginConfig.communityUserPermset) {
1822
+ validateSoqlName(socialLoginConfig.communityUserPermset, 'socialLogin.communityUserPermset');
1823
+ }
1824
+ } catch (err) {
1825
+ console.error(`Invalid org-setup.config.json:\n - ${err.message}`);
1826
+ process.exit(1);
1827
+ }
1828
+ }
1829
+
1830
+ // failFast is a fixed, implementer-owned classification — NOT
1831
+ // user-configurable. A fail-fast failure aborts the run immediately; a
1832
+ // skippable failure is recorded and the run continues. The exit code is
1833
+ // non-zero on any failure regardless of class.
1834
+ // Login is NOT in this picker: it is an unconditional precondition run before
1835
+ // deploy, not a toggleable step. The dev step is also gone: launching the dev
1836
+ // server moved to `npm run dev:preview`, so setup terminates cleanly after
1837
+ // graphql.
1838
+ const stepDefs = [
1839
+ { key: 'uiBundleBuild', label: 'UI Bundle Build — npm install + build (pre-deploy)', enabled: !argSkipUIBundleBuild, available: true, failFast: true },
1840
+ { key: 'deploy', label: 'Deploy — sf project deploy start', enabled: !argSkipDeploy, available: true, failFast: true },
1841
+ { key: 'permset', label: permsetStepLabel, enabled: !argSkipPermset, available: true, failFast: false },
1842
+ { key: 'role', label: `Role — assign "${roleConfig?.roleName ?? '?'}" to current user`, enabled: !argSkipRole && hasRoleConfig, available: hasRoleConfig, failFast: false },
1843
+ { key: 'selfReg', label: 'Self-Registration — enable for site', enabled: !argSkipSelfReg && hasSelfRegConfig, available: hasSelfRegConfig, failFast: false },
1844
+ { key: 'socialLogin', label: 'Social Login — enable auth providers + community profile', enabled: !argSkipSocialLogin && hasSocialLoginConfig, available: hasSocialLoginConfig, failFast: false },
1845
+ { key: 'data', label: 'Data — delete + import records via Apex', enabled: !argSkipData && hasDataPlan, available: hasDataPlan, failFast: true },
1846
+ { key: 'graphql', label: 'GraphQL — schema introspect + codegen', enabled: !argSkipGraphql, available: true, failFast: true },
1847
+ ];
1848
+
1849
+ const selections = yes ? stepDefs.map((s) => s.enabled) : await promptSteps(stepDefs);
1850
+ const on = {};
1851
+ stepDefs.forEach((s, i) => {
1852
+ on[s.key] = selections[i];
1853
+ });
1854
+
1855
+ const skipUIBundleBuild = !on.uiBundleBuild;
1856
+ const skipDeploy = !on.deploy;
1857
+ const skipPermset = !on.permset;
1858
+ const skipRole = !on.role;
1859
+ const skipSelfReg = !on.selfReg;
1860
+ const skipSocialLogin = !on.socialLogin;
1861
+ const skipData = !on.data;
1862
+ const skipGraphql = !on.graphql;
1863
+
1864
+ const needsUIBundle = !skipUIBundleBuild || !skipGraphql;
1865
+ const uiBundleDir = needsUIBundle ? await discoverUIBundleDir(uiBundleName) : null;
1866
+ const doData = !skipData;
1867
+
1868
+ console.log('Setup — target org:', targetOrg, '| UI bundle:', uiBundleDir ?? '(none)');
1869
+ console.log(
1870
+ 'Steps: login=always deploy=%s permset=%s role=%s selfReg=%s socialLogin=%s data=%s graphql=%s uiBundle=%s',
1871
+ !skipDeploy,
1872
+ !skipPermset,
1873
+ !skipRole,
1874
+ !skipSelfReg,
1875
+ !skipSocialLogin,
1876
+ doData,
1877
+ !skipGraphql,
1878
+ !skipUIBundleBuild
1879
+ );
1880
+
1881
+ // Login is an unconditional precondition: it is not part of
1882
+ // the step picker and cannot be skipped. It still no-ops when the org is already
1883
+ // connected, and stays fail-fast — a failed browser login aborts before deploy.
1884
+ const loginStep = { key: 'login', label: 'Login — org authentication', failFast: true };
1885
+ await runStep(loginStep, targetOrg, async () => {
1886
+ if (isOrgConnected(targetOrg)) {
1887
+ console.log('\n--- Login ---');
1888
+ console.log(`Org ${targetOrg} is already authenticated; skipping browser login.`);
1889
+ } else {
1890
+ run('Login (browser)', 'sf', ['org', 'login', 'web', '--alias', targetOrg]);
1891
+ }
1892
+ });
1893
+
1894
+ // Ensure the self-reg profile is in networkMemberGroups before deploy so that
1895
+ // subsequent selfRegProfile / selfRegistration updates don't fail. This is
1896
+ // best-effort prep: if the site can't be derived (no network file, or the
1897
+ // ambiguous multi-network case where deriveSiteName throws), skip the prep
1898
+ // silently here — the selfReg step records that derivation failure as a
1899
+ // skippable StepError, so it stays in the ledger instead of aborting pre-deploy.
1900
+ if (!skipDeploy && selfRegConfig) {
1901
+ let preDeploySiteName = null;
1902
+ try {
1903
+ preDeploySiteName = deriveSiteName();
1904
+ } catch {
1905
+ // ambiguous derivation — surfaced by the selfReg step below
1906
+ }
1907
+ if (preDeploySiteName) {
1908
+ console.log('\n--- Ensure network member profile (pre-deploy) ---');
1909
+ ensureNetworkMemberProfile(selfRegConfig, preDeploySiteName);
1910
+ }
1911
+ }
1912
+
1913
+ // Build all UI Bundles before deploy so dist exists for entity deployment
1914
+ const uiBundleBuildStep = stepDefs.find((s) => s.key === 'uiBundleBuild');
1915
+ let preDeployBundlesBuilt = false;
1916
+ if (!skipUIBundleBuild) {
1917
+ if (!skipDeploy) {
1918
+ await runStep(uiBundleBuildStep, targetOrg, () => {
1919
+ const allUIBundleDirs = discoverAllUIBundleDirs(uiBundleName);
1920
+ for (const dir of allUIBundleDirs) {
1921
+ const name = dir.split(/[/\\]/).pop();
1922
+ run(`UI Bundle install (${name})`, 'npm', ['install'], { cwd: dir });
1923
+ run(`UI Bundle build (${name})`, 'npm', ['run', 'build'], { cwd: dir });
1924
+ }
1925
+ });
1926
+ preDeployBundlesBuilt = true;
1927
+ }
1928
+ // When skipDeploy, the bundle build happens in the GraphQL section below;
1929
+ // its outcome is recorded there.
1930
+ } else {
1931
+ recordSkipped(uiBundleBuildStep, 'not selected');
1932
+ }
1933
+
1934
+ const deployStep = stepDefs.find((s) => s.key === 'deploy');
1935
+ if (!skipDeploy) {
1936
+ await runStep(deployStep, targetOrg, () => {
1937
+ // License pre-check: deploy fails with a cryptic error when the
1938
+ // org lacks the UserLicense the selfRegProfile's metadata requires. Verify a
1939
+ // seat is available BEFORE `sf project deploy start` so the run aborts with a
1940
+ // clean message NAMING the missing license. The required license is read from
1941
+ // the local profile source (the profile isn't in the org yet pre-deploy, so
1942
+ // querying it would only report "profile missing"). Only gates when self-reg
1943
+ // is configured — that config names the profile the license is derived from.
1944
+ if (selfRegConfig) {
1945
+ const licenseGate = checkDeployLicense(selfRegConfig, targetOrg);
1946
+ if (!licenseGate.satisfied) {
1947
+ throw new StepError(`deploy blocked — ${licenseGate.reason}`);
1948
+ }
1949
+ }
1950
+ run('Deploy metadata', 'sf', ['project', 'deploy', 'start', '--target-org', targetOrg], {
1951
+ timeout: 180000,
1952
+ });
1953
+ });
1954
+ } else {
1955
+ recordSkipped(deployStep, 'not selected');
1956
+ }
1957
+
1958
+ const permsetStep = stepDefs.find((s) => s.key === 'permset');
1959
+ if (!skipPermset) {
1960
+ await runStep(permsetStep, targetOrg, async () => {
1961
+ const permsetConfig = loadPermsetConfig(config);
1962
+ if (permsetNames.length === 0) {
1963
+ console.log('\n--- Assign permission sets ---');
1964
+ console.log('No permission sets found under permissionsets/ and none passed via --permset-name; skipping.');
1965
+ return;
1966
+ }
1967
+ console.log('\n--- Assign permission sets ---');
1968
+
1969
+ // Resolve assignments (guest user lookups etc.) then run all sf assign calls in parallel.
1970
+ //
1971
+ // A guest-user resolution failure (no derivable site, or no guest user yet)
1972
+ // is collected — NOT thrown mid-loop. Throwing here would unwind the whole
1973
+ // runStep body before Promise.all and silently drop every assignment already
1974
+ // queued (e.g. a currentUser permset that sorts ahead of a guestUser one and
1975
+ // never depended on the site at all). Resolvable assignments still run; the
1976
+ // combined failure is thrown at the end so the step is still recorded failed.
1977
+ const assignmentJobs = [];
1978
+ const resolutionFailures = [];
1979
+ for (const permsetName of permsetNames) {
1980
+ const assignment = resolveAssignment(permsetName, permsetConfig);
1981
+ if (assignment.assignee === 'skip') {
1982
+ console.log(`Permission set "${permsetName}" — skipped (config).`);
1983
+ continue;
1984
+ }
1985
+ let effectiveUsername = null;
1986
+ if (assignment.assignee === 'guestUser') {
1987
+ // Site name is derived from the single network metadata file the app
1988
+ // ships — never restated per-assignment.
1989
+ const siteName = deriveSiteName();
1990
+ if (!siteName) {
1991
+ console.error(`Permission set "${permsetName}" — assignee is "guestUser" but no networks/<siteName>.network-meta.xml was found to derive the site; skipping.`);
1992
+ resolutionFailures.push(`${permsetName} (no network metadata to derive site)`);
1993
+ continue;
1994
+ }
1995
+ effectiveUsername = resolveGuestUsername(siteName, targetOrg);
1996
+ if (!effectiveUsername) {
1997
+ console.error(`Permission set "${permsetName}" — could not resolve guest user for site "${siteName}"; skipping.`);
1998
+ resolutionFailures.push(`${permsetName} (could not resolve guest user for site "${siteName}")`);
1999
+ continue;
2000
+ }
2001
+ console.log(` Resolved guest user for site "${siteName}": ${effectiveUsername}`);
2002
+ }
2003
+ assignmentJobs.push({ permsetName, effectiveUsername });
2004
+ }
2005
+
2006
+ // Run all permset assignment calls in parallel.
2007
+ const assignResults = await Promise.all(assignmentJobs.map(async ({ permsetName, effectiveUsername }) => {
2008
+ const sfArgs = ['org', 'assign', 'permset', '--name', permsetName, '--target-org', targetOrg];
2009
+ if (effectiveUsername) {
2010
+ sfArgs.push('--on-behalf-of', effectiveUsername);
2011
+ }
2012
+ const assigneeLabel = effectiveUsername || 'current user';
2013
+ const result = await spawnAsync('sf', sfArgs);
2014
+ return { permsetName, assigneeLabel, result };
2015
+ }));
2016
+
2017
+ const failures = [];
2018
+ for (const { permsetName, assigneeLabel, result } of assignResults) {
2019
+ if (result.status === 0) {
2020
+ console.log(`Permission set "${permsetName}" assigned to ${assigneeLabel}.`);
2021
+ } else {
2022
+ const out = (result.stderr || '') + (result.stdout || '');
2023
+ if (out.includes('Duplicate') && out.includes('PermissionSet')) {
2024
+ console.log(`Permission set "${permsetName}" already assigned to ${assigneeLabel}; skipping.`);
2025
+ } else if (out.includes('not found') && out.includes('target org')) {
2026
+ console.log(`Permission set "${permsetName}" not in org; skipping.`);
2027
+ } else {
2028
+ if (result.stdout) process.stdout.write(result.stdout);
2029
+ if (result.stderr) process.stderr.write(result.stderr);
2030
+ failures.push(`${permsetName} (exit ${result.status ?? 1})`);
2031
+ }
2032
+ }
2033
+ }
2034
+ const allFailures = [...resolutionFailures, ...failures];
2035
+ if (allFailures.length > 0) {
2036
+ throw new StepError(`failed to assign permission set(s): ${allFailures.join(', ')}`);
2037
+ }
2038
+ });
2039
+ } else {
2040
+ recordSkipped(permsetStep, 'not selected');
2041
+ }
2042
+
2043
+ const roleStep = stepDefs.find((s) => s.key === 'role');
2044
+ if (!skipRole) {
2045
+ console.log('\n--- Assign role ---');
2046
+ // Config shape (assignee === 'currentUser', non-empty roleName) is guaranteed
2047
+ // by the schema, so there is nothing to re-check here — the step either ran
2048
+ // (ok) or its assignment threw (failed). No manual recordSkipped inference.
2049
+ await runStep(roleStep, targetOrg, () => {
2050
+ assignRoleToCurrentUser(roleConfig.roleName, targetOrg);
2051
+ });
2052
+ } else {
2053
+ recordSkipped(roleStep, roleStep.available ? 'not selected' : 'no config');
2054
+ }
2055
+
2056
+ const selfRegStep = stepDefs.find((s) => s.key === 'selfReg');
2057
+ if (!skipSelfReg) {
2058
+ // License pre-check: self-registration requires a seat on the
2059
+ // UserLicense the selfRegProfile belongs to. Verify it BEFORE running the step
2060
+ // — recordSkipped is only reachable here, ahead of runStep (mirroring the
2061
+ // not-selected branch); once inside a step body an unmet precondition could
2062
+ // only record `failed`. A missing / inactive / seatless license is a soft
2063
+ // precondition, not a setup failure, so warn + recordSkipped and move on.
2064
+ const licenseGate = checkSelfRegLicense(selfRegConfig, targetOrg);
2065
+ if (!licenseGate.satisfied) {
2066
+ console.warn(`\n--- Self-registration skipped ---\n ⚠ ${licenseGate.reason}`);
2067
+ recordSkipped(selfRegStep, licenseGate.reason);
2068
+ } else {
2069
+ console.log('\n--- Enable self-registration ---');
2070
+ // Config shape (selfRegProfile, accountName) is guaranteed by the schema.
2071
+ // The site is derived inside the step body so a "multiple network files"
2072
+ // StepError is recorded in the ledger rather than escaping. No manual
2073
+ // recordSkipped inference.
2074
+ await runStep(selfRegStep, targetOrg, () => {
2075
+ const siteName = deriveSiteName();
2076
+ if (!siteName) {
2077
+ throw new StepError(
2078
+ 'self-registration is configured but no networks/<siteName>.network-meta.xml was found to derive the site',
2079
+ );
2080
+ }
2081
+ enableSelfRegistration(selfRegConfig, siteName, targetOrg);
2082
+ });
2083
+ }
2084
+ } else {
2085
+ recordSkipped(selfRegStep, selfRegStep.available ? 'not selected' : 'no config');
2086
+ }
2087
+
2088
+ const socialLoginStep = stepDefs.find((s) => s.key === 'socialLogin');
2089
+ if (!skipSocialLogin) {
2090
+ console.log('\n--- Social Login — enable auth providers + community profile ---');
2091
+ await runStep(socialLoginStep, targetOrg, () => {
2092
+ const siteName = deriveSiteName();
2093
+ if (!siteName) {
2094
+ throw new StepError(
2095
+ 'socialLogin is configured but no networks/<siteName>.network-meta.xml was found to derive the site',
2096
+ );
2097
+ }
2098
+
2099
+ const totalSubSteps = socialLoginConfig.communityUserPermset ? 4 : 3;
2100
+
2101
+ // Sub-step 1: Enable "Allow using standard external profiles" org setting.
2102
+ // This is required so the SSO registration handler can create users with
2103
+ // standard community profiles (e.g. "Customer Community User").
2104
+ console.log(` [1/${totalSubSteps}] Enabling "Allow standard external profiles" setting...`);
2105
+ enableExternalProfiles(targetOrg);
2106
+
2107
+ // Sub-step 2: Link Auth Providers to the site's AuthConfig.
2108
+ // React (Site Container) sites hide SSO config in Admin UI, so this must
2109
+ // be done programmatically via AuthConfig/AuthConfigProviders records.
2110
+ console.log(` [2/${totalSubSteps}] Linking Auth Providers to site AuthConfig...`);
2111
+ enableAuthProvidersForSite(socialLoginConfig.authProviderNames, siteName, targetOrg);
2112
+
2113
+ // Sub-step 3: Add the community member profile to NetworkMemberGroup.
2114
+ // Without this, users created by the registration handler get
2115
+ // "NO_ACCESS: User was not authorized for the community".
2116
+ console.log(` [3/${totalSubSteps}] Adding community member profile to NetworkMemberGroup...`);
2117
+ addCommunityMemberProfile(socialLoginConfig.communityMemberProfile, siteName, targetOrg);
2118
+
2119
+ // Sub-step 4 (optional): Assign API-enabled permset to community users.
2120
+ // Without this, getCurrentUser() fails because /chatter/users/me requires
2121
+ // PermissionsApiEnabled which the standard community profile lacks.
2122
+ if (socialLoginConfig.communityUserPermset) {
2123
+ console.log(` [4/${totalSubSteps}] Assigning API permset to community users...`);
2124
+ assignPermsetToCommunityUsers(
2125
+ socialLoginConfig.communityUserPermset,
2126
+ socialLoginConfig.communityMemberProfile,
2127
+ targetOrg,
2128
+ );
2129
+ }
2130
+ });
2131
+ } else {
2132
+ recordSkipped(socialLoginStep, socialLoginStep.available ? 'not selected' : 'no config');
2133
+ }
2134
+
2135
+ const dataStep = stepDefs.find((s) => s.key === 'data');
2136
+ if (doData) {
2137
+ await runStep(dataStep, targetOrg, () => {
2138
+ // Prepare data for uniqueness (run before import so repeat imports don't conflict).
2139
+ // Per-app data normalization (reference remapping, unique-field mangling) ships with
2140
+ // the app's seed data as data/prepare-import-unique-fields.js — this script stays
2141
+ // object-agnostic and simply runs it if present.
2142
+ const prepareScript = resolve(DATA_DIR, 'prepare-import-unique-fields.js');
2143
+ if (existsSync(prepareScript)) {
2144
+ run('Prepare data (unique fields)', 'node', [prepareScript, '--data-dir', DATA_DIR], {
2145
+ cwd: ROOT,
2146
+ });
2147
+ }
2148
+
2149
+ // Delete existing records so every run inserts the full dataset without duplicate conflicts.
2150
+ // Reverse plan order ensures children are removed before parents (FK safety).
2151
+ console.log('\n--- Clean existing data for fresh import ---');
2152
+ const planEntries = JSON.parse(readFileSync(DATA_PLAN, 'utf8'));
2153
+ const sobjectsReversed = [...planEntries.map((e) => e.sobject)].reverse();
2154
+ // One private temp dir for both the delete sweep and the import batches;
2155
+ // always removed in finally, even if a batch throws.
2156
+ withApexTempDir((writeApex) => {
2157
+ for (const sobject of sobjectsReversed) {
2158
+ // Bare identifier inside a dynamic-SOQL string literal — whitelist it (the
2159
+ // same guard buildApexInsert applies) so a malformed data-plan sobject
2160
+ // can't alter the delete query.
2161
+ validateApiName(sobject, 'sobject type');
2162
+ const apexCode = [
2163
+ 'try {',
2164
+ ` List<SObject> recs = Database.query('SELECT Id FROM ${sobject} LIMIT 10000');`,
2165
+ ' if (!recs.isEmpty()) {',
2166
+ ' Database.delete(recs, false);',
2167
+ ' Database.emptyRecycleBin(recs);',
2168
+ ' }',
2169
+ '} catch (Exception e) {',
2170
+ ' // non-deletable records (e.g. Contact linked to Case) are skipped via allOrNone=false',
2171
+ '}',
2172
+ ].join('\n');
2173
+ const tmpApex = writeApex('data.apex', apexCode);
2174
+ spawnSync('sf', ['apex', 'run', '--target-org', targetOrg, '--file', tmpApex], {
2175
+ cwd: ROOT,
2176
+ stdio: 'pipe',
2177
+ shell: true,
2178
+ timeout: 60000,
2179
+ });
2180
+ console.log(` ${sobject}: cleaned`);
2181
+ }
2182
+
2183
+ // Import via Anonymous Apex with Database.DMLOptions.duplicateRuleHeader.allowSave = true.
2184
+ // This bypasses both duplicate-rule blocks AND matching-service timeouts that the REST
2185
+ // API headers (Sforce-Duplicate-Rule-Action) cannot override.
2186
+ console.log('\n--- Data import (Apex) ---');
2187
+ const refMap = new Map();
2188
+ // Apex anonymous code is capped at ~1M chars total, but each batch is much
2189
+ // smaller in practice. The real constraint is the SETUP_RESULT_JSON debug log
2190
+ // line: Salesforce truncates debug lines at ~5KB, and large batches produce
2191
+ // JSON arrays that exceed that limit. With RESULT_JSON_PER_RECORD = 150 and
2192
+ // MAX_BATCH = 100, the worst-case output is ~15KB of JSON, which fits
2193
+ // comfortably after the debug-line prefix and the marker.
2194
+ const APEX_CHAR_LIMIT = 25000;
2195
+ const APEX_MAX_BATCH = 100;
2196
+
2197
+ for (const entry of planEntries) {
2198
+ for (const file of entry.files) {
2199
+ const data = JSON.parse(readFileSync(resolve(DATA_DIR, file), 'utf8'));
2200
+ const records = data.records || [];
2201
+
2202
+ for (const rec of records) {
2203
+ for (const key of Object.keys(rec)) {
2204
+ if (key === 'attributes') continue;
2205
+ const val = rec[key];
2206
+ if (typeof val === 'string' && val.startsWith('@')) {
2207
+ const actual = refMap.get(val.slice(1));
2208
+ if (actual) {
2209
+ rec[key] = actual;
2210
+ } else if (refMap.size > 0) {
2211
+ console.warn(` Warning: unresolved ref ${val} in ${file}`);
2212
+ }
2213
+ }
2214
+ }
2215
+ }
2216
+
2217
+ // Measured batching: size each record's rendered Apex (using
2218
+ // the same apexLiteral the insert uses) and pack batches under the char
2219
+ // limit, instead of the old estCharsPerRec = 40 + fields*55 guess that
2220
+ // under-counted long text fields and could overflow the anon-Apex limit.
2221
+ // Overhead is measured from the real builder with zero records so the
2222
+ // fixed boilerplate can't drift from buildApexInsert. Each record also
2223
+ // grows the per-batch `String[] refs = new String[]{'…',…}` line, so its
2224
+ // rendered refId literal is counted here too (mirroring the same
2225
+ // referenceId/_idx fallback the batch emit uses) — otherwise sizing
2226
+ // under-counts and a packed batch could edge past APEX_CHAR_LIMIT.
2227
+ //
2228
+ // CRITICAL: also account for the SETUP_RESULT_JSON output size. The
2229
+ // System.debug line can exceed the Salesforce debug log line limit when
2230
+ // the serialized JSON array is large. Estimate ~85 chars per success
2231
+ // result ({"ref":"_idxNNN","id":"001XXXXXXXXXXXXXXX"}) and ~150 chars per
2232
+ // potential error ({"ref":"_idxNNN","err":"typical error message"}), taking
2233
+ // the higher value to be conservative. This ensures the batching prevents
2234
+ // log truncation that would fail parseApexInsertResults.
2235
+ const overhead = buildApexInsert(entry.sobject, [], []).length;
2236
+ const RESULT_JSON_PER_RECORD = 150;
2237
+ const recordSizes = records.map((rec, i) => {
2238
+ let size = `{ ${entry.sobject} r = new ${entry.sobject}();\n`.length + 'recs.add(r); }\n'.length;
2239
+ for (const [key, val] of Object.entries(rec)) {
2240
+ if (key === 'attributes') continue;
2241
+ size += `r.put('${key}', ${apexLiteral(val)});\n`.length;
2242
+ }
2243
+ const refId = rec.attributes?.referenceId || `_idx${i}`;
2244
+ size += `'${escapeSoqlString(refId)}',`.length;
2245
+ // Add the estimated size of this record's JSON result entry in the
2246
+ // SETUP_RESULT_JSON output. Without this, large batches can produce
2247
+ // debug log lines that exceed Salesforce's limit and get truncated.
2248
+ size += RESULT_JSON_PER_RECORD;
2249
+ return size;
2250
+ });
2251
+ const batches = planApexBatches(recordSizes, {
2252
+ charLimit: APEX_CHAR_LIMIT,
2253
+ maxBatch: APEX_MAX_BATCH,
2254
+ overhead,
2255
+ });
2256
+
2257
+ let imported = 0;
2258
+ for (const { start, count } of batches) {
2259
+ const batch = records.slice(start, start + count);
2260
+ const refIds = batch.map((r, j) => r.attributes?.referenceId || `_idx${start + j}`);
2261
+ const apex = buildApexInsert(entry.sobject, batch, refIds);
2262
+ const tmpApex = writeApex('data.apex', apex);
2263
+ const apexResult = spawnSync(
2264
+ 'sf',
2265
+ ['apex', 'run', '--target-org', targetOrg, '--file', tmpApex],
2266
+ { cwd: ROOT, stdio: 'pipe', shell: true, timeout: 120000 }
2267
+ );
2268
+ const apexOut = apexResult.stdout?.toString() || '';
2269
+ const apexErr = apexResult.stderr?.toString() || '';
2270
+ if (apexResult.status !== 0 && !apexOut.includes('Compiled successfully')) {
2271
+ process.stderr.write(apexErr || apexOut);
2272
+ throw new StepError(`${entry.sobject}: apex execution failed`);
2273
+ }
2274
+ const parsed = parseApexInsertResults(apexOut);
2275
+ if (!parsed.ok) {
2276
+ // A missing/truncated result marker must fail loudly — never read as
2277
+ // "0 errors" and let a partial import look successful.
2278
+ process.stderr.write(apexErr || apexOut);
2279
+ throw new StepError(`data import (${entry.sobject}) — ${parsed.error}`);
2280
+ }
2281
+ if (parsed.errors.length) {
2282
+ for (const e of parsed.errors.slice(0, 5)) {
2283
+ console.error(` ${e.ref}: ${e.message.trim()}`);
2284
+ }
2285
+ if (parsed.errors.length > 5) console.error(` ... and ${parsed.errors.length - 5} more`);
2286
+ throw new StepError(`data import (${entry.sobject}) — ${parsed.errors.length} record error(s)`);
2287
+ }
2288
+ if (entry.saveRefs) {
2289
+ for (const s of parsed.successes) refMap.set(s.ref, s.id);
2290
+ }
2291
+ imported += parsed.successes.length;
2292
+ }
2293
+ console.log(` ${entry.sobject}: imported ${imported} records`);
2294
+ }
2295
+ }
2296
+ });
2297
+ });
2298
+ } else {
2299
+ recordSkipped(dataStep, dataStep.available ? 'not selected' : 'no data plan');
2300
+ }
2301
+
2302
+ const graphqlStep = stepDefs.find((s) => s.key === 'graphql');
2303
+ if (!skipGraphql) {
2304
+ await runStep(graphqlStep, targetOrg, () => {
2305
+ run('UI Bundle npm install', 'npm', ['install'], { cwd: uiBundleDir });
2306
+ run('GraphQL schema (introspect)', 'npm', ['run', 'graphql:schema'], {
2307
+ cwd: uiBundleDir,
2308
+ env: { ...process.env, SF_TARGET_ORG: targetOrg },
2309
+ });
2310
+ run('GraphQL codegen', 'npm', ['run', 'graphql:codegen'], { cwd: uiBundleDir });
2311
+ run('UI Bundle build (post-codegen)', 'npm', ['run', 'build'], { cwd: uiBundleDir });
2312
+ });
2313
+ } else {
2314
+ recordSkipped(graphqlStep, 'not selected');
2315
+ if (!skipUIBundleBuild && skipDeploy && !preDeployBundlesBuilt) {
2316
+ // The pre-deploy build never ran (deploy was skipped); build here and
2317
+ // record the uiBundleBuild outcome that the pre-deploy branch would have.
2318
+ await runStep(uiBundleBuildStep, targetOrg, () => {
2319
+ run('UI Bundle npm install', 'npm', ['install'], { cwd: uiBundleDir });
2320
+ run('UI Bundle build', 'npm', ['run', 'build'], { cwd: uiBundleDir });
2321
+ });
2322
+ preDeployBundlesBuilt = true;
2323
+ }
2324
+ }
2325
+
2326
+ // When uiBundleBuild was selected but the dedicated pre-deploy build never ran
2327
+ // (deploy skipped and graphql selected), the build happened inside the graphql
2328
+ // step — which is fail-fast, so reaching here means it succeeded. Record ok.
2329
+ if (!skipUIBundleBuild && !preDeployBundlesBuilt && !results.some((r) => r.key === 'uiBundleBuild')) {
2330
+ recordOk(uiBundleBuildStep);
2331
+ }
2332
+
2333
+ // Setup terminates cleanly here. Launching the dev server is
2334
+ // no longer part of setup — run `npm run dev:preview` (scripts/org-setup-dev.mjs) for that.
2335
+ printSummary(targetOrg);
2336
+ if (finalExitCode() === 0) {
2337
+ console.log('\nTo launch the dev server, run: npm run dev:preview');
2338
+ }
2339
+ process.exit(finalExitCode());
2340
+ }
2341
+
2342
+ main().catch((err) => {
2343
+ console.error(err);
2344
+ process.exit(1);
2345
+ });