@lunora/cli 1.0.0-alpha.101 → 1.0.0-alpha.102

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 (83) hide show
  1. package/dist/bin.mjs +2 -10
  2. package/dist/index.mjs +1 -18
  3. package/dist/packem_chunks/handler.mjs +1 -160
  4. package/dist/packem_chunks/handler10.mjs +1 -16
  5. package/dist/packem_chunks/handler11.mjs +1 -23
  6. package/dist/packem_chunks/handler12.mjs +2 -192
  7. package/dist/packem_chunks/handler13.mjs +2 -131
  8. package/dist/packem_chunks/handler14.mjs +1 -65
  9. package/dist/packem_chunks/handler15.mjs +1 -100
  10. package/dist/packem_chunks/handler16.mjs +1 -44
  11. package/dist/packem_chunks/handler17.mjs +1 -105
  12. package/dist/packem_chunks/handler18.mjs +3 -170
  13. package/dist/packem_chunks/handler19.mjs +1 -128
  14. package/dist/packem_chunks/handler2.mjs +2 -116
  15. package/dist/packem_chunks/handler20.mjs +1 -94
  16. package/dist/packem_chunks/handler21.mjs +2 -202
  17. package/dist/packem_chunks/handler3.mjs +2 -208
  18. package/dist/packem_chunks/handler4.mjs +1 -33
  19. package/dist/packem_chunks/handler5.mjs +1 -52
  20. package/dist/packem_chunks/handler6.mjs +1 -94
  21. package/dist/packem_chunks/handler7.mjs +1 -42
  22. package/dist/packem_chunks/handler8.mjs +1 -174
  23. package/dist/packem_chunks/handler9.mjs +8 -334
  24. package/dist/packem_chunks/planDevCommand.mjs +7 -1181
  25. package/dist/packem_chunks/runCodegenCommand.mjs +4 -53
  26. package/dist/packem_chunks/runDeployCommand.mjs +1 -619
  27. package/dist/packem_chunks/runInitCommand.mjs +51 -1411
  28. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +9 -442
  29. package/dist/packem_chunks/runResetCommand.mjs +1 -41
  30. package/dist/packem_chunks/runRpcCommand.mjs +1 -69
  31. package/dist/packem_shared/COMMANDS-DRqlsGT2.mjs +3 -0
  32. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-DL87PIEl.mjs +8 -0
  33. package/dist/packem_shared/admin-url-DfVehV3e.mjs +1 -0
  34. package/dist/packem_shared/api-spec-BENwiyUa.mjs +1 -0
  35. package/dist/packem_shared/buildRegistryIndex-DwySASBu.mjs +1 -0
  36. package/dist/packem_shared/codegen-error-DJN6pTH5.mjs +3 -0
  37. package/dist/packem_shared/command-Bjv4VmYA.mjs +1 -0
  38. package/dist/packem_shared/commands-BhX2Bo9B.mjs +19 -0
  39. package/dist/packem_shared/createLogger--C3x1FNE.mjs +2 -0
  40. package/dist/packem_shared/createRecordingSpawner-C8_7nffs.mjs +1 -0
  41. package/dist/packem_shared/detect-package-manager-B2eIuAiP.mjs +1 -0
  42. package/dist/packem_shared/diffSnapshots-9bDd9nOK.mjs +5 -0
  43. package/dist/packem_shared/docker-CKvYE9YF.mjs +1 -0
  44. package/dist/packem_shared/insertSchemaExtension-DZReBZ4_.mjs +8 -0
  45. package/dist/packem_shared/open-url-CTU_g9gr.mjs +1 -0
  46. package/dist/packem_shared/output-format-D7cKB-O5.mjs +2 -0
  47. package/dist/packem_shared/parseManifest-x3WsxKHz.mjs +1 -0
  48. package/dist/packem_shared/prompt-cancelled-C8Sj7OqI.mjs +1 -0
  49. package/dist/packem_shared/resolve-target-vxaXHmvg.mjs +1 -0
  50. package/dist/packem_shared/runAddCommand--TBYJQYi.mjs +1 -0
  51. package/dist/packem_shared/schema-drift-gate-CpqG-xP4.mjs +1 -0
  52. package/dist/packem_shared/schemaIrToSnapshot-Clwd2A8e.mjs +1 -0
  53. package/dist/packem_shared/storage-DOvAKGi4.mjs +1 -0
  54. package/dist/packem_shared/tui-prompts-CCt3jm1k.mjs +4 -0
  55. package/dist/packem_shared/wrangler-name-HIl0Z6yx.mjs +1 -0
  56. package/dist/packem_shared/wrangler-secrets-BMRJwKQU.mjs +1 -0
  57. package/package.json +6 -6
  58. package/dist/packem_shared/COMMANDS-BOJIDoVY.mjs +0 -1031
  59. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-D0VOTerB.mjs +0 -249
  60. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  61. package/dist/packem_shared/api-spec-Bx0iKbxA.mjs +0 -15
  62. package/dist/packem_shared/buildRegistryIndex-BS5ig822.mjs +0 -38
  63. package/dist/packem_shared/codegen-error-DJG-ghs_.mjs +0 -31
  64. package/dist/packem_shared/command-lYnl4QyF.mjs +0 -19
  65. package/dist/packem_shared/commands-D5Yxt9VY.mjs +0 -991
  66. package/dist/packem_shared/createLogger-CIWSHrTL.mjs +0 -105
  67. package/dist/packem_shared/createRecordingSpawner-WuSn20kb.mjs +0 -64
  68. package/dist/packem_shared/detect-package-manager-v4hHpQd0.mjs +0 -62
  69. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  70. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  71. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  72. package/dist/packem_shared/open-url-4PBLY9X0.mjs +0 -42
  73. package/dist/packem_shared/output-format-B4642rjE.mjs +0 -17
  74. package/dist/packem_shared/parseManifest-Dbp-Q2q3.mjs +0 -121
  75. package/dist/packem_shared/prompt-cancelled-APzX1Im-.mjs +0 -9
  76. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  77. package/dist/packem_shared/runAddCommand-D1hgfqFQ.mjs +0 -4
  78. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  79. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  80. package/dist/packem_shared/storage-BXU4ax4O.mjs +0 -84
  81. package/dist/packem_shared/tui-prompts-BjEN8XgP.mjs +0 -658
  82. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
  83. package/dist/packem_shared/wrangler-secrets-Coni-mER.mjs +0 -49
@@ -1,24 +1,4 @@
1
- import { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync, mkdtempSync, lstatSync, cpSync, renameSync } from 'node:fs';
2
- import { tmpdir } from 'node:os';
3
- import { detectFramework as detectFramework$1, isInteractive, LUNA_ART, LUNA_NAME, LUNA_SIGNOFF, paintAnswer, BADGES } from '@lunora/config';
4
- import { walkSync } from '@visulima/fs';
5
- import { join as join$1, dirname as dirname$1, basename, resolve, relative } from '@visulima/path';
6
- import { downloadTemplate } from 'giget';
7
- import { modify, applyEdits } from 'jsonc-parser';
8
- import { join, dirname } from 'node:path';
9
- import { d as defineHandler } from '../packem_shared/command-lYnl4QyF.mjs';
10
- import { d as detectPackageManager, a as detectInstalledManagers, i as installArgsFor, r as runScriptCommand } from '../packem_shared/detect-package-manager-v4hHpQd0.mjs';
11
- import MagicString from 'magic-string';
12
- import { Project, SyntaxKind } from 'ts-morph';
13
- import { P as PromptCancelledError } from '../packem_shared/prompt-cancelled-APzX1Im-.mjs';
14
- import { c as resolveTagVersions, d as resolveSourceRef, e as resolvePinnedSourceRef, f as resolveDistTag, r as runAddCommand } from '../packem_shared/commands-D5Yxt9VY.mjs';
15
- import { defaultSpawner } from '../packem_shared/createRecordingSpawner-WuSn20kb.mjs';
16
- import { d as tuiMascot, e as tuiStep, f as tuiMoonrise, t as tuiText, g as tuiHeadline, h as tuiInfo, a as tuiSelect, b as tuiConfirm, w as withTuiSpinner, i as tuiNextSteps, j as tuiTasks, k as tuiMultiSelect, l as withTuiBadgeProgress } from '../packem_shared/tui-prompts-BjEN8XgP.mjs';
17
- import { logStep } from '../packem_shared/createLogger-CIWSHrTL.mjs';
18
- import { E as EMAIL_ITEM, p as promptBucketName, w as withStorageBucketName, M as MAIL_DESTINATION_PROMPT, r as resolveTypedDestination, f as withMailDestination, e as promptAuthProvider, c as promptDatabaseName, g as withAuthDatabaseName } from '../packem_shared/storage-BXU4ax4O.mjs';
19
- import dns from 'node:dns/promises';
20
-
21
- const GITHUB_CONTENT = `name: Deploy
1
+ import{existsSync as h,mkdirSync as L,writeFileSync as m,readFileSync as k,readdirSync as X,rmSync as _,mkdtempSync as Y,lstatSync as $e,cpSync as W,renameSync as Me}from"node:fs";import{tmpdir as Z}from"node:os";import{detectFramework as Ce,isInteractive as g,LUNA_ART as Le,LUNA_NAME as Se,LUNA_SIGNOFF as Ae,paintAnswer as Ne,BADGES as f}from"@lunora/config";import{walkSync as _e}from"@visulima/fs";import{join as p,dirname as $,basename as S,resolve as B,relative as Ie}from"@visulima/path";import{downloadTemplate as ee}from"giget";import{modify as Re,applyEdits as Te}from"jsonc-parser";import{join as E,dirname as Oe}from"node:path";import{i as je}from"../packem_shared/command-Bjv4VmYA.mjs";import{P as te,t as Be,d as Ee,k as Pe}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import De from"magic-string";import{Project as ae,SyntaxKind as v}from"ts-morph";import{P}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{P as re,g as oe,b as ze,L as se,M as Ve}from"../packem_shared/commands-BhX2Bo9B.mjs";import{defaultSpawner as ie}from"../packem_shared/createRecordingSpawner-C8_7nffs.mjs";import{Y as Ue,h as He,M as We,C as ne,U as qe,i as le,X as ce,B as D,H as Fe,W as Ke,Q as de,I as Je,t as Qe}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{logStep as q}from"../packem_shared/createLogger--C3x1FNE.mjs";import{n as pe,u as Ge,p as Xe,b as Ye,d as Ze,l as et,g as tt,e as at,j as rt}from"../packem_shared/storage-DOvAKGi4.mjs";import ot from"node:dns/promises";const st=`name: Deploy
22
2
 
23
3
  on:
24
4
  push:
@@ -72,8 +52,7 @@ jobs:
72
52
  cache: pnpm
73
53
  - run: pnpm install --frozen-lockfile
74
54
  - run: pnpm exec lunora deploy --preview
75
- `;
76
- const GITLAB_CONTENT = `stages:
55
+ `,it=`stages:
77
56
  - deploy
78
57
 
79
58
  # Prerequisite: commit your pnpm-lock.yaml. \`pnpm install --frozen-lockfile\`
@@ -108,326 +87,16 @@ preview:
108
87
  - if: $CI_PIPELINE_SOURCE == "merge_request_event"
109
88
  script:
110
89
  - pnpm exec lunora deploy --preview
