@lunora/cli 1.0.0-alpha.46 → 1.0.0-alpha.461

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 (142) hide show
  1. package/LICENSE.md +33 -0
  2. package/README.md +3 -1
  3. package/dist/bin.mjs +3 -10
  4. package/dist/cli.d.mts +31 -0
  5. package/dist/cli.d.ts +31 -0
  6. package/dist/cli.mjs +1 -0
  7. package/dist/index.d.mts +1096 -386
  8. package/dist/index.d.ts +1096 -386
  9. package/dist/index.mjs +1 -19
  10. package/dist/packem_chunks/cli.mjs +2 -0
  11. package/dist/packem_chunks/dispatch.mjs +1 -0
  12. package/dist/packem_chunks/handler.mjs +17 -158
  13. package/dist/packem_chunks/handler10.mjs +1 -16
  14. package/dist/packem_chunks/handler11.mjs +1 -22
  15. package/dist/packem_chunks/handler12.mjs +1 -192
  16. package/dist/packem_chunks/handler13.mjs +1 -131
  17. package/dist/packem_chunks/handler14.mjs +1 -65
  18. package/dist/packem_chunks/handler15.mjs +3 -58
  19. package/dist/packem_chunks/handler16.mjs +1 -80
  20. package/dist/packem_chunks/handler17.mjs +1 -43
  21. package/dist/packem_chunks/handler18.mjs +1 -105
  22. package/dist/packem_chunks/handler19.mjs +1 -170
  23. package/dist/packem_chunks/handler2.mjs +1 -114
  24. package/dist/packem_chunks/handler20.mjs +7 -94
  25. package/dist/packem_chunks/handler21.mjs +2 -94
  26. package/dist/packem_chunks/handler22.mjs +1 -0
  27. package/dist/packem_chunks/handler23.mjs +3 -0
  28. package/dist/packem_chunks/handler24.mjs +3 -0
  29. package/dist/packem_chunks/handler25.mjs +1 -0
  30. package/dist/packem_chunks/handler26.mjs +2 -0
  31. package/dist/packem_chunks/handler27.mjs +99 -0
  32. package/dist/packem_chunks/handler28.mjs +15 -0
  33. package/dist/packem_chunks/handler29.mjs +1 -0
  34. package/dist/packem_chunks/handler3.mjs +1 -204
  35. package/dist/packem_chunks/handler30.mjs +1 -0
  36. package/dist/packem_chunks/handler4.mjs +1 -33
  37. package/dist/packem_chunks/handler5.mjs +3 -49
  38. package/dist/packem_chunks/handler6.mjs +1 -91
  39. package/dist/packem_chunks/handler7.mjs +1 -42
  40. package/dist/packem_chunks/handler8.mjs +1 -174
  41. package/dist/packem_chunks/handler9.mjs +2 -315
  42. package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
  43. package/dist/packem_chunks/runDevCommand.mjs +6 -0
  44. package/dist/packem_chunks/runInitCommand.mjs +212 -1432
  45. package/dist/packem_chunks/runResetCommand.mjs +1 -41
  46. package/dist/packem_chunks/runRpcCommand.mjs +1 -68
  47. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-5xxKz-zB.mjs +1 -0
  48. package/dist/packem_shared/EXIT_CODE-DVjUgIaG.mjs +1 -0
  49. package/dist/packem_shared/admin-token-VdUnvnKW.mjs +1 -0
  50. package/dist/packem_shared/admin-url-DJB8P6Jh.mjs +1 -0
  51. package/dist/packem_shared/api-spec-lYyq4vL6.mjs +1 -0
  52. package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
  53. package/dist/packem_shared/buildRegistryIndex-Dc8D8AR6.mjs +1 -0
  54. package/dist/packem_shared/cap-error-body-YBKO32BF.mjs +1 -0
  55. package/dist/packem_shared/catalog-CahzmDLV.mjs +1 -0
  56. package/dist/packem_shared/cli-manifest-DoQ_3bzs.mjs +1 -0
  57. package/dist/packem_shared/cloudflare-credentials-BVmZnDZk.mjs +1 -0
  58. package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
  59. package/dist/packem_shared/command-B6vu47iR.mjs +1 -0
  60. package/dist/packem_shared/commands-DC3ZX1yk.mjs +13 -0
  61. package/dist/packem_shared/createLogger-4TujevyB.mjs +2 -0
  62. package/dist/packem_shared/createRecordingSpawner-01ZngIwK.mjs +1 -0
  63. package/dist/packem_shared/deploy-target-resolve-BTCW1Iv4.mjs +1 -0
  64. package/dist/packem_shared/diffSnapshots-htqNZT8Q.mjs +7 -0
  65. package/dist/packem_shared/docker-DpVxvYpL.mjs +1 -0
  66. package/dist/packem_shared/free-port-DjbFhaaT.mjs +1 -0
  67. package/dist/packem_shared/health-probe-Bw9JFfIy.mjs +1 -0
  68. package/dist/packem_shared/import-DoAUdyfU.mjs +13 -0
  69. package/dist/packem_shared/index-oHZBGBwB.mjs +1 -0
  70. package/dist/packem_shared/insertSchemaExtension-CbTH3lCQ.mjs +10 -0
  71. package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
  72. package/dist/packem_shared/mcp-config-file-GR1Y_CVw.mjs +2 -0
  73. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  74. package/dist/packem_shared/output-format-DWe_tkTR.mjs +2 -0
  75. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  76. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  77. package/dist/packem_shared/plan-BH4ZfiFs.mjs +5 -0
  78. package/dist/packem_shared/planDevCommand-I8-NB_CN.mjs +1 -0
  79. package/dist/packem_shared/platform-diagnostics-Cn2g6Jh-.mjs +4 -0
  80. package/dist/packem_shared/prompt-cancelled-BvsNxg_Q.mjs +1 -0
  81. package/dist/packem_shared/render-lunora-error-DUo0pA61.mjs +2 -0
  82. package/dist/packem_shared/resolve-Bdc9KEUv.mjs +5 -0
  83. package/dist/packem_shared/resolve-target-C_ZloTvd.mjs +1 -0
  84. package/dist/packem_shared/runAddCommand-CTblwN9O.mjs +1 -0
  85. package/dist/packem_shared/runDeployCommand-Tgy9tGRV.mjs +1 -0
  86. package/dist/packem_shared/runExportCommand-DiMCQ-Il.mjs +5 -0
  87. package/dist/packem_shared/runMigrateGenerateCommand-Bd2W9t1k.mjs +11 -0
  88. package/dist/packem_shared/schemaIrToSnapshot-BHuNOfgs.mjs +1 -0
  89. package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
  90. package/dist/packem_shared/storage-BLLoZRJa.mjs +1 -0
  91. package/dist/packem_shared/tui-prompts-B3YwUhGw.mjs +4 -0
  92. package/dist/packem_shared/variables-CPYyJtsL.mjs +1 -0
  93. package/dist/packem_shared/vectorize-metadata-BVSF8z2h.mjs +2 -0
  94. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  95. package/dist/packem_shared/wrangler-secrets-DlSlWvRH.mjs +1 -0
  96. package/package.json +44 -19
  97. package/skills/README.md +36 -17
  98. package/skills/lunora/SKILL.md +158 -65
  99. package/skills/lunora-cloudflare-audit/SKILL.md +164 -0
  100. package/skills/lunora-create-package/SKILL.md +97 -84
  101. package/skills/lunora-deploy/SKILL.md +178 -105
  102. package/skills/lunora-functions/SKILL.md +367 -60
  103. package/skills/lunora-migration-helper/SKILL.md +168 -137
  104. package/skills/lunora-performance-audit/SKILL.md +137 -95
  105. package/skills/lunora-quickstart/SKILL.md +136 -136
  106. package/skills/lunora-realtime/SKILL.md +217 -97
  107. package/skills/lunora-setup-auth/SKILL.md +203 -101
  108. package/skills/lunora-setup-hyperdrive/SKILL.md +138 -109
  109. package/skills/lunora-setup-hyperdrive-global/SKILL.md +137 -92
  110. package/skills/lunora-setup-mail/SKILL.md +87 -113
  111. package/skills/lunora-setup-scheduler/SKILL.md +133 -97
  112. package/skills/lunora-setup-storage/SKILL.md +189 -95
  113. package/dist/packem_chunks/planDevCommand.mjs +0 -541
  114. package/dist/packem_chunks/runDeployCommand.mjs +0 -594
  115. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +0 -397
  116. package/dist/packem_shared/COMMANDS-B0ftFD_3.mjs +0 -948
  117. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  118. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  119. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  120. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  121. package/dist/packem_shared/codegen-error-DJG-ghs_.mjs +0 -31
  122. package/dist/packem_shared/command-D3lB_4Az.mjs +0 -19
  123. package/dist/packem_shared/commands-B-gR09Z_.mjs +0 -845
  124. package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
  125. package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
  126. package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
  127. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  128. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  129. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  130. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  131. package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
  132. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  133. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  134. package/dist/packem_shared/prompt-cancelled-APzX1Im-.mjs +0 -9
  135. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  136. package/dist/packem_shared/runAddCommand-bnY6-HKb.mjs +0 -4
  137. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  138. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  139. package/dist/packem_shared/storage-BIsph-Vk.mjs +0 -84
  140. package/dist/packem_shared/tui-prompts-BjEN8XgP.mjs +0 -658
  141. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
  142. package/dist/packem_shared/wrangler-secrets-P2_ZUR-k.mjs +0 -47
