create-ilorb 0.0.0-stage → 0.3.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.
package/dist/main.js ADDED
@@ -0,0 +1,642 @@
1
+ // create-ilorb (ex create-overture): template folder (+ ilorb.env) → questions → project → Cloudflare (or local) → panel → URLs.
2
+ // Ilorb Code templates are FREE (owner, 12/11/2026): no license. The old license path stays dormant: it only runs when
3
+ // --license / --purchase-code (or their env vars) are given.
4
+ // main() receives everything from outside (exec, fetch, provider, questions, output) so tests can run the whole flow.
5
+ import { existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs';
6
+ import { basename, isAbsolute, join, resolve } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { parseArgs, str } from "./args.js";
9
+ import { RealCloudflare } from "./cloudflare/real.js";
10
+ import { SimulatedCloudflare } from "./cloudflare/simulated.js";
11
+ import { printPlan, runSteps } from "./engine.js";
12
+ import { HumanError, isHuman } from "./errors.js";
13
+ import { realExec } from "./exec.js";
14
+ import { detectLang, hasMsg, setLang, t } from "./i18n/index.js";
15
+ import { DEFAULT_LICENSE_SERVER } from "./license/keys.js";
16
+ import { looksLikeLicenseKey, looksLikePurchaseCode, maskCredential } from "./license/verify.js";
17
+ import { BUNDLE_RE, DEFAULT_LOCALES, DOMAIN_RE, EMAIL_RE, HEX_RE, LOCALES, PRODUCTS, slugify, suggestBundleId } from "./products.js";
18
+ import { licensePath, loadSecrets, loadState, newState, saveSecrets, saveState, STATE_DIR, } from "./state.js";
19
+ import { buildSteps } from "./steps.js";
20
+ import { normalizeHex, PRESET_IDS, primaryReport, readThemeFile, resolveTheme, themeLine } from "./theme/preview.js";
21
+ import { PRESETS } from "./theme/vendor/tokens.js";
22
+ import { ttyPrompter } from "./ui/prompt.js";
23
+ import { runUpdate } from "./update.js";
24
+ import { Out } from "./ui/term.js";
25
+ export const CLI_VERSION = (() => {
26
+ try {
27
+ return JSON.parse(readFileSync(fileURLToPath(new URL('../package.json', import.meta.url)), 'utf8')).version;
28
+ }
29
+ catch {
30
+ return '0.0.0';
31
+ }
32
+ })();
33
+ export async function main(argv, deps = {}) {
34
+ let env = ilorbEnvAliases(deps.env ?? process.env);
35
+ const { positionals, flags } = parseArgs(argv);
36
+ ilorbFlagAliases(flags);
37
+ const lang = detectLang(str(flags.lang), env);
38
+ setLang(lang.lang);
39
+ const out = deps.out ?? new Out();
40
+ const cwd = deps.cwd ?? process.cwd();
41
+ if (flags.help) {
42
+ out.line(t('help'));
43
+ return 0;
44
+ }
45
+ if (flags.version) {
46
+ out.line(CLI_VERSION);
47
+ return 0;
48
+ }
49
+ let dir = '';
50
+ let ctx = null;
51
+ // create-ilorb update [folder] [--apply <new folder>] [--yes] [--site <url>] — update.ts (never downloads, never deploys)
52
+ if (positionals[0] === 'update') {
53
+ const target = positionals[1] ? resolve(cwd, positionals[1]) : cwd;
54
+ try {
55
+ return await runUpdate({ dir: target, out, fetch: deps.fetch ?? fetch, env, flags, cwd });
56
+ }
57
+ catch (e) {
58
+ printError(out, e, '');
59
+ return 1;
60
+ }
61
+ }
62
+ try {
63
+ const major = Number(process.versions.node.split('.')[0]);
64
+ if (major < 20)
65
+ throw new HumanError('node_too_old', { version: process.versions.node });
66
+ // ── who and where ─────────────────────────────────────────────────────────────────────────
67
+ const resume = flags.resume === true;
68
+ let productId = positionals[0];
69
+ let dirArg = positionals[1];
70
+ if (resume && productId && !PRODUCTS[productId]) {
71
+ dirArg = productId;
72
+ productId = undefined;
73
+ }
74
+ if (dirArg)
75
+ dir = isAbsolute(dirArg) ? dirArg : resolve(cwd, dirArg);
76
+ else if (resume)
77
+ dir = cwd;
78
+ let state = dir ? loadState(dir) : null;
79
+ if (resume && !state)
80
+ throw new HumanError('no_state', { dir: dir || cwd });
81
+ productId ??= state?.product;
82
+ if (!productId) {
83
+ out.line(t('help'));
84
+ return 1;
85
+ }
86
+ const product = PRODUCTS[productId];
87
+ if (!product)
88
+ throw new HumanError('unknown_product', { product: productId, list: Object.keys(PRODUCTS).join(', ') });
89
+ const target = str(flags.target) ?? state?.target ?? 'cloud';
90
+ if (target !== 'cloud' && target !== 'local')
91
+ throw new HumanError('invalid_answer', { field: '--target', value: String(flags.target), hint: 'cloud | local' });
92
+ if (state && (state.product !== product.id || state.target !== target))
93
+ throw new HumanError('state_mismatch', { product: state.product, target: state.target });
94
+ const interactive = !flags.yes && deps.prompter !== null && (deps.prompter !== undefined || !!process.stdin.isTTY);
95
+ const prompter = interactive ? deps.prompter ?? ttyPrompter(out, { yes: t('yes'), no: t('no'), choose: t('choose'), invalid: t('invalid') }) : null;
96
+ out.line();
97
+ out.line(`${out.bold(out.magenta('◆'))} ${out.bold(t('app.title'))} ${out.dim(`v${CLI_VERSION}`)}`);
98
+ out.line(` ${out.dim(t('app.subtitle', { product: `${product.name} Template` }))}`);
99
+ if (lang.fallbackFrom)
100
+ out.line(` ${out.dim('(ar → en)')}`);
101
+ out.line();
102
+ // ── template source, Ilorb key, answers ─────────────────────────────────────────────────
103
+ const secrets = dir ? loadSecrets(dir) : {};
104
+ // legacy (dormant): a license only when one is given; Ilorb Code templates need none
105
+ const legacyLicense = !!(str(flags.license) ?? str(flags['purchase-code']) ?? env.OVERTURE_LICENSE ?? env.ENVATO_PURCHASE_CODE);
106
+ const credential = state ? loadCredential(dir) ?? (legacyLicense ? await askCredential(flags, env, prompter) : null) : legacyLicense ? await askCredential(flags, env, prompter) : null;
107
+ // where the template is: --templates, OVERTURE_TEMPLATES, or the folder we run in (an unzipped Ilorb Code download)
108
+ const templatesDir = str(flags.templates)
109
+ ? resolve(cwd, str(flags.templates))
110
+ : env.OVERTURE_TEMPLATES
111
+ ? resolve(cwd, env.OVERTURE_TEMPLATES)
112
+ : existsSync(join(cwd, 'overture-core')) && existsSync(join(cwd, `overture-${product.id}`))
113
+ ? cwd
114
+ : null;
115
+ if (!templatesDir && !credential)
116
+ throw new HumanError('templates_needed', { product: product.id });
117
+ // ilorb.env (written by the Ilorb Code download) feeds the Ilorb Signal key and endpoints; flags/env still win
118
+ const ilorb = templatesDir ? readIlorbEnv(templatesDir) : {};
119
+ if (ilorb.ILORB_APP_ID && flags['opera-app-id'] === undefined && (product.opera || product.ilorbOptional))
120
+ flags['opera-app-id'] = ilorb.ILORB_APP_ID;
121
+ env = {
122
+ ...env,
123
+ ...(ilorb.ILORB_APP_SECRET && !env.OPERA_APP_SECRET ? { OPERA_APP_SECRET: ilorb.ILORB_APP_SECRET } : {}),
124
+ ...(ilorb.ILORB_CHAT_URL && !env.ILORB_CHAT_URL ? { ILORB_CHAT_URL: ilorb.ILORB_CHAT_URL } : {}),
125
+ ...(ilorb.ILORB_API_URL && !env.ILORB_API_URL ? { ILORB_API_URL: ilorb.ILORB_API_URL } : {}),
126
+ };
127
+ if (ilorb.ILORB_APP_ID)
128
+ out.line(` ${out.dim(t('ilorb.key', { appId: ilorb.ILORB_APP_ID }))}`);
129
+ const answers = await collectAnswers({ flags, env, prompter, out, product, target, state, secrets, credential, templatesDir });
130
+ if (!dir)
131
+ dir = resolve(cwd, answers.slug);
132
+ if (!state) {
133
+ state = loadState(dir);
134
+ if (state && (state.product !== product.id || state.target !== target))
135
+ throw new HumanError('state_mismatch', { product: state.product, target: state.target });
136
+ if (!state && existsSync(dir) && readdirSync(dir).filter((f) => f !== '.DS_Store').length)
137
+ throw new HumanError('dir_not_empty', { dir });
138
+ }
139
+ Object.assign(secrets, { ...loadSecrets(dir), ...pick(secrets) });
140
+ if (prompter && !state) {
141
+ printSummary(out, answers, dir);
142
+ if (!(await prompter.confirm(t('q.confirm'), true))) {
143
+ out.line(t('q.cancelled'));
144
+ prompter.close();
145
+ return 1;
146
+ }
147
+ }
148
+ const isNew = !state;
149
+ state ??= newState(product.id, target, CLI_VERSION);
150
+ state.answers = answers;
151
+ const provider = target === 'cloud'
152
+ ? deps.provider ??
153
+ (str(flags.provider) === 'simulated' || env.OVERTURE_PROVIDER === 'simulated' || state.simulated
154
+ ? new SimulatedCloudflare({ delayMs: Number(env.OVERTURE_SIM_DELAY ?? 250) })
155
+ : new RealCloudflare({
156
+ exec: deps.exec ?? realExec,
157
+ fetch: deps.fetch,
158
+ apiToken: env.CLOUDFLARE_API_TOKEN,
159
+ stateDir: join(dir, STATE_DIR),
160
+ wrangler: () => join(dir, 'overture-core/api/workers/node_modules/.bin', process.platform === 'win32' ? 'wrangler.cmd' : 'wrangler'),
161
+ }))
162
+ : null;
163
+ if (provider?.kind === 'simulated') {
164
+ if (!deps.provider)
165
+ state.simulated = true;
166
+ out.line(` ${out.yellow('!')} ${out.bold(t('cf.simulated'))}`);
167
+ out.line();
168
+ }
169
+ ctx = {
170
+ dir, product, answers, secrets, state, out, provider, prompter, credential,
171
+ exec: deps.exec ?? realExec,
172
+ fetch: deps.fetch ?? fetch,
173
+ licenseServer: str(flags['license-server']) ?? env.OVERTURE_LICENSE_SERVER ?? state.licenseServer ?? DEFAULT_LICENSE_SERVER,
174
+ templatesDir,
175
+ cliVersion: CLI_VERSION,
176
+ serve: !(flags['no-serve'] === true || flags.serve === false),
177
+ env,
178
+ };
179
+ state.licenseServer = ctx.licenseServer;
180
+ const steps = buildSteps(product, target, answers, !!credential);
181
+ if (flags['dry-run']) {
182
+ printPlan(ctx, steps);
183
+ prompter?.close();
184
+ return 0;
185
+ }
186
+ // ── from here on it writes ───────────────────────────────────────────────────────────────
187
+ mkdirSync(join(dir, STATE_DIR), { recursive: true });
188
+ out.logTo(join(dir, STATE_DIR, 'install.log'));
189
+ const logFlag = str(flags.log);
190
+ if (logFlag)
191
+ out.logTo(resolve(cwd, logFlag));
192
+ out.log(`\n===== ${new Date().toISOString()} create-ilorb ${CLI_VERSION} ${argv.map((a) => (/^osc1\.|^[0-9a-f]{8}-/i.test(a) ? maskCredential(a) : a)).join(' ')}`);
193
+ if (isNew)
194
+ out.info(`${t('sum.folder')}: ${dir}`);
195
+ saveSecrets(dir, secrets);
196
+ saveState(dir, state);
197
+ prompter?.close();
198
+ await runSteps(ctx, steps);
199
+ printFinal(ctx);
200
+ if (target === 'local' && ctx.child) {
201
+ if (!ctx.serve || deps.noWait) {
202
+ await stopChild(ctx);
203
+ out.line(out.dim(t('local.stopped')));
204
+ return 0;
205
+ }
206
+ out.line(out.dim(t('local.stop')));
207
+ await new Promise((resolveWait) => {
208
+ let stopping = false;
209
+ const stop = async () => {
210
+ stopping = true;
211
+ await stopChild(ctx);
212
+ out.line(out.dim(t('local.stopped')));
213
+ resolveWait();
214
+ };
215
+ process.once('SIGINT', stop);
216
+ process.once('SIGTERM', stop);
217
+ // dev-local went down on its own (not us): finish as well
218
+ ctx.child.once('exit', () => !stopping && resolveWait());
219
+ });
220
+ }
221
+ return 0;
222
+ }
223
+ catch (e) {
224
+ if (ctx?.child)
225
+ await stopChild(ctx);
226
+ if (e.aborted) {
227
+ out.line();
228
+ out.line(t('aborted'));
229
+ return 130;
230
+ }
231
+ printError(out, e, dir);
232
+ return 1;
233
+ }
234
+ }
235
+ /**
236
+ * Ilorb names for the Ilorb Signal flags: --ilorb-app-id = --opera-app-id, --skip-ilorb = --skip-opera. The --opera-* names
237
+ * stay a contract (scripts, template READMEs, saved installs); when both are given, the --opera-* one wins.
238
+ */
239
+ export function ilorbFlagAliases(flags) {
240
+ if (flags['ilorb-app-id'] !== undefined && flags['opera-app-id'] === undefined)
241
+ flags['opera-app-id'] = flags['ilorb-app-id'];
242
+ if (flags['skip-ilorb'] !== undefined && flags['skip-opera'] === undefined)
243
+ flags['skip-opera'] = flags['skip-ilorb'];
244
+ return flags;
245
+ }
246
+ /** ILORB_APP_SECRET / ILORB_CALLBACK_SECRET in the environment = OPERA_APP_SECRET / OPERA_CALLBACK_SECRET (OPERA_* wins) */
247
+ export function ilorbEnvAliases(env) {
248
+ const extra = {};
249
+ if (env.ILORB_APP_SECRET && !env.OPERA_APP_SECRET)
250
+ extra.OPERA_APP_SECRET = env.ILORB_APP_SECRET;
251
+ if (env.ILORB_CALLBACK_SECRET && !env.OPERA_CALLBACK_SECRET)
252
+ extra.OPERA_CALLBACK_SECRET = env.ILORB_CALLBACK_SECRET;
253
+ return Object.keys(extra).length ? { ...env, ...extra } : env;
254
+ }
255
+ const pick = (s) => Object.fromEntries(Object.entries(s).filter(([, v]) => v));
256
+ async function stopChild(ctx) {
257
+ const c = ctx.child;
258
+ if (!c || c.exitCode !== null)
259
+ return;
260
+ await new Promise((r) => {
261
+ const timer = setTimeout(() => {
262
+ try {
263
+ c.kill('SIGKILL');
264
+ }
265
+ catch { }
266
+ r();
267
+ }, 8000);
268
+ c.once('exit', () => {
269
+ clearTimeout(timer);
270
+ r();
271
+ });
272
+ c.kill('SIGTERM');
273
+ });
274
+ ctx.child = null;
275
+ }
276
+ /** ilorb.env (KEY=VALUE lines) of an Ilorb Code template folder; {} when there is none */
277
+ export function readIlorbEnv(dir) {
278
+ const file = join(dir, 'ilorb.env');
279
+ if (!existsSync(file))
280
+ return {};
281
+ const out = {};
282
+ for (const line of readFileSync(file, 'utf8').split(/\r?\n/)) {
283
+ const m = line.match(/^\s*(ILORB_[A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
284
+ if (m && m[2])
285
+ out[m[1]] = m[2].replace(/^"(.*)"$/, '$1');
286
+ }
287
+ return out;
288
+ }
289
+ function loadCredential(dir) {
290
+ if (!existsSync(licensePath(dir)))
291
+ return null;
292
+ try {
293
+ return JSON.parse(readFileSync(licensePath(dir), 'utf8')).credential ?? null;
294
+ }
295
+ catch {
296
+ return null;
297
+ }
298
+ }
299
+ async function askCredential(flags, env, prompter) {
300
+ let raw = str(flags.license) ?? str(flags['purchase-code']) ?? env.OVERTURE_LICENSE ?? env.ENVATO_PURCHASE_CODE;
301
+ if (!raw) {
302
+ if (!prompter)
303
+ throw new HumanError('license_missing');
304
+ raw = await prompter.text(t('license.ask'), { validate: (v) => (looksLikeLicenseKey(v) || looksLikePurchaseCode(v) ? null : t('err.license_malformed.do')) });
305
+ }
306
+ raw = raw.trim();
307
+ if (looksLikeLicenseKey(raw))
308
+ return { type: 'license', key: raw };
309
+ if (looksLikePurchaseCode(raw))
310
+ return { type: 'envato', purchaseCode: raw.toLowerCase() };
311
+ if (str(flags['purchase-code']) || env.ENVATO_PURCHASE_CODE)
312
+ throw new HumanError('purchase_code_malformed');
313
+ throw new HumanError('license_malformed');
314
+ }
315
+ async function collectAnswers(i) {
316
+ const { flags, env, prompter, out, target, secrets } = i;
317
+ const prev = i.state?.answers ?? null;
318
+ const need = async (field, flag, ask) => {
319
+ if (!prompter)
320
+ throw new HumanError('missing_answer', { field, flag });
321
+ return ask();
322
+ };
323
+ const invalid = (field, value, hint) => new HumanError('invalid_answer', { field, value, hint });
324
+ // name
325
+ let appName = str(flags.name) ?? prev?.appName;
326
+ if (appName && (appName.length < 2 || appName.length > 40))
327
+ throw invalid('--name', appName, t('q.name.invalid'));
328
+ appName ??= await need(t('q.name'), '--name "<app name>"', () => prompter.text(t('q.name'), { validate: (v) => (v.trim().length >= 2 && v.trim().length <= 40 ? null : t('q.name.invalid')) }));
329
+ appName = appName.trim();
330
+ const slug = prev?.slug && prev.appName === appName ? prev.slug : slugify(appName);
331
+ // owner
332
+ let ownerEmail = str(flags['owner-email']) ?? prev?.ownerEmail;
333
+ if (ownerEmail && !EMAIL_RE.test(ownerEmail))
334
+ throw invalid('--owner-email', ownerEmail, t('q.owner.invalid'));
335
+ ownerEmail ??= await need(t('q.owner'), '--owner-email <e-mail>', () => prompter.text(t('q.owner'), { validate: (v) => (EMAIL_RE.test(v.trim()) ? null : t('q.owner.invalid')) }));
336
+ ownerEmail = ownerEmail.trim().toLowerCase();
337
+ // languages
338
+ const parseLangs = (v) => [...new Set(v.split(/[\s,]+/).map((x) => x.trim().toLowerCase()).filter(Boolean))];
339
+ let languages = str(flags.languages) ? parseLangs(str(flags.languages)) : prev?.languages ?? null;
340
+ if (!languages && prompter)
341
+ languages = parseLangs(await prompter.text(t('q.languages'), { default: DEFAULT_LOCALES.join(','), validate: (v) => (parseLangs(v).every((l) => LOCALES.includes(l)) && parseLangs(v).length ? null : t('q.languages.invalid')) }));
342
+ languages ??= [...DEFAULT_LOCALES];
343
+ if (!languages.length || !languages.every((l) => LOCALES.includes(l)))
344
+ throw invalid('--languages', languages.join(','), t('q.languages.invalid'));
345
+ // style + color (samples with the app's engine)
346
+ // the look chosen on Ilorb Code (overture.theme.json next to ilorb.env) is the default answer when nothing else
347
+ // says otherwise: no --style/--primary and no saved state; --yes uses it as is, a prompt offers it as the default
348
+ let fileTheme = null;
349
+ if (!str(flags.style) && !str(flags.primary) && !prev && i.templatesDir) {
350
+ const f = readThemeFile(i.templatesDir);
351
+ if (f && 'error' in f)
352
+ out.line(` ${out.dim(t('q.theme.file.invalid', { reason: f.error }))}`);
353
+ else if (f) {
354
+ fileTheme = f.theme;
355
+ out.line(` ${out.dim(t('q.theme.file', { style: PRESETS[f.theme.preset].label, primary: f.theme.primary, radius: f.theme.radius, font: f.theme.font }))}`);
356
+ }
357
+ }
358
+ let preset = str(flags.style) ?? prev?.theme.preset ?? (fileTheme && !prompter ? fileTheme.preset : undefined);
359
+ if (preset && !PRESET_IDS.includes(preset))
360
+ throw invalid('--style', preset, PRESET_IDS.join(' | '));
361
+ let primary = str(flags.primary) ?? (prev && prev.theme.preset === preset ? prev.theme.primary : undefined) ?? (fileTheme && !prompter ? fileTheme.primary : undefined);
362
+ if (primary && !HEX_RE.test(primary))
363
+ throw invalid('--primary', primary, t('q.primary.invalid'));
364
+ if (!preset && prompter) {
365
+ out.line(` ${out.dim(`${' '.repeat(8)}${t('theme.light').padEnd(31)}${t('theme.dark')}`)}`);
366
+ preset = await prompter.select(t('q.style'), PRESET_IDS.map((id) => ({ value: id, label: themeLine(out, { preset: id }, PRESETS[id].label, t('theme.button')) })), fileTheme ? Math.max(0, PRESET_IDS.indexOf(fileTheme.preset)) : 0);
367
+ }
368
+ preset ??= 'clean';
369
+ if (!primary && prompter && !str(flags.style)) {
370
+ const def = fileTheme && fileTheme.preset === preset ? fileTheme.primary : PRESETS[preset].primary;
371
+ primary = normalizeHex(await prompter.text(t('q.primary'), { default: def, validate: (v) => (HEX_RE.test(v.trim()) ? null : t('q.primary.invalid')) }));
372
+ }
373
+ // the file's look as it is (its radius and font too) while the buyer keeps its style and color
374
+ const theme = fileTheme && fileTheme.preset === preset && (!primary || normalizeHex(primary) === fileTheme.primary)
375
+ ? fileTheme
376
+ : resolveTheme(preset, primary ? normalizeHex(primary) : null);
377
+ if (!prev || prev.theme.primary !== theme.primary || prev.theme.preset !== theme.preset) {
378
+ const rep = primaryReport(theme);
379
+ out.line(` ${themeLine(out, theme, PRESETS[preset].label, t('theme.button'))}`);
380
+ out.line(` ${out.dim(rep.adjusted ? t('q.primary.adjusted', { from: theme.primary, to: rep.light, ratio: rep.ratioLight, dark: rep.dark }) : t('q.primary.kept', { ratio: rep.ratioLight }))}`);
381
+ }
382
+ // bundle id (derived; only changes with --bundle-id). Product without an app (Widgets): does not exist
383
+ let bundleId = null;
384
+ if (i.product.app) {
385
+ bundleId = str(flags['bundle-id']) ?? (prev && prev.slug === slug && prev.bundleId ? prev.bundleId : suggestBundleId(ownerEmail, slug));
386
+ if (!BUNDLE_RE.test(bundleId))
387
+ throw invalid('--bundle-id', bundleId, 'com.empresa.app');
388
+ }
389
+ // Cloudflare (the account is chosen in the account step, after login)
390
+ const accountId = str(flags['account-id']) ?? i.env.CLOUDFLARE_ACCOUNT_ID ?? prev?.cloudflare.accountId ?? null;
391
+ // Opera. Cloud: the production app (or "I'll set it up later" in the panel). Local: the buyer's TEST app is REQUIRED
392
+ // in the cloud Opera — the Opera chat server is not in the package. Without the keys, the "local.opera" step stops and explains.
393
+ // Product without Opera (Status): neither asks nor stores an Opera key.
394
+ // Optional Ilorb chat (Classificados): the key is TAKEN when given (ilorb.env / flag + env), never asked nor required.
395
+ const usesOpera = i.product.opera;
396
+ const takesKey = usesOpera || !!i.product.ilorbOptional;
397
+ let operaAppId = takesKey ? str(flags['opera-app-id']) ?? prev?.opera.appId ?? null : null;
398
+ if (takesKey && env.OPERA_APP_SECRET)
399
+ secrets.OPERA_APP_SECRET = env.OPERA_APP_SECRET;
400
+ if (usesOpera && env.OPERA_CALLBACK_SECRET)
401
+ secrets.OPERA_CALLBACK_SECRET = env.OPERA_CALLBACK_SECRET;
402
+ const askOpera = !usesOpera ? false : target === 'cloud' ? !operaAppId && !flags['skip-opera'] && !prev : !operaAppId || !secrets.OPERA_APP_SECRET;
403
+ if (askOpera) {
404
+ if (prompter) {
405
+ out.line();
406
+ if (target === 'local')
407
+ out.line(` ${out.dim(t(i.product.app ? 'q.opera.localHint' : 'q.opera.localHint.site', { product: i.product.name.replace(/^Ilorb /, '') }))}`);
408
+ const now = await prompter.select(target === 'local' ? t('q.opera.local') : t('q.opera'), [{ value: true, label: t('q.opera.now') }, { value: false, label: target === 'local' ? t('q.opera.localLater') : t('q.opera.later') }], 0);
409
+ if (now) {
410
+ operaAppId = (await prompter.text(t('q.opera.appId'), { default: operaAppId ?? undefined, validate: (v) => (/^app_[A-Za-z0-9_-]{4,}$/.test(v.trim()) ? null : 'app_…') })).trim();
411
+ secrets.OPERA_APP_SECRET = await prompter.secret(t('q.opera.secret'));
412
+ const cb = await prompter.secret(t('q.opera.callback'), { allowEmpty: true });
413
+ if (cb)
414
+ secrets.OPERA_CALLBACK_SECRET = cb;
415
+ }
416
+ }
417
+ }
418
+ if (operaAppId && !/^app_[A-Za-z0-9_-]{4,}$/.test(operaAppId))
419
+ throw invalid('--opera-app-id', operaAppId, 'app_…');
420
+ // optional product secrets (Sites: TURNSTILE_SECRET) — only through the environment, never through a flag
421
+ for (const k of i.product.envSecrets ?? [])
422
+ if (env[k])
423
+ secrets[k] = env[k];
424
+ // code email (cloud only; local shows the code on screen)
425
+ let emailFrom = str(flags['email-from']) ?? prev?.email.from ?? null;
426
+ if (env.RESEND_API_KEY)
427
+ secrets.RESEND_API_KEY = env.RESEND_API_KEY;
428
+ if (target === 'cloud' && !emailFrom && !flags['skip-email'] && !prev && prompter) {
429
+ const now = await prompter.select(t('q.email'), [{ value: true, label: t('q.email.now') }, { value: false, label: t('q.email.later') }], 0);
430
+ if (now) {
431
+ secrets.RESEND_API_KEY = await prompter.secret(t('q.email.key'));
432
+ emailFrom = (await prompter.text(t('q.email.from'), { default: `${appName} <login@${ownerEmail.split('@')[1]}>` })).trim();
433
+ }
434
+ }
435
+ // Resend key without a sender (--yes): uses the owner's domain — the buyer changes it in the panel
436
+ if (target === 'cloud' && secrets.RESEND_API_KEY && !emailFrom)
437
+ emailFrom = `${appName} <login@${ownerEmail.split('@')[1]}>`;
438
+ if (target === 'local')
439
+ emailFrom = null;
440
+ // own domain (only products with customDomain: the Status page). Optional: without it, stays on workers.dev
441
+ let domain = null;
442
+ if (i.product.customDomain) {
443
+ const flag = i.product.domainFlag ?? 'status-domain';
444
+ const raw = str(flags[flag]) ?? prev?.domain ?? null;
445
+ domain = raw ? raw.trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/+$/, '') : null;
446
+ if (domain && !DOMAIN_RE.test(domain))
447
+ throw invalid(`--${flag}`, raw, t('q.domain.invalid'));
448
+ if (target === 'local')
449
+ domain = null;
450
+ }
451
+ // paid Workers plan (Link: turns on the click queue). --workers-paid / --no-workers-paid; default: no. Cloud only.
452
+ let workersPaid;
453
+ if (i.product.paidQueue) {
454
+ const f = flags['workers-paid'];
455
+ workersPaid = typeof f === 'boolean' ? f : prev?.workersPaid ?? undefined;
456
+ if (workersPaid === undefined && target === 'cloud' && prompter) {
457
+ workersPaid = await prompter.select(t('q.workersPaid'), [{ value: false, label: t('q.workersPaid.no') }, { value: true, label: t('q.workersPaid.yes') }], 0);
458
+ }
459
+ workersPaid = target === 'cloud' ? !!workersPaid : false;
460
+ }
461
+ // sample data (Quiz: questions). --sample-data / --no-sample-data; default: yes locally, no in the cloud
462
+ let sampleData;
463
+ if (i.product.sampleImport) {
464
+ const f = flags['sample-data'];
465
+ sampleData = typeof f === 'boolean' ? f : prev?.sampleData ?? undefined;
466
+ if (sampleData === undefined && prompter)
467
+ sampleData = await prompter.confirm(t('q.sampleData'), target === 'local');
468
+ sampleData ??= target === 'local';
469
+ }
470
+ return {
471
+ product: i.product.id,
472
+ target,
473
+ appName,
474
+ slug,
475
+ ownerEmail,
476
+ languages: languages,
477
+ theme,
478
+ bundleId,
479
+ cloudflare: { accountId, accountName: prev?.cloudflare.accountName ?? null },
480
+ opera: { appId: operaAppId },
481
+ email: { from: emailFrom },
482
+ ...(i.product.customDomain ? { domain } : {}),
483
+ ...(i.product.paidQueue ? { workersPaid } : {}),
484
+ ...(i.product.sampleImport ? { sampleData } : {}),
485
+ license: i.credential ? { type: i.credential.type, masked: maskCredential(i.credential.type === 'license' ? i.credential.key : i.credential.purchaseCode) } : null,
486
+ };
487
+ }
488
+ function printSummary(out, a, dir) {
489
+ out.line();
490
+ out.line(` ${out.bold(t('q.summary'))}`);
491
+ const row = (k, v) => out.line(` ${out.dim(k.padEnd(16))} ${v}`);
492
+ row(t('sum.product'), PRODUCTS[a.product]?.name ?? a.product);
493
+ row(t('sum.app'), `${a.appName} ${out.dim(`(${a.slug})`)}`);
494
+ row(t('sum.owner'), a.ownerEmail);
495
+ row(t('sum.languages'), a.languages.join(', '));
496
+ row(t('sum.style'), `${PRESETS[a.theme.preset].label} · ${a.theme.primary}`);
497
+ if (a.bundleId)
498
+ row(t('sum.bundle'), a.bundleId);
499
+ row(t('sum.folder'), dir);
500
+ row(t('sum.target'), a.target === 'cloud' ? t('sum.target.cloud') : t('sum.target.local'));
501
+ if (PRODUCTS[a.product]?.opera !== false)
502
+ row(t('sum.opera'), a.opera.appId ? `${a.opera.appId}${a.target === 'local' ? ` ${out.dim(t('sum.opera.test'))}` : ''}` : t('sum.opera.skip'));
503
+ if (a.target === 'cloud')
504
+ row(t('sum.email'), a.email.from ?? t('sum.email.skip'));
505
+ if (a.target === 'cloud' && PRODUCTS[a.product]?.customDomain)
506
+ row(t('sum.domain'), a.domain ?? t('sum.domain.skip'));
507
+ if (a.target === 'cloud' && PRODUCTS[a.product]?.paidQueue)
508
+ row(t('sum.workersPaid'), a.workersPaid ? t('sum.workersPaid.yes') : t('sum.workersPaid.no'));
509
+ out.line();
510
+ }
511
+ function printFinal(c) {
512
+ const { out, answers: a, state } = c;
513
+ const u = state.resources.urls;
514
+ out.line();
515
+ out.line(`${out.green('✔')} ${out.bold(a.target === 'local' ? t('final.local.title', { app: a.appName }) : t('final.title', { app: a.appName }))}`);
516
+ out.line();
517
+ out.line(` ${out.bold(t('final.urls'))}`);
518
+ const row = (k, v) => v && out.line(` ${k.padEnd(28)} ${out.cyan(v)}`);
519
+ row(t('final.admin'), u.admin);
520
+ row(t('final.app'), u.app);
521
+ row(t('final.auth'), u.auth);
522
+ row(t('final.api', { product: c.product.name }), u.api);
523
+ row(t(c.product.id === 'agenda' ? 'final.bookingPage' : 'final.site'), u.site);
524
+ // Status: the public page is the Worker itself (or the own domain)
525
+ if (c.product.id === 'status')
526
+ row(t('final.statusPage'), a.target === 'cloud' && a.domain ? `https://${a.domain}` : u.api);
527
+ if (c.product.id === 'sites')
528
+ row(t('final.siteUrl'), u.api);
529
+ if (a.target === 'local' && c.product.opera)
530
+ row(t('final.opera'), u.opera);
531
+ if (a.target === 'local' && c.product.opera)
532
+ row(t('final.callback'), `${u.api}/v1/opera/callback`);
533
+ out.line();
534
+ // owner's first-access link: signs in to the panel without a code and without an email provider (single use, 15 min)
535
+ if (c.bootstrap?.url) {
536
+ out.line(` ${out.bold(t('final.bootstrap'))}`);
537
+ const mask = c.bootstrap.url.replace(/bootstrap=[^&]+/, 'bootstrap=bst_…');
538
+ out.secretLine(` ${out.cyan(c.bootstrap.url)}`, ` ${mask} (hidden in the log)`);
539
+ out.line(` ${out.dim(t('final.bootstrapNote', { email: a.ownerEmail }))}`);
540
+ out.line();
541
+ }
542
+ else if (c.bootstrapError) {
543
+ out.line(` ${out.yellow('!')} ${t('final.bootstrapFailed')}`);
544
+ out.line();
545
+ }
546
+ out.line(` ${out.bold(t('final.next'))}`);
547
+ const n = (s) => out.line(` → ${s}`);
548
+ // local: the code appears on screen (no email) — mentioning Resend here only confuses
549
+ n(t(c.bootstrap?.url ? (a.target === 'local' ? 'final.next.panelLinkLocal' : 'final.next.panelLink') : 'final.next.panel', { email: a.ownerEmail }));
550
+ // Widgets: create the widget in the panel, set the domain and copy the snippet (local: the test page already loads it)
551
+ if (c.product.id === 'widgets')
552
+ n(t(a.target === 'local' ? 'final.next.widgetLocal' : 'final.next.widget', { site: u.site ?? '', host: u.site?.replace(/^https?:\/\//, '') ?? '' }));
553
+ // Consultas: professionals/services in the panel; payments (simulated locally) and the reminders cron
554
+ if (c.product.id === 'consultas')
555
+ n(t(a.target === 'local' ? 'final.next.consultasLocal' : 'final.next.consultas'));
556
+ // Agenda: panel (hours, professionals, services), the booking page + embed.js; payments (simulated locally) and the cron
557
+ // Sites: pick a demo or create the pages and publish (changes instantly, no deploy); own domain is manual
558
+ if (c.product.id === 'sites')
559
+ n(t(a.target === 'local' ? 'final.next.sitesLocal' : 'final.next.sites', { site: u.api ?? '', worker: state.resources.workers.api?.name ?? `${a.slug}-sites` }));
560
+ if (c.product.id === 'starter')
561
+ n(t(a.target === 'local' ? 'final.next.starterLocal' : 'final.next.starter', { app: u.app ?? '' }));
562
+ // Help Center: Email Routing is manual (Cloudflare does not let the installer do it) — it also goes in the generated README
563
+ // Classificados: the 4 steps after installing (INSTALADOR.md) + the site domain (SEO lives off it)
564
+ if (c.product.id === 'classificados') {
565
+ for (const k of ['final.next.cls1', 'final.next.cls2', 'final.next.cls3'])
566
+ n(t(k));
567
+ n(t('final.next.cls4', { site: a.target === 'cloud' && a.domain ? `https://${a.domain}` : u.api ?? '' }));
568
+ if (a.target === 'cloud' && !a.domain)
569
+ n(t('final.next.clsDomain', { worker: state.resources.workers.api?.name ?? `${a.slug}-classificados` }));
570
+ }
571
+ if (c.product.id === 'helpcenter') {
572
+ n(t(a.target === 'local' ? 'final.next.helpcenterLocal' : 'final.next.helpcenter', { api: u.api ?? '' }));
573
+ if (a.target === 'cloud')
574
+ n(t('final.next.helpcenterEmail', { worker: state.resources.workers.api?.name ?? `${a.slug}-helpcenter` }));
575
+ }
576
+ if (c.product.id === 'imoveis')
577
+ n(t(a.target === 'local' ? 'final.next.imoveisLocal' : 'final.next.imoveis', { site: u.api ?? '', app: u.app ?? '' }));
578
+ if (c.product.id === 'quiz')
579
+ n(t(a.target === 'local' ? 'final.next.quizLocal' : 'final.next.quiz', { app: u.app ?? '' }));
580
+ if (c.product.id === 'link') {
581
+ n(t(a.target === 'local' ? 'final.next.linkLocal' : 'final.next.link', { app: u.app ?? '' }));
582
+ if (a.target === 'cloud')
583
+ n(t(a.workersPaid ? 'final.next.linkQueue' : 'final.next.linkNoQueue', { queue: `${a.slug}-link-clicks` }));
584
+ if (a.target === 'cloud' && !a.domain)
585
+ n(t('final.next.linkDomain', { worker: state.resources.workers.api?.name ?? `${a.slug}-link` }));
586
+ }
587
+ if (c.product.id === 'agenda')
588
+ n(t(a.target === 'local' ? 'final.next.agendaLocal' : 'final.next.agenda', { site: u.site ?? '' }));
589
+ // Status: monitors, components and alerts in the panel; the checks cron; the page's own domain
590
+ if (c.product.id === 'status') {
591
+ n(t(a.target === 'local' ? 'final.next.statusLocal' : 'final.next.status', { page: a.target === 'cloud' && a.domain ? `https://${a.domain}` : u.api ?? '' }));
592
+ if (a.target === 'cloud')
593
+ n(a.domain ? t('final.next.statusDomainSet', { domain: a.domain, worker: state.resources.workers.api?.name ?? `${a.slug}-status` }) : t('final.next.statusDomain', { worker: state.resources.workers.api?.name ?? `${a.slug}-status` }));
594
+ }
595
+ // new products: the steps come from the spec (i18n keys; `<key>Local` in local mode when it exists)
596
+ for (const k of c.product.finalNext ?? []) {
597
+ const key = a.target === 'local' && hasMsg(`${k}Local`) ? `${k}Local` : k;
598
+ if (hasMsg(key))
599
+ n(t(key, { site: u.site ?? u.api ?? '', app: u.app ?? '', api: u.api ?? '', admin: u.admin ?? '', worker: state.resources.workers.api?.name ?? `${a.slug}-${c.product.api.suffix}` }));
600
+ }
601
+ if (a.target === 'local') {
602
+ n(t('final.next.localCode'));
603
+ // the cloud Opera cannot reach localhost: push and callback reports need a tunnel or the cloud deploy
604
+ if (c.product.opera)
605
+ n(t('final.next.localCallback', { port: String(state.local?.ports.api ?? '<api>'), path: '/v1/opera/callback' }));
606
+ }
607
+ else {
608
+ if (!c.product.opera) { /* no Opera: nothing to configure */ }
609
+ else if (a.opera.appId)
610
+ n(t('final.next.opera', { url: `${u.api}/v1/opera/callback` }));
611
+ else
612
+ n(t(c.product.id === 'consultas' ? 'final.next.operaSkip.consultas' : c.product.app ? 'final.next.operaSkip' : 'final.next.operaSkip.widgets'));
613
+ if (!a.email.from || !c.secrets.RESEND_API_KEY)
614
+ n(t(c.product.id === 'status' ? 'final.next.emailSkip.status' : 'final.next.emailSkip'));
615
+ if (c.product.app)
616
+ n(t('final.next.eas', { dir: c.product.app.dir }));
617
+ }
618
+ n(t('final.next.secrets'));
619
+ out.line(` ${out.dim(t('final.again'))}`);
620
+ out.line();
621
+ }
622
+ function printError(out, e, dir) {
623
+ const human = isHuman(e) ? e : null;
624
+ out.line();
625
+ out.line(`${out.red('✖')} ${out.bold(human ? human.what() : t('err.unexpected.what', { message: e?.message ?? String(e) }))}`);
626
+ out.line(` ${out.bold(t('err.whatToDo'))}: ${human ? human.todo() : t('err.unexpected.do')}`);
627
+ const detail = human?.detail ?? (human ? undefined : e?.stack);
628
+ if (detail) {
629
+ out.line(` ${out.dim(t('err.details'))}:`);
630
+ for (const l of String(detail).trim().split('\n').slice(-8))
631
+ out.line(` ${out.dim(l)}`);
632
+ out.log(String(detail));
633
+ }
634
+ if (dir && existsSync(join(dir, STATE_DIR, 'install.json'))) {
635
+ out.line(` ${t('err.resume', { cmd: out.cyan(`npx create-ilorb --resume ${shortDir(dir)}`) })}`);
636
+ }
637
+ out.line();
638
+ }
639
+ const shortDir = (dir) => {
640
+ const rel = dir.startsWith(process.cwd() + '/') ? dir.slice(process.cwd().length + 1) : dir;
641
+ return rel.includes(' ') ? `"${rel}"` : rel || basename(dir);
642
+ };