111
- `;
112
- const WORKFLOWS = {
113
- github: {
114
- content: GITHUB_CONTENT,
115
- file: join(".github", "workflows", "deploy.yml"),
116
- secretsHint: "repository secrets (Settings → Secrets and variables → Actions)"
117
- },
118
- gitlab: {
119
- content: GITLAB_CONTENT,
120
- file: ".gitlab-ci.yml",
121
- secretsHint: "masked CI/CD variables (Settings → CI/CD → Variables)"
122
- }
123
- };
124
- const isCiProvider = (value) => value === "github" || value === "gitlab";
125
- const writeCiWorkflow = (projectRoot, provider, options = {}) => {
126
- const spec = WORKFLOWS[provider];
127
- const path = join(projectRoot, spec.file);
128
- if (existsSync(path) && options.overwrite !== true) {
129
- return { path, skipped: true, written: false };
130
- }
131
- mkdirSync(dirname(path), { recursive: true });
132
- writeFileSync(path, spec.content, "utf8");
133
- return { path, skipped: false, written: true };
134
- };
135
- const scaffoldCiWorkflow = (projectRoot, provider, logger, options = {}) => {
136
- const spec = WORKFLOWS[provider];
137
- try {
138
- const result = writeCiWorkflow(projectRoot, provider, options);
139
- if (result.skipped) {
140
- logger.info(`--ci ${provider}: ${spec.file} already exists — left unchanged (re-run with overwrite to replace).`);
141
- } else {
142
- logger.success(`--ci ${provider}: wrote ${spec.file}`);
143
- logger.info(`--ci ${provider}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${spec.secretsHint} to enable deploys.`);
144
- logger.info(
145
- `--ci ${provider}: run \`pnpm install\` and commit pnpm-lock.yaml before pushing — the pipeline runs \`pnpm install --frozen-lockfile\`.`
146
- );
147
- }
148
- return result;
149
- } catch (error) {
150
- const message = error instanceof Error ? error.message : String(error);
151
- logger.warn(`--ci ${provider}: could not write ${spec.file} (${message})`);
152
- return { path: join(projectRoot, spec.file), skipped: false, written: false };
153
- }
154
- };
155
-
156
- const ADAPTER_BY_FRAMEWORK = {
157
- astro: "@lunora/react",
158
- none: "@lunora/react",
159
- nuxt: "@lunora/vue",
160
- "react-router": "@lunora/react",
161
- "solid-start": "@lunora/solid",
162
- sveltekit: "@lunora/svelte",
163
- "tanstack-start": "@lunora/react",
164
- "tanstack-start-solid": "@lunora/solid"
165
- };
166
- const detectFramework = (root) => {
167
- const base = detectFramework$1(root);
168
- return { ...base, adapter: ADAPTER_BY_FRAMEWORK[base.framework] };
169
- };
170
-
171
- const LUNORA_CALL = "lunora()";
172
- const LUNORA_IMPORT = 'import { lunora } from "@lunora/vite";';
173
- const LUNORA_CALL_RE = /\blunora\s*\(/u;
174
- const LUNORA_VITE_DOUBLE = '"@lunora/vite"';
175
- const LUNORA_VITE_SINGLE = "'@lunora/vite'";
176
- const findDefineConfigObject = (sf) => {
177
- for (const statement of sf.getStatements()) {
178
- if (statement.getKind() !== SyntaxKind.ExportAssignment) {
179
- continue;
180
- }
181
- const expr = statement.asKindOrThrow(SyntaxKind.ExportAssignment).getExpression();
182
- if (expr.getKind() !== SyntaxKind.CallExpression) {
183
- continue;
184
- }
185
- const call = expr.asKindOrThrow(SyntaxKind.CallExpression);
186
- if (call.getExpression().getText() !== "defineConfig") {
187
- continue;
188
- }
189
- const argument = call.getArguments()[0];
190
- if (argument?.getKind() === SyntaxKind.ObjectLiteralExpression) {
191
- return argument.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);
192
- }
193
- }
194
- return void 0;
195
- };
196
- const findPlainExportObject = (sf) => {
197
- for (const statement of sf.getStatements()) {
198
- if (statement.getKind() !== SyntaxKind.ExportAssignment) {
199
- continue;
200
- }
201
- const expr = statement.asKindOrThrow(SyntaxKind.ExportAssignment).getExpression();
202
- if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {
203
- return expr.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);
204
- }
205
- }
206
- return void 0;
207
- };
208
- const findConfigObject = (sourceText) => {
209
- const project = new Project({
210
- compilerOptions: { allowJs: true },
211
- useInMemoryFileSystem: true
212
- });
213
- const sf = project.createSourceFile("vite.config.ts", sourceText, { overwrite: true });
214
- return findDefineConfigObject(sf) ?? findPlainExportObject(sf);
215
- };
216
- const importInsertPosition = (sourceText) => {
217
- const project = new Project({
218
- compilerOptions: { allowJs: true },
219
- useInMemoryFileSystem: true
220
- });
221
- const sf = project.createSourceFile("vite.config.ts", sourceText, { overwrite: true });
222
- const imports = sf.getImportDeclarations();
223
- if (imports.length === 0) {
224
- return 0;
225
- }
226
- const last = imports[imports.length - 1];
227
- if (last === void 0) {
228
- return 0;
229
- }
230
- return last.getEnd();
231
- };
232
- const addImport = (ms, source) => {
233
- const insertAt = importInsertPosition(source);
234
- if (insertAt === 0) {
235
- ms.prepend(`${LUNORA_IMPORT}
236
- `);
237
- } else {
238
- ms.appendLeft(insertAt, `
239
- ${LUNORA_IMPORT}`);
240
- }
241
- };
242
- const patchPluginsArray = (ms, configObject) => {
243
- const pluginsProp = configObject.getProperty("plugins");
244
- if (pluginsProp === void 0) {
245
- const properties = configObject.getProperties();
246
- const openBrace = configObject.getStart() + 1;
247
- if (properties.length === 0) {
248
- ms.appendLeft(openBrace, ` plugins: [${LUNORA_CALL}] `);
249
- } else {
250
- const firstProp = properties[0];
251
- if (firstProp !== void 0) {
252
- ms.appendLeft(firstProp.getStart(), `plugins: [${LUNORA_CALL}],
253
- `);
254
- }
255
- }
256
- return;
257
- }
258
- const arrayLit = pluginsProp.getDescendantsOfKind(SyntaxKind.ArrayLiteralExpression)[0];
259
- if (arrayLit === void 0) {
260
- return;
261
- }
262
- const elements = arrayLit.getElements();
263
- if (elements.length === 0) {
264
- ms.appendLeft(arrayLit.getStart() + 1, LUNORA_CALL);
265
- } else {
266
- const firstElement = elements[0];
267
- if (firstElement !== void 0) {
268
- ms.appendLeft(firstElement.getStart(), `${LUNORA_CALL}, `);
269
- }
270
- }
271
- };
272
- const patchViteConfig = (source) => {
273
- if (LUNORA_CALL_RE.test(source)) {
274
- return { changed: false, code: source, reason: "lunora plugin already present" };
275
- }
276
- const configObject = findConfigObject(source);
277
- if (configObject === void 0) {
278
- return { changed: false, code: source, reason: "could not locate a Vite config plugins array to patch" };
279
- }
280
- const ms = new MagicString(source);
281
- const alreadyImported = source.includes(LUNORA_VITE_DOUBLE) || source.includes(LUNORA_VITE_SINGLE);
282
- if (alreadyImported) {
283
- patchPluginsArray(ms, configObject);
284
- } else {
285
- addImport(ms, source);
286
- patchPluginsArray(ms, configObject);
287
- }
288
- return { changed: true, code: ms.toString() };
289
- };
290
-
291
- const NETWORK_ERROR_PATTERN = /enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u;
292
- const NOT_FOUND_ERROR_PATTERN = /404|not found|could not find|no such/u;
293
- const describeDownloadFailure = (error, context) => {
294
- const raw = error instanceof Error ? error.message : String(error);
295
- const lower = raw.toLowerCase();
296
- const genericMessage = `failed to download template "${context.templateType}" from ${context.remote}: ${raw}`;
297
- if (NOT_FOUND_ERROR_PATTERN.test(lower)) {
298
- return {
299
- hints: [
300
- `Check the template name "${context.templateType}" and the ref "${context.ref}".`,
301
- "List/inspect available templates, or target a branch/tag with `--ref <branch>`."
302
- ],
303
- message: `template "${context.templateType}" not found at ${context.remote}: ${raw}`
304
- };
305
- }
306
- if (NETWORK_ERROR_PATTERN.test(lower)) {
307
- return {
308
- hints: [
309
- "You appear to be offline or unable to reach GitHub.",
310
- "To scaffold without a network, point at a local template root: `lunora init --from <dir>`."
311
- ],
312
- message: genericMessage
313
- };
314
- }
315
- return {
316
- hints: ["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],
317
- message: genericMessage
318
- };
319
- };
320
-
321
- const emitStep = async (type, message, answer) => {
322
- if (isInteractive()) {
323
- await tuiStep(BADGES[type], message, answer);
324
- return;
325
- }
326
- process.stdout.write("\n");
327
- if (answer === void 0 || answer === "") {
328
- logStep(type, message);
329
- return;
330
- }
331
- const dimmed = answer.split("\n").map((line) => paintAnswer(line)).join("\n");
332
- logStep(type, `${message}
333
- ${dimmed}`);
334
- };
335
- const emitMascot = async (logger) => {
336
- if (isInteractive()) {
337
- await tuiMascot();
338
- return;
339
- }
340
- logger.info(`
341
- ${LUNA_ART}
342
- ${LUNA_NAME}: ${LUNA_SIGNOFF}`);
343
- };
344
-
345
- const STACK_FEATURE_OPTIONS = [
346
- { description: "LLMs via Workers AI (summarize, generate, stream)", label: "AI", value: "ai" },
347
- { description: "Sign-up / sign-in (asks which provider)", label: "Authentication", value: "auth" },
348
- { description: "Snapshot + restore your Durable Object data", label: "Backups", value: "backup" },
349
- { description: "Headless browser screenshots + PDFs", label: "Browser rendering", value: "browser" },
350
- { description: "Zero Trust identity via Cloudflare Access", label: "Cloudflare Access", value: "cloudflare-access" },
351
- { description: "Scheduled jobs via Cron Triggers (@lunora/scheduler)", label: "Cron jobs", value: "crons" },
352
- { description: "Cloudflare Email Workers + a dev mail catcher", label: "Transactional email", value: "email" },
353
- { description: "OpenFeature feature flags (ctx.flags)", label: "Feature flags", value: "flags" },
354
- { description: "External Postgres/MySQL via Hyperdrive", label: "Hyperdrive", value: "hyperdrive" },
355
- { description: "Stripe-first payments (checkout, subscription, webhooks)", label: "Payments", value: "payment" },
356
- { description: "Live presence / who's-online over hibernated WebSockets", label: "Presence", value: "presence" },
357
- { description: "Async message queues (push/pull consumers)", label: "Queues", value: "queue" },
358
- { description: "Typed R2 buckets + signed URLs (@lunora/storage)", label: "File storage", value: "storage" },
359
- { description: "Durable long-running workflows (step.do, sleep, branch)", label: "Workflows", value: "workflow" }
360
- ];
361
- const STACK_FEATURE_VALUES = STACK_FEATURE_OPTIONS.map((option) => option.value);
362
- const featureItem = (feature) => feature === "email" ? EMAIL_ITEM : feature;
363
- const parseFeatureList = (raw, warn) => {
364
- const features = [];
365
- for (const part of raw.split(",").map((entry) => entry.trim()).filter(Boolean)) {
366
- if (STACK_FEATURE_VALUES.includes(part)) {
367
- if (!features.includes(part)) {
368
- features.push(part);
369
- }
370
- } else {
371
- warn(`init: unknown --add feature "${part}" — expected ${STACK_FEATURE_VALUES.join(" | ")}; skipping.`);
372
- }
373
- }
374
- return features;
375
- };
376
- const collectAuthFeature = async (deps) => {
377
- const provider = await promptAuthProvider(deps.select);
378
- const databaseName = await promptDatabaseName(deps.text, deps.projectName);
379
- return { label: "auth", names: [provider], transformManifest: (manifest) => withAuthDatabaseName(manifest, databaseName) };
380
- };
381
- const collectEmailFeature = async (deps) => {
382
- const answer = await deps.text(MAIL_DESTINATION_PROMPT, { placeholder: "you@yourdomain.com" });
383
- const destination = resolveTypedDestination(answer, (message) => {
384
- deps.logger.warn(message);
385
- });
386
- return {
387
- label: "email",
388
- names: [EMAIL_ITEM],
389
- transformManifest: destination === void 0 ? void 0 : (manifest) => withMailDestination(manifest, destination)
390
- };
391
- };
392
- const collectStorageFeature = async (deps) => {
393
- const bucketName = await promptBucketName(deps.text, deps.projectName);
394
- return { label: "storage", names: ["storage"], transformManifest: (manifest) => withStorageBucketName(manifest, bucketName) };
395
- };
396
- const FEATURE_COLLECTORS = {
397
- auth: collectAuthFeature,
398
- email: collectEmailFeature,
399
- storage: collectStorageFeature
400
- };
401
- const offerRegistryExtras = async (deps) => {
402
- if (deps.preselected !== void 0 && deps.preselected.length > 0) {
403
- await deps.applyAll(
404
- deps.preselected.map((feature) => {
405
- return { label: feature, names: [featureItem(feature)] };
406
- })
407
- );
408
- return;
409
- }
410
- if (!deps.interactive) {
411
- deps.logger.info(
412
- // eslint-disable-next-line no-secrets/no-secrets -- the pipe-separated feature list in this tip is a UI prompt, not a credential
413
- "tip: add features later with `lunora add <ai|auth|backup|browser|cloudflare-access|crons|email|flags|hyperdrive|payment|presence|queue|storage|workflow>`."
414
- );
415
- return;
416
- }
417
- const picked = await deps.multiSelect("Which features do you want to add?", STACK_FEATURE_OPTIONS, { defaults: [] });
418
- if (picked.length === 0) {
419
- return;
420
- }
421
- const plans = [];
422
- for (const feature of picked) {
423
- const collect = FEATURE_COLLECTORS[feature];
424
- plans.push(collect ? await collect(deps) : { label: feature, names: [feature] });
425
- }
426
- await deps.applyAll(plans);
427
- };
428
-
429
- const LOGO_PATH = "M 259.500 10.552 C 220.080 15.859, 182.424 32.566, 152.500 58.025 C 110.179 94.031, 85.380 137.183, 77.518 188.500 C 75.410 202.255, 74.569 225.677, 75.796 236.466 C 76.757 244.917, 76.683 245.692, 74.518 249.966 C 63.118 272.466, 53.141 303.876, 51.382 322.799 L 50.718 329.943 71.960 320.471 C 83.643 315.262, 93.326 311, 93.478 311 C 93.630 311, 96.547 316.063, 99.959 322.250 C 103.371 328.438, 107.249 334.850, 108.577 336.500 L 110.990 339.500 110.981 336 C 110.977 334.075, 111.499 324.991, 112.143 315.813 L 113.312 299.127 121.406 293.336 C 132.495 285.403, 149.593 271.554, 161 261.268 C 171.556 251.748, 189.116 235, 188.540 235 C 188.337 235, 183.069 238.648, 176.835 243.106 C 142.318 267.789, 68.537 314, 63.646 314 C 61.843 314, 72.791 281.179, 80.905 262.259 C 92.233 235.845, 107.473 212.389, 132.106 183.453 L 138.451 176 148.268 176 C 176.192 176, 197.512 187.154, 212.868 209.797 C 216.470 215.108, 217.035 216.595, 216.477 219.297 C 211.386 243.968, 202.359 274.496, 193.797 296 C 183.898 320.861, 167.147 352.101, 152.395 373.215 L 147.004 380.930 152.891 385.830 C 161.400 392.911, 165.563 396, 166.594 395.998 C 167.092 395.998, 168.772 391.641, 170.327 386.317 C 176.279 365.934, 188.422 338.749, 200.942 317.778 C 223.060 280.731, 256.432 244.369, 294.500 215.836 C 309.956 204.252, 313.937 201.603, 314.719 202.385 C 315.116 202.783, 315.449 213.096, 315.460 225.304 C 315.474 241.855, 315.021 250.405, 313.680 258.924 C 307.009 301.272, 291.175 336.677, 263.112 372 C 255.259 381.883, 227.182 410.673, 218.516 417.727 L 213.532 421.783 223.439 424.880 C 281.705 443.093, 349.165 436.018, 398.616 406.508 C 446.728 377.797, 483.322 331.466, 497.366 281.481 C 503.381 260.075, 504.480 250.741, 504.491 221 C 504.501 191.997, 503.598 184.047, 497.987 163.732 C 484.768 115.871, 452.505 72.708, 407.718 42.964 C 381.051 25.254, 352.818 14.828, 319.695 10.460 C 305.932 8.645, 273.298 8.695, 259.500 10.552";
430
- const WELCOME_CSS = `/* The welcome page is a full-bleed starter — reset the browser's default
90
+ `,ue={github:{content:st,file:E(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{content:it,file:".gitlab-ci.yml",secretsHint:"masked CI/CD variables (Settings → CI/CD → Variables)"}},nt=e=>e==="github"||e==="gitlab",lt=(e,t,a={})=>{const r=ue[t],o=E(e,r.file);return h(o)&&a.overwrite!==!0?{path:o,skipped:!0,written:!1}:(L(Oe(o),{recursive:!0}),m(o,r.content,"utf8"),{path:o,skipped:!1,written:!0})},ct=(e,t,a,r={})=>{const o=ue[t];try{const s=lt(e,t,r);return s.skipped?a.info(`--ci ${t}: ${o.file} already exists — left unchanged (re-run with overwrite to replace).`):(a.success(`--ci ${t}: wrote ${o.file}`),a.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${o.secretsHint} to enable deploys.`),a.info(`--ci ${t}: run \`pnpm install\` and commit pnpm-lock.yaml before pushing — the pipeline runs \`pnpm install --frozen-lockfile\`.`)),s}catch(s){const i=s instanceof Error?s.message:String(s);return a.warn(`--ci ${t}: could not write ${o.file} (${i})`),{path:E(e,o.file),skipped:!1,written:!1}}},dt={astro:"@lunora/react",none:"@lunora/react",nuxt:"@lunora/vue","react-router":"@lunora/react","solid-start":"@lunora/solid",sveltekit:"@lunora/svelte","tanstack-start":"@lunora/react","tanstack-start-solid":"@lunora/solid"},pt=e=>{const t=Ce(e);return{...t,adapter:dt[t.framework]}},N="lunora()",F='import { lunora } from "@lunora/vite";',ut=/\blunora\s*\(/u,ht='"@lunora/vite"',mt="'@lunora/vite'",gt=e=>{for(const t of e.getStatements()){if(t.getKind()!==v.ExportAssignment)continue;const a=t.asKindOrThrow(v.ExportAssignment).getExpression();if(a.getKind()!==v.CallExpression)continue;const r=a.asKindOrThrow(v.CallExpression);if(r.getExpression().getText()!=="defineConfig")continue;const o=r.getArguments()[0];if(o?.getKind()===v.ObjectLiteralExpression)return o.asKindOrThrow(v.ObjectLiteralExpression)}},vt=e=>{for(const t of e.getStatements()){if(t.getKind()!==v.ExportAssignment)continue;const a=t.asKindOrThrow(v.ExportAssignment).getExpression();if(a.getKind()===v.ObjectLiteralExpression)return a.asKindOrThrow(v.ObjectLiteralExpression)}},ft=e=>{const t=new ae({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0});return gt(t)??vt(t)},wt=e=>{const t=new ae({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}).getImportDeclarations();if(t.length===0)return 0;const a=t[t.length-1];return a===void 0?0:a.getEnd()},yt=(e,t)=>{const a=wt(t);a===0?e.prepend(`${F}
91
+ `):e.appendLeft(a,`
92
+ ${F}`)},bt=(e,t)=>{const a=t.getProperty("plugins");if(a===void 0){const s=t.getProperties(),i=t.getStart()+1;if(s.length===0)e.appendLeft(i,` plugins: [${N}] `);else{const n=s[0];n!==void 0&&e.appendLeft(n.getStart(),`plugins: [${N}],
93
+ `)}return}const r=a.getDescendantsOfKind(v.ArrayLiteralExpression)[0];if(r===void 0)return;const o=r.getElements();if(o.length===0)e.appendLeft(r.getStart()+1,N);else{const s=o[0];s!==void 0&&e.appendLeft(s.getStart(),`${N}, `)}},he=e=>{if(ut.test(e))return{changed:!1,code:e,reason:"lunora plugin already present"};const t=ft(e);if(t===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const a=new De(e);return e.includes(ht)||e.includes(mt)||yt(a,e),bt(a,t),{changed:!0,code:a.toString()}},xt=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,kt=/404|not found|could not find|no such/u,$t=(e,t)=>{const a=e instanceof Error?e.message:String(e),r=a.toLowerCase(),o=`failed to download template "${t.templateType}" from ${t.remote}: ${a}`;return kt.test(r)?{hints:[`Check the template name "${t.templateType}" and the ref "${t.ref}".`,"List/inspect available templates, or target a branch/tag with `--ref <branch>`."],message:`template "${t.templateType}" not found at ${t.remote}: ${a}`}:xt.test(r)?{hints:["You appear to be offline or unable to reach GitHub.","To scaffold without a network, point at a local template root: `lunora init --from <dir>`."],message:o}:{hints:["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],message:o}},I=async(e,t,a)=>{if(g()){await He(f[e],t,a);return}if(process.stdout.write(`
94
+ `),a===void 0||a===""){q(e,t);return}const r=a.split(`
95
+ `).map(o=>Ne(o)).join(`
96
+ `);q(e,`${t}
97
+ ${r}`)},Mt=async e=>{if(g()){await Ue();return}e.info(`
98
+ ${Le}
99
+ ${Se}: ${Ae}`)},me=[{description:"LLMs via Workers AI (summarize, generate, stream)",label:"AI",value:"ai"},{description:"Sign-up / sign-in (asks which provider)",label:"Authentication",value:"auth"},{description:"Snapshot + restore your Durable Object data",label:"Backups",value:"backup"},{description:"Headless browser screenshots + PDFs",label:"Browser rendering",value:"browser"},{description:"Zero Trust identity via Cloudflare Access",label:"Cloudflare Access",value:"cloudflare-access"},{description:"Scheduled jobs via Cron Triggers (@lunora/scheduler)",label:"Cron jobs",value:"crons"},{description:"Cloudflare Email Workers + a dev mail catcher",label:"Transactional email",value:"email"},{description:"OpenFeature feature flags (ctx.flags)",label:"Feature flags",value:"flags"},{description:"External Postgres/MySQL via Hyperdrive",label:"Hyperdrive",value:"hyperdrive"},{description:"Stripe-first payments (checkout, subscription, webhooks)",label:"Payments",value:"payment"},{description:"Live presence / who's-online over hibernated WebSockets",label:"Presence",value:"presence"},{description:"Async message queues (push/pull consumers)",label:"Queues",value:"queue"},{description:"Typed R2 buckets + signed URLs (@lunora/storage)",label:"File storage",value:"storage"},{description:"Durable long-running workflows (step.do, sleep, branch)",label:"Workflows",value:"workflow"}],K=me.map(e=>e.value),Ct=e=>e==="email"?pe:e,Lt=(e,t)=>{const a=[];for(const r of e.split(",").map(o=>o.trim()).filter(Boolean))K.includes(r)?a.includes(r)||a.push(r):t(`init: unknown --add feature "${r}" — expected ${K.join(" | ")}; skipping.`);return a},St=async e=>{const t=await tt(e.select),a=await at(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:r=>rt(r,a)}},At=async e=>{const t=await e.text(Ye,{placeholder:"you@yourdomain.com"}),a=Ze(t,r=>{e.logger.warn(r)});return{label:"email",names:[pe],transformManifest:a===void 0?void 0:r=>et(r,a)}},Nt=async e=>{const t=await Ge(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:a=>Xe(a,t)}},_t={auth:St,email:At,storage:Nt},J=async e=>{if(e.preselected!==void 0&&e.preselected.length>0){await e.applyAll(e.preselected.map(r=>({label:r,names:[Ct(r)]})));return}if(!e.interactive){e.logger.info("tip: add features later with `lunora add <ai|auth|backup|browser|cloudflare-access|crons|email|flags|hyperdrive|payment|presence|queue|storage|workflow>`.");return}const t=await e.multiSelect("Which features do you want to add?",me,{defaults:[]});if(t.length===0)return;const a=[];for(const r of t){const o=_t[r];a.push(o?await o(e):{label:r,names:[r]})}await e.applyAll(a)},A="M 259.500 10.552 C 220.080 15.859, 182.424 32.566, 152.500 58.025 C 110.179 94.031, 85.380 137.183, 77.518 188.500 C 75.410 202.255, 74.569 225.677, 75.796 236.466 C 76.757 244.917, 76.683 245.692, 74.518 249.966 C 63.118 272.466, 53.141 303.876, 51.382 322.799 L 50.718 329.943 71.960 320.471 C 83.643 315.262, 93.326 311, 93.478 311 C 93.630 311, 96.547 316.063, 99.959 322.250 C 103.371 328.438, 107.249 334.850, 108.577 336.500 L 110.990 339.500 110.981 336 C 110.977 334.075, 111.499 324.991, 112.143 315.813 L 113.312 299.127 121.406 293.336 C 132.495 285.403, 149.593 271.554, 161 261.268 C 171.556 251.748, 189.116 235, 188.540 235 C 188.337 235, 183.069 238.648, 176.835 243.106 C 142.318 267.789, 68.537 314, 63.646 314 C 61.843 314, 72.791 281.179, 80.905 262.259 C 92.233 235.845, 107.473 212.389, 132.106 183.453 L 138.451 176 148.268 176 C 176.192 176, 197.512 187.154, 212.868 209.797 C 216.470 215.108, 217.035 216.595, 216.477 219.297 C 211.386 243.968, 202.359 274.496, 193.797 296 C 183.898 320.861, 167.147 352.101, 152.395 373.215 L 147.004 380.930 152.891 385.830 C 161.400 392.911, 165.563 396, 166.594 395.998 C 167.092 395.998, 168.772 391.641, 170.327 386.317 C 176.279 365.934, 188.422 338.749, 200.942 317.778 C 223.060 280.731, 256.432 244.369, 294.500 215.836 C 309.956 204.252, 313.937 201.603, 314.719 202.385 C 315.116 202.783, 315.449 213.096, 315.460 225.304 C 315.474 241.855, 315.021 250.405, 313.680 258.924 C 307.009 301.272, 291.175 336.677, 263.112 372 C 255.259 381.883, 227.182 410.673, 218.516 417.727 L 213.532 421.783 223.439 424.880 C 281.705 443.093, 349.165 436.018, 398.616 406.508 C 446.728 377.797, 483.322 331.466, 497.366 281.481 C 503.381 260.075, 504.480 250.741, 504.491 221 C 504.501 191.997, 503.598 184.047, 497.987 163.732 C 484.768 115.871, 452.505 72.708, 407.718 42.964 C 381.051 25.254, 352.818 14.828, 319.695 10.460 C 305.932 8.645, 273.298 8.695, 259.500 10.552",C=`/* The welcome page is a full-bleed starter — reset the browser's default
431
100
  body margin/padding so it sits flush; everything else is scoped under
432
101
  .lunora-welcome (collision-safe). */
433
102
  body {
@@ -532,8 +201,7 @@ body {
532
201
  .lunora-welcome .lw-foot { text-align: center; padding-top: 26px; font-family: var(--mono); font-size: 11px; letter-spacing: .1em; text-transform: uppercase; color: var(--t-faint); }
533
202
 
534
203
  @media (prefers-reduced-motion: reduce) { .lunora-welcome * { transition: none !important; } }
535
- `;
536
- const REACT_APP = `import { useEffect, useState } from "react";
204
+ `,It=`import { useEffect, useState } from "react";
537
205
 
538
206
  type Theme = "dark" | "light";
539
207
 
@@ -575,7 +243,7 @@ export default function App() {
575
243
  <div className="lw-wrap">
576
244
  <div className="brand">
577
245
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
578
- <path d="${LOGO_PATH}" fill="currentColor" fillRule="evenodd" />
246
+ <path d="${A}" fill="currentColor" fillRule="evenodd" />
579
247
  </svg>
580
248
  <span className="word">Lunora</span>
581
249
  </div>
@@ -694,8 +362,7 @@ export default function App() {
694
362
  </div>
695
363
  );
696
364
  }
697
- `;
698
- const VUE_APP = `<script setup lang="ts">
365
+ `,Rt=`<script setup lang="ts">
699
366
  import { onMounted, ref } from "vue";
700
367
 
701
368
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -735,7 +402,7 @@ const toggle = (): void => {
735
402
  <div class="lw-wrap">
736
403
  <div class="brand">
737
404
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
738
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
405
+ <path d="${A}" fill="currentColor" fill-rule="evenodd" />
739
406
  </svg>
740
407
  <span class="word">Lunora</span>
741
408
  </div>
@@ -851,8 +518,7 @@ const toggle = (): void => {
851
518
  </div>
852
519
  </div>
853
520
  </template>
854
- `;
855
- const SOLID_APP = `import { createSignal, onMount } from "solid-js";
521
+ `,Tt=`import { createSignal, onMount } from "solid-js";
856
522
 
857
523
  export default function App() {
858
524
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -892,7 +558,7 @@ export default function App() {
892
558
  <div class="lw-wrap">
893
559
  <div class="brand">
894
560
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
895
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
561
+ <path d="${A}" fill="currentColor" fill-rule="evenodd" />
896
562
  </svg>
897
563
  <span class="word">Lunora</span>
898
564
  </div>
@@ -1011,8 +677,7 @@ export default function App() {
1011
677
  </div>
1012
678
  );
1013
679
  }
1014
- `;
1015
- const SVELTE_APP = `<script lang="ts">
680
+ `,Ot=`<script lang="ts">
1016
681
  import { onMount } from "svelte";
1017
682
 
1018
683
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -1055,7 +720,7 @@ const SVELTE_APP = `<script lang="ts">
1055
720
  <div class="lw-wrap">
1056
721
  <div class="brand">
1057
722
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
1058
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
723
+ <path d="${A}" fill="currentColor" fill-rule="evenodd" />
1059
724
  </svg>
1060
725
  <span class="word">Lunora</span>
1061
726
  </div>
@@ -1170,8 +835,7 @@ const SVELTE_APP = `<script lang="ts">
1170
835
  <div class="lw-foot">Running on Lunora · Vite + Svelte</div>
1171
836
  </div>
1172
837
  </div>
1173
- `;
1174
- const VANILLA_MAIN = `import "./style.css";
838
+ `,jt=`import "./style.css";
1175
839
 
1176
840
  import { LunoraClient } from "lunorash/client";
1177
841
 
@@ -1199,7 +863,7 @@ const welcomeHtml = \`
1199
863
  <div class="lw-wrap">
1200
864
  <div class="brand">
1201
865
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
1202
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
866
+ <path d="${A}" fill="currentColor" fill-rule="evenodd" />
1203
867
  </svg>
1204
868
  <span class="word">Lunora</span>
1205
869
  </div>
@@ -1338,10 +1002,7 @@ const count = document.querySelector<HTMLSpanElement>("#lw-count")!;
1338
1002
  client.onUpdate(api.messages.list, { channelId: "channel:demo" }, (result) => {
1339
1003
  count.textContent = String(result.messages.length);
1340
1004
  });
1341
- `;
1342
-
1343
- const READ_URL = `const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;`;
1344
- const REACT_MAIN = `import "./index.css";
1005
+ `,R="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",Bt=`import "./index.css";
1345
1006
 
1346
1007
  import { LunoraProvider } from "@lunora/react";
1347
1008
  import { LunoraClient } from "lunorash/client";
@@ -1353,7 +1014,7 @@ import App from "./App.tsx";
1353
1014
  // \`@lunora/vite\` runs the Worker on the same origin as Vite, so default to
1354
1015
  // \`location.origin\`. Point \`VITE_LUNORA_URL\` at a deployed Worker to develop
1355
1016
  // the client against production data.
1356
- ${READ_URL}
1017
+ ${R}
1357
1018
  const client = new LunoraClient({ url });
1358
1019
 
1359
1020
  const root = document.getElementById("root");
@@ -1369,8 +1030,7 @@ createRoot(root).render(
1369
1030
  </LunoraProvider>
1370
1031
  </StrictMode>,
1371
1032
  );
1372
- `;
1373
- const VUE_MAIN = `import "./style.css";
1033
+ `,Et=`import "./style.css";
1374
1034
 
1375
1035
  import { createLunora } from "@lunora/vue";
1376
1036
  import { LunoraClient } from "lunorash/client";
@@ -1379,10 +1039,9 @@ import { createApp } from "vue";
1379
1039
  import App from "./App.vue";
1380
1040
 
1381
1041
  // Provide one LunoraClient at the app root via the Vue plugin form.
1382
- ${READ_URL}
1042
+ ${R}
1383
1043
  createApp(App).use(createLunora(new LunoraClient({ url }))).mount("#app");
1384
- `;
1385
- const SOLID_INDEX = `import "./index.css";
1044
+ `,Pt=`import "./index.css";
1386
1045
 
1387
1046
  import { LunoraContext } from "@lunora/solid";
1388
1047
  import { LunoraClient } from "lunorash/client";
@@ -1390,7 +1049,7 @@ import { render } from "solid-js/web";
1390
1049
 
1391
1050
  import App from "./App";
1392
1051
 
1393
- ${READ_URL}
1052
+ ${R}
1394
1053
  const client = new LunoraClient({ url });
1395
1054
  const root = document.getElementById("root");
1396
1055
 
@@ -1402,20 +1061,18 @@ render(
1402
1061
  ),
1403
1062
  root!,
1404
1063
  );
1405
- `;
1406
- const SVELTE_ROOT = `<script lang="ts">
1064
+ `,Dt=`<script lang="ts">
1407
1065
  import { setLunoraClient } from "@lunora/svelte";
1408
1066
  import { LunoraClient } from "lunorash/client";
1409
1067
 
1410
1068
  import App from "./App.svelte";
1411
1069
 
1412
- ${READ_URL}
1070
+ ${R}
1413
1071
  setLunoraClient(new LunoraClient({ url }));
1414
1072
  <\/script>
1415
1073
 
1416
1074
  <App />
1417
- `;
1418
- const SVELTE_MAIN = `import "./app.css";
1075
+ `,zt=`import "./app.css";
1419
1076
 
1420
1077
  import { mount } from "svelte";
1421
1078
 
@@ -1425,62 +1082,7 @@ import Root from "./Root.svelte";
1425
1082
  const app = mount(Root, { target: document.getElementById("app")! });
1426
1083
 
1427
1084
  export default app;
1428
- `;
1429
- const ADAPTERS = {
1430
- react: {
1431
- adapter: "@lunora/react",
1432
- createViteTemplate: "react-ts",
1433
- files: [
1434
- { contents: REACT_MAIN, path: "src/main.tsx" },
1435
- { contents: REACT_APP, path: "src/App.tsx" },
1436
- { contents: WELCOME_CSS, path: "src/index.css" }
1437
- ],
1438
- label: "React"
1439
- },
1440
- solid: {
1441
- adapter: "@lunora/solid",
1442
- createViteTemplate: "solid-ts",
1443
- files: [
1444
- { contents: SOLID_INDEX, path: "src/index.tsx" },
1445
- { contents: SOLID_APP, path: "src/App.tsx" },
1446
- { contents: WELCOME_CSS, path: "src/index.css" }
1447
- ],
1448
- label: "Solid"
1449
- },
1450
- svelte: {
1451
- adapter: "@lunora/svelte",
1452
- createViteTemplate: "svelte-ts",
1453
- files: [
1454
- { contents: SVELTE_ROOT, path: "src/Root.svelte" },
1455
- { contents: SVELTE_MAIN, path: "src/main.ts" },
1456
- { contents: SVELTE_APP, path: "src/App.svelte" },
1457
- { contents: WELCOME_CSS, path: "src/app.css" }
1458
- ],
1459
- label: "Svelte"
1460
- },
1461
- vanilla: {
1462
- adapter: "lunorash/client",
1463
- createViteTemplate: "vanilla-ts",
1464
- files: [
1465
- { contents: VANILLA_MAIN, path: "src/main.ts" },
1466
- { contents: WELCOME_CSS, path: "src/style.css" }
1467
- ],
1468
- label: "Vanilla"
1469
- },
1470
- vue: {
1471
- adapter: "@lunora/vue",
1472
- createViteTemplate: "vue-ts",
1473
- files: [
1474
- { contents: VUE_MAIN, path: "src/main.ts" },
1475
- { contents: VUE_APP, path: "src/App.vue" },
1476
- { contents: WELCOME_CSS, path: "src/style.css" }
1477
- ],
1478
- label: "Vue"
1479
- }
1480
- };
1481
- const isOverlayFramework = (value) => Object.hasOwn(ADAPTERS, value);
1482
-
1483
- const RATELIMIT_SCHEMA = `import type { Middleware } from "lunorash/server";
1085
+ `,T={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:Bt,path:"src/main.tsx"},{contents:It,path:"src/App.tsx"},{contents:C,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:Pt,path:"src/index.tsx"},{contents:Tt,path:"src/App.tsx"},{contents:C,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:Dt,path:"src/Root.svelte"},{contents:zt,path:"src/main.ts"},{contents:Ot,path:"src/App.svelte"},{contents:C,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:jt,path:"src/main.ts"},{contents:C,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:Et,path:"src/main.ts"},{contents:Rt,path:"src/App.vue"},{contents:C,path:"src/style.css"}],label:"Vue"}},z=e=>Object.hasOwn(T,e),Vt=`import type { Middleware } from "lunorash/server";
1484
1086
  import { defineSchemaExtension, defineTable, definePlugin, v } from "lunorash/server";
1485
1087
  import { createDbStore, RateLimiter } from "lunorash/ratelimit";
1486
1088
  import type { RateLimitConfigMap } from "lunorash/ratelimit";
@@ -1520,8 +1122,7 @@ export const ratelimit = definePlugin("ratelimit", {
1520
1122
  }),
1521
1123
  middleware,
1522
1124
  });
1523
- `;
1524
- const LUNORA_SCHEMA = `import { ratelimit } from "./ratelimit/schema.js";
1125
+ `,Ut=`import { ratelimit } from "./ratelimit/schema.js";
1525
1126
  import { defineSchema, defineTable, v } from "lunorash/server";
1526
1127
 
1527
1128
  export default defineSchema({
@@ -1532,8 +1133,7 @@ export default defineSchema({
1532
1133
  .shardBy("channelId")
1533
1134
  .index("by_channel", ["channelId"]),
1534
1135
  }).extend(ratelimit.extension);
1535
- `;
1536
- const LUNORA_MESSAGES = `import { RateLimiter, rateLimit, createDbStore } from "lunorash/ratelimit";
1136
+ `,Ht=`import { RateLimiter, rateLimit, createDbStore } from "lunorash/ratelimit";
1537
1137
 
1538
1138
  import { mutation, query, v } from "#lunora/_generated/server.js";
1539
1139
 
@@ -1561,8 +1161,7 @@ export const send = mutation
1561
1161
 
1562
1162
  return { channelId: args.channelId, id, text: args.text };
1563
1163
  });
1564
- `;
1565
- const SERVER_ENTRY = `import type { ShardNamespaceLike } from "lunorash/runtime";
1164
+ `,Wt=`import type { ShardNamespaceLike } from "lunorash/runtime";
1566
1165
 
1567
1166
  import { defineApp } from "../lunora/_generated/app.js";
1568
1167
 
@@ -1576,8 +1175,7 @@ const app = defineApp<Env>()
1576
1175
 
1577
1176
  export const ShardDO = app.ShardDO;
1578
1177
  export default app;
1579
- `;
1580
- const WRANGLER = `{
1178
+ `,qt=`{
1581
1179
  "$schema": "node_modules/wrangler/config-schema.json",
1582
1180
  "name": "__NAME__",
1583
1181
  "main": "src/server.ts",
@@ -1589,207 +1187,23 @@ const WRANGLER = `{
1589
1187
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ShardDO"] }],
1590
1188
  "observability": { "enabled": true, "head_sampling_rate": 1 },
1591
1189
  }
1592
- `;
1593
- const GITIGNORE_ADDITIONS = [".wrangler", ".env", ".env.*", "!.env.example", ".lunora/", ".lunora-cache", "lunora/_generated"];
1594
- const ENV_EXAMPLE = `# Lunora endpoint for the browser client.
1190
+ `,Ft=[".wrangler",".env",".env.*","!.env.example",".lunora/",".lunora-cache","lunora/_generated"],Kt=`# Lunora endpoint for the browser client.
1595
1191
  # Vite statically replaces \`import.meta.env.VITE_LUNORA_URL\` at \`vite dev\` / build.
1596
1192
  # Leave it unset to use the page origin; set it to point at a deployed Worker:
1597
1193
  #
1598
1194
  # VITE_LUNORA_URL=https://my-app.example.workers.dev
1599
- `;
1600
- const COMMON_DEV_DEPENDENCIES = {
1601
- "@cloudflare/workers-types": "^4.20260611.1",
1602
- wrangler: "^4.100.0"
1603
- };
1604
- const writeFile = (target, relativePath, contents, written) => {
1605
- const destination = join$1(target, relativePath);
1606
- mkdirSync(dirname$1(destination), { recursive: true });
1607
- writeFileSync(destination, contents, "utf8");
1608
- written.push(destination);
1609
- };
1610
- const NEWLINE = /\r?\n/;
1611
- const ensureGitignore = (target) => {
1612
- const path = join$1(target, ".gitignore");
1613
- const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
1614
- const missing = GITIGNORE_ADDITIONS.filter((entry) => !existing.split(NEWLINE).includes(entry));
1615
- if (missing.length === 0) {
1616
- return;
1617
- }
1618
- const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
1619
- writeFileSync(path, `${existing}${prefix}
1195
+ `,Jt={"@cloudflare/workers-types":"^4.20260611.1",wrangler:"^4.100.0"},b=(e,t,a,r)=>{const o=p(e,t);L($(o),{recursive:!0}),m(o,a,"utf8"),r.push(o)},Qt=/\r?\n/,Gt=e=>{const t=p(e,".gitignore"),a=h(t)?k(t,"utf8"):"",r=Ft.filter(s=>!a.split(Qt).includes(s));if(r.length===0)return;const o=a.length>0&&!a.endsWith(`
1196
+ `)?`
1197
+ `:"";m(t,`${a}${o}
1620
1198
  # Lunora
1621
- ${missing.join("\n")}
1622
- `, "utf8");
1623
- };
1624
- const isLunoraDep$1 = (name) => name === "lunorash" || name.startsWith("@lunora/");
1625
- const stampRange = (name, range, distTag, versions) => isLunoraDep$1(name) ? versions?.get(name) ?? distTag : range;
1626
- const withDependency = (map, name, range, distTag) => {
1627
- return { ...map, [name]: stampRange(name, range, distTag) };
1628
- };
1629
- const restampLunora = (map, distTag, versions) => Object.fromEntries(Object.entries(map).map(([name, range]) => [name, stampRange(name, range, distTag, versions)]));
1630
- const patchPackageJson = async (target, name, adapter, distTag) => {
1631
- const path = join$1(target, "package.json");
1632
- const parsed = JSON.parse(readFileSync(path, "utf8"));
1633
- let dependencies = withDependency(parsed.dependencies ?? {}, "lunorash", distTag, distTag);
1634
- dependencies = withDependency(dependencies, "@lunora/ratelimit", distTag, distTag);
1635
- if (adapter.adapter.startsWith("@lunora/")) {
1636
- dependencies = withDependency(dependencies, adapter.adapter, distTag, distTag);
1637
- }
1638
- for (const [depName, range] of Object.entries(adapter.extraDependencies ?? {})) {
1639
- dependencies = withDependency(dependencies, depName, range, distTag);
1640
- }
1641
- let devDependencies = withDependency(parsed.devDependencies ?? {}, "@lunora/vite", distTag, distTag);
1642
- devDependencies = withDependency(devDependencies, "@lunora/studio", distTag, distTag);
1643
- for (const [depName, range] of Object.entries(COMMON_DEV_DEPENDENCIES)) {
1644
- devDependencies = withDependency(devDependencies, depName, range, distTag);
1645
- }
1646
- const lunoraNames = [...Object.keys(dependencies), ...Object.keys(devDependencies)].filter((depName) => isLunoraDep$1(depName));
1647
- const versions = await resolveTagVersions(lunoraNames, distTag);
1648
- parsed.name = name;
1649
- parsed.imports = { ...parsed.imports, "#lunora/*": "./lunora/*" };
1650
- parsed.dependencies = restampLunora(dependencies, distTag, versions);
1651
- parsed.devDependencies = restampLunora(devDependencies, distTag, versions);
1652
- parsed.scripts = { ...parsed.scripts, codegen: "lunora codegen", deploy: "vite build && lunora deploy" };
1653
- writeFileSync(path, `${JSON.stringify(parsed, void 0, 4)}
1654
- `, "utf8");
1655
- };
1656
- const patchBaseViteConfig = (target, logger) => {
1657
- const candidate = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"].map((file) => join$1(target, file)).find((path) => existsSync(path));
1658
- if (candidate === void 0) {
1659
- logger.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");
1660
- return;
1661
- }
1662
- const result = patchViteConfig(readFileSync(candidate, "utf8"));
1663
- if (result.changed) {
1664
- writeFileSync(candidate, result.code, "utf8");
1665
- }
1666
- };
1667
- const applyLunoraOverlay = async (options) => {
1668
- const { adapter, distTag, logger, name, target } = options;
1669
- const written = [];
1670
- writeFile(target, join$1("lunora", "ratelimit", "schema.ts"), RATELIMIT_SCHEMA, written);
1671
- writeFile(target, join$1("lunora", "schema.ts"), LUNORA_SCHEMA, written);
1672
- writeFile(target, join$1("lunora", "messages.ts"), LUNORA_MESSAGES, written);
1673
- writeFile(target, join$1("src", "server.ts"), SERVER_ENTRY, written);
1674
- writeFile(target, "wrangler.jsonc", WRANGLER.replaceAll("__NAME__", name), written);
1675
- writeFile(target, ".env.example", ENV_EXAMPLE, written);
1676
- for (const file of adapter.files) {
1677
- writeFile(target, file.path, file.contents, written);
1678
- }
1679
- patchBaseViteConfig(target, logger);
1680
- await patchPackageJson(target, name, adapter, distTag);
1681
- ensureGitignore(target);
1682
- return written;
1683
- };
1684
-
1685
- const ADJECTIVES = [
1686
- "lunar",
1687
- "silver",
1688
- "silent",
1689
- "waning",
1690
- "waxing",
1691
- "crescent",
1692
- "cosmic",
1693
- "stellar",
1694
- "orbital",
1695
- "gibbous",
1696
- "twilight",
1697
- "midnight",
1698
- "shimmering",
1699
- "drifting",
1700
- "weightless"
1701
- ];
1702
- const NOUNS = [
1703
- "moon",
1704
- "tide",
1705
- "crater",
1706
- "comet",
1707
- "eclipse",
1708
- "halo",
1709
- "orbit",
1710
- "nebula",
1711
- "voyager",
1712
- "lander",
1713
- "rover",
1714
- "beacon",
1715
- "harbor",
1716
- "meadow",
1717
- "fox"
1718
- ];
1719
- const pick = (items) => (
1720
- // eslint-disable-next-line sonarjs/pseudo-random -- cosmetic default project name, not a security decision.
1721
- items[Math.floor(Math.random() * items.length)]
1722
- );
1723
- const generateProjectName = () => `${pick(ADJECTIVES)}-${pick(NOUNS)}`;
1724
-
1725
- const isOnline = async () => dns.lookup("github.com").then(
1726
- () => true,
1727
- () => false
1728
- );
1729
- const GITHUB_SOURCE = /^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/;
1730
- const parseGitHubSource = (source) => {
1731
- const match = GITHUB_SOURCE.exec(source);
1732
- if (match === null) {
1733
- return void 0;
1734
- }
1735
- const [, owner, repo, ref] = match;
1736
- if (owner === void 0 || repo === void 0) {
1737
- return void 0;
1738
- }
1739
- return { owner, ref: ref ?? "HEAD", repo };
1740
- };
1741
- const templateRefExists = async (source) => {
1742
- const parsed = parseGitHubSource(source);
1743
- if (parsed === void 0) {
1744
- return void 0;
1745
- }
1746
- const url = `https://codeload.github.com/${parsed.owner}/${parsed.repo}/tar.gz/${parsed.ref}`;
1747
- try {
1748
- const response = await fetch(url, { method: "HEAD" });
1749
- if (response.status === 404) {
1750
- return false;
1751
- }
1752
- return response.ok ? true : void 0;
1753
- } catch {
1754
- return void 0;
1755
- }
1756
- };
1757
- const verifyRemoteTemplate = async (params) => {
1758
- if (params.isLocal) {
1759
- return true;
1760
- }
1761
- const isGitHubBacked = params.source === void 0 || parseGitHubSource(params.source) !== void 0;
1762
- if (!isGitHubBacked) {
1763
- return true;
1764
- }
1765
- if (!await isOnline()) {
1766
- params.logger.error("you appear to be offline — connect to the internet and try again, or scaffold from a local template with `--from <dir>`.");
1767
- return false;
1768
- }
1769
- if (params.source !== void 0 && await templateRefExists(params.source) === false) {
1770
- params.logger.error(`template source not found: ${params.source} — double-check --ref / --source, or browse the templates at https://lunora.sh/docs.`);
1771
- return false;
1772
- }
1773
- return true;
1774
- };
1775
-
1776
- const COPY = {
1777
- extras: "Let's finish setting up your app.",
1778
- framework: "Which framework should we launch?",
1779
- git: "Initialize a new git repository? (optional)",
1780
- install: "Install dependencies now?",
1781
- name: "Where should we land your project?",
1782
- nextHeader: "Liftoff confirmed — explore your project!",
1783
- packageManager: "Which package manager?"
1784
- };
1785
- const TEXT_EXTENSIONS = /* @__PURE__ */ new Set([".gitignore", ".html", ".js", ".json", ".jsonc", ".md", ".mjs", ".ts", ".tsx"]);
1786
- const VITE_CONFIG_CANDIDATES = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"];
1787
- const MINIMAL_VITE_CONFIG = `import { defineConfig } from "vite";
1199
+ ${r.join(`
1200
+ `)}
1201
+ `,"utf8")},ge=e=>e==="lunorash"||e.startsWith("@lunora/"),ve=(e,t,a,r)=>ge(e)?r?.get(e)??a:t,x=(e,t,a,r)=>({...e,[t]:ve(t,a,r)}),Q=(e,t,a)=>Object.fromEntries(Object.entries(e).map(([r,o])=>[r,ve(r,o,t,a)])),Xt=async(e,t,a,r)=>{const o=p(e,"package.json"),s=JSON.parse(k(o,"utf8"));let i=x(s.dependencies??{},"lunorash",r,r);i=x(i,"@lunora/ratelimit",r,r),a.adapter.startsWith("@lunora/")&&(i=x(i,a.adapter,r,r));for(const[u,l]of Object.entries(a.extraDependencies??{}))i=x(i,u,l,r);let n=x(s.devDependencies??{},"@lunora/vite",r,r);n=x(n,"@lunora/studio",r,r);for(const[u,l]of Object.entries(Jt))n=x(n,u,l,r);const c=[...Object.keys(i),...Object.keys(n)].filter(u=>ge(u)),d=await re(c,r);s.name=t,s.imports={...s.imports,"#lunora/*":"./lunora/*"},s.dependencies=Q(i,r,d),s.devDependencies=Q(n,r,d),s.scripts={...s.scripts,codegen:"lunora codegen",deploy:"vite build && lunora deploy"},m(o,`${JSON.stringify(s,void 0,4)}
1202
+ `,"utf8")},Yt=(e,t)=>{const a=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"].map(o=>p(e,o)).find(o=>h(o));if(a===void 0){t.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");return}const r=he(k(a,"utf8"));r.changed&&m(a,r.code,"utf8")},Zt=async e=>{const{adapter:t,distTag:a,logger:r,name:o,target:s}=e,i=[];b(s,p("lunora","ratelimit","schema.ts"),Vt,i),b(s,p("lunora","schema.ts"),Ut,i),b(s,p("lunora","messages.ts"),Ht,i),b(s,p("src","server.ts"),Wt,i),b(s,"wrangler.jsonc",qt.replaceAll("__NAME__",o),i),b(s,".env.example",Kt,i);for(const n of t.files)b(s,n.path,n.contents,i);return Yt(s,r),await Xt(s,o,t,a),Gt(s),i},ea=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],ta=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],G=e=>e[Math.floor(Math.random()*e.length)],aa=()=>`${G(ea)}-${G(ta)}`,ra=async()=>ot.lookup("github.com").then(()=>!0,()=>!1),oa=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,fe=e=>{const t=oa.exec(e);if(t===null)return;const[,a,r,o]=t;if(!(a===void 0||r===void 0))return{owner:a,ref:o??"HEAD",repo:r}},sa=async e=>{const t=fe(e);if(t===void 0)return;const a=`https://codeload.github.com/${t.owner}/${t.repo}/tar.gz/${t.ref}`;try{const r=await fetch(a,{method:"HEAD"});return r.status===404?!1:r.ok?!0:void 0}catch{return}},we=async e=>e.isLocal||!(e.source===void 0||fe(e.source)!==void 0)?!0:await ra()?e.source!==void 0&&await sa(e.source)===!1?(e.logger.error(`template source not found: ${e.source} — double-check --ref / --source, or browse the templates at https://lunora.sh/docs.`),!1):!0:(e.logger.error("you appear to be offline — connect to the internet and try again, or scaffold from a local template with `--from <dir>`."),!1),y={extras:"Let's finish setting up your app.",framework:"Which framework should we launch?",git:"Initialize a new git repository? (optional)",install:"Install dependencies now?",name:"Where should we land your project?",nextHeader:"Liftoff confirmed — explore your project!",packageManager:"Which package manager?"},ia=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),na=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],la=`import { defineConfig } from "vite";
1788
1203
  import { lunora } from "@lunora/vite";
1789
1204
 
1790
1205
  export default defineConfig({ plugins: [lunora()] });
1791
- `;
1792
- const SAMPLE_SCHEMA = `import { defineSchema, defineTable, v } from "@lunora/server";
1206
+ `,ca=`import { defineSchema, defineTable, v } from "@lunora/server";
1793
1207
 
1794
1208
  export default defineSchema({
1795
1209
  messages: defineTable({
@@ -1799,8 +1213,7 @@ export default defineSchema({
1799
1213
  .shardBy("channelId")
1800
1214
  .index("by_channel", ["channelId"]),
1801
1215
  });
1802
- `;
1803
- const SAMPLE_FUNCTION = `import { mutation, query, v } from "./_generated/server";
1216
+ `,da=`import { mutation, query, v } from "./_generated/server";
1804
1217
 
1805
1218
  export const list = query
1806
1219
  .input({ channelId: v.id("channels"), limit: v.optional(v.number()) })
@@ -1813,781 +1226,8 @@ export const send = mutation
1813
1226
  .mutation(async ({ args }) => {
1814
1227
  return { channelId: args.channelId, text: args.text };
1815
1228
  });
1816
- `;
1817
- const DEFAULT_SOURCE_BASE = "gh:anolilab/lunora/templates";
1818
- const isTextFile = (filePath) => {
1819
- const lastDot = filePath.lastIndexOf(".");
1820
- if (lastDot === -1) {
1821
- return false;
1822
- }
1823
- return TEXT_EXTENSIONS.has(filePath.slice(lastDot));
1824
- };
1825
- const substitute = (content, name) => content.replaceAll("{{name}}", name);
1826
- const isLunoraDep = (name) => name === "lunorash" || name.startsWith("@lunora/");
1827
- const resolveLunoraVersions = async (files, distTag) => {
1828
- const names = /* @__PURE__ */ new Set();
1829
- for (const file of files) {
1830
- if (basename(file) !== "package.json") {
1831
- continue;
1832
- }
1833
- try {
1834
- const parsed = JSON.parse(readFileSync(file, "utf8"));
1835
- for (const section of ["dependencies", "devDependencies"]) {
1836
- for (const name of Object.keys(parsed[section] ?? {})) {
1837
- if (isLunoraDep(name)) {
1838
- names.add(name);
1839
- }
1840
- }
1841
- }
1842
- } catch {
1843
- }
1844
- }
1845
- return resolveTagVersions(names, distTag);
1846
- };
1847
- const stampLunoraDeps = (packageJsonText, distTag, versions) => {
1848
- let parsed;
1849
- try {
1850
- parsed = JSON.parse(packageJsonText);
1851
- } catch {
1852
- return packageJsonText;
1853
- }
1854
- let text = packageJsonText;
1855
- for (const section of ["dependencies", "devDependencies"]) {
1856
- for (const name of Object.keys(parsed[section] ?? {})) {
1857
- if (!isLunoraDep(name)) {
1858
- continue;
1859
- }
1860
- const pin = versions.get(name) ?? distTag;
1861
- const edits = modify(text, [section, name], pin, { formattingOptions: { insertSpaces: true, tabSize: 4 } });
1862
- text = applyEdits(text, edits);
1863
- }
1864
- }
1865
- return text;
1866
- };
1867
- const PNPM_BUILT_DEPENDENCIES = [
1868
- "@parcel/watcher",
1869
- "esbuild",
1870
- "lmdb",
1871
- "msgpackr-extract",
1872
- "rs-module-lexer",
1873
- "sharp",
1874
- "unrs-resolver",
1875
- "workerd"
1876
- ];
1877
- const PNPM_DENIED_BUILD_DEPENDENCIES = ["cpu-features", "protobufjs", "ssh2"];
1878
- const PNPM_WORKSPACE_FILENAME = "pnpm-workspace.yaml";
1879
- const pnpmWorkspaceYaml = () => [
1880
- "# pnpm reads its settings from here (the package.json `pnpm` field is no longer read).",
1881
- "# Pre-approve the toolchain's native build scripts so `pnpm install` runs them",
1882
- "# without the interactive `pnpm approve-builds` step; deny the optional native",
1883
- "# builds a scaffold doesn't need (so no C/C++ toolchain is required).",
1884
- "allowBuilds:",
1885
- ...PNPM_BUILT_DEPENDENCIES.map((name) => ` '${name}': true`),
1886
- ...PNPM_DENIED_BUILD_DEPENDENCIES.map((name) => ` '${name}': false`),
1887
- ""
1888
- ].join("\n");
1889
- const collectFiles = (directory) => {
1890
- const out = [];
1891
- for (const entry of walkSync(directory, { includeDirs: false, includeFiles: true })) {
1892
- if (lstatSync(entry.path).isSymbolicLink()) {
1893
- continue;
1894
- }
1895
- out.push(entry.path);
1896
- }
1897
- return out;
1898
- };
1899
- const copyTemplate = async (sourceDirectory, target, name) => {
1900
- const files = collectFiles(sourceDirectory);
1901
- const written = [];
1902
- const distTag = resolveDistTag();
1903
- const versions = await resolveLunoraVersions(files, distTag);
1904
- for (const source of files) {
1905
- const relativePath = relative(sourceDirectory, source);
1906
- const destination = join$1(target, relativePath);
1907
- mkdirSync(dirname$1(destination), { recursive: true });
1908
- const raw = readFileSync(source);
1909
- let text = isTextFile(source) ? substitute(raw.toString("utf8"), name) : void 0;
1910
- if (text !== void 0 && basename(source) === "package.json") {
1911
- text = stampLunoraDeps(text, distTag, versions);
1912
- }
1913
- if (text === void 0) {
1914
- writeFileSync(destination, raw);
1915
- } else {
1916
- writeFileSync(destination, text, "utf8");
1917
- }
1918
- written.push(destination);
1919
- }
1920
- return written;
1921
- };
1922
- const resolveTemplateSource = (templateType, source, ref) => {
1923
- if (source !== void 0 && source.length > 0) {
1924
- return source;
1925
- }
1926
- return `${DEFAULT_SOURCE_BASE}/${templateType}#${resolveSourceRef(ref)}`;
1927
- };
1928
- const isSafeSource = (source) => {
1929
- if (source.includes("..")) {
1930
- return false;
1931
- }
1932
- return source.startsWith("gh:") || source.startsWith("github:") || source.startsWith("https://");
1933
- };
1934
- const logWould = (logger, action) => {
1935
- logger.info(`[dry-run] would ${action}`);
1936
- };
1937
- const logScaffoldSuccess = (logger, written, target) => {
1938
- if (isInteractive()) {
1939
- process.stdout.write("\n");
1940
- }
1941
- logger.success(`scaffolded ${String(written.length)} files into ${target}`);
1942
- };
1943
- const installCommand = (manager, packages) => {
1944
- const verb = manager === "npm" ? "install" : "add";
1945
- return `${manager} ${verb} ${packages.join(" ")}`;
1946
- };
1947
- const isInsideMonorepo = (startDirectory) => {
1948
- let directory = resolve(startDirectory);
1949
- for (; ; ) {
1950
- if (existsSync(join$1(directory, "pnpm-workspace.yaml"))) {
1951
- return true;
1952
- }
1953
- const packagePath = join$1(directory, "package.json");
1954
- if (existsSync(packagePath)) {
1955
- try {
1956
- const parsed = JSON.parse(readFileSync(packagePath, "utf8"));
1957
- if (parsed.workspaces !== void 0) {
1958
- return true;
1959
- }
1960
- } catch {
1961
- }
1962
- }
1963
- const parent = dirname$1(directory);
1964
- if (parent === directory) {
1965
- return false;
1966
- }
1967
- directory = parent;
1968
- }
1969
- };
1970
- const isInsideGitRepo = (startDirectory) => {
1971
- let directory = resolve(startDirectory);
1972
- for (; ; ) {
1973
- if (existsSync(join$1(directory, ".git"))) {
1974
- return true;
1975
- }
1976
- const parent = dirname$1(directory);
1977
- if (parent === directory) {
1978
- return false;
1979
- }
1980
- directory = parent;
1981
- }
1982
- };
1983
- const maybeOfferGit = async (options, target) => {
1984
- if (options.yes === true || !isInteractive() || isInsideGitRepo(dirname$1(target))) {
1985
- return;
1986
- }
1987
- if (!await tuiConfirm(COPY.git, { badge: BADGES.git, defaultYes: false })) {
1988
- await tuiInfo("Sounds good! You can always run git init manually.");
1989
- return;
1990
- }
1991
- if (options.dryRun === true) {
1992
- logWould(options.logger, "initialize a git repository");
1993
- return;
1994
- }
1995
- const spawner = options.spawner ?? defaultSpawner;
1996
- const result = await withTuiSpinner("Initializing a git repository…", () => spawner({ args: ["init"], command: "git", cwd: target }));
1997
- if (result.code === 0) {
1998
- await emitStep("git", "Initialized an empty git repository.");
1999
- } else {
2000
- options.logger.warn("`git init` failed — initialize it yourself later with `git init`.");
2001
- }
2002
- };
2003
- const printNextSteps = async (name, installed, manager, insideMonorepo) => {
2004
- const steps = [{ code: `cd ./${name}`, lead: "Enter your project directory using" }];
2005
- if (installed === void 0) {
2006
- steps.push({ code: `${manager} install`, lead: "Install dependencies with", tail: insideMonorepo ? " from the workspace root" : void 0 });
2007
- }
2008
- steps.push(
2009
- { code: runScriptCommand(manager, "dev"), lead: "Run", tail: " to start the dev server." },
2010
- { code: "lunora add", lead: "Add features like auth or storage using" }
2011
- );
2012
- const help = [
2013
- { code: "https://lunora.sh/docs", lead: "Read the docs at" },
2014
- { code: "https://lunora.sh/chat", lead: "Stuck? Join the chat at" }
2015
- ];
2016
- if (isInteractive()) {
2017
- await tuiNextSteps(BADGES.next, COPY.nextHeader, steps, help);
2018
- return;
2019
- }
2020
- const lines = steps.map((step) => `${step.lead} ${step.code}${step.tail ?? ""}`);
2021
- lines.push("", ...help.map((line) => `${line.lead} ${line.code}${line.tail ?? ""}`));
2022
- await emitStep("next", COPY.nextHeader, lines.join("\n"));
2023
- };
2024
- const offerInstallIsInteractive = (options) => options.yes !== true && (options.installPrompt !== void 0 || isInteractive());
2025
- const maybeOfferInstall = async (options, target) => {
2026
- if (!offerInstallIsInteractive(options)) {
2027
- return void 0;
2028
- }
2029
- if (isInsideMonorepo(dirname$1(target))) {
2030
- return void 0;
2031
- }
2032
- const managers = detectInstalledManagers(options.packageManagerProbe);
2033
- const [defaultManager] = managers;
2034
- if (defaultManager === void 0) {
2035
- return void 0;
2036
- }
2037
- const confirm = options.installPrompt?.confirmInstall ?? (async () => tuiConfirm(COPY.install, { badge: BADGES.deps, defaultYes: true }));
2038
- if (!await confirm()) {
2039
- await tuiInfo("No problem! Remember to install dependencies after setup.");
2040
- return void 0;
2041
- }
2042
- let manager = defaultManager;
2043
- if (managers.length > 1) {
2044
- manager = options.installPrompt ? await options.installPrompt.selectManager(managers) : await tuiSelect(
2045
- COPY.packageManager,
2046
- managers.map((candidate) => {
2047
- return { label: candidate, value: candidate };
2048
- }),
2049
- { badge: BADGES.deps, default: defaultManager }
2050
- ) ?? defaultManager;
2051
- }
2052
- if (options.dryRun === true) {
2053
- logWould(options.logger, `install dependencies with ${manager}`);
2054
- return void 0;
2055
- }
2056
- if (manager === "pnpm") {
2057
- const workspacePath = join$1(target, PNPM_WORKSPACE_FILENAME);
2058
- if (!existsSync(workspacePath)) {
2059
- writeFileSync(workspacePath, pnpmWorkspaceYaml(), "utf8");
2060
- }
2061
- }
2062
- const spawner = options.spawner ?? defaultSpawner;
2063
- const { args, command } = installArgsFor(manager);
2064
- await emitStep("deps", `Installing dependencies with ${manager}…`);
2065
- const result = await spawner({ args, command, cwd: target });
2066
- if (result.code !== 0) {
2067
- options.logger.warn(`\`${command} install\` exited with code ${String(result.code)} — run it yourself in ${basename(target)}/.`);
2068
- return void 0;
2069
- }
2070
- await emitStep("deps", `Dependencies installed with ${manager}.`);
2071
- return manager;
2072
- };
2073
- const scaffoldFromLocal = async (fromRoot, templateType, target, name, logger) => {
2074
- const templateDirectory = join$1(fromRoot, templateType);
2075
- if (!existsSync(templateDirectory)) {
2076
- logger.error(`template not found in local source: ${templateDirectory}`);
2077
- return { code: 1, files: [], target };
2078
- }
2079
- const written = await copyTemplate(templateDirectory, target, name);
2080
- logScaffoldSuccess(logger, written, target);
2081
- return { code: 0, files: written, target };
2082
- };
2083
- const scaffoldFromRemote = async (options) => {
2084
- const { logger, name, ref, source, target, templateType } = options;
2085
- const stagingRoot = mkdtempSync(join$1(tmpdir(), "lunora-init-fetch-"));
2086
- const stagingDirectory = join$1(stagingRoot, "template");
2087
- try {
2088
- const pinnedRef = source !== void 0 && source.length > 0 ? ref : await resolvePinnedSourceRef(ref, logger);
2089
- const remote = resolveTemplateSource(templateType, source, pinnedRef);
2090
- let downloaded;
2091
- let written = [];
2092
- await tuiTasks(
2093
- [
2094
- {
2095
- label: `${templateType} template fetched`,
2096
- run: async () => {
2097
- downloaded = await downloadTemplate(remote, {
2098
- cwd: stagingRoot,
2099
- dir: stagingDirectory,
2100
- force: true,
2101
- install: false,
2102
- silent: true
2103
- });
2104
- }
2105
- },
2106
- {
2107
- label: `files copied into ${name}/`,
2108
- run: async () => {
2109
- written = await copyTemplate(stagingDirectory, target, name);
2110
- }
2111
- }
2112
- ],
2113
- { end: "Project initialized!", start: "Project initializing…" }
2114
- );
2115
- const staged = collectFiles(stagingDirectory);
2116
- if (isInteractive()) {
2117
- process.stdout.write("\n");
2118
- }
2119
- logger.info(
2120
- downloaded?.commit ? `template: ${downloaded.source} @ ${downloaded.commit} (${String(staged.length)} files)` : `template: ${downloaded?.source ?? remote} (${String(staged.length)} files)`
2121
- );
2122
- logScaffoldSuccess(logger, written, target);
2123
- return { code: 0, files: written, target };
2124
- } catch (error) {
2125
- if (error instanceof PromptCancelledError) {
2126
- throw error;
2127
- }
2128
- const { hints, message } = describeDownloadFailure(error, {
2129
- ref: resolveSourceRef(ref),
2130
- remote: resolveTemplateSource(templateType, source, ref),
2131
- templateType
2132
- });
2133
- logger.error(message);
2134
- for (const hint of hints) {
2135
- logger.warn(hint);
2136
- }
2137
- return { code: 1, files: [], target };
2138
- } finally {
2139
- rmSync(stagingRoot, { force: true, recursive: true });
2140
- }
2141
- };
2142
- const renameCreateViteDotfiles = (directory) => {
2143
- for (const file of ["_gitignore", "_npmrc", "_gitattributes"]) {
2144
- const from = join$1(directory, file);
2145
- if (existsSync(from)) {
2146
- renameSync(from, join$1(directory, `.${file.slice(1)}`));
2147
- }
2148
- }
2149
- };
2150
- const scaffoldViteOverlay = async (options) => {
2151
- const { framework, logger, name, overlayBaseFrom, target } = options;
2152
- const adapter = ADAPTERS[framework];
2153
- const stagingRoot = mkdtempSync(join$1(tmpdir(), "lunora-vite-base-"));
2154
- try {
2155
- let localBase;
2156
- if (overlayBaseFrom !== void 0) {
2157
- localBase = join$1(overlayBaseFrom, `template-${adapter.createViteTemplate}`);
2158
- if (!existsSync(localBase)) {
2159
- logger.error(`create-vite base not found on disk: ${localBase}`);
2160
- return { code: 1, files: [], target };
2161
- }
2162
- }
2163
- const copyBase = async () => {
2164
- if (localBase !== void 0) {
2165
- cpSync(localBase, target, { recursive: true });
2166
- return;
2167
- }
2168
- const stagingDirectory = join$1(stagingRoot, "base");
2169
- const remote = `github:vitejs/vite/packages/create-vite/template-${adapter.createViteTemplate}#main`;
2170
- await downloadTemplate(remote, { cwd: stagingRoot, dir: stagingDirectory, force: true, install: false, silent: true });
2171
- renameCreateViteDotfiles(stagingDirectory);
2172
- cpSync(stagingDirectory, target, { recursive: true });
2173
- };
2174
- let written = [];
2175
- await tuiTasks(
2176
- [
2177
- { label: `create-vite (${adapter.label}) base ready`, run: copyBase },
2178
- {
2179
- label: `Lunora overlay applied (${adapter.label})`,
2180
- run: async () => {
2181
- written = await applyLunoraOverlay({ adapter, distTag: resolveDistTag(), logger, name, target });
2182
- }
2183
- }
2184
- ],
2185
- { end: "Project initialized!", start: "Project initializing…" }
2186
- );
2187
- logScaffoldSuccess(logger, written, target);
2188
- return { code: 0, files: [...collectFiles(target)], target };
2189
- } catch (error) {
2190
- if (error instanceof PromptCancelledError) {
2191
- throw error;
2192
- }
2193
- const message = error instanceof Error ? error.message : String(error);
2194
- logger.error(`failed to scaffold the ${adapter.label} base: ${message}`);
2195
- return { code: 1, files: [], target };
2196
- } finally {
2197
- rmSync(stagingRoot, { force: true, recursive: true });
2198
- }
2199
- };
2200
- const createMinimalViteConfig = (cwd, logger) => {
2201
- const target = join$1(cwd, "vite.config.ts");
2202
- try {
2203
- writeFileSync(target, MINIMAL_VITE_CONFIG, "utf8");
2204
- } catch (error) {
2205
- const message = error instanceof Error ? error.message : String(error);
2206
- logger.error(`init --in-place: could not write ${target}: ${message}`);
2207
- return { code: 1, files: [], target: cwd };
2208
- }
2209
- logger.success(`created ${target} with lunora() plugin`);
2210
- return { code: 0, files: [target], target: cwd };
2211
- };
2212
- const patchExistingViteConfig = (viteConfigPath, cwd, logger) => {
2213
- let source;
2214
- try {
2215
- source = readFileSync(viteConfigPath, "utf8");
2216
- } catch (error) {
2217
- const message = error instanceof Error ? error.message : String(error);
2218
- logger.error(`init --in-place: could not read ${viteConfigPath}: ${message}`);
2219
- return { code: 1, files: [], target: cwd };
2220
- }
2221
- const result = patchViteConfig(source);
2222
- if (!result.changed) {
2223
- logger.info(`${viteConfigPath}: ${result.reason ?? "no changes needed"}`);
2224
- return { code: 0, files: [], target: cwd };
2225
- }
2226
- try {
2227
- writeFileSync(viteConfigPath, result.code, "utf8");
2228
- } catch (error) {
2229
- const message = error instanceof Error ? error.message : String(error);
2230
- logger.error(`init --in-place: could not write ${viteConfigPath}: ${message}`);
2231
- return { code: 1, files: [], target: cwd };
2232
- }
2233
- logger.success(`patched ${viteConfigPath} — added lunora() plugin`);
2234
- return { code: 0, files: [viteConfigPath], target: cwd };
2235
- };
2236
- const scaffoldLunoraDirectory = (cwd, logger) => {
2237
- const lunoraDirectory = join$1(cwd, "lunora");
2238
- const schemaPath = join$1(lunoraDirectory, "schema.ts");
2239
- if (existsSync(schemaPath)) {
2240
- logger.info(`lunora/ already present — left ${schemaPath} untouched`);
2241
- return [];
2242
- }
2243
- const written = [];
2244
- try {
2245
- mkdirSync(lunoraDirectory, { recursive: true });
2246
- writeFileSync(schemaPath, SAMPLE_SCHEMA, "utf8");
2247
- written.push(schemaPath);
2248
- const functionPath = join$1(lunoraDirectory, "messages.ts");
2249
- if (!existsSync(functionPath)) {
2250
- writeFileSync(functionPath, SAMPLE_FUNCTION, "utf8");
2251
- written.push(functionPath);
2252
- }
2253
- logger.success(`scaffolded lunora/ (${String(written.length)} file(s))`);
2254
- } catch (error) {
2255
- const message = error instanceof Error ? error.message : String(error);
2256
- logger.error(`init --here: could not scaffold lunora/: ${message}`);
2257
- }
2258
- return written;
2259
- };
2260
- const printFrameworkNextSteps = (detection, manager, logger) => {
2261
- const { adapter, class: frameworkClass, framework } = detection;
2262
- logger.info("");
2263
- logger.info(`detected framework: ${framework} (class ${frameworkClass})`);
2264
- logger.info("next steps:");
2265
- logger.info(` 1. install the adapter: ${installCommand(manager, [adapter, "@lunora/client", "@lunora/runtime", "@lunora/server"])}`);
2266
- logger.info(" 2. run codegen: lunora codegen");
2267
- if (frameworkClass === "A") {
2268
- logger.info(" 3. compose one worker: wrap your worker entry with");
2269
- logger.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })");
2270
- logger.info(` 4. add the provider: mount the ${adapter} provider in your root layout/route`);
2271
- logger.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component");
2272
- logger.info(" see https://lunora.sh/docs/frameworks/reactive-loaders");
2273
- } else if (frameworkClass === "B") {
2274
- logger.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook");
2275
- logger.info(` (${framework} owns its Cloudflare adapter — Lunora composes into its server entry)`);
2276
- logger.info(` 4. add the provider: mount the ${adapter} provider in your root layout`);
2277
- logger.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy");
2278
- } else {
2279
- logger.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react");
2280
- logger.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework");
2281
- }
2282
- logger.info("");
2283
- };
2284
- const findExistingViteConfig = (cwd) => {
2285
- for (const candidate of VITE_CONFIG_CANDIDATES) {
2286
- const full = join$1(cwd, candidate);
2287
- if (existsSync(full)) {
2288
- return full;
2289
- }
2290
- }
2291
- return void 0;
2292
- };
2293
- const patchOrCreateViteConfig = (cwd, framework, logger) => {
2294
- const viteConfigPath = findExistingViteConfig(cwd);
2295
- if (viteConfigPath === void 0) {
2296
- if (framework === "sveltekit" || framework === "nuxt" || framework === "astro") {
2297
- logger.info(`no Vite config found — ${framework} wires Lunora through its server entry (see next steps)`);
2298
- return { code: 0, files: [], target: cwd };
2299
- }
2300
- return createMinimalViteConfig(cwd, logger);
2301
- }
2302
- return patchExistingViteConfig(viteConfigPath, cwd, logger);
2303
- };
2304
- const runInPlaceInit = (cwd, logger) => {
2305
- const detection = detectFramework(cwd);
2306
- const viteResult = patchOrCreateViteConfig(cwd, detection.framework, logger);
2307
- if (viteResult.code !== 0) {
2308
- return viteResult;
2309
- }
2310
- const scaffolded = scaffoldLunoraDirectory(cwd, logger);
2311
- printFrameworkNextSteps(detection, detectPackageManager(cwd), logger);
2312
- return { code: 0, files: [...viteResult.files, ...scaffolded], target: cwd };
2313
- };
2314
- const offerIsInteractive = (options) => options.yes !== true && (options.prompt !== void 0 || (options.interactive ?? isInteractive()));
2315
- const maybeOfferExtras = async (options, projectDirectory) => {
2316
- const interactive = offerIsInteractive(options);
2317
- const preselected = options.add === void 0 ? [] : parseFeatureList(options.add, (message) => {
2318
- options.logger.warn(message);
2319
- });
2320
- const applyAll = async (plans) => {
2321
- if (plans.length === 0) {
2322
- return true;
2323
- }
2324
- if (options.dryRun === true) {
2325
- logWould(options.logger, `add ${plans.map((plan) => plan.label).join(", ")}`);
2326
- return true;
2327
- }
2328
- const buffered = [];
2329
- const applyLogger = isInteractive() ? {
2330
- error: (message) => {
2331
- buffered.push({ level: "error", message });
2332
- },
2333
- info: () => {
2334
- },
2335
- success: () => {
2336
- },
2337
- warn: (message) => {
2338
- buffered.push({ level: "warn", message });
2339
- }
2340
- } : options.logger;
2341
- const steps = plans.map((plan) => {
2342
- return {
2343
- running: `adding ${plan.label}…`,
2344
- task: () => runAddCommand({
2345
- allowUnsafeSource: options.allowUnsafeSource,
2346
- cwd: projectDirectory,
2347
- from: options.registryFrom,
2348
- logger: applyLogger,
2349
- names: [...plan.names],
2350
- ref: options.ref,
2351
- source: options.registrySource,
2352
- transformManifest: plan.transformManifest,
2353
- yes: true
2354
- })
2355
- };
2356
- });
2357
- const done = `added ${plans.map((plan) => plan.label).join(", ")}`;
2358
- const results = await withTuiBadgeProgress(BADGES.add, steps, done);
2359
- for (const { level, message } of buffered) {
2360
- options.logger[level](message);
2361
- }
2362
- return results.every((result) => result.code === 0);
2363
- };
2364
- const deps = {
2365
- applyAll,
2366
- interactive,
2367
- logger: options.logger,
2368
- multiSelect: options.prompt?.multiSelect ?? ((message, choices, settings) => tuiMultiSelect(message, choices, { ...settings, badge: BADGES.add })),
2369
- preselected: preselected.length > 0 ? preselected : void 0,
2370
- projectName: basename(projectDirectory),
2371
- select: options.prompt?.select ?? ((message, choices, settings) => tuiSelect(message, choices, { ...settings, badge: BADGES.add })),
2372
- text: options.prompt?.text ?? ((message, settings) => tuiText(message, { ...settings, badge: BADGES.add }))
2373
- };
2374
- if (preselected.length > 0) {
2375
- await offerRegistryExtras(deps);
2376
- return;
2377
- }
2378
- if (isInteractive()) {
2379
- await tuiHeadline(COPY.extras);
2380
- }
2381
- await offerRegistryExtras(deps);
2382
- };
2383
- const DEFAULT_FRAMEWORK = "react";
2384
- const FRAMEWORK_CHOICES = [
2385
- { description: "React SPA — official create-vite base + the Lunora layer (the default)", label: "React", value: "react" },
2386
- { description: "Vue SPA — create-vite base + Lunora", label: "Vue", value: "vue" },
2387
- { description: "Solid SPA — create-vite base + Lunora", label: "Solid", value: "solid" },
2388
- { description: "Svelte SPA — create-vite base + Lunora", label: "Svelte", value: "svelte" },
2389
- { description: "Next.js (App Router) — OpenNext on Cloudflare + a standalone Lunora worker", label: "Next.js", value: "next" },
2390
- { description: "TanStack Start (React) — SSR with live-loader routes", label: "TanStack Start · React", value: "tanstack-start-react" },
2391
- { description: "TanStack Start (Solid)", label: "TanStack Start · Solid", value: "tanstack-start-solid" },
2392
- { description: "React Router (v7, framework mode) — SSR composed into the Lunora worker", label: "React Router", value: "react-router" },
2393
- { description: "Astro + a standalone Lunora worker", label: "Astro", value: "astro" },
2394
- { description: "AnalogJS (Angular) — single-worker, Lunora mounted in Nitro", label: "Analog", value: "analog" },
2395
- { description: "Nuxt (Vue) — single-worker, Lunora mounted in Nitro", label: "Nuxt", value: "nuxt" },
2396
- { description: "SvelteKit + a standalone Lunora worker", label: "SvelteKit", value: "sveltekit" },
2397
- { description: "React Native (Expo) — an iOS/Android/web app + a Lunora worker backend", label: "React Native · Expo", value: "expo" },
2398
- { description: "Worker only — no frontend", label: "Standalone", value: "standalone" }
2399
- ];
2400
- const OVERLAY_VALUES = Object.keys(ADAPTERS).join("|");
2401
- const TEMPLATE_VALUES = FRAMEWORK_CHOICES.filter((choice) => !isOverlayFramework(choice.value)).map((choice) => choice.value).join("|");
2402
- const toScaffoldChoice = (value) => isOverlayFramework(value) ? { framework: value, kind: "overlay" } : { kind: "template", templateType: value };
2403
- const resolveScaffoldChoice = async (options) => {
2404
- if (options.vite !== void 0) {
2405
- return { framework: options.vite, kind: "overlay" };
2406
- }
2407
- if (options.templateType !== void 0) {
2408
- return { kind: "template", templateType: options.templateType };
2409
- }
2410
- if (!isInteractive() || options.yes === true) {
2411
- return { framework: DEFAULT_FRAMEWORK, kind: "overlay" };
2412
- }
2413
- return toScaffoldChoice(await tuiSelect(COPY.framework, FRAMEWORK_CHOICES, { badge: BADGES.tmpl, default: DEFAULT_FRAMEWORK }) ?? DEFAULT_FRAMEWORK);
2414
- };
2415
- const nonInteractiveInitError = (options) => {
2416
- if (isInteractive() || options.yes === true) {
2417
- return void 0;
2418
- }
2419
- const missing = [];
2420
- if (options.name === void 0) {
2421
- missing.push("a project name (`lunora init <name>`)");
2422
- }
2423
- if (options.templateType === void 0 && options.vite === void 0) {
2424
- missing.push(`a framework — \`--vite <${OVERLAY_VALUES}>\` for an SPA, or \`-t <${TEMPLATE_VALUES}>\` for a bespoke template`);
2425
- }
2426
- if (missing.length === 0) {
2427
- return void 0;
2428
- }
2429
- return `lunora init can't prompt in a non-interactive terminal — provide ${missing.join(" and ")}, or pass --yes to accept the defaults.`;
2430
- };
2431
- const scaffoldOverlayPath = async (options, framework, name, target) => {
2432
- if (!isOverlayFramework(framework)) {
2433
- options.logger.error(`init: unknown framework "${framework}". Supported overlays: ${Object.keys(ADAPTERS).join(", ")}.`);
2434
- return { code: 1, files: [], target };
2435
- }
2436
- if (!await verifyRemoteTemplate({ isLocal: options.overlayBaseFrom !== void 0, logger: options.logger })) {
2437
- return { code: 1, files: [], target };
2438
- }
2439
- mkdirSync(target, { recursive: true });
2440
- return scaffoldViteOverlay({ framework, logger: options.logger, name, overlayBaseFrom: options.overlayBaseFrom, target });
2441
- };
2442
- const scaffoldTemplatePath = async (options, templateType, name, target) => {
2443
- if (options.from !== void 0) {
2444
- return await scaffoldFromLocal(options.from, templateType, target, name, options.logger);
2445
- }
2446
- if (options.source !== void 0 && options.source.length > 0 && !options.allowUnsafeSource && !isSafeSource(options.source)) {
2447
- options.logger.error(
2448
- `init: refusing --source ${options.source} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`
2449
- );
2450
- return { code: 1, files: [], target };
2451
- }
2452
- if (!await verifyRemoteTemplate({ isLocal: false, logger: options.logger, source: resolveTemplateSource(templateType, options.source, options.ref) })) {
2453
- return { code: 1, files: [], target };
2454
- }
2455
- return scaffoldFromRemote({ logger: options.logger, name, ref: options.ref, source: options.source, target, templateType });
2456
- };
2457
- const scaffoldNewProject = async (options, cwd, recordTarget) => {
2458
- await tuiMoonrise("realtime backend on Cloudflare Workers + Durable Objects");
2459
- const blocked = nonInteractiveInitError(options);
2460
- if (blocked !== void 0) {
2461
- options.logger.error(blocked);
2462
- return { code: 1, files: [], target: "" };
2463
- }
2464
- const suggestedName = generateProjectName();
2465
- const rawName = options.name ?? await tuiText(COPY.name, { badge: BADGES.dir, default: suggestedName, placeholder: suggestedName });
2466
- const choice = await resolveScaffoldChoice(options);
2467
- const name = rawName.trim();
2468
- if (name.length === 0) {
2469
- options.logger.error(`init: refusing an empty project name — pass a directory name (e.g. \`lunora init my-app\`).`);
2470
- return { code: 1, files: [], target: "" };
2471
- }
2472
- if (name.includes("/") || name.includes("\\") || name === ".." || name === ".") {
2473
- options.logger.error(`init: refusing project name "${name}" — must not contain path separators or be "." / "..".`);
2474
- return { code: 1, files: [], target: "" };
2475
- }
2476
- const target = resolve(cwd, name);
2477
- const targetPreExisted = existsSync(target);
2478
- if (targetPreExisted) {
2479
- const entries = readdirSync(target);
2480
- if (entries.length > 0) {
2481
- options.logger.error(`target directory not empty: ${target}`);
2482
- return { code: 1, files: [], target };
2483
- }
2484
- }
2485
- if (options.dryRun === true) {
2486
- const what = choice.kind === "overlay" ? `the ${choice.framework} create-vite overlay` : `the ${choice.templateType} template`;
2487
- logWould(options.logger, `scaffold ${what} into ${target}`);
2488
- return { code: 0, files: [], target };
2489
- }
2490
- recordTarget(target, targetPreExisted);
2491
- return choice.kind === "overlay" ? scaffoldOverlayPath(options, choice.framework, name, target) : scaffoldTemplatePath(options, choice.templateType, name, target);
2492
- };
2493
- const resetScaffoldOnCancel = (cleanup, logger) => {
2494
- const { target, targetPreExisted } = cleanup;
2495
- if (target === void 0 || !existsSync(target)) {
2496
- return;
2497
- }
2498
- if (targetPreExisted === true) {
2499
- for (const entry of readdirSync(target)) {
2500
- rmSync(join$1(target, entry), { force: true, recursive: true });
2501
- }
2502
- } else {
2503
- rmSync(target, { force: true, recursive: true });
2504
- }
2505
- logger.info(`removed the partially-created project at ${target}`);
2506
- };
2507
- const runScaffoldStep = async (options, cwd, recordTarget) => {
2508
- if (options.inPlace !== true) {
2509
- return scaffoldNewProject(options, cwd, recordTarget);
2510
- }
2511
- if (options.dryRun === true) {
2512
- logWould(options.logger, `configure Lunora into ${cwd}`);
2513
- return { code: 0, files: [], target: cwd };
2514
- }
2515
- return runInPlaceInit(cwd, options.logger);
2516
- };
2517
- const runPostScaffold = async (options, result, cwd) => {
2518
- await maybeOfferExtras(options, result.target);
2519
- const installedManager = options.inPlace === true ? void 0 : await maybeOfferInstall(options, result.target);
2520
- if (options.inPlace !== true) {
2521
- await maybeOfferGit(options, result.target);
2522
- const manager = installedManager ?? detectPackageManager(result.target);
2523
- await printNextSteps(basename(result.target), installedManager, manager, isInsideMonorepo(cwd));
2524
- await emitMascot(options.logger);
2525
- }
2526
- };
2527
- const scaffoldCiPipeline = (options, result, cwd) => {
2528
- if (result.code !== 0 || options.ci === void 0) {
2529
- return;
2530
- }
2531
- if (options.dryRun === true) {
2532
- logWould(options.logger, `scaffold a ${options.ci} CI deploy pipeline`);
2533
- return;
2534
- }
2535
- scaffoldCiWorkflow(options.inPlace === true ? cwd : result.target, options.ci, options.logger);
2536
- };
2537
- const runInitCommand = async (options) => {
2538
- const cwd = options.cwd ?? process.cwd();
2539
- const cleanup = {};
2540
- let result;
2541
- try {
2542
- result = await runScaffoldStep(options, cwd, (target, preExisted) => {
2543
- cleanup.target = target;
2544
- cleanup.targetPreExisted = preExisted;
2545
- });
2546
- if (result.code === 0 && result.target !== "") {
2547
- cleanup.target = void 0;
2548
- await runPostScaffold(options, result, cwd);
2549
- }
2550
- } catch (error) {
2551
- if (error instanceof PromptCancelledError) {
2552
- resetScaffoldOnCancel(cleanup, options.logger);
2553
- process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n");
2554
- return { code: 130, files: [], target: "" };
2555
- }
2556
- throw error;
2557
- }
2558
- scaffoldCiPipeline(options, result, cwd);
2559
- return result;
2560
- };
2561
- const isTemplate = (value) => value === "analog" || value === "astro" || value === "expo" || value === "next" || value === "nuxt" || value === "react-router" || value === "standalone" || value === "sveltekit" || value === "tanstack-start-react" || value === "tanstack-start-solid";
2562
- const resolveCiProvider = (raw, logger) => {
2563
- if (raw === void 0) {
2564
- return void 0;
2565
- }
2566
- if (isCiProvider(raw)) {
2567
- return raw;
2568
- }
2569
- logger.warn(`init: unknown --ci "${raw}" — expected github | gitlab; skipping CI scaffold.`);
2570
- return void 0;
2571
- };
2572
- const execute = defineHandler(({ argument, cwd, logger, options }) => {
2573
- const templateType = options.template !== void 0 && isTemplate(options.template) ? options.template : void 0;
2574
- return runInitCommand({
2575
- add: options.add,
2576
- allowUnsafeSource: options.allowUnsafeSource === true,
2577
- cwd,
2578
- ci: resolveCiProvider(options.ci, logger),
2579
- dryRun: options.dryRun === true,
2580
- from: options.from,
2581
- inPlace: options.here === true,
2582
- interactive: options.interactive === true ? true : void 0,
2583
- logger,
2584
- name: argument[0],
2585
- ref: options.ref,
2586
- source: options.source,
2587
- templateType,
2588
- vite: options.vite,
2589
- yes: options.yes === true
2590
- });
2591
- });
2592
-
2593
- export { execute, isTemplate, resolveTemplateSource, runInitCommand };
1229
+ `,pa="gh:anolilab/lunora/templates",ua=e=>{const t=e.lastIndexOf(".");return t===-1?!1:ia.has(e.slice(t))},ha=(e,t)=>e.replaceAll("{{name}}",t),ye=e=>e==="lunorash"||e.startsWith("@lunora/"),ma=async(e,t)=>{const a=new Set;for(const r of e)if(S(r)==="package.json")try{const o=JSON.parse(k(r,"utf8"));for(const s of["dependencies","devDependencies"])for(const i of Object.keys(o[s]??{}))ye(i)&&a.add(i)}catch{}return re(a,t)},ga=(e,t,a)=>{let r;try{r=JSON.parse(e)}catch{return e}let o=e;for(const s of["dependencies","devDependencies"])for(const i of Object.keys(r[s]??{})){if(!ye(i))continue;const n=a.get(i)??t,c=Re(o,[s,i],n,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=Te(o,c)}return o},va=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","workerd"],fa=["cpu-features","protobufjs","ssh2"],wa="pnpm-workspace.yaml",ya=()=>["# pnpm reads its settings from here (the package.json `pnpm` field is no longer read).","# Pre-approve the toolchain's native build scripts so `pnpm install` runs them","# without the interactive `pnpm approve-builds` step; deny the optional native","# builds a scaffold doesn't need (so no C/C++ toolchain is required).","allowBuilds:",...va.map(e=>` '${e}': true`),...fa.map(e=>` '${e}': false`),""].join(`
1230
+ `),V=e=>{const t=[];for(const a of _e(e,{includeDirs:!1,includeFiles:!0}))$e(a.path).isSymbolicLink()||t.push(a.path);return t},be=async(e,t,a)=>{const r=V(e),o=[],s=se(),i=await ma(r,s);for(const n of r){const c=Ie(e,n),d=p(t,c);L($(d),{recursive:!0});const u=k(n);let l=ua(n)?ha(u.toString("utf8"),a):void 0;l!==void 0&&S(n)==="package.json"&&(l=ga(l,s,i)),l===void 0?m(d,u):m(d,l,"utf8"),o.push(d)}return o},j=(e,t,a)=>t!==void 0&&t.length>0?t:`${pa}/${e}#${oe(a)}`,ba=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),M=(e,t)=>{e.info(`[dry-run] would ${t}`)},U=(e,t,a)=>{g()&&process.stdout.write(`
1231
+ `),e.success(`scaffolded ${String(t.length)} files into ${a}`)},xa=(e,t)=>`${e} ${e==="npm"?"install":"add"} ${t.join(" ")}`,xe=e=>{let t=B(e);for(;;){if(h(p(t,"pnpm-workspace.yaml")))return!0;const a=p(t,"package.json");if(h(a))try{if(JSON.parse(k(a,"utf8")).workspaces!==void 0)return!0}catch{}const r=$(t);if(r===t)return!1;t=r}},ka=e=>{let t=B(e);for(;;){if(h(p(t,".git")))return!0;const a=$(t);if(a===t)return!1;t=a}},$a=async(e,t)=>{if(e.yes===!0||!g()||ka($(t)))return;if(!await le(y.git,{badge:f.git,defaultYes:!1})){await ce("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){M(e.logger,"initialize a git repository");return}const a=e.spawner??ie;(await Fe("Initializing a git repository…",()=>a({args:["init"],command:"git",cwd:t}))).code===0?await I("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},Ma=async(e,t,a,r)=>{const o=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&o.push({code:`${a} install`,lead:"Install dependencies with",tail:r?" from the workspace root":void 0}),o.push({code:Pe(a,"dev"),lead:"Run",tail:" to start the dev server."},{code:"lunora add",lead:"Add features like auth or storage using"});const s=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(g()){await Ke(f.next,y.nextHeader,o,s);return}const i=o.map(n=>`${n.lead} ${n.code}${n.tail??""}`);i.push("",...s.map(n=>`${n.lead} ${n.code}${n.tail??""}`)),await I("next",y.nextHeader,i.join(`
1232
+ `))},Ca=e=>e.yes!==!0&&(e.installPrompt!==void 0||g()),La=async(e,t)=>{if(!Ca(e)||xe($(t)))return;const a=Be(e.packageManagerProbe),[r]=a;if(r===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>le(y.install,{badge:f.deps,defaultYes:!0})))()){await ce("No problem! Remember to install dependencies after setup.");return}let o=r;if(a.length>1&&(o=e.installPrompt?await e.installPrompt.selectManager(a):await D(y.packageManager,a.map(d=>({label:d,value:d})),{badge:f.deps,default:r})??r),e.dryRun===!0){M(e.logger,`install dependencies with ${o}`);return}if(o==="pnpm"){const d=p(t,wa);h(d)||m(d,ya(),"utf8")}const s=e.spawner??ie,{args:i,command:n}=Ee(o);await I("deps",`Installing dependencies with ${o}…`);const c=await s({args:i,command:n,cwd:t});if(c.code!==0){e.logger.warn(`\`${n} install\` exited with code ${String(c.code)} — run it yourself in ${S(t)}/.`);return}return await I("deps",`Dependencies installed with ${o}.`),o},Sa=async(e,t,a,r,o)=>{const s=p(e,t);if(!h(s))return o.error(`template not found in local source: ${s}`),{code:1,files:[],target:a};const i=await be(s,a,r);return U(o,i,a),{code:0,files:i,target:a}},Aa=async e=>{const{logger:t,name:a,ref:r,source:o,target:s,templateType:i}=e,n=Y(p(Z(),"lunora-init-fetch-")),c=p(n,"template");try{const d=o!==void 0&&o.length>0?r:await ze(r,t),u=j(i,o,d);let l,w=[];await de([{label:`${i} template fetched`,run:async()=>{l=await ee(u,{cwd:n,dir:c,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{w=await be(c,s,a)}}],{end:"Project initialized!",start:"Project initializing…"});const H=V(c);return g()&&process.stdout.write(`
1233
+ `),t.info(l?.commit?`template: ${l.source} @ ${l.commit} (${String(H.length)} files)`:`template: ${l?.source??u} (${String(H.length)} files)`),U(t,w,s),{code:0,files:w,target:s}}catch(d){if(d instanceof P)throw d;const{hints:u,message:l}=$t(d,{ref:oe(r),remote:j(i,o,r),templateType:i});t.error(l);for(const w of u)t.warn(w);return{code:1,files:[],target:s}}finally{_(n,{force:!0,recursive:!0})}},Na=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const a=p(e,t);h(a)&&Me(a,p(e,`.${t.slice(1)}`))}},_a=async e=>{const{framework:t,logger:a,name:r,overlayBaseFrom:o,target:s}=e,i=T[t],n=Y(p(Z(),"lunora-vite-base-"));try{let c;if(o!==void 0&&(c=p(o,`template-${i.createViteTemplate}`),!h(c)))return a.error(`create-vite base not found on disk: ${c}`),{code:1,files:[],target:s};const d=async()=>{if(c!==void 0){W(c,s,{recursive:!0});return}const l=p(n,"base"),w=`github:vitejs/vite/packages/create-vite/template-${i.createViteTemplate}#main`;await ee(w,{cwd:n,dir:l,force:!0,install:!1,silent:!0}),Na(l),W(l,s,{recursive:!0})};let u=[];return await de([{label:`create-vite (${i.label}) base ready`,run:d},{label:`Lunora overlay applied (${i.label})`,run:async()=>{u=await Zt({adapter:i,distTag:se(),logger:a,name:r,target:s})}}],{end:"Project initialized!",start:"Project initializing…"}),U(a,u,s),{code:0,files:[...V(s)],target:s}}catch(c){if(c instanceof P)throw c;const d=c instanceof Error?c.message:String(c);return a.error(`failed to scaffold the ${i.label} base: ${d}`),{code:1,files:[],target:s}}finally{_(n,{force:!0,recursive:!0})}},Ia=(e,t)=>{const a=p(e,"vite.config.ts");try{m(a,la,"utf8")}catch(r){const o=r instanceof Error?r.message:String(r);return t.error(`init --in-place: could not write ${a}: ${o}`),{code:1,files:[],target:e}}return t.success(`created ${a} with lunora() plugin`),{code:0,files:[a],target:e}},Ra=(e,t,a)=>{let r;try{r=k(e,"utf8")}catch(s){const i=s instanceof Error?s.message:String(s);return a.error(`init --in-place: could not read ${e}: ${i}`),{code:1,files:[],target:t}}const o=he(r);if(!o.changed)return a.info(`${e}: ${o.reason??"no changes needed"}`),{code:0,files:[],target:t};try{m(e,o.code,"utf8")}catch(s){const i=s instanceof Error?s.message:String(s);return a.error(`init --in-place: could not write ${e}: ${i}`),{code:1,files:[],target:t}}return a.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},Ta=(e,t)=>{const a=p(e,"lunora"),r=p(a,"schema.ts");if(h(r))return t.info(`lunora/ already present — left ${r} untouched`),[];const o=[];try{L(a,{recursive:!0}),m(r,ca,"utf8"),o.push(r);const s=p(a,"messages.ts");h(s)||(m(s,da,"utf8"),o.push(s)),t.success(`scaffolded lunora/ (${String(o.length)} file(s))`)}catch(s){const i=s instanceof Error?s.message:String(s);t.error(`init --here: could not scaffold lunora/: ${i}`)}return o},Oa=(e,t,a)=>{const{adapter:r,class:o,framework:s}=e;a.info(""),a.info(`detected framework: ${s} (class ${o})`),a.info("next steps:"),a.info(` 1. install the adapter: ${xa(t,[r,"@lunora/client","@lunora/runtime","@lunora/server"])}`),a.info(" 2. run codegen: lunora codegen"),o==="A"?(a.info(" 3. compose one worker: wrap your worker entry with"),a.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),a.info(` 4. add the provider: mount the ${r} provider in your root layout/route`),a.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),a.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):o==="B"?(a.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),a.info(` (${s} owns its Cloudflare adapter — Lunora composes into its server entry)`),a.info(` 4. add the provider: mount the ${r} provider in your root layout`),a.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(a.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),a.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),a.info("")},ja=e=>{for(const t of na){const a=p(e,t);if(h(a))return a}},Ba=(e,t,a)=>{const r=ja(e);return r===void 0?t==="sveltekit"||t==="nuxt"||t==="astro"?(a.info(`no Vite config found — ${t} wires Lunora through its server entry (see next steps)`),{code:0,files:[],target:e}):Ia(e,a):Ra(r,e,a)},Ea=(e,t)=>{const a=pt(e),r=Ba(e,a.framework,t);if(r.code!==0)return r;const o=Ta(e,t);return Oa(a,te(e),t),{code:0,files:[...r.files,...o],target:e}},Pa=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??g())),Da=async(e,t)=>{const a=Pa(e),r=e.add===void 0?[]:Lt(e.add,s=>{e.logger.warn(s)}),o={applyAll:async s=>{if(s.length===0)return!0;if(e.dryRun===!0)return M(e.logger,`add ${s.map(l=>l.label).join(", ")}`),!0;const i=[],n=g()?{error:l=>{i.push({level:"error",message:l})},info:()=>{},success:()=>{},warn:l=>{i.push({level:"warn",message:l})}}:e.logger,c=s.map(l=>({running:`adding ${l.label}…`,task:()=>Ve({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:n,names:[...l.names],ref:e.ref,source:e.registrySource,transformManifest:l.transformManifest,yes:!0})})),d=`added ${s.map(l=>l.label).join(", ")}`,u=await Qe(f.add,c,d);for(const{level:l,message:w}of i)e.logger[l](w);return u.every(l=>l.code===0)},interactive:a,logger:e.logger,multiSelect:e.prompt?.multiSelect??((s,i,n)=>Je(s,i,{...n,badge:f.add})),preselected:r.length>0?r:void 0,projectName:S(t),select:e.prompt?.select??((s,i,n)=>D(s,i,{...n,badge:f.add})),text:e.prompt?.text??((s,i)=>ne(s,{...i,badge:f.add}))};if(r.length>0){await J(o);return}g()&&await qe(y.extras),await J(o)},O="react",ke=[{description:"React SPA — official create-vite base + the Lunora layer (the default)",label:"React",value:"react"},{description:"Vue SPA — create-vite base + Lunora",label:"Vue",value:"vue"},{description:"Solid SPA — create-vite base + Lunora",label:"Solid",value:"solid"},{description:"Svelte SPA — create-vite base + Lunora",label:"Svelte",value:"svelte"},{description:"Next.js (App Router) — OpenNext on Cloudflare + a standalone Lunora worker",label:"Next.js",value:"next"},{description:"TanStack Start (React) — SSR with live-loader routes",label:"TanStack Start · React",value:"tanstack-start-react"},{description:"TanStack Start (Solid)",label:"TanStack Start · Solid",value:"tanstack-start-solid"},{description:"React Router (v7, framework mode) — SSR composed into the Lunora worker",label:"React Router",value:"react-router"},{description:"Astro + a standalone Lunora worker",label:"Astro",value:"astro"},{description:"AnalogJS (Angular) — single-worker, Lunora mounted in Nitro",label:"Analog",value:"analog"},{description:"Nuxt (Vue) — single-worker, Lunora mounted in Nitro",label:"Nuxt",value:"nuxt"},{description:"SvelteKit + a standalone Lunora worker",label:"SvelteKit",value:"sveltekit"},{description:"React Native (Expo) — an iOS/Android/web app + a Lunora worker backend",label:"React Native · Expo",value:"expo"},{description:"Worker only — no frontend",label:"Standalone",value:"standalone"}],za=Object.keys(T).join("|"),Va=ke.filter(e=>!z(e.value)).map(e=>e.value).join("|"),Ua=e=>z(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},Ha=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!g()||e.yes===!0?{framework:O,kind:"overlay"}:Ua(await D(y.framework,ke,{badge:f.tmpl,default:O})??O),Wa=e=>{if(g()||e.yes===!0)return;const t=[];if(e.name===void 0&&t.push("a project name (`lunora init <name>`)"),e.templateType===void 0&&e.vite===void 0&&t.push(`a framework — \`--vite <${za}>\` for an SPA, or \`-t <${Va}>\` for a bespoke template`),t.length!==0)return`lunora init can't prompt in a non-interactive terminal — provide ${t.join(" and ")}, or pass --yes to accept the defaults.`},qa=async(e,t,a,r)=>z(t)?await we({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(L(r,{recursive:!0}),_a({framework:t,logger:e.logger,name:a,overlayBaseFrom:e.overlayBaseFrom,target:r})):{code:1,files:[],target:r}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(T).join(", ")}.`),{code:1,files:[],target:r}),Fa=async(e,t,a,r)=>e.from!==void 0?await Sa(e.from,t,r,a,e.logger):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!ba(e.source)?(e.logger.error(`init: refusing --source ${e.source} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`),{code:1,files:[],target:r}):await we({isLocal:!1,logger:e.logger,source:j(t,e.source,e.ref)})?Aa({logger:e.logger,name:a,ref:e.ref,source:e.source,target:r,templateType:t}):{code:1,files:[],target:r},Ka=async(e,t,a)=>{await We("realtime backend on Cloudflare Workers + Durable Objects");const r=Wa(e);if(r!==void 0)return e.logger.error(r),{code:1,files:[],target:""};const o=aa(),s=e.name??await ne(y.name,{badge:f.dir,default:o,placeholder:o}),i=await Ha(e),n=s.trim();if(n.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:1,files:[],target:""};if(n.includes("/")||n.includes("\\")||n===".."||n===".")return e.logger.error(`init: refusing project name "${n}" — must not contain path separators or be "." / "..".`),{code:1,files:[],target:""};const c=B(t,n),d=h(c);if(d&&X(c).length>0)return e.logger.error(`target directory not empty: ${c}`),{code:1,files:[],target:c};if(e.dryRun===!0){const u=i.kind==="overlay"?`the ${i.framework} create-vite overlay`:`the ${i.templateType} template`;return M(e.logger,`scaffold ${u} into ${c}`),{code:0,files:[],target:c}}return a(c,d),i.kind==="overlay"?qa(e,i.framework,n,c):Fa(e,i.templateType,n,c)},Ja=(e,t)=>{const{target:a,targetPreExisted:r}=e;if(!(a===void 0||!h(a))){if(r===!0)for(const o of X(a))_(p(a,o),{force:!0,recursive:!0});else _(a,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${a}`)}},Qa=async(e,t,a)=>e.inPlace!==!0?Ka(e,t,a):e.dryRun===!0?(M(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):Ea(t,e.logger),Ga=async(e,t,a)=>{await Da(e,t.target);const r=e.inPlace===!0?void 0:await La(e,t.target);if(e.inPlace!==!0){await $a(e,t.target);const o=r??te(t.target);await Ma(S(t.target),r,o,xe(a)),await Mt(e.logger)}},Xa=(e,t,a)=>{if(!(t.code!==0||e.ci===void 0)){if(e.dryRun===!0){M(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}ct(e.inPlace===!0?a:t.target,e.ci,e.logger)}},Ya=async e=>{const t=e.cwd??process.cwd(),a={};let r;try{r=await Qa(e,t,(o,s)=>{a.target=o,a.targetPreExisted=s}),r.code===0&&r.target!==""&&(a.target=void 0,await Ga(e,r,t))}catch(o){if(o instanceof P)return Ja(a,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw o}return Xa(e,r,t),r},Za=e=>e==="analog"||e==="astro"||e==="expo"||e==="next"||e==="nuxt"||e==="react-router"||e==="standalone"||e==="sveltekit"||e==="tanstack-start-react"||e==="tanstack-start-solid",er=(e,t)=>{if(e!==void 0){if(nt(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},br=je(({argument:e,cwd:t,logger:a,options:r})=>{const o=r.template!==void 0&&Za(r.template)?r.template:void 0;return Ya({add:r.add,allowUnsafeSource:r.allowUnsafeSource===!0,cwd:t,ci:er(r.ci,a),dryRun:r.dryRun===!0,from:r.from,inPlace:r.here===!0,interactive:r.interactive===!0?!0:void 0,logger:a,name:e[0],ref:r.ref,source:r.source,templateType:o,vite:r.vite,yes:r.yes===!0})});export{br as execute,Za as isTemplate,j as resolveTemplateSource,Ya as runInitCommand};