@@ -1,24 +1,13 @@
1
- import { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync, mkdtempSync, 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-D3lB_4Az.mjs';
10
- import { a as detectInstalledManagers, i as installArgsFor } from '../packem_shared/detect-package-manager-DYp7n3mJ.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 resolveDistTag, r as runAddCommand } from '../packem_shared/commands-B-gR09Z_.mjs';
15
- import { defaultSpawner } from '../packem_shared/createRecordingSpawner-DxI3mebw.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-B40gPzQo.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-BIsph-Vk.mjs';
19
- import dns from 'node:dns/promises';
20
-
21
- const GITHUB_CONTENT = `name: Deploy
1
+ import{existsSync as m,mkdirSync as M,writeFileSync as v,readFileSync as x,appendFileSync as ot,readdirSync as Y,rmSync as R,lstatSync as ge,mkdtempSync as we,copyFileSync as st,renameSync as lt}from"node:fs";import{tmpdir as ye}from"node:os";import{detectFramework as ct,DEV_VARS_EXAMPLE_FILE as be,DEV_VARS_FILE as dt,isInteractive as b,LUNA_ART as ut,LUNA_NAME as pt,LUNA_SIGNOFF as ht,BADGES as g,paintAnswer as ft,detectLintTools as mt,readProjectDependencies as ke,applyLintIgnores as vt,readProjectManifest as gt}from"@lunora/config";import{readJsonSync as wt,walkSync as yt}from"@visulima/fs";import{relative as D,join as u,dirname as C,basename as T,resolve as xe}from"@visulima/path";import{downloadTemplate as Se}from"giget";import{modify as bt,applyEdits as kt}from"jsonc-parser";import{join as J,dirname as xt}from"node:path";import{installArgsFor as Ce,execArgsFor as St,detectPackageManager as B,detectInstalledManagers as Ct,runScriptCommand as Lt,addArgsFor as At}from"@lunora/config/cli";import{d as Et}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as w}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import Mt from"magic-string";import{Project as It,SyntaxKind as y}from"ts-morph";import{P as X}from"../packem_shared/prompt-cancelled-BvsNxg_Q.mjs";import{l as Le,m as _t,n as Ae,o as Ee,a as Tt}from"../packem_shared/resolve-Bdc9KEUv.mjs";import{defaultSpawner as Me}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{d as $t,e as Nt,f as Rt,a as Ie,t as O,g as _e,h as Ot,b as Te,i as $e,w as Pt,j as Dt,k as Ne,l as Bt}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{A as Re,p as Ut,w as jt,M as Vt,r as Ft,E as Oe,k as Wt,e as Ht,c as Pe,l as De,i as zt,f as Kt}from"../packem_shared/storage-BLLoZRJa.mjs";import{r as qt}from"../packem_shared/commands-DC3ZX1yk.mjs";import{findWranglerFile as Gt,readWranglerJsonc as Yt,DEFAULT_OBSERVABILITY as Jt,CLOUDFLARE_TOOLCHAIN_VERSIONS as re}from"@lunora/config/cloudflare";import{logStep as ae}from"../packem_shared/createLogger-4TujevyB.mjs";import{r as Xt}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import Qt from"node:dns/promises";const Q={bun:{githubCacheKey:void 0,githubSetupStep:` - uses: oven-sh/setup-bun@v2
2
+ `,gitlabImage:"oven/bun:1",gitlabProvisionScript:[],installCmd:"bun install --frozen-lockfile",lockfile:"bun.lockb"},npm:{githubCacheKey:"npm",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:[],installCmd:"npm ci",lockfile:"package-lock.json"},pnpm:{githubCacheKey:"pnpm",githubSetupStep:` - uses: pnpm/action-setup@v4
3
+ with:
4
+ version: latest
5
+ `,gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"pnpm install --frozen-lockfile",lockfile:"pnpm-lock.yaml"},yarn:{githubCacheKey:"yarn",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"yarn install --frozen-lockfile",lockfile:"yarn.lock"}},E=(e,t)=>{const r=St(e,"lunora",t);return[r.command,...r.args].join(" ")},ne=e=>` - uses: actions/checkout@v4
6
+ ${e.githubSetupStep} - uses: actions/setup-node@v4
7
+ with:
8
+ node-version: 22
9
+ ${e.githubCacheKey===void 0?"":` cache: ${e.githubCacheKey}
10
+ `} - run: ${e.installCmd}`,Zt=e=>{const t=Q[e],r=t.githubCacheKey===void 0?`# (below) requires it — run \`${e} install\` locally and`:`# (below) and the ${e} cache both require it — run \`${e} install\` locally and`;return`name: Deploy
22
11
 
23
12
  on:
24
13
  push:
@@ -26,8 +15,8 @@ on:
26
15
  pull_request:
27
16
  workflow_dispatch:
28
17
 
29
- # Prerequisite: commit your pnpm-lock.yaml. \`pnpm install --frozen-lockfile\`
30
- # (below) and the pnpm cache both require it — run \`pnpm install\` locally and
18
+ # Prerequisite: commit your ${t.lockfile}. \`${t.installCmd}\`
19
+ ${r}
31
20
  # commit the lockfile before pushing, or the first CI run fails.
32
21
  #
33
22
  # Set these repository secrets (Settings → Secrets and variables → Actions):
@@ -45,16 +34,10 @@ jobs:
45
34
  permissions:
46
35
  contents: read
47
36
  steps:
48
- - uses: actions/checkout@v4
49
- - uses: pnpm/action-setup@v4
50
- - uses: actions/setup-node@v4
51
- with:
52
- node-version: 22
53
- cache: pnpm
54
- - run: pnpm install --frozen-lockfile
37
+ ${ne(t)}
55
38
  # Codegen + wrangler validation gate (no deploy) — fails fast on drift.
56
- - run: pnpm exec lunora prepare
57
- - run: pnpm exec lunora deploy
39
+ - run: ${E(e,["prepare"])}
40
+ - run: ${E(e,["deploy"])}
58
41
 
59
42
  # Preview version on every pull request — uploads a versioned preview URL;
60
43
  # production traffic is untouched.
@@ -64,31 +47,24 @@ jobs:
64
47
  permissions:
65
48
  contents: read
66
49
  steps:
67
- - uses: actions/checkout@v4
68
- - uses: pnpm/action-setup@v4
69
- - uses: actions/setup-node@v4
70
- with:
71
- node-version: 22
72
- cache: pnpm
73
- - run: pnpm install --frozen-lockfile
74
- - run: pnpm exec lunora deploy --preview
75
- `;
76
- const GITLAB_CONTENT = `stages:
50
+ ${ne(t)}
51
+ - run: ${E(e,["deploy","--preview"])}
52
+ `},er=e=>{const t=Q[e],r=[...t.gitlabProvisionScript,t.installCmd].map(a=>` - ${a}`).join(`
53
+ `);return`stages:
77
54
  - deploy
78
55
 
79
- # Prerequisite: commit your pnpm-lock.yaml. \`pnpm install --frozen-lockfile\`
80
- # (below) requires it — run \`pnpm install\` locally and commit the lockfile
56
+ # Prerequisite: commit your ${t.lockfile}. \`${t.installCmd}\`
57
+ # (below) requires it — run \`${e} install\` locally and commit the lockfile
81
58
  # before pushing, or the first pipeline fails.
82
59
  #
83
60
  # Set these as masked CI/CD variables (Settings → CI/CD → Variables):
84
61
  # CLOUDFLARE_API_TOKEN — a Workers-scoped API token
85
62
  # CLOUDFLARE_ACCOUNT_ID — your Cloudflare account id
86
63
  .lunora_base:
87
- image: node:22
64
+ image: ${t.gitlabImage}
88
65
  stage: deploy
89
66
  before_script:
90
- - corepack enable
91
- - pnpm install --frozen-lockfile
67
+ ${r}
92
68
 
93
69
  # Production deploy on the default branch.
94
70
  deploy:
@@ -97,8 +73,8 @@ deploy:
97
73
  - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
98
74
  script:
99
75
  # Codegen + wrangler validation gate (no deploy) — fails fast on drift.
100
- - pnpm exec lunora prepare
101
- - pnpm exec lunora deploy
76
+ - ${E(e,["prepare"])}
77
+ - ${E(e,["deploy"])}
102
78
 
103
79
  # Preview version on every merge request (versioned preview URL; production
104
80
  # traffic is untouched).
@@ -107,317 +83,41 @@ preview:
107
83
  rules:
108
84
  - if: $CI_PIPELINE_SOURCE == "merge_request_event"
109
85
  script:
110
- - 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: "Sign-up / sign-in (asks which provider)", label: "Authentication", value: "auth" },
347
- { description: "Cloudflare Email Workers + a dev mail catcher", label: "Transactional email", value: "email" },
348
- { description: "Typed R2 buckets + signed URLs (@lunora/storage)", label: "File storage", value: "storage" },
349
- { description: "Token-bucket / sliding-window limits (@lunora/ratelimit)", label: "Rate limiting", value: "ratelimit" },
350
- { description: "Scheduled jobs via Cron Triggers (@lunora/scheduler)", label: "Cron jobs", value: "crons" },
351
- { description: "Live presence / who's-online over hibernated WebSockets", label: "Presence", value: "presence" },
352
- { description: "Snapshot + restore your Durable Object data", label: "Backups", value: "backup" }
353
- ];
354
- const STACK_FEATURE_VALUES = STACK_FEATURE_OPTIONS.map((option) => option.value);
355
- const featureItem = (feature) => feature === "email" ? EMAIL_ITEM : feature;
356
- const parseFeatureList = (raw, warn) => {
357
- const features = [];
358
- for (const part of raw.split(",").map((entry) => entry.trim()).filter(Boolean)) {
359
- if (STACK_FEATURE_VALUES.includes(part)) {
360
- if (!features.includes(part)) {
361
- features.push(part);
362
- }
363
- } else {
364
- warn(`init: unknown --add feature "${part}" — expected ${STACK_FEATURE_VALUES.join(" | ")}; skipping.`);
365
- }
366
- }
367
- return features;
368
- };
369
- const collectAuthFeature = async (deps) => {
370
- const provider = await promptAuthProvider(deps.select);
371
- const databaseName = await promptDatabaseName(deps.text, deps.projectName);
372
- return { label: "auth", names: [provider], transformManifest: (manifest) => withAuthDatabaseName(manifest, databaseName) };
373
- };
374
- const collectEmailFeature = async (deps) => {
375
- const answer = await deps.text(MAIL_DESTINATION_PROMPT, { placeholder: "you@yourdomain.com" });
376
- const destination = resolveTypedDestination(answer, (message) => {
377
- deps.logger.warn(message);
378
- });
379
- return {
380
- label: "email",
381
- names: [EMAIL_ITEM],
382
- transformManifest: destination === void 0 ? void 0 : (manifest) => withMailDestination(manifest, destination)
383
- };
384
- };
385
- const collectStorageFeature = async (deps) => {
386
- const bucketName = await promptBucketName(deps.text, deps.projectName);
387
- return { label: "storage", names: ["storage"], transformManifest: (manifest) => withStorageBucketName(manifest, bucketName) };
388
- };
389
- const FEATURE_COLLECTORS = {
390
- auth: collectAuthFeature,
391
- email: collectEmailFeature,
392
- storage: collectStorageFeature
393
- };
394
- const offerRegistryExtras = async (deps) => {
395
- if (deps.preselected !== void 0 && deps.preselected.length > 0) {
396
- await deps.applyAll(
397
- deps.preselected.map((feature) => {
398
- return { label: feature, names: [featureItem(feature)] };
399
- })
400
- );
401
- return;
402
- }
403
- if (!deps.interactive) {
404
- deps.logger.info("tip: add features later with `lunora add <auth|email|storage|ratelimit|crons|presence|backup>`.");
405
- return;
406
- }
407
- const picked = await deps.multiSelect("Which features do you want to add?", STACK_FEATURE_OPTIONS, { defaults: [] });
408
- if (picked.length === 0) {
409
- return;
410
- }
411
- const plans = [];
412
- for (const feature of picked) {
413
- const collect = FEATURE_COLLECTORS[feature];
414
- plans.push(collect ? await collect(deps) : { label: feature, names: [feature] });
415
- }
416
- await deps.applyAll(plans);
417
- };
418
-
419
- 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";
420
- const WELCOME_CSS = `/* The welcome page is a full-bleed starter — reset the browser's default
86
+ - ${E(e,["deploy","--preview"])}
87
+ `},Be={github:{file:J(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{file:".gitlab-ci.yml",secretsHint:"masked CI/CD variables (Settings → CI/CD → Variables)"}},tr=(e,t)=>e==="github"?Zt(t):er(t),rr=e=>e==="github"||e==="gitlab",ar=(e,t,r,a={})=>{const n=J(e,Be[t].file);return m(n)&&a.overwrite!==!0?{path:n,skipped:!0,written:!1}:(M(xt(n),{recursive:!0}),v(n,tr(t,r),"utf8"),{path:n,skipped:!1,written:!0})},nr=(e,t,r,a,n={})=>{const i=Be[t];try{const s=ar(e,t,r,n);if(s.skipped)a.info(`--ci ${t}: ${i.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const o=Ce(r),l=[o.command,...o.args].join(" "),{installCmd:c,lockfile:d}=Q[r];a.success(`--ci ${t}: wrote ${i.file}`),a.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${i.secretsHint} to enable deploys.`),a.info(`--ci ${t}: run \`${l}\` and commit ${d} before pushing — the pipeline runs \`${c}\`.`)}return s}catch(s){const o=s instanceof Error?s.message:String(s);return a.warn(`--ci ${t}: could not write ${i.file} (${o})`),{path:J(e,i.file),skipped:!1,written:!1}}},ir={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",vinext:"@lunora/react"},or=e=>{const t=ct(e);return{...t,adapter:ir[t.framework]}},N="lunora()",ie='import { lunora } from "@lunora/vite";',sr="@lunora/vite",lr="lunora",cr=e=>{for(const t of e.getStatements()){if(t.getKind()!==y.ExportAssignment)continue;const r=t.asKindOrThrow(y.ExportAssignment).getExpression();if(r.getKind()!==y.CallExpression)continue;const a=r.asKindOrThrow(y.CallExpression);if(a.getExpression().getText()!=="defineConfig")continue;const n=a.getArguments()[0];if(n?.getKind()===y.ObjectLiteralExpression)return n.asKindOrThrow(y.ObjectLiteralExpression)}},dr=e=>{for(const t of e.getStatements()){if(t.getKind()!==y.ExportAssignment)continue;const r=t.asKindOrThrow(y.ExportAssignment).getExpression();if(r.getKind()===y.ObjectLiteralExpression)return r.asKindOrThrow(y.ObjectLiteralExpression)}},ur=e=>e.getDescendantsOfKind(y.CallExpression).some(t=>t.getExpression().getText()===lr),pr=e=>e.getImportDeclarations().some(t=>t.getModuleSpecifierValue()===sr),hr=e=>new It({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}),fr=(e,t)=>{const r=t.getImportDeclarations().at(-1)?.getEnd()??0;r===0?e.prepend(`${ie}
88
+ `):e.appendLeft(r,`
89
+ ${ie}`)},mr=(e,t)=>{const r=t.getProperty("plugins");if(r===void 0){const s=t.getProperties(),o=t.getStart()+1;if(s.length===0){e.appendLeft(o,` plugins: [${N}] `);return}const l=s[0];if(l===void 0)return"could not locate the start of the Vite config object's first property";e.appendLeft(l.getStart(),`plugins: [${N}],
90
+ `);return}const a=r.getDescendantsOfKind(y.ArrayLiteralExpression)[0];if(a===void 0)return"the Vite config's `plugins` is not an array literal — add `lunora()` to it by hand";const n=a.getElements();if(n.length===0){e.appendLeft(a.getStart()+1,N);return}const i=n[0];if(i===void 0)return"could not locate the first entry of the Vite config's `plugins` array";e.appendLeft(i.getStart(),`${N}, `)},Ue=e=>{const t=hr(e);if(ur(t))return{changed:!1,code:e,reason:"lunora plugin already present"};const r=cr(t)??dr(t);if(r===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const a=new Mt(e);pr(t)||fr(a,t);const n=mr(a,r);return n!==void 0?{changed:!1,code:e,reason:n}:{changed:!0,code:a.toString()}},vr=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,gr=/404|not found|could not find|no such/u,wr=(e,t)=>{const r=e instanceof Error?e.message:String(e),a=r.toLowerCase(),n=`failed to download template "${t.templateType}" from ${t.remote}: ${r}`;return gr.test(a)?{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}: ${r}`}:vr.test(a)?{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:n}:{hints:["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],message:n}},je=[{description:"No sign-in yet; add it later with `lunora add auth`",label:"None",value:"none"},{description:"Users and sessions in your own D1, via better-auth (@lunora/auth)",label:"Lunora auth",value:"lunora"},{description:"Clerk owns the session; the Worker verifies its session token",label:"Clerk",value:"clerk"},{description:"WorkOS AuthKit owns the session; the Worker verifies its access token",label:"WorkOS AuthKit",value:"workos"},{description:"Auth0 owns the session; the Worker verifies its access token",label:"Auth0",value:"auth0"}],oe=je.map(e=>e.value),Z={auth0:{clientSnippet:["// @auth0/auth0-react: <Auth0Provider authorizationParams={{ audience: AUTH0_AUDIENCE }} useRefreshTokens>","// const { getAccessTokenSilently, isLoading, user } = useAuth0();","// In a useEffect over [client, getAccessTokenSilently, isLoading, user?.sub]:","if (isLoading) return;","if (!user) return client.setAuthToken(null);","const fetchToken = () => getAccessTokenSilently().catch((error) => {",' if (["login_required", "missing_refresh_token"].includes(error?.error)) return null; // signed out'," throw error;","});","return setAuthTokenProvider(client, fetchToken, { subject: user.sub });"].join(`
91
+ `),envVars:["AUTH0_DOMAIN","AUTH0_AUDIENCE"],identity:"auth0Identity",identityFile:"auth0",item:"auth-auth0-jwt"},clerk:{clientSnippet:["// @clerk/react: const { getToken, isLoaded, isSignedIn, userId } = useAuth();","// In a useEffect over [client, getToken, isLoaded, isSignedIn, userId]:","if (!isLoaded) return;","if (!isSignedIn) return client.setAuthToken(null);","return setAuthTokenProvider(client, getToken, { subject: userId });"].join(`
92
+ `),envVars:["CLERK_PUBLISHABLE_KEY","CLERK_AUTHORIZED_PARTIES"],identity:"clerkIdentity",identityFile:"clerk",item:"auth-clerk-jwt"},workos:{clientSnippet:["// @workos-inc/authkit-react: const { getAccessToken, isLoading, user } = useAuth();","// In a useEffect over [client, getAccessToken, isLoading, user?.id]:","if (isLoading) return;","if (!user) return client.setAuthToken(null);","const fetchToken = () => getAccessToken().catch((error) => {"," if (error instanceof LoginRequiredError) return null; // signed out"," throw error;","});","return setAuthTokenProvider(client, fetchToken, { subject: user.id });"].join(`
93
+ `),envVars:["WORKOS_CLIENT_ID"],identity:"workosIdentity",identityFile:"workos",item:"auth-workos-jwt"}},yr=e=>Object.hasOwn(Z,e),br=(e,t)=>{const r=e.trim().toLowerCase();return oe.includes(r)?r:(t(`init: unknown --auth "${e}" — expected ${oe.join(" | ")}; skipping auth.`),"none")},kr=["lunora/app.ts","src/app.ts","lunora/server.ts","src/server.ts","src/server/index.ts","src/server/index.tsx","src/index.ts","src/worker.ts"],xr="virtual:lunora/worker",Sr=["lunora.config.ts","lunora.config.mts","lunora.config.js","lunora.config.mjs"],Cr=["src","app","pages","plugins"],Lr=/\.(?:[jt]sx?|svelte|vue)$/u,H="new LunoraClient({",se=/\n([\t ]*)\.build(?:FrameworkWorker)?\(/uy,Ar=new Set(["(","[","{"]),Er=new Set([")","]","}"]),Mr=(e,t)=>{const r=e[t];if(r==="/"&&e[t+1]==="/"){const n=e.indexOf(`
94
+ `,t);return n===-1?e.length:n}if(r==="/"&&e[t+1]==="*"){const n=e.indexOf("*/",t+2);return n===-1?e.length:n+2}if(r!=='"'&&r!=="'"&&r!=="`")return t;let a=t+1;for(;a<e.length&&e[a]!==r;)a+=e[a]==="\\"?2:1;return a+1},Ir=(e,t)=>{let r=0,a=t;for(;a<e.length;){const n=Mr(e,a);if(n!==a){a=n;continue}const i=e[a]??"";se.lastIndex=a;const s=r===0?se.exec(e)??void 0:void 0;if(s!==void 0)return{at:a,indent:s[1]??" "};if(r===0&&i===";")return{at:a,indent:" "};r+=Ar.has(i)?1:0,r-=Er.has(i)?1:0,a+=1}},_r=(e,t,r)=>{const a=D(C(u(e,t)),u(e,"lunora","identity",r.identityFile));return`${a.startsWith(".")?a:`./${a}`}.js`},Tr=/\bresolveIdentity\b/u,$r=/^import[^"']*["'][^"'\n]*["'][^\n]*\n/u,Nr=(e,t,r,a)=>{const n=r.indexOf("defineApp<"),i=n===-1?void 0:Ir(r,n);if(i===void 0)return;if(r.includes(`${a.identity}(env)`))return{outcome:"already-wired"};if(Tr.test(r))return{outcome:"has-resolver"};const{at:s,indent:o}=i,l=`
95
+ ${o}// Verify the provider's token on every request and feed it into ctx.auth (memoized for 5 s).
96
+ ${o}.extend((env) => ({ resolveIdentity: ${a.identity}(env) }))`,c=`import { ${a.identity} } from "${_r(e,t,a)}";
97
+ `,d=r.lastIndexOf(`
98
+ import `,n),h=d===-1?void 0:$r.exec(r.slice(d+1)),f=h==null?0:d+1+h[0].length;return{outcome:"wired",patched:r.slice(0,f)+c+r.slice(f,s)+l+r.slice(s)}},Rr=(e,t)=>{for(const r of kr){const a=u(e,r),n=m(a)?Nr(e,r,x(a,"utf8"),t):void 0;if(n?.outcome==="wired"&&v(a,n.patched),n!==void 0)return{file:r,outcome:n.outcome}}},Or=e=>{const t=Gt(e);return t!==void 0&&Yt(t).parsed?.main===xr},Pr=(e,t)=>{if(!(!Or(e)||Sr.some(r=>m(u(e,r)))))return v(u(e,"lunora.config.ts"),`import type { AppBuilder, LunoraConfig } from "./lunora/_generated/app";
99
+ import { ${t.identity} } from "./lunora/identity/${t.identityFile}";
100
+
101
+ export default {
102
+ // Verify the provider's token on every request and feed it into ctx.auth (memoized for 5 s).
103
+ app: (app: AppBuilder<object>): AppBuilder<object> => app.extend((env) => ({ resolveIdentity: ${t.identity}(env) })),
104
+ } satisfies LunoraConfig<object>;
105
+ `),"lunora.config.ts"},Ve=(e,t=0)=>t>3||!m(e)?[]:Y(e,{withFileTypes:!0}).flatMap(r=>{const a=u(e,r.name);return r.isDirectory()?r.name==="node_modules"?[]:Ve(a,t+1):Lr.test(r.name)?[a]:[]}),Dr=e=>Cr.flatMap(t=>Ve(u(e,t))).filter(t=>{const r=x(t,"utf8");return!r.includes(H)||r.includes("authTokenOnUpgrade")?!1:(v(t,r.replaceAll(H,`${H} authTokenOnUpgrade: true,`)),!0)}),Br=(e,t)=>{const r=u(e,be),a=u(e,dt),n=m(r)?x(r,"utf8"):"",i=m(a)?x(a,"utf8").split(`
106
+ `):[],s=t.envVars.filter(c=>!n.split(`
107
+ `).some(d=>d.startsWith(`${c}=`)));if(s.length===0)return!1;const o=s.map(c=>i.find(d=>d.startsWith(`${c}=`))??`${c}=`),l=n.length===0||n.endsWith(`
108
+ `)?"":`
109
+ `;return ot(r,`${l}# ${t.item}: the identity provider the Worker verifies tokens from.
110
+ ${o.join(`
111
+ `)}
112
+ `),!0},Ur=(e,t,r)=>{const a=Z[t],n=()=>{const s=Pr(e,a);return s===void 0?void 0:{file:s,outcome:"wired"}},i=Rr(e,a)??n();i===void 0?r.warn(`auth: add \`.extend((env) => ({ resolveIdentity: ${a.identity}(env) }))\` to your app builder (lunora.config.ts \`app\` hook or the Worker entry) — ${a.identity} is in lunora/identity/${a.identityFile}.ts.`):i.outcome==="already-wired"?r.info(`auth: ${i.file} already wires ${a.identity}; left as is.`):i.outcome==="has-resolver"?r.warn(`auth: ${i.file} already sets resolveIdentity, so it was left as is. Compose the two: \`resolveIdentity: composeIdentityResolvers([${a.identity}(env), <your resolver>])\` — ${a.identity} is in lunora/identity/${a.identityFile}.ts.`):r.success(`auth: wired ${a.identity} as resolveIdentity in ${i.file}`),Br(e,a)&&r.success(`auth: listed ${a.envVars.join(", ")} in ${be}`);for(const s of Dr(e))r.success(`auth: turned on authTokenOnUpgrade in ${D(e,s)}`);r.info(`auth: hand the provider's token to Lunora once signed in (setAuthTokenProvider from lunorash/client or @lunora/client):
113
+ ${a.clientSnippet}
114
+ Fill in the env vars the item wrote to .dev.vars.`)},P=async(e,t,r)=>{if(b()){await Nt(g[e],t,r);return}if(process.stdout.write(`
115
+ `),r===void 0||r===""){ae(e,t);return}const a=r.split(`
116
+ `).map(n=>ft(n)).join(`
117
+ `);ae(e,`${t}
118
+ ${a}`)},jr=async e=>{if(b()){await $t();return}e.info(`
119
+ ${ut}
120
+ ${pt}: ${ht}`)},Fe=[{description:"LLMs via Workers AI (summarize, generate, stream)",label:"AI",value:"ai"},{description:"Sign-up / sign-in with @lunora/auth (asks which provider)",label:"Authentication",value:"auth"},{description:"Copy-in auth screens for your framework (sign in/up, reset, 2FA)",label:"Auth UI",value:"auth-ui"},{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"}],le=Fe.map(e=>e.value),ce=Fe.filter(e=>e.value!=="auth"),We=new Set(["auth","auth-ui"]),Vr=e=>e==="email"?Oe:e,Fr=(e,t)=>{const r=[];for(const a of e.split(",").map(n=>n.trim()).filter(Boolean))le.includes(a)?r.includes(a)||r.push(a):t(`init: unknown --add feature "${a}" — expected ${le.join(" | ")}; skipping.`);return r},He=e=>e.resolveAuthUiItem===void 0?"auth-ui-react":e.resolveAuthUiItem(),Wr=async e=>{const t=await Ht(e.select),r=await Pe(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:a=>De(a,r)}},Hr=async e=>{const t=await e.text(Vt,{placeholder:"you@yourdomain.com"}),r=Ft(t,a=>{e.logger.warn(a)});return{label:"email",names:[Oe],transformManifest:r===void 0?void 0:a=>Wt(a,r)}},zr=async(e,t)=>{const r=He(e);if(r===void 0){e.logger.error(`init: ${Re}`);return}if(t)return{label:"auth-ui",names:[r]};const a=await Pe(e.text,e.projectName);return{label:"auth-ui",names:[r],transformManifest:n=>De(n,a)}},Kr=async e=>{const t=await Ut(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:r=>jt(r,t)}},qr=(e,t)=>{const r=[];let a=!1;for(const n of t){if(n!=="auth-ui"){r.push({label:n,names:[Vr(n)]});continue}const i=He(e);if(i===void 0){e.logger.error(`init: ${Re}`),a=!0;continue}r.push({label:n,names:[i]})}return{plans:r,refused:a}},ze=e=>e!==void 0&&yr(e)?{externalAuth:e,label:e,names:[Z[e].item]}:void 0,Gr={auth:Wr,"auth-ui":async(e,t)=>zr(e,t.includes("auth")),email:Hr,storage:Kr},Yr=async e=>{const t=ze(e.auth),r=e.auth!==void 0&&e.auth!=="lunora",a=new Set(r?(e.preselected??[]).filter(l=>We.has(l)):[]),n=(e.preselected??[]).filter(l=>!a.has(l));for(const l of a)e.logger.warn(`--auth ${String(e.auth)} rules out Lunora auth; ignoring \`${l}\` from --add.`);e.auth==="lunora"&&!n.includes("auth")&&n.unshift("auth");const{plans:i,refused:s}=qr(e,n);return t!==void 0&&i.unshift(t),await e.applyAll(i)&&!s&&a.size===0},de=async e=>{if(e.preselected!==void 0&&e.preselected.length>0||e.auth!==void 0&&!e.interactive)return Yr(e);if(!e.interactive)return 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>`."),!0;const t=e.auth??await e.selectAuth("Which auth do you want?",je,{default:"none"})??"none",r=ze(t),a=t==="lunora"?ce:ce.filter(o=>!We.has(o.value)),n=await e.multiSelect("Which features do you want to add?",a,{defaults:[]}),i=t==="lunora"&&!n.includes("auth")?["auth",...n]:n;if(i.length===0&&r===void 0)return!0;const s=r===void 0?[]:[r];for(const o of i){const l=Gr[o],c=l?await l(e,i):{label:o,names:[o]};c!==void 0&&s.push(c)}return await e.applyAll(s),!0},Jr=[{description:"Adds an ignores entry to eslint.config.js",label:"ESLint",value:"eslint"},{description:"Writes .prettierignore",label:"Prettier",value:"prettier"},{description:"Adds negated patterns to biome.json",label:"Biome",value:"biome"},{description:"Writes ignorePatterns to .oxlintrc.json",label:"oxlint (oxc)",value:"oxlint"}],Xr="Which linter/formatter do you use? We'll tell it to skip Lunora's generated files.",Qr=async e=>{const t=e.interactive?await e.multiSelect(Xr,Jr,{defaults:e.detected}):[...e.detected];if(t.length===0)return[];const r=e.apply(t);return Xt(r,e.logger),r},$="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",_=`/* The welcome page is a full-bleed starter — reset the browser's default
421
121
  body margin/padding so it sits flush; everything else is scoped under
422
122
  .lunora-welcome (collision-safe). */
423
123
  body {
@@ -522,8 +222,7 @@ body {
522
222
  .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); }
523
223
 
524
224
  @media (prefers-reduced-motion: reduce) { .lunora-welcome * { transition: none !important; } }
525
- `;
526
- const REACT_APP = `import { useEffect, useState } from "react";
225
+ `,Zr=`import { useEffect, useState } from "react";
527
226
 
528
227
  type Theme = "dark" | "light";
529
228
 
@@ -565,7 +264,7 @@ export default function App() {
565
264
  <div className="lw-wrap">
566
265
  <div className="brand">
567
266
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
568
- <path d="${LOGO_PATH}" fill="currentColor" fillRule="evenodd" />
267
+ <path d="${$}" fill="currentColor" fillRule="evenodd" />
569
268
  </svg>
570
269
  <span className="word">Lunora</span>
571
270
  </div>
@@ -684,8 +383,7 @@ export default function App() {
684
383
  </div>
685
384
  );
686
385
  }
687
- `;
688
- const VUE_APP = `<script setup lang="ts">
386
+ `,ea=`<script setup lang="ts">
689
387
  import { onMounted, ref } from "vue";
690
388
 
691
389
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -725,7 +423,7 @@ const toggle = (): void => {
725
423
  <div class="lw-wrap">
726
424
  <div class="brand">
727
425
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
728
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
426
+ <path d="${$}" fill="currentColor" fill-rule="evenodd" />
729
427
  </svg>
730
428
  <span class="word">Lunora</span>
731
429
  </div>
@@ -841,8 +539,7 @@ const toggle = (): void => {
841
539
  </div>
842
540
  </div>
843
541
  </template>
844
- `;
845
- const SOLID_APP = `import { createSignal, onMount } from "solid-js";
542
+ `,ta=`import { createSignal, onMount } from "solid-js";
846
543
 
847
544
  export default function App() {
848
545
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -882,7 +579,7 @@ export default function App() {
882
579
  <div class="lw-wrap">
883
580
  <div class="brand">
884
581
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
885
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
582
+ <path d="${$}" fill="currentColor" fill-rule="evenodd" />
886
583
  </svg>
887
584
  <span class="word">Lunora</span>
888
585
  </div>
@@ -1001,8 +698,7 @@ export default function App() {
1001
698
  </div>
1002
699
  );
1003
700
  }
1004
- `;
1005
- const SVELTE_APP = `<script lang="ts">
701
+ `,ra=`<script lang="ts">
1006
702
  import { onMount } from "svelte";
1007
703
 
1008
704
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -1045,7 +741,7 @@ const SVELTE_APP = `<script lang="ts">
1045
741
  <div class="lw-wrap">
1046
742
  <div class="brand">
1047
743
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
1048
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
744
+ <path d="${$}" fill="currentColor" fill-rule="evenodd" />
1049
745
  </svg>
1050
746
  <span class="word">Lunora</span>
1051
747
  </div>
@@ -1160,8 +856,7 @@ const SVELTE_APP = `<script lang="ts">
1160
856
  <div class="lw-foot">Running on Lunora · Vite + Svelte</div>
1161
857
  </div>
1162
858
  </div>
1163
- `;
1164
- const VANILLA_MAIN = `import "./style.css";
859
+ `,aa=`import "./style.css";
1165
860
 
1166
861
  import { LunoraClient } from "lunorash/client";
1167
862
 
@@ -1189,7 +884,7 @@ const welcomeHtml = \`
1189
884
  <div class="lw-wrap">
1190
885
  <div class="brand">
1191
886
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
1192
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
887
+ <path d="${$}" fill="currentColor" fill-rule="evenodd" />
1193
888
  </svg>
1194
889
  <span class="word">Lunora</span>
1195
890
  </div>
@@ -1325,13 +1020,10 @@ toggleButton.addEventListener("click", () => {
1325
1020
  // Live demo: the message count of a demo channel re-renders on every delta.
1326
1021
  const count = document.querySelector<HTMLSpanElement>("#lw-count")!;
1327
1022
 
1328
- client.onUpdate(api.messages.list, { channelId: "channel:demo" }, (result) => {
1023
+ client.subscribe(api.messages.list, { channelId: "channel:demo" }, (result) => {
1329
1024
  count.textContent = String(result.messages.length);
1330
1025
  });
1331
- `;
1332
-
1333
- const READ_URL = `const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;`;
1334
- const REACT_MAIN = `import "./index.css";
1026
+ `,U="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",na=`import "./index.css";
1335
1027
 
1336
1028
  import { LunoraProvider } from "@lunora/react";
1337
1029
  import { LunoraClient } from "lunorash/client";
@@ -1343,7 +1035,7 @@ import App from "./App.tsx";
1343
1035
  // \`@lunora/vite\` runs the Worker on the same origin as Vite, so default to
1344
1036
  // \`location.origin\`. Point \`VITE_LUNORA_URL\` at a deployed Worker to develop
1345
1037
  // the client against production data.
1346
- ${READ_URL}
1038
+ ${U}
1347
1039
  const client = new LunoraClient({ url });
1348
1040
 
1349
1041
  const root = document.getElementById("root");
@@ -1359,8 +1051,7 @@ createRoot(root).render(
1359
1051
  </LunoraProvider>
1360
1052
  </StrictMode>,
1361
1053
  );
1362
- `;
1363
- const VUE_MAIN = `import "./style.css";
1054
+ `,ia=`import "./style.css";
1364
1055
 
1365
1056
  import { createLunora } from "@lunora/vue";
1366
1057
  import { LunoraClient } from "lunorash/client";
@@ -1369,43 +1060,40 @@ import { createApp } from "vue";
1369
1060
  import App from "./App.vue";
1370
1061
 
1371
1062
  // Provide one LunoraClient at the app root via the Vue plugin form.
1372
- ${READ_URL}
1063
+ ${U}
1373
1064
  createApp(App).use(createLunora(new LunoraClient({ url }))).mount("#app");
1374
- `;
1375
- const SOLID_INDEX = `import "./index.css";
1065
+ `,oa=`import "./index.css";
1376
1066
 
1377
- import { LunoraContext } from "@lunora/solid";
1067
+ import { LunoraProvider } from "@lunora/solid";
1378
1068
  import { LunoraClient } from "lunorash/client";
1379
1069
  import { render } from "solid-js/web";
1380
1070
 
1381
1071
  import App from "./App";
1382
1072
 
1383
- ${READ_URL}
1073
+ ${U}
1384
1074
  const client = new LunoraClient({ url });
1385
1075
  const root = document.getElementById("root");
1386
1076
 
1387
1077
  render(
1388
1078
  () => (
1389
- <LunoraContext.Provider value={client}>
1079
+ <LunoraProvider client={client}>
1390
1080
  <App />
1391
- </LunoraContext.Provider>
1081
+ </LunoraProvider>
1392
1082
  ),
1393
1083
  root!,
1394
1084
  );
1395
- `;
1396
- const SVELTE_ROOT = `<script lang="ts">
1085
+ `,sa=`<script lang="ts">
1397
1086
  import { setLunoraClient } from "@lunora/svelte";
1398
1087
  import { LunoraClient } from "lunorash/client";
1399
1088
 
1400
1089
  import App from "./App.svelte";
1401
1090
 
1402
- ${READ_URL}
1091
+ ${U}
1403
1092
  setLunoraClient(new LunoraClient({ url }));
1404
1093
  <\/script>
1405
1094
 
1406
1095
  <App />
1407
- `;
1408
- const SVELTE_MAIN = `import "./app.css";
1096
+ `,la=`import "./app.css";
1409
1097
 
1410
1098
  import { mount } from "svelte";
1411
1099
 
@@ -1415,62 +1103,84 @@ import Root from "./Root.svelte";
1415
1103
  const app = mount(Root, { target: document.getElementById("app")! });
1416
1104
 
1417
1105
  export default app;
1418
- `;
1419
- const ADAPTERS = {
1420
- react: {
1421
- adapter: "@lunora/react",
1422
- createViteTemplate: "react-ts",
1423
- files: [
1424
- { contents: REACT_MAIN, path: "src/main.tsx" },
1425
- { contents: REACT_APP, path: "src/App.tsx" },
1426
- { contents: WELCOME_CSS, path: "src/index.css" }
1427
- ],
1428
- label: "React"
1429
- },
1430
- solid: {
1431
- adapter: "@lunora/solid",
1432
- createViteTemplate: "solid",
1433
- files: [
1434
- { contents: SOLID_INDEX, path: "src/index.tsx" },
1435
- { contents: SOLID_APP, path: "src/App.tsx" },
1436
- { contents: WELCOME_CSS, path: "src/index.css" }
1437
- ],
1438
- label: "Solid"
1439
- },
1440
- svelte: {
1441
- adapter: "@lunora/svelte",
1442
- createViteTemplate: "svelte-ts",
1443
- files: [
1444
- { contents: SVELTE_ROOT, path: "src/Root.svelte" },
1445
- { contents: SVELTE_MAIN, path: "src/main.ts" },
1446
- { contents: SVELTE_APP, path: "src/App.svelte" },
1447
- { contents: WELCOME_CSS, path: "src/app.css" }
1448
- ],
1449
- label: "Svelte"
1450
- },
1451
- vanilla: {
1452
- adapter: "lunorash/client",
1453
- createViteTemplate: "vanilla-ts",
1454
- files: [
1455
- { contents: VANILLA_MAIN, path: "src/main.ts" },
1456
- { contents: WELCOME_CSS, path: "src/style.css" }
1457
- ],
1458
- label: "Vanilla"
1459
- },
1460
- vue: {
1461
- adapter: "@lunora/vue",
1462
- createViteTemplate: "vue-ts",
1463
- files: [
1464
- { contents: VUE_MAIN, path: "src/main.ts" },
1465
- { contents: VUE_APP, path: "src/App.vue" },
1466
- { contents: WELCOME_CSS, path: "src/style.css" }
1467
- ],
1468
- label: "Vue"
1469
- }
1470
- };
1471
- const isOverlayFramework = (value) => Object.hasOwn(ADAPTERS, value);
1106
+ `,j={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:na,path:"src/main.tsx"},{contents:Zr,path:"src/App.tsx"},{contents:_,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:oa,path:"src/index.tsx"},{contents:ta,path:"src/App.tsx"},{contents:_,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:sa,path:"src/Root.svelte"},{contents:la,path:"src/main.ts"},{contents:ra,path:"src/App.svelte"},{contents:_,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:aa,path:"src/main.ts"},{contents:_,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:ia,path:"src/main.ts"},{contents:ea,path:"src/App.vue"},{contents:_,path:"src/style.css"}],label:"Vue"}},V=e=>Object.hasOwn(j,e),ca=`/**
1107
+ * Rate-limit schema extension + plugin.
1108
+ *
1109
+ * Defines the \`ratelimit_buckets\` table used by \`createDbStore\` for durable,
1110
+ * DO-backed rate limiting. Included automatically in every Lunora project.
1111
+ */
1112
+ import type { RateLimitConfigMap } from "lunorash/ratelimit";
1113
+ import { createDbStore, RateLimiter } from "lunorash/ratelimit";
1114
+ import type { Middleware } from "lunorash/server";
1115
+ import { definePlugin, defineSchemaExtension, defineTable, v } from "lunorash/server";
1116
+
1117
+ /**
1118
+ * Named limits this app enforces. This is the one place they live — add your own
1119
+ * and reference them by name from \`rateLimit(limiter, "<name>", …)\` (see
1120
+ * \`lunora/messages.ts\`).
1121
+ */
1122
+ export const limits = {
1123
+ /** Chat writes: 10 per caller per minute, refilling continuously over 60s. */
1124
+ send: { kind: "token bucket", period: 60_000, rate: 10 },
1125
+ } as const satisfies RateLimitConfigMap;
1472
1126
 
1473
- const LUNORA_SCHEMA = `import { defineSchema, defineTable, v } from "lunorash/server";
1127
+ /** The limit names you've configured above. */
1128
+ export type LimitName = keyof typeof limits;
1129
+
1130
+ /**
1131
+ * Build a durable {@link RateLimiter} bound to this request's \`ctx.db\`. State is
1132
+ * persisted in the \`ratelimit_buckets\` table, so limits survive Durable Object
1133
+ * hibernation/eviction and are shared across every call into the same DO. Each
1134
+ * \`get\`→\`set\` runs under the DO input gate, so the read-modify-write is atomic.
1135
+ */
1136
+ export const makeRateLimiter = (ctx: { db: unknown }): RateLimiter<LimitName> =>
1137
+ new RateLimiter<LimitName>({
1138
+ config: limits,
1139
+ // The merged table name carries the plugin prefix.
1140
+ store: createDbStore({ db: ctx.db as never, table: "ratelimit_buckets" }),
1141
+ });
1142
+
1143
+ /**
1144
+ * Middleware that injects \`ctx.api.ratelimit\` — a per-request limiter helper —
1145
+ * for any procedure that opts in with \`.use(ratelimit.middleware)\`. Convention
1146
+ * (see \`definePlugin\`): helpers hang off \`ctx.api.<key>\`.
1147
+ */
1148
+ const middleware: Middleware<{ api?: Record<string, unknown>; db: unknown }, { api: Record<string, unknown>; db: unknown }> = ({ ctx, next }) =>
1149
+ next({
1150
+ ctx: {
1151
+ ...ctx,
1152
+ api: { ...ctx.api, ratelimit: makeRateLimiter(ctx) },
1153
+ },
1154
+ });
1155
+
1156
+ /**
1157
+ * The rate-limit plugin: a schema extension (\`ratelimit_buckets\`) + middleware
1158
+ * (\`ctx.api.ratelimit\`). \`lunora/schema.ts\` wires the extension in with
1159
+ * \`.extend(ratelimit.extension)\`; attach the middleware yourself with
1160
+ * \`c.mutation.use(ratelimit.middleware)\`.
1161
+ */
1162
+ export const ratelimit = definePlugin("ratelimit", {
1163
+ extension: defineSchemaExtension("ratelimit", {
1164
+ tables: {
1165
+ // Bare name — auto-prefixes to \`ratelimit_buckets\` at merge time.
1166
+ // \`externallyManaged\`: rows are written by \`createDbStore\` (via
1167
+ // \`makeRateLimiter\`), not a discoverable \`ctx.db.insert(...)\`, so the
1168
+ // \`table_without_insert\` advisor correctly skips it.
1169
+ buckets: defineTable({
1170
+ key: v.string(),
1171
+ value: v.number(),
1172
+ ts: v.number(),
1173
+ prev: v.optional(v.number()),
1174
+ })
1175
+ .index("by_key", ["key"])
1176
+ .index("by_ts", ["ts"])
1177
+ .externallyManaged(),
1178
+ },
1179
+ }),
1180
+ middleware,
1181
+ });
1182
+ `,da=`import { ratelimit } from "./ratelimit/schema.js";
1183
+ import { defineSchema, defineTable, v } from "lunorash/server";
1474
1184
 
1475
1185
  export default defineSchema({
1476
1186
  messages: defineTable({
@@ -1479,25 +1189,40 @@ export default defineSchema({
1479
1189
  })
1480
1190
  .shardBy("channelId")
1481
1191
  .index("by_channel", ["channelId"]),
1482
- });
1483
- `;
1484
- const LUNORA_MESSAGES = `import { RateLimiter, rateLimit } from "@lunora/ratelimit";
1192
+ }).extend(ratelimit.extension);
1193
+ `,ua=`import { rateLimit } from "lunorash/ratelimit";
1485
1194
 
1195
+ import { makeRateLimiter } from "./ratelimit/schema.js";
1196
+ import type { MutationCtx } from "#lunora/_generated/server.js";
1486
1197
  import { mutation, query, v } from "#lunora/_generated/server.js";
1487
1198
 
1488
1199
  /**
1489
- * One in-memory limiter so the public \`send\` mutation isn't an open flood target
1490
- * out of the box. The default store is in-memory (per-isolate, resets on
1491
- * eviction) — fine for a starter; run \`lunora add ratelimit\` for the durable,
1492
- * \`ctx.db\`-backed store when you ship to production.
1200
+ * The limiter comes from \`lunora/ratelimit/schema.ts\` — that file owns the named
1201
+ * limits and the durable store, so tuning \`send\` there is what changes this
1202
+ * procedure's budget. Build it from the generated \`MutationCtx\` so
1203
+ * \`rateLimit(limiter, …)\` infers the full procedure context: \`ctx.auth\`/\`ctx.ip\`
1204
+ * in the key callback and a typed \`ctx.db\` in the handler both depend on it.
1493
1205
  */
1494
- const limiter = new RateLimiter({
1495
- config: {
1496
- send: { kind: "token bucket", period: 60_000, rate: 30 },
1497
- },
1498
- });
1206
+ const limiter = (ctx: MutationCtx) => makeRateLimiter(ctx);
1499
1207
 
1500
- export const list = query.input({ channelId: v.string().meta({ schema: { maxLength: 256 } }), limit: v.optional(v.number()) }).query(async ({ args, ctx }) => {
1208
+ /**
1209
+ * One bucket per caller, not one bucket for the whole app.
1210
+ *
1211
+ * \`ctx.auth.userId\` is \`null\` until you wire auth (\`lunora registry add auth\`),
1212
+ * so the \`ctx.ip\` fallback is what actually keys the limit in a fresh project.
1213
+ * Keying on \`"anon"\` alone would let one script exhaust the budget for every user.
1214
+ *
1215
+ * \`ctx.ip\` is Cloudflare's server-side \`CF-Connecting-IP\` and is populated ONLY
1216
+ * when the app runs on Cloudflare, where the edge stamps that header over
1217
+ * anything the client sent. Deploy this to another target and \`ctx.ip\` is
1218
+ * \`undefined\` by design — the runtime will not pass on a header the caller can
1219
+ * type — so every anonymous caller falls back to the shared \`"anon"\` bucket.
1220
+ * Off Cloudflare, key on something the caller cannot choose (an API key, a
1221
+ * signed session) before relying on this limit.
1222
+ */
1223
+ const byCaller = { key: (ctx: { auth: { userId?: null | string }; ip?: string }): string => ctx.auth.userId ?? ctx.ip ?? "anon" };
1224
+
1225
+ export const list = query.input({ channelId: v.string().max(256), limit: v.optional(v.number()) }).query(async ({ args, ctx }) => {
1501
1226
  const messages = await ctx.db
1502
1227
  .query("messages")
1503
1228
  .withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
@@ -1507,15 +1232,14 @@ export const list = query.input({ channelId: v.string().meta({ schema: { maxLeng
1507
1232
  });
1508
1233
 
1509
1234
  export const send = mutation
1510
- .input({ channelId: v.string().meta({ schema: { maxLength: 256 } }), text: v.string().meta({ schema: { maxLength: 4096 } }) })
1511
- .use(rateLimit(limiter, "send", { key: (ctx) => ctx.auth.userId ?? "anon" }))
1235
+ .input({ channelId: v.string().max(256), text: v.string().max(4096) })
1236
+ .use(rateLimit(limiter, "send", byCaller))
1512
1237
  .mutation(async ({ args, ctx }) => {
1513
1238
  const id = await ctx.db.insert("messages", { channelId: args.channelId, text: args.text });
1514
1239
 
1515
1240
  return { channelId: args.channelId, id, text: args.text };
1516
1241
  });
1517
- `;
1518
- const SERVER_ENTRY = `import type { ShardNamespaceLike } from "lunorash/runtime";
1242
+ `,pa=`import type { ShardNamespaceLike } from "lunorash/runtime";
1519
1243
 
1520
1244
  import { defineApp } from "../lunora/_generated/app.js";
1521
1245
 
@@ -1529,1003 +1253,59 @@ const app = defineApp<Env>()
1529
1253
 
1530
1254
  export const ShardDO = app.ShardDO;
1531
1255
  export default app;
1532
- `;
1533
- const WRANGLER = `{
1256
+ `,ha=`{ ${Object.entries(Jt).map(([e,t])=>`${JSON.stringify(e)}: ${JSON.stringify(t)}`).join(", ")} }`,fa=`{
1534
1257
  "$schema": "node_modules/wrangler/config-schema.json",
1535
1258
  "name": "__NAME__",
1536
1259
  "main": "src/server.ts",
1537
- "compatibility_date": "2026-06-10",
1260
+ "compatibility_date": "2026-10-01",
1538
1261
  "compatibility_flags": ["nodejs_compat"],
1539
1262
  "durable_objects": {
1540
1263
  "bindings": [{ "name": "SHARD", "class_name": "ShardDO" }],
1541
1264
  },
1542
1265
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ShardDO"] }],
1543
- "observability": { "enabled": true, "head_sampling_rate": 1 },
1266
+ "observability": ${ha},
1544
1267
  }
1545
- `;
1546
- const GITIGNORE_ADDITIONS = [".wrangler", ".env", ".env.*", "!.env.example", ".lunora/", ".lunora-cache", "lunora/_generated"];
1547
- const ENV_EXAMPLE = `# Lunora endpoint for the browser client.
1268
+ `,ue=[".wrangler",".env",".env.*","!.env.example",".dev.vars",".dev.vars.*","!.dev.vars.example",".lunora/",".lunora-cache","lunora/_generated"],ma=`# Lunora endpoint for the browser client.
1548
1269
  # Vite statically replaces \`import.meta.env.VITE_LUNORA_URL\` at \`vite dev\` / build.
1549
1270
  # Leave it unset to use the page origin; set it to point at a deployed Worker:
1550
1271
  #
1551
1272
  # VITE_LUNORA_URL=https://my-app.example.workers.dev
1552
- `;
1553
- const COMMON_DEV_DEPENDENCIES = {
1554
- "@cloudflare/workers-types": "^4.20260611.1",
1555
- wrangler: "^4.100.0"
1556
- };
1557
- const writeFile = (target, relativePath, contents, written) => {
1558
- const destination = join$1(target, relativePath);
1559
- mkdirSync(dirname$1(destination), { recursive: true });
1560
- writeFileSync(destination, contents, "utf8");
1561
- written.push(destination);
1562
- };
1563
- const NEWLINE = /\r?\n/;
1564
- const ensureGitignore = (target) => {
1565
- const path = join$1(target, ".gitignore");
1566
- const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
1567
- const missing = GITIGNORE_ADDITIONS.filter((entry) => !existing.split(NEWLINE).includes(entry));
1568
- if (missing.length === 0) {
1569
- return;
1570
- }
1571
- const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
1572
- writeFileSync(path, `${existing}${prefix}
1273
+ `,va={"@cloudflare/workers-types":re["@cloudflare/workers-types"],wrangler:re.wrangler},L=(e,t,r,a)=>{const n=u(e,t);M(C(n),{recursive:!0}),v(n,r,"utf8"),a.push(n)},ga=/\r?\n/,wa=e=>{const t=u(e,".gitignore"),r=m(t)?x(t,"utf8"):"",a=new Set(r.split(ga)),n=ue.filter(o=>!a.has(o));if(n.length===0)return;const i=n.some(o=>!o.startsWith("!"))?[...n.filter(o=>!o.startsWith("!")),...ue.filter(o=>o.startsWith("!"))]:n,s=r.length>0&&!r.endsWith(`
1274
+ `)?`
1275
+ `:"";v(t,`${r}${s}
1573
1276
  # Lunora
1574
- ${missing.join("\n")}
1575
- `, "utf8");
1576
- };
1577
- const isLunoraDep$1 = (name) => name === "lunorash" || name.startsWith("@lunora/");
1578
- const stampRange = (name, range, distTag, versions) => isLunoraDep$1(name) ? versions?.get(name) ?? distTag : range;
1579
- const withDependency = (map, name, range, distTag) => {
1580
- return { ...map, [name]: stampRange(name, range, distTag) };
1581
- };
1582
- const restampLunora = (map, distTag, versions) => Object.fromEntries(Object.entries(map).map(([name, range]) => [name, stampRange(name, range, distTag, versions)]));
1583
- const patchPackageJson = async (target, name, adapter, distTag) => {
1584
- const path = join$1(target, "package.json");
1585
- const parsed = JSON.parse(readFileSync(path, "utf8"));
1586
- let dependencies = withDependency(parsed.dependencies ?? {}, "lunorash", distTag, distTag);
1587
- dependencies = withDependency(dependencies, "@lunora/ratelimit", distTag, distTag);
1588
- if (adapter.adapter.startsWith("@lunora/")) {
1589
- dependencies = withDependency(dependencies, adapter.adapter, distTag, distTag);
1590
- }
1591
- for (const [depName, range] of Object.entries(adapter.extraDependencies ?? {})) {
1592
- dependencies = withDependency(dependencies, depName, range, distTag);
1593
- }
1594
- let devDependencies = withDependency(parsed.devDependencies ?? {}, "@lunora/vite", distTag, distTag);
1595
- devDependencies = withDependency(devDependencies, "@lunora/studio", distTag, distTag);
1596
- for (const [depName, range] of Object.entries(COMMON_DEV_DEPENDENCIES)) {
1597
- devDependencies = withDependency(devDependencies, depName, range, distTag);
1598
- }
1599
- const lunoraNames = [...Object.keys(dependencies), ...Object.keys(devDependencies)].filter((depName) => isLunoraDep$1(depName));
1600
- const versions = await resolveTagVersions(lunoraNames, distTag);
1601
- parsed.name = name;
1602
- parsed.imports = { ...parsed.imports, "#lunora/*": "./lunora/*" };
1603
- parsed.dependencies = restampLunora(dependencies, distTag, versions);
1604
- parsed.devDependencies = restampLunora(devDependencies, distTag, versions);
1605
- parsed.scripts = { ...parsed.scripts, codegen: "lunora codegen", deploy: "vite build && lunora deploy" };
1606
- writeFileSync(path, `${JSON.stringify(parsed, void 0, 4)}
1607
- `, "utf8");
1608
- };
1609
- const patchBaseViteConfig = (target, logger) => {
1610
- const candidate = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"].map((file) => join$1(target, file)).find((path) => existsSync(path));
1611
- if (candidate === void 0) {
1612
- logger.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");
1613
- return;
1614
- }
1615
- const result = patchViteConfig(readFileSync(candidate, "utf8"));
1616
- if (result.changed) {
1617
- writeFileSync(candidate, result.code, "utf8");
1618
- }
1619
- };
1620
- const applyLunoraOverlay = async (options) => {
1621
- const { adapter, distTag, logger, name, target } = options;
1622
- const written = [];
1623
- writeFile(target, join$1("lunora", "schema.ts"), LUNORA_SCHEMA, written);
1624
- writeFile(target, join$1("lunora", "messages.ts"), LUNORA_MESSAGES, written);
1625
- writeFile(target, join$1("src", "server.ts"), SERVER_ENTRY, written);
1626
- writeFile(target, "wrangler.jsonc", WRANGLER.replaceAll("__NAME__", name), written);
1627
- writeFile(target, ".env.example", ENV_EXAMPLE, written);
1628
- for (const file of adapter.files) {
1629
- writeFile(target, file.path, file.contents, written);
1630
- }
1631
- patchBaseViteConfig(target, logger);
1632
- await patchPackageJson(target, name, adapter, distTag);
1633
- ensureGitignore(target);
1634
- return written;
1635
- };
1636
-
1637
- const ADJECTIVES = [
1638
- "lunar",
1639
- "silver",
1640
- "silent",
1641
- "waning",
1642
- "waxing",
1643
- "crescent",
1644
- "cosmic",
1645
- "stellar",
1646
- "orbital",
1647
- "gibbous",
1648
- "twilight",
1649
- "midnight",
1650
- "shimmering",
1651
- "drifting",
1652
- "weightless"
1653
- ];
1654
- const NOUNS = [
1655
- "moon",
1656
- "tide",
1657
- "crater",
1658
- "comet",
1659
- "eclipse",
1660
- "halo",
1661
- "orbit",
1662
- "nebula",
1663
- "voyager",
1664
- "lander",
1665
- "rover",
1666
- "beacon",
1667
- "harbor",
1668
- "meadow",
1669
- "fox"
1670
- ];
1671
- const pick = (items) => (
1672
- // eslint-disable-next-line sonarjs/pseudo-random -- cosmetic default project name, not a security decision.
1673
- items[Math.floor(Math.random() * items.length)]
1674
- );
1675
- const generateProjectName = () => `${pick(ADJECTIVES)}-${pick(NOUNS)}`;
1676
-
1677
- const isOnline = async () => dns.lookup("github.com").then(
1678
- () => true,
1679
- () => false
1680
- );
1681
- const GITHUB_SOURCE = /^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/;
1682
- const parseGitHubSource = (source) => {
1683
- const match = GITHUB_SOURCE.exec(source);
1684
- if (match === null) {
1685
- return void 0;
1686
- }
1687
- const [, owner, repo, ref] = match;
1688
- if (owner === void 0 || repo === void 0) {
1689
- return void 0;
1690
- }
1691
- return { owner, ref: ref ?? "HEAD", repo };
1692
- };
1693
- const templateRefExists = async (source) => {
1694
- const parsed = parseGitHubSource(source);
1695
- if (parsed === void 0) {
1696
- return void 0;
1697
- }
1698
- const url = `https://codeload.github.com/${parsed.owner}/${parsed.repo}/tar.gz/${parsed.ref}`;
1699
- try {
1700
- const response = await fetch(url, { method: "HEAD" });
1701
- if (response.status === 404) {
1702
- return false;
1703
- }
1704
- return response.ok ? true : void 0;
1705
- } catch {
1706
- return void 0;
1707
- }
1708
- };
1709
- const verifyRemoteTemplate = async (params) => {
1710
- if (params.isLocal) {
1711
- return true;
1712
- }
1713
- const isGitHubBacked = params.source === void 0 || parseGitHubSource(params.source) !== void 0;
1714
- if (!isGitHubBacked) {
1715
- return true;
1716
- }
1717
- if (!await isOnline()) {
1718
- params.logger.error("you appear to be offline — connect to the internet and try again, or scaffold from a local template with `--from <dir>`.");
1719
- return false;
1720
- }
1721
- if (params.source !== void 0 && await templateRefExists(params.source) === false) {
1722
- params.logger.error(`template source not found: ${params.source} — double-check --ref / --source, or browse the templates at https://lunora.sh/docs.`);
1723
- return false;
1724
- }
1725
- return true;
1726
- };
1727
-
1728
- const COPY = {
1729
- extras: "Let's finish setting up your app.",
1730
- framework: "Which framework should we launch?",
1731
- git: "Initialize a new git repository? (optional)",
1732
- install: "Install dependencies now?",
1733
- name: "Where should we land your project?",
1734
- nextHeader: "Liftoff confirmed — explore your project!",
1735
- packageManager: "Which package manager?"
1736
- };
1737
- const TEXT_EXTENSIONS = /* @__PURE__ */ new Set([".gitignore", ".html", ".js", ".json", ".jsonc", ".md", ".mjs", ".ts", ".tsx"]);
1738
- const VITE_CONFIG_CANDIDATES = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"];
1739
- const MINIMAL_VITE_CONFIG = `import { defineConfig } from "vite";
1277
+ ${i.join(`
1278
+ `)}
1279
+ `,"utf8")},F=e=>e==="lunorash"||e.startsWith("@lunora/"),ya=(e,t,r,a)=>F(e)?a.get(e)??r:t,A=(e,t,r)=>({...e,[t]:r}),pe=(e,t,r)=>Object.fromEntries(Object.entries(e).map(([a,n])=>[a,ya(a,n,t,r)])),ba=async(e,t,r,a)=>{const n=u(e,"package.json"),i=wt(n);let s=A(i.dependencies??{},"lunorash",a);s=A(s,"@lunora/ratelimit",a),r.adapter.startsWith("@lunora/")&&(s=A(s,r.adapter,a));for(const[d,h]of Object.entries(r.extraDependencies??{}))s=A(s,d,h);let o=A(i.devDependencies??{},"@lunora/vite",a);o=A(o,"@lunora/studio",a);for(const[d,h]of Object.entries(va))o=A(o,d,h);const l=[...Object.keys(s),...Object.keys(o)].filter(d=>F(d)),c=await Le(l,a);i.name=t,i.imports={...i.imports,"#lunora/*":"./lunora/*"},i.dependencies=pe(s,a,c),i.devDependencies=pe(o,a,c),i.scripts={...i.scripts,codegen:"lunora codegen",deploy:"lunora deploy"},v(n,`${JSON.stringify(i,void 0,4)}
1280
+ `,"utf8")},ka=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Ke=e=>ka.map(t=>u(e,t)).find(t=>m(t)),xa=(e,t)=>{const r=Ke(e);if(r===void 0){t.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");return}const a=Ue(x(r,"utf8"));a.changed&&v(r,a.code,"utf8")},Sa=async e=>{const{adapter:t,distTag:r,logger:a,name:n,target:i}=e,s=[];L(i,u("lunora","ratelimit","schema.ts"),ca,s),L(i,u("lunora","schema.ts"),da,s),L(i,u("lunora","messages.ts"),ua,s),L(i,u("src","server.ts"),pa,s),L(i,"wrangler.jsonc",fa.replaceAll("__NAME__",n),s),L(i,".env.example",ma,s);for(const o of t.files)L(i,o.path,o.contents,s);return xa(i,a),await ba(i,n,t,r),wa(i),s},Ca=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],La=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],he=e=>e[Math.floor(Math.random()*e.length)],Aa=()=>`${he(Ca)}-${he(La)}`,Ea=async()=>Qt.lookup("github.com").then(()=>!0,()=>!1),Ma=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,qe=e=>{const t=Ma.exec(e);if(t===null)return;const[,r,a,n]=t;if(!(r===void 0||a===void 0))return{owner:r,ref:n??"HEAD",repo:a}},Ia=async e=>{const t=qe(e);if(t===void 0)return;const r=`https://codeload.github.com/${t.owner}/${t.repo}/tar.gz/${t.ref}`;try{const a=await fetch(r,{method:"HEAD"});return a.status===404?!1:a.ok?!0:void 0}catch{return}},Ge=async e=>e.isLocal||!(e.source===void 0||qe(e.source)!==void 0)?!0:await Ea()?e.source!==void 0&&await Ia(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),S={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?"},_a=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),Ta=`import { defineConfig } from "vite";
1740
1281
  import { lunora } from "@lunora/vite";
1741
1282
 
1742
1283
  export default defineConfig({ plugins: [lunora()] });
1743
- `;
1744
- const SAMPLE_SCHEMA = `import { defineSchema, defineTable, v } from "@lunora/server";
1284
+ `,$a=`import { defineSchema, defineTable, v } from "@lunora/server";
1745
1285
 
1746
1286
  export default defineSchema({
1747
1287
  messages: defineTable({
1748
- channelId: v.id("channels"),
1288
+ channelId: v.string(),
1749
1289
  text: v.string(),
1750
1290
  })
1751
1291
  .shardBy("channelId")
1752
1292
  .index("by_channel", ["channelId"]),
1753
1293
  });
1754
- `;
1755
- const SAMPLE_FUNCTION = `import { mutation, query, v } from "./_generated/server";
1294
+ `,Na=`import { mutation, query, v } from "./_generated/server";
1756
1295
 
1757
1296
  export const list = query
1758
- .input({ channelId: v.id("channels"), limit: v.optional(v.number()) })
1297
+ .input({ channelId: v.string(), limit: v.optional(v.number()) })
1759
1298
  .query(async ({ args }) => {
1760
1299
  return { channelId: args.channelId, limit: args.limit ?? 50, messages: [] };
1761
1300
  });
1762
1301
 
1763
1302
  export const send = mutation
1764
- .input({ channelId: v.id("channels"), text: v.string() })
1303
+ .input({ channelId: v.string(), text: v.string() })
1765
1304
  .mutation(async ({ args }) => {
1766
1305
  return { channelId: args.channelId, text: args.text };
1767
1306
  });
1768
- `;
1769
- const DEFAULT_SOURCE_BASE = "gh:anolilab/lunora/templates";
1770
- const isTextFile = (filePath) => {
1771
- const lastDot = filePath.lastIndexOf(".");
1772
- if (lastDot === -1) {
1773
- return false;
1774
- }
1775
- return TEXT_EXTENSIONS.has(filePath.slice(lastDot));
1776
- };
1777
- const substitute = (content, name) => content.replaceAll("{{name}}", name);
1778
- const isLunoraDep = (name) => name === "lunorash" || name.startsWith("@lunora/");
1779
- const resolveLunoraVersions = async (files, distTag) => {
1780
- const names = /* @__PURE__ */ new Set();
1781
- for (const file of files) {
1782
- if (basename(file) !== "package.json") {
1783
- continue;
1784
- }
1785
- try {
1786
- const parsed = JSON.parse(readFileSync(file, "utf8"));
1787
- for (const section of ["dependencies", "devDependencies"]) {
1788
- for (const name of Object.keys(parsed[section] ?? {})) {
1789
- if (isLunoraDep(name)) {
1790
- names.add(name);
1791
- }
1792
- }
1793
- }
1794
- } catch {
1795
- }
1796
- }
1797
- return resolveTagVersions(names, distTag);
1798
- };
1799
- const stampLunoraDeps = (packageJsonText, distTag, versions) => {
1800
- let parsed;
1801
- try {
1802
- parsed = JSON.parse(packageJsonText);
1803
- } catch {
1804
- return packageJsonText;
1805
- }
1806
- let text = packageJsonText;
1807
- for (const section of ["dependencies", "devDependencies"]) {
1808
- for (const name of Object.keys(parsed[section] ?? {})) {
1809
- if (!isLunoraDep(name)) {
1810
- continue;
1811
- }
1812
- const pin = versions.get(name) ?? distTag;
1813
- const edits = modify(text, [section, name], pin, { formattingOptions: { insertSpaces: true, tabSize: 4 } });
1814
- text = applyEdits(text, edits);
1815
- }
1816
- }
1817
- return text;
1818
- };
1819
- const PNPM_BUILT_DEPENDENCIES = ["esbuild", "sharp", "workerd"];
1820
- const PNPM_WORKSPACE_FILENAME = "pnpm-workspace.yaml";
1821
- const pnpmWorkspaceYaml = () => [
1822
- "# pnpm reads its settings from here (the package.json `pnpm` field is no longer read).",
1823
- "# Pre-approve the toolchain's native build scripts so `pnpm install` runs them",
1824
- "# without the interactive `pnpm approve-builds` step.",
1825
- "allowBuilds:",
1826
- ...PNPM_BUILT_DEPENDENCIES.map((name) => ` ${name}: true`),
1827
- ""
1828
- ].join("\n");
1829
- const collectFiles = (directory) => {
1830
- const out = [];
1831
- for (const entry of walkSync(directory, { includeDirs: false, includeFiles: true })) {
1832
- out.push(entry.path);
1833
- }
1834
- return out;
1835
- };
1836
- const copyTemplate = async (sourceDirectory, target, name) => {
1837
- const files = collectFiles(sourceDirectory);
1838
- const written = [];
1839
- const distTag = resolveDistTag();
1840
- const versions = await resolveLunoraVersions(files, distTag);
1841
- for (const source of files) {
1842
- const relativePath = relative(sourceDirectory, source);
1843
- const destination = join$1(target, relativePath);
1844
- mkdirSync(dirname$1(destination), { recursive: true });
1845
- const raw = readFileSync(source);
1846
- let text = isTextFile(source) ? substitute(raw.toString("utf8"), name) : void 0;
1847
- if (text !== void 0 && basename(source) === "package.json") {
1848
- text = stampLunoraDeps(text, distTag, versions);
1849
- }
1850
- if (text === void 0) {
1851
- writeFileSync(destination, raw);
1852
- } else {
1853
- writeFileSync(destination, text, "utf8");
1854
- }
1855
- written.push(destination);
1856
- }
1857
- return written;
1858
- };
1859
- const resolveTemplateSource = (templateType, source, ref) => {
1860
- if (source !== void 0 && source.length > 0) {
1861
- return source;
1862
- }
1863
- return `${DEFAULT_SOURCE_BASE}/${templateType}#${resolveSourceRef(ref)}`;
1864
- };
1865
- const isSafeSource = (source) => {
1866
- if (source.includes("..")) {
1867
- return false;
1868
- }
1869
- return source.startsWith("gh:") || source.startsWith("github:") || source.startsWith("https://");
1870
- };
1871
- const logWould = (logger, action) => {
1872
- logger.info(`[dry-run] would ${action}`);
1873
- };
1874
- const logScaffoldSuccess = (logger, written, target) => {
1875
- if (isInteractive()) {
1876
- process.stdout.write("\n");
1877
- }
1878
- logger.success(`scaffolded ${String(written.length)} files into ${target}`);
1879
- };
1880
- const runScriptCommand = (manager, script) => {
1881
- if (manager === "npm") {
1882
- return `npm run ${script}`;
1883
- }
1884
- if (manager === "bun") {
1885
- return `bun run ${script}`;
1886
- }
1887
- return `${manager} ${script}`;
1888
- };
1889
- const isInsideMonorepo = (startDirectory) => {
1890
- let directory = resolve(startDirectory);
1891
- for (; ; ) {
1892
- if (existsSync(join$1(directory, "pnpm-workspace.yaml"))) {
1893
- return true;
1894
- }
1895
- const packagePath = join$1(directory, "package.json");
1896
- if (existsSync(packagePath)) {
1897
- try {
1898
- const parsed = JSON.parse(readFileSync(packagePath, "utf8"));
1899
- if (parsed.workspaces !== void 0) {
1900
- return true;
1901
- }
1902
- } catch {
1903
- }
1904
- }
1905
- const parent = dirname$1(directory);
1906
- if (parent === directory) {
1907
- return false;
1908
- }
1909
- directory = parent;
1910
- }
1911
- };
1912
- const isInsideGitRepo = (startDirectory) => {
1913
- let directory = resolve(startDirectory);
1914
- for (; ; ) {
1915
- if (existsSync(join$1(directory, ".git"))) {
1916
- return true;
1917
- }
1918
- const parent = dirname$1(directory);
1919
- if (parent === directory) {
1920
- return false;
1921
- }
1922
- directory = parent;
1923
- }
1924
- };
1925
- const maybeOfferGit = async (options, target) => {
1926
- if (options.yes === true || !isInteractive() || isInsideGitRepo(dirname$1(target))) {
1927
- return;
1928
- }
1929
- if (!await tuiConfirm(COPY.git, { badge: BADGES.git, defaultYes: false })) {
1930
- await tuiInfo("Sounds good! You can always run git init manually.");
1931
- return;
1932
- }
1933
- if (options.dryRun === true) {
1934
- logWould(options.logger, "initialize a git repository");
1935
- return;
1936
- }
1937
- const spawner = options.spawner ?? defaultSpawner;
1938
- const result = await withTuiSpinner("Initializing a git repository…", () => spawner({ args: ["init"], command: "git", cwd: target }));
1939
- if (result.code === 0) {
1940
- await emitStep("git", "Initialized an empty git repository.");
1941
- } else {
1942
- options.logger.warn("`git init` failed — initialize it yourself later with `git init`.");
1943
- }
1944
- };
1945
- const printNextSteps = async (name, installed, insideMonorepo) => {
1946
- const manager = installed ?? "pnpm";
1947
- const steps = [{ code: `cd ./${name}`, lead: "Enter your project directory using" }];
1948
- if (installed === void 0) {
1949
- steps.push({ code: `${manager} install`, lead: "Install dependencies with", tail: insideMonorepo ? " from the workspace root" : void 0 });
1950
- }
1951
- steps.push(
1952
- { code: runScriptCommand(manager, "dev"), lead: "Run", tail: " to start the dev server." },
1953
- { code: "lunora add", lead: "Add features like auth or storage using" }
1954
- );
1955
- const help = [
1956
- { code: "https://lunora.sh/docs", lead: "Read the docs at" },
1957
- { code: "https://lunora.sh/chat", lead: "Stuck? Join the chat at" }
1958
- ];
1959
- if (isInteractive()) {
1960
- await tuiNextSteps(BADGES.next, COPY.nextHeader, steps, help);
1961
- return;
1962
- }
1963
- const lines = steps.map((step) => `${step.lead} ${step.code}${step.tail ?? ""}`);
1964
- lines.push("", ...help.map((line) => `${line.lead} ${line.code}${line.tail ?? ""}`));
1965
- await emitStep("next", COPY.nextHeader, lines.join("\n"));
1966
- };
1967
- const offerInstallIsInteractive = (options) => options.yes !== true && (options.installPrompt !== void 0 || isInteractive());
1968
- const maybeOfferInstall = async (options, target) => {
1969
- if (!offerInstallIsInteractive(options)) {
1970
- return void 0;
1971
- }
1972
- if (isInsideMonorepo(dirname$1(target))) {
1973
- return void 0;
1974
- }
1975
- const managers = detectInstalledManagers(options.packageManagerProbe);
1976
- const [defaultManager] = managers;
1977
- if (defaultManager === void 0) {
1978
- return void 0;
1979
- }
1980
- const confirm = options.installPrompt?.confirmInstall ?? (async () => tuiConfirm(COPY.install, { badge: BADGES.deps, defaultYes: true }));
1981
- if (!await confirm()) {
1982
- await tuiInfo("No problem! Remember to install dependencies after setup.");
1983
- return void 0;
1984
- }
1985
- let manager = defaultManager;
1986
- if (managers.length > 1) {
1987
- manager = options.installPrompt ? await options.installPrompt.selectManager(managers) : await tuiSelect(
1988
- COPY.packageManager,
1989
- managers.map((candidate) => {
1990
- return { label: candidate, value: candidate };
1991
- }),
1992
- { badge: BADGES.deps, default: defaultManager }
1993
- ) ?? defaultManager;
1994
- }
1995
- if (options.dryRun === true) {
1996
- logWould(options.logger, `install dependencies with ${manager}`);
1997
- return void 0;
1998
- }
1999
- if (manager === "pnpm") {
2000
- const workspacePath = join$1(target, PNPM_WORKSPACE_FILENAME);
2001
- if (!existsSync(workspacePath)) {
2002
- writeFileSync(workspacePath, pnpmWorkspaceYaml(), "utf8");
2003
- }
2004
- }
2005
- const spawner = options.spawner ?? defaultSpawner;
2006
- const { args, command } = installArgsFor(manager);
2007
- await emitStep("deps", `Installing dependencies with ${manager}…`);
2008
- const result = await spawner({ args, command, cwd: target });
2009
- if (result.code !== 0) {
2010
- options.logger.warn(`\`${command} install\` exited with code ${String(result.code)} — run it yourself in ${basename(target)}/.`);
2011
- return void 0;
2012
- }
2013
- await emitStep("deps", `Dependencies installed with ${manager}.`);
2014
- return manager;
2015
- };
2016
- const scaffoldFromLocal = async (fromRoot, templateType, target, name, logger) => {
2017
- const templateDirectory = join$1(fromRoot, templateType);
2018
- if (!existsSync(templateDirectory)) {
2019
- logger.error(`template not found in local source: ${templateDirectory}`);
2020
- return { code: 1, files: [], target };
2021
- }
2022
- const written = await copyTemplate(templateDirectory, target, name);
2023
- logScaffoldSuccess(logger, written, target);
2024
- return { code: 0, files: written, target };
2025
- };
2026
- const scaffoldFromRemote = async (options) => {
2027
- const { logger, name, ref, source, target, templateType } = options;
2028
- const stagingRoot = mkdtempSync(join$1(tmpdir(), "lunora-init-fetch-"));
2029
- const stagingDirectory = join$1(stagingRoot, "template");
2030
- try {
2031
- const remote = resolveTemplateSource(templateType, source, ref);
2032
- let downloaded;
2033
- let written = [];
2034
- await tuiTasks(
2035
- [
2036
- {
2037
- label: `${templateType} template fetched`,
2038
- run: async () => {
2039
- downloaded = await downloadTemplate(remote, {
2040
- cwd: stagingRoot,
2041
- dir: stagingDirectory,
2042
- force: true,
2043
- install: false,
2044
- silent: true
2045
- });
2046
- }
2047
- },
2048
- {
2049
- label: `files copied into ${name}/`,
2050
- run: async () => {
2051
- written = await copyTemplate(stagingDirectory, target, name);
2052
- }
2053
- }
2054
- ],
2055
- { end: "Project initialized!", start: "Project initializing…" }
2056
- );
2057
- const staged = collectFiles(stagingDirectory);
2058
- if (isInteractive()) {
2059
- process.stdout.write("\n");
2060
- }
2061
- logger.info(
2062
- downloaded?.commit ? `template: ${downloaded.source} @ ${downloaded.commit} (${String(staged.length)} files)` : `template: ${downloaded?.source ?? remote} (${String(staged.length)} files)`
2063
- );
2064
- logScaffoldSuccess(logger, written, target);
2065
- return { code: 0, files: written, target };
2066
- } catch (error) {
2067
- if (error instanceof PromptCancelledError) {
2068
- throw error;
2069
- }
2070
- const { hints, message } = describeDownloadFailure(error, {
2071
- ref: resolveSourceRef(ref),
2072
- remote: resolveTemplateSource(templateType, source, ref),
2073
- templateType
2074
- });
2075
- logger.error(message);
2076
- for (const hint of hints) {
2077
- logger.warn(hint);
2078
- }
2079
- return { code: 1, files: [], target };
2080
- } finally {
2081
- rmSync(stagingRoot, { force: true, recursive: true });
2082
- }
2083
- };
2084
- const renameCreateViteDotfiles = (directory) => {
2085
- for (const file of ["_gitignore", "_npmrc", "_gitattributes"]) {
2086
- const from = join$1(directory, file);
2087
- if (existsSync(from)) {
2088
- renameSync(from, join$1(directory, `.${file.slice(1)}`));
2089
- }
2090
- }
2091
- };
2092
- const scaffoldViteOverlay = async (options) => {
2093
- const { framework, logger, name, overlayBaseFrom, target } = options;
2094
- const adapter = ADAPTERS[framework];
2095
- const stagingRoot = mkdtempSync(join$1(tmpdir(), "lunora-vite-base-"));
2096
- try {
2097
- let localBase;
2098
- if (overlayBaseFrom !== void 0) {
2099
- localBase = join$1(overlayBaseFrom, `template-${adapter.createViteTemplate}`);
2100
- if (!existsSync(localBase)) {
2101
- logger.error(`create-vite base not found on disk: ${localBase}`);
2102
- return { code: 1, files: [], target };
2103
- }
2104
- }
2105
- const copyBase = async () => {
2106
- if (localBase !== void 0) {
2107
- cpSync(localBase, target, { recursive: true });
2108
- return;
2109
- }
2110
- const stagingDirectory = join$1(stagingRoot, "base");
2111
- const remote = `github:vitejs/vite/packages/create-vite/template-${adapter.createViteTemplate}#main`;
2112
- await downloadTemplate(remote, { cwd: stagingRoot, dir: stagingDirectory, force: true, install: false, silent: true });
2113
- renameCreateViteDotfiles(stagingDirectory);
2114
- cpSync(stagingDirectory, target, { recursive: true });
2115
- };
2116
- let written = [];
2117
- await tuiTasks(
2118
- [
2119
- { label: `create-vite (${adapter.label}) base ready`, run: copyBase },
2120
- {
2121
- label: `Lunora overlay applied (${adapter.label})`,
2122
- run: async () => {
2123
- written = await applyLunoraOverlay({ adapter, distTag: resolveDistTag(), logger, name, target });
2124
- }
2125
- }
2126
- ],
2127
- { end: "Project initialized!", start: "Project initializing…" }
2128
- );
2129
- logScaffoldSuccess(logger, written, target);
2130
- return { code: 0, files: [...collectFiles(target)], target };
2131
- } catch (error) {
2132
- if (error instanceof PromptCancelledError) {
2133
- throw error;
2134
- }
2135
- const message = error instanceof Error ? error.message : String(error);
2136
- logger.error(`failed to scaffold the ${adapter.label} base: ${message}`);
2137
- return { code: 1, files: [], target };
2138
- } finally {
2139
- rmSync(stagingRoot, { force: true, recursive: true });
2140
- }
2141
- };
2142
- const createMinimalViteConfig = (cwd, logger) => {
2143
- const target = join$1(cwd, "vite.config.ts");
2144
- try {
2145
- writeFileSync(target, MINIMAL_VITE_CONFIG, "utf8");
2146
- } catch (error) {
2147
- const message = error instanceof Error ? error.message : String(error);
2148
- logger.error(`init --in-place: could not write ${target}: ${message}`);
2149
- return { code: 1, files: [], target: cwd };
2150
- }
2151
- logger.success(`created ${target} with lunora() plugin`);
2152
- return { code: 0, files: [target], target: cwd };
2153
- };
2154
- const patchExistingViteConfig = (viteConfigPath, cwd, logger) => {
2155
- let source;
2156
- try {
2157
- source = readFileSync(viteConfigPath, "utf8");
2158
- } catch (error) {
2159
- const message = error instanceof Error ? error.message : String(error);
2160
- logger.error(`init --in-place: could not read ${viteConfigPath}: ${message}`);
2161
- return { code: 1, files: [], target: cwd };
2162
- }
2163
- const result = patchViteConfig(source);
2164
- if (!result.changed) {
2165
- logger.info(`${viteConfigPath}: ${result.reason ?? "no changes needed"}`);
2166
- return { code: 0, files: [], target: cwd };
2167
- }
2168
- try {
2169
- writeFileSync(viteConfigPath, result.code, "utf8");
2170
- } catch (error) {
2171
- const message = error instanceof Error ? error.message : String(error);
2172
- logger.error(`init --in-place: could not write ${viteConfigPath}: ${message}`);
2173
- return { code: 1, files: [], target: cwd };
2174
- }
2175
- logger.success(`patched ${viteConfigPath} — added lunora() plugin`);
2176
- return { code: 0, files: [viteConfigPath], target: cwd };
2177
- };
2178
- const scaffoldLunoraDirectory = (cwd, logger) => {
2179
- const lunoraDirectory = join$1(cwd, "lunora");
2180
- const schemaPath = join$1(lunoraDirectory, "schema.ts");
2181
- if (existsSync(schemaPath)) {
2182
- logger.info(`lunora/ already present — left ${schemaPath} untouched`);
2183
- return [];
2184
- }
2185
- const written = [];
2186
- try {
2187
- mkdirSync(lunoraDirectory, { recursive: true });
2188
- writeFileSync(schemaPath, SAMPLE_SCHEMA, "utf8");
2189
- written.push(schemaPath);
2190
- const functionPath = join$1(lunoraDirectory, "messages.ts");
2191
- if (!existsSync(functionPath)) {
2192
- writeFileSync(functionPath, SAMPLE_FUNCTION, "utf8");
2193
- written.push(functionPath);
2194
- }
2195
- logger.success(`scaffolded lunora/ (${String(written.length)} file(s))`);
2196
- } catch (error) {
2197
- const message = error instanceof Error ? error.message : String(error);
2198
- logger.error(`init --here: could not scaffold lunora/: ${message}`);
2199
- }
2200
- return written;
2201
- };
2202
- const printFrameworkNextSteps = (detection, logger) => {
2203
- const { adapter, class: frameworkClass, framework } = detection;
2204
- logger.info("");
2205
- logger.info(`detected framework: ${framework} (class ${frameworkClass})`);
2206
- logger.info("next steps:");
2207
- logger.info(` 1. install the adapter: pnpm add ${adapter} @lunora/client @lunora/runtime @lunora/server`);
2208
- logger.info(" 2. run codegen: lunora codegen");
2209
- if (frameworkClass === "A") {
2210
- logger.info(" 3. compose one worker: wrap your worker entry with");
2211
- logger.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })");
2212
- logger.info(` 4. add the provider: mount the ${adapter} provider in your root layout/route`);
2213
- logger.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component");
2214
- logger.info(" see https://lunora.sh/docs/frameworks/reactive-loaders");
2215
- } else if (frameworkClass === "B") {
2216
- logger.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook");
2217
- logger.info(` (${framework} owns its Cloudflare adapter — Lunora composes into its server entry)`);
2218
- logger.info(` 4. add the provider: mount the ${adapter} provider in your root layout`);
2219
- logger.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy");
2220
- } else {
2221
- logger.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react");
2222
- logger.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework");
2223
- }
2224
- logger.info("");
2225
- };
2226
- const findExistingViteConfig = (cwd) => {
2227
- for (const candidate of VITE_CONFIG_CANDIDATES) {
2228
- const full = join$1(cwd, candidate);
2229
- if (existsSync(full)) {
2230
- return full;
2231
- }
2232
- }
2233
- return void 0;
2234
- };
2235
- const patchOrCreateViteConfig = (cwd, framework, logger) => {
2236
- const viteConfigPath = findExistingViteConfig(cwd);
2237
- if (viteConfigPath === void 0) {
2238
- if (framework === "sveltekit" || framework === "nuxt" || framework === "astro") {
2239
- logger.info(`no Vite config found — ${framework} wires Lunora through its server entry (see next steps)`);
2240
- return { code: 0, files: [], target: cwd };
2241
- }
2242
- return createMinimalViteConfig(cwd, logger);
2243
- }
2244
- return patchExistingViteConfig(viteConfigPath, cwd, logger);
2245
- };
2246
- const runInPlaceInit = (cwd, logger) => {
2247
- const detection = detectFramework(cwd);
2248
- const viteResult = patchOrCreateViteConfig(cwd, detection.framework, logger);
2249
- if (viteResult.code !== 0) {
2250
- return viteResult;
2251
- }
2252
- const scaffolded = scaffoldLunoraDirectory(cwd, logger);
2253
- printFrameworkNextSteps(detection, logger);
2254
- return { code: 0, files: [...viteResult.files, ...scaffolded], target: cwd };
2255
- };
2256
- const offerIsInteractive = (options) => options.yes !== true && (options.prompt !== void 0 || (options.interactive ?? isInteractive()));
2257
- const maybeOfferExtras = async (options, projectDirectory) => {
2258
- const interactive = offerIsInteractive(options);
2259
- const preselected = options.add === void 0 ? [] : parseFeatureList(options.add, (message) => {
2260
- options.logger.warn(message);
2261
- });
2262
- const applyAll = async (plans) => {
2263
- if (plans.length === 0) {
2264
- return true;
2265
- }
2266
- if (options.dryRun === true) {
2267
- logWould(options.logger, `add ${plans.map((plan) => plan.label).join(", ")}`);
2268
- return true;
2269
- }
2270
- const buffered = [];
2271
- const applyLogger = isInteractive() ? {
2272
- error: (message) => {
2273
- buffered.push({ level: "error", message });
2274
- },
2275
- info: () => {
2276
- },
2277
- success: () => {
2278
- },
2279
- warn: (message) => {
2280
- buffered.push({ level: "warn", message });
2281
- }
2282
- } : options.logger;
2283
- const steps = plans.map((plan) => {
2284
- return {
2285
- running: `adding ${plan.label}…`,
2286
- task: () => runAddCommand({
2287
- allowUnsafeSource: options.allowUnsafeSource,
2288
- cwd: projectDirectory,
2289
- from: options.registryFrom,
2290
- logger: applyLogger,
2291
- names: [...plan.names],
2292
- ref: options.ref,
2293
- source: options.registrySource,
2294
- transformManifest: plan.transformManifest,
2295
- yes: true
2296
- })
2297
- };
2298
- });
2299
- const done = `added ${plans.map((plan) => plan.label).join(", ")}`;
2300
- const results = await withTuiBadgeProgress(BADGES.add, steps, done);
2301
- for (const { level, message } of buffered) {
2302
- options.logger[level](message);
2303
- }
2304
- return results.every((result) => result.code === 0);
2305
- };
2306
- const deps = {
2307
- applyAll,
2308
- interactive,
2309
- logger: options.logger,
2310
- multiSelect: options.prompt?.multiSelect ?? ((message, choices, settings) => tuiMultiSelect(message, choices, { ...settings, badge: BADGES.add })),
2311
- preselected: preselected.length > 0 ? preselected : void 0,
2312
- projectName: basename(projectDirectory),
2313
- select: options.prompt?.select ?? ((message, choices, settings) => tuiSelect(message, choices, { ...settings, badge: BADGES.add })),
2314
- text: options.prompt?.text ?? ((message, settings) => tuiText(message, { ...settings, badge: BADGES.add }))
2315
- };
2316
- if (preselected.length > 0) {
2317
- await offerRegistryExtras(deps);
2318
- return;
2319
- }
2320
- if (isInteractive()) {
2321
- await tuiHeadline(COPY.extras);
2322
- }
2323
- await offerRegistryExtras(deps);
2324
- };
2325
- const DEFAULT_FRAMEWORK = "react";
2326
- const FRAMEWORK_CHOICES = [
2327
- { description: "React SPA — official create-vite base + the Lunora layer (the default)", label: "React", value: "react" },
2328
- { description: "Vue SPA — create-vite base + Lunora", label: "Vue", value: "vue" },
2329
- { description: "Solid SPA — create-vite base + Lunora", label: "Solid", value: "solid" },
2330
- { description: "Svelte SPA — create-vite base + Lunora", label: "Svelte", value: "svelte" },
2331
- { description: "TanStack Start (React) — SSR with live-loader routes", label: "TanStack Start · React", value: "tanstack-start-react" },
2332
- { description: "TanStack Start (Solid)", label: "TanStack Start · Solid", value: "tanstack-start-solid" },
2333
- { description: "React Router (v7, framework mode) — SSR composed into the Lunora worker", label: "React Router", value: "react-router" },
2334
- { description: "Astro + a standalone Lunora worker", label: "Astro", value: "astro" },
2335
- { description: "AnalogJS (Angular) — single-worker, Lunora mounted in Nitro", label: "Analog", value: "analog" },
2336
- { description: "Nuxt (Vue) — single-worker, Lunora mounted in Nitro", label: "Nuxt", value: "nuxt" },
2337
- { description: "SvelteKit + a standalone Lunora worker", label: "SvelteKit", value: "sveltekit" },
2338
- { description: "Worker only — no frontend", label: "Standalone", value: "standalone" }
2339
- ];
2340
- const OVERLAY_VALUES = Object.keys(ADAPTERS).join("|");
2341
- const TEMPLATE_VALUES = FRAMEWORK_CHOICES.filter((choice) => !isOverlayFramework(choice.value)).map((choice) => choice.value).join("|");
2342
- const toScaffoldChoice = (value) => isOverlayFramework(value) ? { framework: value, kind: "overlay" } : { kind: "template", templateType: value };
2343
- const resolveScaffoldChoice = async (options) => {
2344
- if (options.vite !== void 0) {
2345
- return { framework: options.vite, kind: "overlay" };
2346
- }
2347
- if (options.templateType !== void 0) {
2348
- return { kind: "template", templateType: options.templateType };
2349
- }
2350
- if (!isInteractive() || options.yes === true) {
2351
- return { framework: DEFAULT_FRAMEWORK, kind: "overlay" };
2352
- }
2353
- return toScaffoldChoice(await tuiSelect(COPY.framework, FRAMEWORK_CHOICES, { badge: BADGES.tmpl, default: DEFAULT_FRAMEWORK }) ?? DEFAULT_FRAMEWORK);
2354
- };
2355
- const nonInteractiveInitError = (options) => {
2356
- if (isInteractive() || options.yes === true) {
2357
- return void 0;
2358
- }
2359
- const missing = [];
2360
- if (options.name === void 0) {
2361
- missing.push("a project name (`lunora init <name>`)");
2362
- }
2363
- if (options.templateType === void 0 && options.vite === void 0) {
2364
- missing.push(`a framework — \`--vite <${OVERLAY_VALUES}>\` for an SPA, or \`-t <${TEMPLATE_VALUES}>\` for a bespoke template`);
2365
- }
2366
- if (missing.length === 0) {
2367
- return void 0;
2368
- }
2369
- return `lunora init can't prompt in a non-interactive terminal — provide ${missing.join(" and ")}, or pass --yes to accept the defaults.`;
2370
- };
2371
- const scaffoldOverlayPath = async (options, framework, name, target) => {
2372
- if (!isOverlayFramework(framework)) {
2373
- options.logger.error(`init: unknown framework "${framework}". Supported overlays: ${Object.keys(ADAPTERS).join(", ")}.`);
2374
- return { code: 1, files: [], target };
2375
- }
2376
- if (!await verifyRemoteTemplate({ isLocal: options.overlayBaseFrom !== void 0, logger: options.logger })) {
2377
- return { code: 1, files: [], target };
2378
- }
2379
- mkdirSync(target, { recursive: true });
2380
- return scaffoldViteOverlay({ framework, logger: options.logger, name, overlayBaseFrom: options.overlayBaseFrom, target });
2381
- };
2382
- const scaffoldTemplatePath = async (options, templateType, name, target) => {
2383
- if (templateType === "next") {
2384
- options.logger.warn('template "next" is not yet available — re-run with `--vite react` or `-t standalone`.');
2385
- return { code: 1, files: [], target };
2386
- }
2387
- if (options.from !== void 0) {
2388
- return await scaffoldFromLocal(options.from, templateType, target, name, options.logger);
2389
- }
2390
- if (options.source !== void 0 && options.source.length > 0 && !options.allowUnsafeSource && !isSafeSource(options.source)) {
2391
- options.logger.error(
2392
- `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.`
2393
- );
2394
- return { code: 1, files: [], target };
2395
- }
2396
- if (!await verifyRemoteTemplate({ isLocal: false, logger: options.logger, source: resolveTemplateSource(templateType, options.source, options.ref) })) {
2397
- return { code: 1, files: [], target };
2398
- }
2399
- return scaffoldFromRemote({ logger: options.logger, name, ref: options.ref, source: options.source, target, templateType });
2400
- };
2401
- const scaffoldNewProject = async (options, cwd, recordTarget) => {
2402
- await tuiMoonrise("realtime backend on Cloudflare Workers + Durable Objects");
2403
- const blocked = nonInteractiveInitError(options);
2404
- if (blocked !== void 0) {
2405
- options.logger.error(blocked);
2406
- return { code: 1, files: [], target: "" };
2407
- }
2408
- const suggestedName = generateProjectName();
2409
- const name = options.name ?? await tuiText(COPY.name, { badge: BADGES.dir, default: suggestedName, placeholder: suggestedName });
2410
- const choice = await resolveScaffoldChoice(options);
2411
- if (name.includes("/") || name.includes("\\") || name === ".." || name === ".") {
2412
- options.logger.error(`init: refusing project name "${name}" — must not contain path separators or be "." / "..".`);
2413
- return { code: 1, files: [], target: "" };
2414
- }
2415
- const target = resolve(cwd, name);
2416
- const targetPreExisted = existsSync(target);
2417
- if (targetPreExisted) {
2418
- const entries = readdirSync(target);
2419
- if (entries.length > 0) {
2420
- options.logger.error(`target directory not empty: ${target}`);
2421
- return { code: 1, files: [], target };
2422
- }
2423
- }
2424
- if (options.dryRun === true) {
2425
- const what = choice.kind === "overlay" ? `the ${choice.framework} create-vite overlay` : `the ${choice.templateType} template`;
2426
- logWould(options.logger, `scaffold ${what} into ${target}`);
2427
- return { code: 0, files: [], target };
2428
- }
2429
- recordTarget(target, targetPreExisted);
2430
- return choice.kind === "overlay" ? scaffoldOverlayPath(options, choice.framework, name, target) : scaffoldTemplatePath(options, choice.templateType, name, target);
2431
- };
2432
- const resetScaffoldOnCancel = (cleanup, logger) => {
2433
- const { target, targetPreExisted } = cleanup;
2434
- if (target === void 0 || !existsSync(target)) {
2435
- return;
2436
- }
2437
- if (targetPreExisted === true) {
2438
- for (const entry of readdirSync(target)) {
2439
- rmSync(join$1(target, entry), { force: true, recursive: true });
2440
- }
2441
- } else {
2442
- rmSync(target, { force: true, recursive: true });
2443
- }
2444
- logger.info(`removed the partially-created project at ${target}`);
2445
- };
2446
- const runScaffoldStep = async (options, cwd, recordTarget) => {
2447
- if (options.inPlace !== true) {
2448
- return scaffoldNewProject(options, cwd, recordTarget);
2449
- }
2450
- if (options.dryRun === true) {
2451
- logWould(options.logger, `configure Lunora into ${cwd}`);
2452
- return { code: 0, files: [], target: cwd };
2453
- }
2454
- return runInPlaceInit(cwd, options.logger);
2455
- };
2456
- const runPostScaffold = async (options, result, cwd) => {
2457
- await maybeOfferExtras(options, result.target);
2458
- const installedManager = options.inPlace === true ? void 0 : await maybeOfferInstall(options, result.target);
2459
- if (options.inPlace !== true) {
2460
- await maybeOfferGit(options, result.target);
2461
- await printNextSteps(basename(result.target), installedManager, isInsideMonorepo(cwd));
2462
- await emitMascot(options.logger);
2463
- }
2464
- };
2465
- const scaffoldCiPipeline = (options, result, cwd) => {
2466
- if (result.code !== 0 || options.ci === void 0) {
2467
- return;
2468
- }
2469
- if (options.dryRun === true) {
2470
- logWould(options.logger, `scaffold a ${options.ci} CI deploy pipeline`);
2471
- return;
2472
- }
2473
- scaffoldCiWorkflow(options.inPlace === true ? cwd : result.target, options.ci, options.logger);
2474
- };
2475
- const runInitCommand = async (options) => {
2476
- const cwd = options.cwd ?? process.cwd();
2477
- const cleanup = {};
2478
- let result;
2479
- try {
2480
- result = await runScaffoldStep(options, cwd, (target, preExisted) => {
2481
- cleanup.target = target;
2482
- cleanup.targetPreExisted = preExisted;
2483
- });
2484
- if (result.code === 0 && result.target !== "") {
2485
- cleanup.target = void 0;
2486
- await runPostScaffold(options, result, cwd);
2487
- }
2488
- } catch (error) {
2489
- if (error instanceof PromptCancelledError) {
2490
- resetScaffoldOnCancel(cleanup, options.logger);
2491
- process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n");
2492
- return { code: 130, files: [], target: "" };
2493
- }
2494
- throw error;
2495
- }
2496
- scaffoldCiPipeline(options, result, cwd);
2497
- return result;
2498
- };
2499
- const isTemplate = (value) => value === "analog" || value === "astro" || value === "next" || value === "nuxt" || value === "react-router" || value === "standalone" || value === "sveltekit" || value === "tanstack-start-react" || value === "tanstack-start-solid";
2500
- const resolveCiProvider = (raw, logger) => {
2501
- if (raw === void 0) {
2502
- return void 0;
2503
- }
2504
- if (isCiProvider(raw)) {
2505
- return raw;
2506
- }
2507
- logger.warn(`init: unknown --ci "${raw}" — expected github | gitlab; skipping CI scaffold.`);
2508
- return void 0;
2509
- };
2510
- const execute = defineHandler(({ argument, cwd, logger, options }) => {
2511
- const templateType = options.template !== void 0 && isTemplate(options.template) ? options.template : void 0;
2512
- return runInitCommand({
2513
- add: options.add,
2514
- allowUnsafeSource: options.allowUnsafeSource === true,
2515
- cwd,
2516
- ci: resolveCiProvider(options.ci, logger),
2517
- dryRun: options.dryRun === true,
2518
- from: options.from,
2519
- inPlace: options.here === true,
2520
- interactive: options.interactive === true ? true : void 0,
2521
- logger,
2522
- name: argument[0],
2523
- ref: options.ref,
2524
- source: options.source,
2525
- templateType,
2526
- vite: options.vite,
2527
- yes: options.yes === true
2528
- });
2529
- });
2530
-
2531
- export { execute, isTemplate, resolveTemplateSource, runInitCommand };
1307
+ `,Ra="gh:anolilab/lunora/templates",Oa=e=>{const t=e.lastIndexOf(".");return t===-1?!1:_a.has(e.slice(t))},Pa=/^[a-z0-9_][a-z0-9\-_]*$/u,Da=/([a-z0-9])([A-Z])/gu,Ba=/[^a-z0-9_]/gu,Ua=e=>{const t=e.replaceAll(Da,"$1-$2").toLowerCase().replaceAll(Ba,"-").split("-").filter(r=>r.length>0);return t.length>0?t.join("-"):"my-app"},ja=(e,t)=>e.replaceAll("{{name}}",t),Va=async(e,t)=>{const r=new Set;for(const a of e)if(T(a)==="package.json")for(const n of Object.keys(ke(C(a))))F(n)&&r.add(n);return Le(r,t)},Fa=(e,t,r)=>{let a;try{a=JSON.parse(e)}catch{return e}let n=e;for(const i of["dependencies","devDependencies"])for(const s of Object.keys(a[i]??{})){if(!F(s))continue;const o=r.get(s)??t,l=bt(n,[i,s],o,{formattingOptions:{insertSpaces:!0,tabSize:4}});n=kt(n,l)}return n},Wa=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],Ha=["cpu-features","protobufjs","ssh2"],Ye="pnpm-workspace.yaml",za=()=>["# 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:",...Wa.map(e=>` '${e}': true`),...Ha.map(e=>` '${e}': false`),""].join(`
1308
+ `),Je=e=>{const t=u(e,Ye);m(t)||v(t,za(),"utf8")},W=e=>{const t=[];for(const r of yt(e,{includeDirs:!1,includeFiles:!0}))ge(r.path).isSymbolicLink()||t.push(r.path);return t},fe="vitejs/vite",me=(e,t)=>{for(const r of W(e)){const a=u(t,D(e,r));M(C(a),{recursive:!0}),st(r,a)}},Xe=async(e,t,r)=>{const a=W(e),n=[],i=Ae(),s=await Va(a,i);for(const o of a){const l=D(e,o),c=u(t,l);M(C(c),{recursive:!0});const d=x(o);let h=Oa(o)?ja(d.toString("utf8"),r):void 0;h!==void 0&&T(o)==="package.json"&&(h=Fa(h,i,s)),h===void 0?v(c,d):v(c,h,"utf8"),n.push(c)}return n},q=(e,t,r)=>t!==void 0&&t.length>0?t:`${Ra}/${e}#${Ee(r)}`,Ka=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),I=(e,t)=>{e.info(`[dry-run] would ${t}`)},Qe=(e,t,r)=>(e.error(`init: the template at ${r} contains no files — nothing was scaffolded. Check the template name, \`--source\` layout and \`--ref\`.`),{code:w.NOT_FOUND,files:[],target:t}),Ze="Template files copied.",ee=(e,t,r)=>{b()&&process.stdout.write(`
1309
+ `),e.success(`scaffolded ${String(t.length)} files into ${r}`)},qa=(e,t)=>{const{args:r,command:a}=At(e,t);return`${a} ${r.join(" ")}`},et=(e,t)=>{let r=xe(e);for(;;){if(t(r))return!0;const a=C(r);if(a===r)return!1;r=a}},Ga=e=>m(u(e,Ye))?!0:gt(e)?.workspaces!==void 0,te=e=>et(e,Ga),Ya=e=>et(e,t=>m(u(t,".git"))),Ja=async(e,t)=>{if(e.yes===!0||!b()||Ya(C(t)))return;if(!await Te(S.git,{badge:g.git,defaultYes:!1})){await $e("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){I(e.logger,"initialize a git repository");return}const r=e.spawner??Me;(await Pt("Initializing a git repository…",()=>r({args:["init"],command:"git",cwd:t}))).code===0?await P("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},Xa=async(e,t,r,a)=>{const n=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&n.push({code:`${r} install`,lead:"Install dependencies with",tail:a?" from the workspace root":void 0}),n.push({code:Lt(r,"dev"),lead:"Run",tail:" to start the dev server."},{code:"lunora add",lead:"Add features like auth or storage using"});const i=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(b()){await Dt(g.next,S.nextHeader,n,i);return}const s=n.map(o=>`${o.lead} ${o.code}${o.tail??""}`);s.push("",...i.map(o=>`${o.lead} ${o.code}${o.tail??""}`)),await P("next",S.nextHeader,s.join(`
1310
+ `))},Qa=e=>e.yes!==!0&&(e.installPrompt!==void 0||b()),Za=async(e,t)=>{if(!Qa(e)||te(C(t)))return;const r=Ct(e.packageManagerProbe),[a]=r;if(a===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>Te(S.install,{badge:g.deps,defaultYes:!0})))()){await $e("No problem! Remember to install dependencies after setup.");return}let i=a;if(r.length>1&&(i=e.installPrompt?await e.installPrompt.selectManager(r):await O(S.packageManager,r.map(d=>({label:d,value:d})),{badge:g.deps,default:a})??a),e.dryRun===!0){I(e.logger,`install dependencies with ${i}`);return}i==="pnpm"&&Je(t);const s=e.spawner??Me,{args:o,command:l}=Ce(i);await P("deps",`Installing dependencies with ${i}…`);const c=await s({args:o,command:l,cwd:t});if(c.code!==0){e.logger.warn(`\`${l} install\` exited with code ${String(c.code)} — run it yourself in ${T(t)}/.`);return}return await P("deps",`Dependencies installed with ${i}.`),i},en=async(e,t,r,a,n,i)=>{const s=u(e,t);if(!m(s))return n.error(`template not found in local source: ${s}`),{code:w.NOT_FOUND,files:[],target:r};const o=await Xe(s,r,a);return o.length===0?Qe(n,r,s):(i(),ee(n,o,r),{code:0,files:o,target:r})},tn=async e=>{const{logger:t,markComplete:r,name:a,ref:n,source:i,target:s,templateType:o}=e,l=we(u(ye(),"lunora-init-fetch-")),c=u(l,"template");try{const d=i!==void 0&&i.length>0?n:await Tt(n,t),h=q(o,i,d);let f,p=[];if(await Ne([{label:`${o} template fetched`,run:async()=>{f=await Se(h,{cwd:l,dir:c,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{p=await Xe(c,s,a)}}],{end:Ze,start:"Project initializing…"}),p.length===0)return Qe(t,s,f?.source??h);r();const k=W(c);return b()&&process.stdout.write(`
1311
+ `),t.info(f?.commit?`template: ${f.source} @ ${f.commit} (${String(k.length)} files)`:`template: ${f?.source??h} (${String(k.length)} files)`),ee(t,p,s),{code:0,files:p,target:s}}catch(d){if(d instanceof X)throw d;const{hints:h,message:f}=wr(d,{ref:Ee(n),remote:q(o,i,n),templateType:o});t.error(f);for(const p of h)t.warn(p);return{code:1,files:[],target:s}}finally{R(l,{force:!0,recursive:!0})}},rn=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const r=u(e,t);m(r)&&lt(r,u(e,`.${t.slice(1)}`))}},an=async e=>{const{framework:t,logger:r,markComplete:a,name:n,overlayBaseFrom:i,target:s}=e,o=j[t],l=we(u(ye(),"lunora-vite-base-"));try{let c;if(i!==void 0&&(c=u(i,`template-${o.createViteTemplate}`),!m(c)))return r.error(`create-vite base not found on disk: ${c}`),{code:w.NOT_FOUND,files:[],target:s};const d=async()=>{if(c!==void 0){me(c,s);return}const f=u(l,"base"),p=await _t(fe,"main",r),k=`github:${fe}/packages/create-vite/template-${o.createViteTemplate}#${p}`;await Se(k,{cwd:l,dir:f,force:!0,install:!1,silent:!0}),rn(f),me(f,s)};let h=[];return await Ne([{label:`create-vite (${o.label}) base ready`,run:d},{label:`Lunora overlay applied (${o.label})`,run:async()=>{h=await Sa({adapter:o,distTag:Ae(),logger:r,name:n,target:s})}}],{end:Ze,start:"Project initializing…"}),a(),ee(r,h,s),{code:0,files:[...W(s)],target:s}}catch(c){if(c instanceof X)throw c;const d=c instanceof Error?c.message:String(c);return r.error(`failed to scaffold the ${o.label} base: ${d}`),{code:1,files:[],target:s}}finally{R(l,{force:!0,recursive:!0})}},G=(e,t,r,a,n)=>(n.error(`init --in-place: could not ${e} ${t}: ${r instanceof Error?r.message:String(r)}`),{code:1,files:[],target:a}),nn=(e,t)=>{const r=u(e,"vite.config.ts");try{v(r,Ta,"utf8")}catch(a){return G("write",r,a,e,t)}return t.success(`created ${r} with lunora() plugin`),{code:0,files:[r],target:e}},on=(e,t,r)=>{let a;try{a=x(e,"utf8")}catch(i){return G("read",e,i,t,r)}const n=Ue(a);if(!n.changed)return r.info(`${e}: ${n.reason??"no changes needed"}`),{code:0,files:[],target:t};try{v(e,n.code,"utf8")}catch(i){return G("write",e,i,t,r)}return r.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},sn=(e,t)=>{const r=u(e,"lunora"),a=u(r,"schema.ts");if(m(a))return t.info(`lunora/ already present — left ${a} untouched`),[];const n=[];try{M(r,{recursive:!0}),v(a,$a,"utf8"),n.push(a);const i=u(r,"messages.ts");m(i)||(v(i,Na,"utf8"),n.push(i)),t.success(`scaffolded lunora/ (${String(n.length)} file(s))`)}catch(i){const s=i instanceof Error?i.message:String(i);t.error(`init --here: could not scaffold lunora/: ${s}`)}return n},tt=e=>e==="sveltekit"||e==="nuxt"||e==="astro",ln=(e,t,r)=>{const{adapter:a,class:n,framework:i}=e;r.info(""),r.info(`detected framework: ${i} (class ${n})`),r.info("next steps:");const s=[a,"@lunora/client","@lunora/runtime","@lunora/server"];tt(i)||s.push("@lunora/vite"),r.info(` 1. install the adapter: ${qa(t,s)}`),r.info(" 2. run codegen: lunora codegen"),n==="A"?(r.info(" 3. compose one worker: wrap your worker entry with"),r.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),r.info(` 4. add the provider: mount the ${a} provider in your root layout/route`),r.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),r.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):n==="B"?(r.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),r.info(` (${i} owns its Cloudflare adapter — Lunora composes into its server entry)`),r.info(` 4. add the provider: mount the ${a} provider in your root layout`),r.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(r.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),r.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),r.info("")},cn=(e,t,r)=>{if(tt(t))return r.info(`${t} wires Lunora through its server entry, not a lunora() Vite plugin — leaving the Vite config alone (see next steps)`),{code:0,files:[],target:e};const a=Ke(e);return a===void 0?nn(e,r):on(a,e,r)},dn=(e,t)=>{const r=or(e),a=cn(e,r.framework,t);if(a.code!==0)return a;const n=sn(e,t);return ln(r,B(e),t),{code:0,files:[...a.files,...n],target:e}},un=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??b())),ve=async(e,t,r)=>{r.dryRun!==!0&&await Qr({apply:a=>vt(e,a),detected:mt(e),interactive:t,logger:r.logger,multiSelect:r.lintPrompt??((a,n,i)=>_e(a,n,{...i,badge:g.add}))})},pn=async(e,t)=>{const r=un(e),a=e.add===void 0?[]:Fr(e.add,o=>{e.logger.warn(o)}),n=async o=>{if(o.length===0)return!0;if(e.dryRun===!0)return I(e.logger,`add ${o.map(p=>p.externalAuth===void 0?p.label:`${p.label} (and wire resolveIdentity)`).join(", ")}`),!0;const l=[],c=b()?{error:p=>{l.push({level:"error",message:p})},info:()=>{},success:()=>{},warn:p=>{l.push({level:"warn",message:p})}}:e.logger,d=o.map(p=>({running:`adding ${p.label}…`,task:()=>qt({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:c,names:[...p.names],ref:e.ref,source:e.registrySource,transformManifest:p.transformManifest,yes:!0})})),h=`added ${o.map(p=>p.label).join(", ")}`,f=await Bt(g.add,d,h);for(const{level:p,message:k}of l)e.logger[p](k);for(const[p,k]of o.entries())k.externalAuth!==void 0&&f[p]?.code===0&&Ur(t,k.externalAuth,e.logger);return f.every(p=>p.code===0)},i=e.auth===void 0?void 0:br(e.auth,o=>{e.logger.warn(o)}),s={applyAll:n,auth:i,interactive:r,logger:e.logger,multiSelect:e.prompt?.multiSelect??((o,l,c)=>_e(o,l,{...c,badge:g.add})),preselected:a.length>0?a:void 0,projectName:T(t),resolveAuthUiItem:()=>{const o=ke(t);if(!zt(o))return Kt(o)??"auth-ui-react"},select:e.prompt?.select??((o,l,c)=>O(o,l,{...c,badge:g.add})),selectAuth:e.prompt===void 0?(o,l,c)=>O(o,l,{...c,badge:g.add}):e.prompt.selectAuth??(()=>Promise.resolve("none")),text:e.prompt?.text??((o,l)=>Ie(o,{...l,badge:g.add}))};if(a.length>0||i!==void 0&&!r){const o=await de(s);return await ve(t,r,e),o}return b()&&await Ot(S.extras),await de(s),await ve(t,r,e),!0},z="react",rt=[{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:"Solid 2.0 SPA — the Solid 2 line (@solidjs/web, vite-plugin-solid 3)",label:"Solid 2",value:"solid-v2"},{description:"Svelte SPA — create-vite base + Lunora",label:"Svelte",value:"svelte"},{description:"React SPA on Rsbuild — the Worker runs under wrangler dev behind the dev server",label:"React · Rsbuild",value:"rspack-react"},{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 (React) on Rsbuild — SSR composed into the Lunora worker",label:"TanStack Start · React · Rsbuild",value:"tanstack-start-react-rspack"},{description:"SaaS kit — multi-tenant app on TanStack Start: organizations, projects, activity, admin",label:"SaaS kit",value:"saas"},{description:"TanStack Start (Solid)",label:"TanStack Start · Solid",value:"tanstack-start-solid"},{description:"Next.js App Router on Vite (vinext) — composed into the Lunora worker (experimental)",label:"vinext · App Router",value:"vinext"},{description:"Next.js Pages Router on Vite (vinext) — composed into one worker (experimental)",label:"vinext · Pages Router",value:"vinext-pages"},{description:"Astro (islands) — single-worker, Lunora composed into the adapter 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 — single-worker, Lunora composed into the adapter 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"}],at=Object.keys(j).join("|"),nt=rt.filter(e=>!V(e.value)).map(e=>e.value),it=nt.join("|"),hn=e=>V(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},fn=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!b()||e.yes===!0?{framework:z,kind:"overlay"}:hn(await O(S.framework,rt,{badge:g.tmpl,default:z})??z),mn=e=>{if(b()||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 <${at}>\` for an SPA, or \`-t <${it}>\` 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.`},vn=async(e,t,r,a,n)=>V(t)?await Ge({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(M(a,{recursive:!0}),an({framework:t,logger:e.logger,markComplete:n,name:r,overlayBaseFrom:e.overlayBaseFrom,target:a})):{code:1,files:[],target:a}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(j).join(", ")}.`),{code:w.USAGE,files:[],target:a}),gn=async(e,t,r,a,n)=>e.from!==void 0?await en(e.from,t,a,r,e.logger,n):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!Ka(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:w.USAGE,files:[],target:a}):await Ge({isLocal:!1,logger:e.logger,source:q(t,e.source,e.ref)})?tn({logger:e.logger,markComplete:n,name:r,ref:e.ref,source:e.source,target:a,templateType:t}):{code:1,files:[],target:a},wn=(e,t)=>{if(te(t))return;let r;try{r=B(e)}catch{return}r==="pnpm"&&Je(e)},yn=async(e,t,r)=>{await Rt("realtime backend on Cloudflare Workers + Durable Objects");const a=mn(e);if(a!==void 0)return e.logger.error(a),{code:w.USAGE,files:[],target:""};const n=Aa(),i=e.name??await Ie(S.name,{badge:g.dir,default:n,placeholder:n}),s=await fn(e),o=i.trim();if(o.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:w.USAGE,files:[],target:""};if(o.includes("/")||o.includes("\\")||o===".."||o===".")return e.logger.error(`init: refusing project name "${o}" — must not contain path separators or be "." / "..".`),{code:w.USAGE,files:[],target:""};if(!Pa.test(o))return e.logger.error(`init: refusing project name "${o}" — a Cloudflare Worker name must be lowercase letters, digits, "-" or "_" (starting with a letter, digit or "_"), and wrangler rejects anything else. Try \`${Ua(o)}\`.`),{code:w.USAGE,files:[],target:""};const l=xe(t,o),c=ge(l,{throwIfNoEntry:!1});if(c?.isSymbolicLink()===!0)return e.logger.error(`init: refusing to scaffold into "${l}" — it is a symlink. Remove it, or scaffold into a different directory name.`),{code:w.CONFLICT,files:[],target:l};const d=c!==void 0;if(d&&Y(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:w.CONFLICT,files:[],target:l};if(e.dryRun===!0){const f=s.kind==="overlay"?`the ${s.framework} create-vite overlay`:`the ${s.templateType} template`;return I(e.logger,`scaffold ${f} into ${l}`),{code:0,files:[],target:l}}r.record(l,d);const h=s.kind==="overlay"?await vn(e,s.framework,o,l,r.complete):await gn(e,s.templateType,o,l,r.complete);return h.code===0&&wn(l,t),h},K=(e,t)=>{const{target:r,targetPreExisted:a}=e;if(!(r===void 0||!m(r))){if(a===!0)for(const n of Y(r))R(u(r,n),{force:!0,recursive:!0});else R(r,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${r}`)}},bn=async(e,t,r)=>e.inPlace!==!0?yn(e,t,r):e.dryRun===!0?(I(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):dn(t,e.logger),kn=async(e,t,r)=>{const a=await pn(e,t.target),n=e.inPlace===!0?void 0:await Za(e,t.target);if(e.inPlace!==!0){await Ja(e,t.target);const i=n??B(t.target);await Xa(T(t.target),n,i,te(r)),await jr(e.logger)}return a},xn=(e,t,r)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){I(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const a=e.inPlace===!0?r:t.target;try{const n=B(a);nr(a,e.ci,n,e.logger)}catch{e.logger.warn(`--ci ${e.ci}: could not detect a package manager for this project — skipped the CI pipeline.`)}},Sn=async e=>{const t=e.cwd??process.cwd(),r={};let a;try{a=await bn(e,t,{complete:()=>{r.target=void 0},record:(n,i)=>{r.target=n,r.targetPreExisted=i}}),a.code===0&&a.target!==""?(r.target=void 0,await kn(e,a,t)||(a={...a,code:1})):a.code!==0&&K(r,e.logger)}catch(n){if(n instanceof X)return K(r,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw K(r,e.logger),n}return xn(e,a,t),a},Cn=e=>typeof e=="string"&&nt.includes(e),Ln=(e,t)=>{if(e!==void 0){if(rr(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},An=e=>e===void 0?{}:Cn(e)?{templateType:e}:V(e)?{vite:e}:{error:`init: unknown --template "${e}" — expected a bespoke template (${it}) or an overlay framework (${at}).`},Jn=Et(({argument:e,cwd:t,logger:r,options:a})=>{const n=An(a.template);return"error"in n?(r.error(n.error),{code:w.USAGE}):Sn({add:a.add,auth:a.auth,allowUnsafeSource:a.allowUnsafeSource===!0,cwd:t,ci:Ln(a.ci,r),dryRun:a.dryRun===!0,from:a.from,inPlace:a.here===!0,interactive:a.interactive===!0?!0:void 0,logger:r,name:e[0],ref:a.ref,source:a.source,templateType:n.templateType,vite:a.vite??n.vite,yes:a.yes===!0})});export{rt as FRAMEWORK_CHOICES,Jn as execute,Cn as isTemplate,An as resolveTemplateFlag,q as resolveTemplateSource,Sn as runInitCommand};