@lunora/cli 1.0.0-alpha.464 → 1.0.0-alpha.465

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.
@@ -1,18 +1,21 @@
1
- import{existsSync as m,mkdirSync as E,writeFileSync as g,readFileSync as x,appendFileSync as it,readdirSync as Y,rmSync as R,lstatSync as ve,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 ht,LUNA_SIGNOFF as pt,BADGES as v,paintAnswer as ft,detectLintTools as mt,readProjectDependencies as ke,applyLintIgnores as gt,readProjectManifest as vt}from"@lunora/config";import{readJsonSync as wt,walkSync as yt}from"@visulima/fs";import{relative as D,join as u,dirname as S,basename as _,resolve as xe}from"@visulima/path";import{downloadTemplate as Le}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 Se,execArgsFor as Lt,detectPackageManager as U,detectInstalledManagers as St,runScriptCommand as At,addArgsFor as Ct}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 Ae,m as _t,n as Ce,o as Ee,a as Nt}from"../packem_shared/resolve-Bdc9KEUv.mjs";import{defaultSpawner as Me}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{d as Tt,e as Rt,f as Ot,a as Ie,t as O,g as _e,h as $t,b as Ne,i as Te,w as Pt,j as Dt,k as Re,l as Ut}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{A as Oe,p as jt,w as Bt,M as Vt,r as Ft,E as $e,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
1
+ import{existsSync as f,mkdirSync as A,writeFileSync as v,readFileSync as E,appendFileSync as st,readdirSync as J,rmSync as N,lstatSync as we,mkdtempSync as ye,copyFileSync as lt,renameSync as ct}from"node:fs";import{tmpdir as be}from"node:os";import{detectFramework as dt,DEV_VARS_EXAMPLE_FILE as ke,DEV_VARS_FILE as ut,isInteractive as b,LUNA_ART as ht,LUNA_NAME as pt,LUNA_SIGNOFF as mt,BADGES as w,paintAnswer as ft,detectLintTools as vt,readProjectDependencies as xe,applyLintIgnores as gt,readProjectManifest as wt}from"@lunora/config";import{readJsonSync as yt,walkSync as bt}from"@visulima/fs";import{relative as U,join as u,dirname as C,basename as T,resolve as Ee}from"@visulima/path";import{downloadTemplate as _e}from"giget";import{modify as kt,applyEdits as xt}from"jsonc-parser";import{join as Q,dirname as Et}from"node:path";import{EXIT_CODE as g}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{installArgsFor as Ce,execArgsFor as _t,detectPackageManager as j,detectInstalledManagers as Ct,runScriptCommand as Lt,addArgsFor as St}from"@lunora/config/cli";import{d as At}from"../packem_shared/command-B6vu47iR.mjs";import It from"magic-string";import{Project as Rt,SyntaxKind as y}from"ts-morph";import{P as X}from"../packem_shared/prompt-cancelled-BvsNxg_Q.mjs";import{l as Le,m as Tt,n as Se,o as Ae,a as $t}from"../packem_shared/resolve-Bdc9KEUv.mjs";import{defaultSpawner as Ie}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{d as Mt,e as Ot,f as Nt,a as Re,t as P,g as Te,h as Pt,b as $e,i as Me,w as Dt,j as Ut,k as Oe,l as jt}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{A as Ne,p as Vt,w as Bt,M as Ft,r as Wt,E as Pe,k as qt,e as Ht,c as De,l as Ue,i as Kt,f as zt}from"../packem_shared/storage-BLLoZRJa.mjs";import{r as Gt}from"../packem_shared/commands-DC3ZX1yk.mjs";import{findWranglerFile as Yt,readWranglerJsonc as Jt,DEFAULT_OBSERVABILITY as Qt,CLOUDFLARE_TOOLCHAIN_VERSIONS as ne}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 Zt from"node:dns/promises";const Z={bun:{githubCacheKey:void 0,githubSetupStep:` - uses: oven-sh/setup-bun@v2
2
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
3
  with:
4
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,t)=>{const r=Lt(e,"lunora",t);return[r.command,...r.args].join(" ")},ne=e=>` - uses: actions/checkout@v4
6
- ${e.githubSetupStep} - uses: actions/setup-node@v4
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"}},x=(e,t)=>{const r=_t(e,"lunora",t);return[r.command,...r.args].join(" ")},M=(e,t,r="")=>` - uses: actions/checkout@v4
6
+ ${t===void 0?"":` with:
7
+ ref: ${t}
8
+ `}${e.githubSetupStep} - uses: actions/setup-node@v4
7
9
  with:
8
10
  node-version: 22
9
11
  ${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
12
+ `} - run: ${e.installCmd}${r}`,er=e=>{const t=Z[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
11
13
 
12
14
  on:
13
15
  push:
14
16
  branches: [main]
15
17
  pull_request:
18
+ types: [opened, synchronize, reopened, closed]
16
19
  workflow_dispatch:
17
20
 
18
21
  # Prerequisite: commit your ${t.lockfile}. \`${t.installCmd}\`
@@ -20,14 +23,28 @@ ${r}
20
23
  # commit the lockfile before pushing, or the first CI run fails.
21
24
  #
22
25
  # Set these repository secrets (Settings → Secrets and variables → Actions):
23
- # CLOUDFLARE_API_TOKEN — a Workers-scoped API token
26
+ # CLOUDFLARE_API_TOKEN — the production deploy's token (Workers Scripts: Edit).
27
+ # Only the production deploy step receives it.
28
+ # CLOUDFLARE_PREVIEW_API_TOKEN — a separate token for previews: Workers Scripts,
29
+ # D1, Workers KV Storage and Workers R2 Storage: Edit
30
+ # (previews make their own D1, KV and R2), limited to
31
+ # one account. Only the \`lunora preview\` steps receive
32
+ # it, never the install or checkout steps, which run
33
+ # a pull request's own dependency scripts.
24
34
  # CLOUDFLARE_ACCOUNT_ID — your Cloudflare account id
25
35
  # LUNORA_DEPLOY_URL — the production worker's URL (after the first deploy)
26
36
  # LUNORA_ADMIN_TOKEN — the production worker's admin token
27
- env:
28
- CLOUDFLARE_API_TOKEN: \${{ secrets.CLOUDFLARE_API_TOKEN }}
29
- CLOUDFLARE_ACCOUNT_ID: \${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
30
-
37
+ # LUNORA_PREVIEW_SECRET_SEED — optional: any long random string; previews then
38
+ # keep their minted secrets across pushes. The preview
39
+ # job builds this repository's own pull requests with
40
+ # CLOUDFLARE_PREVIEW_API_TOKEN in its environment, and
41
+ # that token can redeploy any preview with any secrets,
42
+ # so the seed adds no access. Never run previews for
43
+ # untrusted pull requests; forks get no secrets here.
44
+ #
45
+ # Previews are recorded under "lunora.appId" in package.json, which the first
46
+ # local \`lunora preview deploy\` writes. Commit it: the jobs below find a
47
+ # project's previews by it, so it survives a rename of the Worker.
31
48
  jobs:
32
49
  # Production deploy on push to the default branch.
33
50
  deploy:
@@ -36,29 +53,88 @@ jobs:
36
53
  permissions:
37
54
  contents: read
38
55
  steps:
39
- ${ne(t)}
56
+ ${M(t)}
40
57
  # When a schema change tightens a table, the drift gate reads that table's
41
58
  # stored rows from this worker and lets the change ship if every row fits.
42
59
  # Unset (a first deploy), the gate blocks as before. A *.workers.dev URL is
43
60
  # only trusted when the project is linked and .lunora/ is not committed, so
44
61
  # CI has no link: there the gate stays blocked, and a tightening needs a
45
62
  # migration or --allow-schema-drift. A custom domain on a declared route works.
46
- - run: ${$(e,["deploy","--migrate-url",'"${{ secrets.LUNORA_DEPLOY_URL }}"'])}
63
+ - run: ${x(e,["deploy","--migrate-url",'"${{ secrets.LUNORA_DEPLOY_URL }}"'])}
47
64
  env:
65
+ CLOUDFLARE_API_TOKEN: \${{ secrets.CLOUDFLARE_API_TOKEN }}
66
+ CLOUDFLARE_ACCOUNT_ID: \${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
48
67
  LUNORA_ADMIN_TOKEN: \${{ secrets.LUNORA_ADMIN_TOKEN }}
49
68
 
50
- # Every pull request runs the full deploy pipeline, bundle included, and
51
- # publishes nothing. A Worker version would share production's Durable
52
- # Objects and D1, so a PR never uploads one.
69
+ # Every pull request from this repository gets an isolated preview: its own
70
+ # Worker, Durable Objects, D1, KV and R2, never production's. One run per
71
+ # pull request at a time, so a teardown never races a deploy.
72
+ preview:
73
+ if: github.event_name == 'pull_request' && github.event.action != 'closed' && github.event.pull_request.head.repo.full_name == github.repository && github.event.pull_request.user.login != 'dependabot[bot]'
74
+ runs-on: ubuntu-latest
75
+ concurrency: lunora-preview-\${{ github.event.pull_request.number }}
76
+ permissions:
77
+ contents: read
78
+ steps:
79
+ ${M(t)}
80
+ - run: ${x(e,["preview","deploy","${{ github.event.pull_request.number }}"])}
81
+ env:
82
+ CLOUDFLARE_API_TOKEN: \${{ secrets.CLOUDFLARE_PREVIEW_API_TOKEN }}
83
+ CLOUDFLARE_ACCOUNT_ID: \${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
84
+ LUNORA_PREVIEW_SECRET_SEED: \${{ secrets.LUNORA_PREVIEW_SECRET_SEED }}
85
+
86
+ # Closing or merging the pull request deletes the preview Worker and every
87
+ # resource recorded for it.
88
+ preview-delete:
89
+ if: github.event_name == 'pull_request' && github.event.action == 'closed' && github.event.pull_request.head.repo.full_name == github.repository && github.event.pull_request.user.login != 'dependabot[bot]'
90
+ runs-on: ubuntu-latest
91
+ concurrency: lunora-preview-\${{ github.event.pull_request.number }}
92
+ permissions:
93
+ contents: read
94
+ steps:
95
+ # Deleting needs none of the project's dependency scripts, and one that fails must not keep a closed preview alive.
96
+ # A closed, unmerged pull request may have no merge ref left to check out;
97
+ # the base branch names the same production Worker the record is keyed by.
98
+ ${M(t,"${{ github.event.pull_request.base.ref }}"," --ignore-scripts")}
99
+ # The pull request may have changed lunora.appId or the Worker name, so its previews are recorded under an identity
100
+ # this base checkout does not have. Its package.json and wrangler config are copied out with git and read by the CLI
101
+ # as data: nothing from the head is installed, built or run. The values never pass through a shell or a \${{ }} in a script.
102
+ - name: Copy the pull request head's project files
103
+ env:
104
+ PR_NUMBER: \${{ github.event.pull_request.number }}
105
+ HEAD_DIR: \${{ runner.temp }}/lunora-head
106
+ run: |
107
+ mkdir -p "$HEAD_DIR"
108
+ if git fetch --depth=1 origin "refs/pull/$PR_NUMBER/head"; then
109
+ for file in package.json wrangler.jsonc wrangler.json; do
110
+ git show "FETCH_HEAD:$file" > "$HEAD_DIR/$file" 2>/dev/null || rm -f "$HEAD_DIR/$file"
111
+ done
112
+ else
113
+ echo "could not fetch the pull request head; the preview is looked up under the base branch's identity only"
114
+ fi
115
+ # Exit 5 is "no record": the pull request never got a preview (refused, or opened before this workflow). The CLI
116
+ # answers it only when the head's identity is the base's; a head whose identity differs, or cannot be read, with no
117
+ # record under the base's fails the job, since the preview may be recorded under the head's.
118
+ - run: ${x(e,["preview","delete","${{ github.event.pull_request.number }}","--head-dir",'"$HEAD_DIR"'])} || [ "$?" -eq ${String(g.NOT_FOUND)} ]
119
+ env:
120
+ CLOUDFLARE_API_TOKEN: \${{ secrets.CLOUDFLARE_PREVIEW_API_TOKEN }}
121
+ CLOUDFLARE_ACCOUNT_ID: \${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
122
+ HEAD_DIR: \${{ runner.temp }}/lunora-head
123
+
124
+ # A fork's or Dependabot's pull request gets no secrets, so it runs the
125
+ # deploy pipeline, bundle included, and publishes nothing.
53
126
  check:
54
- if: github.event_name == 'pull_request'
127
+ if: github.event_name == 'pull_request' && github.event.action != 'closed' && (github.event.pull_request.head.repo.full_name != github.repository || github.event.pull_request.user.login == 'dependabot[bot]')
55
128
  runs-on: ubuntu-latest
56
129
  permissions:
57
130
  contents: read
58
131
  steps:
59
- ${ne(t)}
60
- - run: ${$(e,["deploy","--dry-run"])}
61
- `},er=e=>{const t=Q[e],r=[...t.gitlabProvisionScript,t.installCmd].map(a=>` - ${a}`).join(`
132
+ ${M(t)}
133
+ - run: ${x(e,["deploy","--dry-run"])}
134
+ `},oe="lunora-preview-$CI_MERGE_REQUEST_IID",tr=e=>{const t=Z[e],r=[...t.gitlabProvisionScript,t.installCmd].map(s=>` - ${s}`).join(`
135
+ `),n=t.gitlabProvisionScript.map(s=>` - ${s}`).join(`
136
+ `),a=n===""?" []":`
137
+ ${n}`,o=[n,` - ${t.installCmd} --ignore-scripts`].filter(s=>s!=="").join(`
62
138
  `);return`stages:
63
139
  - deploy
64
140
 
@@ -77,6 +153,37 @@ ${ne(t)}
77
153
  # code, gets none of them. Keep your default branch protected (it is by default).
78
154
  # The "production" scope reaches only jobs that declare environment: production,
79
155
  # which is the deploy job alone; the check job below uses none of these.
156
+ #
157
+ # Previews run in merge-request pipelines, so they need credentials of their own.
158
+ # Set these two again, Masked but NOT Protected, with Environment scope "preview/*"
159
+ # (only jobs that declare a preview/* environment get them):
160
+ # CLOUDFLARE_API_TOKEN — a separate token: Workers Scripts, D1, Workers KV
161
+ # Storage and Workers R2 Storage: Edit (previews make
162
+ # their own D1, KV and R2). Never the production token.
163
+ # Create it in Cloudflare (My Profile > API Tokens >
164
+ # Create Custom Token) with only those four Account
165
+ # permissions, "Account Resources" limited to this one
166
+ # account (and no Zone, User or other permission).
167
+ # Residual risk: the variable is not Protected, so
168
+ # anyone who can push a branch here can read it and
169
+ # can then edit or delete every Worker, D1 database,
170
+ # KV namespace and R2 bucket on that account, not just
171
+ # previews: the token cannot be narrowed to the
172
+ # preview-named resources. Use a dedicated account for
173
+ # previews if production shares this one.
174
+ # CLOUDFLARE_ACCOUNT_ID — your Cloudflare account id
175
+ # LUNORA_PREVIEW_SECRET_SEED — optional: any long random string; previews then
176
+ # keep their minted secrets across pushes. The preview
177
+ # jobs run only for merge requests from this project
178
+ # (never forks) and already hold the preview token, which
179
+ # can redeploy any preview with any secrets, so the seed
180
+ # adds no access. Anyone who can push a branch here can
181
+ # run code with it: never run previews for untrusted
182
+ # merge requests.
183
+ #
184
+ # Previews are recorded under "lunora.appId" in package.json, which the first
185
+ # local \`lunora preview deploy\` writes. Commit it: the jobs below find a
186
+ # project's previews by it, so it survives a rename of the Worker.
80
187
  .lunora_base:
81
188
  image: ${t.gitlabImage}
82
189
  stage: deploy
@@ -97,51 +204,106 @@ deploy:
97
204
  # only trusted when the project is linked and .lunora/ is not committed, so
98
205
  # CI has no link: there the gate stays blocked, and a tightening needs a
99
206
  # migration or --allow-schema-drift. A custom domain on a declared route works.
100
- - ${$(e,["deploy","--migrate-url",'"$LUNORA_DEPLOY_URL"'])}
207
+ - ${x(e,["deploy","--migrate-url",'"$LUNORA_DEPLOY_URL"'])}
208
+
209
+ # Every merge request from this project gets an isolated preview: its own
210
+ # Worker, Durable Objects, D1, KV and R2, never production's. GitLab runs the
211
+ # stop job below when the environment stops: its source branch is deleted (merge
212
+ # with "delete source branch"), someone stops it under Operate > Environments,
213
+ # or it auto-stops. A closed merge request that keeps its branch is cleaned up
214
+ # by the auto-stop, or by stopping the environment by hand.
215
+ #
216
+ # The install runs the merge request's own dependency scripts, so it is a job of
217
+ # its own with no environment: the preview/* variables are scoped to jobs that
218
+ # declare one, so this job never receives the preview token. The preview job
219
+ # reuses its node_modules and holds the token only for the preview command.
220
+ preview_install:
221
+ extends: .lunora_base
222
+ stage: .pre
223
+ rules:
224
+ - if: $CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_SOURCE_PROJECT_ID == $CI_PROJECT_ID
225
+ script:
226
+ - echo "dependencies installed without credentials"
227
+ artifacts:
228
+ paths:
229
+ - node_modules/
230
+ expire_in: 1 hour
231
+
232
+ preview:
233
+ extends: .lunora_base
234
+ needs:
235
+ - preview_install
236
+ before_script:${a}
237
+ rules:
238
+ - if: $CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_SOURCE_PROJECT_ID == $CI_PROJECT_ID
239
+ resource_group: ${oe}
240
+ environment:
241
+ name: preview/$CI_MERGE_REQUEST_IID
242
+ on_stop: preview_delete
243
+ auto_stop_in: 2 weeks
244
+ script:
245
+ - ${x(e,["preview","deploy",'"$CI_MERGE_REQUEST_IID"'])}
246
+
247
+ # Deletes the preview Worker and every resource recorded for it. It installs in the
248
+ # job that holds the preview token, so dependency scripts are switched off: deleting
249
+ # needs none of them.
250
+ preview_delete:
251
+ extends: .lunora_base
252
+ before_script:
253
+ ${o}
254
+ rules:
255
+ - if: $CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_SOURCE_PROJECT_ID == $CI_PROJECT_ID
256
+ when: manual
257
+ allow_failure: true
258
+ resource_group: ${oe}
259
+ environment:
260
+ name: preview/$CI_MERGE_REQUEST_IID
261
+ action: stop
262
+ script:
263
+ - ${x(e,["preview","delete",'"$CI_MERGE_REQUEST_IID"'])}
101
264
 
102
- # Every merge request runs the full deploy pipeline, bundle included, and
103
- # publishes nothing. A Worker version would share production's Durable Objects
104
- # and D1, so an MR never uploads one.
265
+ # A fork's merge request runs without this project's CI/CD variables, so it
266
+ # runs the deploy pipeline, bundle included, and publishes nothing.
105
267
  check:
106
268
  extends: .lunora_base
107
269
  rules:
108
- - if: $CI_PIPELINE_SOURCE == "merge_request_event"
270
+ - if: $CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_SOURCE_PROJECT_ID != $CI_PROJECT_ID
109
271
  script:
110
- - ${$(e,["deploy","--dry-run"])}
111
- `},Ue={github:{file:J(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{file:".gitlab-ci.yml",secretsHint:"CI/CD variables, Masked and Protected, scoped to the production environment (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,Ue[t].file);return m(n)&&a.overwrite!==!0?{path:n,skipped:!0,written:!1}:(E(xt(n),{recursive:!0}),g(n,tr(t,r),"utf8"),{path:n,skipped:!1,written:!0})},nr=(e,t,r,a,n={})=>{const o=Ue[t];try{const s=ar(e,t,r,n);if(s.skipped)a.info(`--ci ${t}: ${o.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const i=Se(r),l=[i.command,...i.args].join(" "),{installCmd:c,lockfile:d}=Q[r];a.success(`--ci ${t}: wrote ${o.file}`),a.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${o.secretsHint} to enable deploys.`),a.info(`--ci ${t}: run \`${l}\` and commit ${d} before pushing — the pipeline runs \`${c}\`.`)}return s}catch(s){const i=s instanceof Error?s.message:String(s);return a.warn(`--ci ${t}: could not write ${o.file} (${i})`),{path:J(e,o.file),skipped:!1,written:!1}}},or={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"},ir=e=>{const t=ct(e);return{...t,adapter:or[t.framework]}},T="lunora()",oe='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),hr=e=>e.getImportDeclarations().some(t=>t.getModuleSpecifierValue()===sr),pr=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(`${oe}
272
+ - ${x(e,["deploy","--dry-run"])}
273
+ `},je={github:{file:Q(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{file:".gitlab-ci.yml",secretsHint:"CI/CD variables, Masked and Protected, scoped to the production environment (Settings → CI/CD → Variables)"}},rr=(e,t)=>e==="github"?er(t):tr(t),nr=e=>e==="github"||e==="gitlab",ar=(e,t,r,n={})=>{const a=Q(e,je[t].file);return f(a)&&n.overwrite!==!0?{path:a,skipped:!0,written:!1}:(A(Et(a),{recursive:!0}),v(a,rr(t,r),"utf8"),{path:a,skipped:!1,written:!0})},or=(e,t,r,n,a={})=>{const o=je[t];try{const s=ar(e,t,r,a);if(s.skipped)n.info(`--ci ${t}: ${o.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const i=Ce(r),l=[i.command,...i.args].join(" "),{installCmd:c,lockfile:d}=Z[r];n.success(`--ci ${t}: wrote ${o.file}`),n.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${o.secretsHint} to enable deploys.`),n.info(`--ci ${t}: run \`${l}\` and commit ${d} before pushing — the pipeline runs \`${c}\`.`)}return s}catch(s){const i=s instanceof Error?s.message:String(s);return n.warn(`--ci ${t}: could not write ${o.file} (${i})`),{path:Q(e,o.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"},sr=e=>{const t=dt(e);return{...t,adapter:ir[t.framework]}},O="lunora()",ie='import { lunora } from "@lunora/vite";',lr="@lunora/vite",cr="lunora",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.CallExpression)continue;const n=r.asKindOrThrow(y.CallExpression);if(n.getExpression().getText()!=="defineConfig")continue;const a=n.getArguments()[0];if(a?.getKind()===y.ObjectLiteralExpression)return a.asKindOrThrow(y.ObjectLiteralExpression)}},ur=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)}},hr=e=>e.getDescendantsOfKind(y.CallExpression).some(t=>t.getExpression().getText()===cr),pr=e=>e.getImportDeclarations().some(t=>t.getModuleSpecifierValue()===lr),mr=e=>new Rt({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}
112
274
  `):e.appendLeft(r,`
113
- ${oe}`)},mr=(e,t)=>{const r=t.getProperty("plugins");if(r===void 0){const s=t.getProperties(),i=t.getStart()+1;if(s.length===0){e.appendLeft(i,` plugins: [${T}] `);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: [${T}],
114
- `);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,T);return}const o=n[0];if(o===void 0)return"could not locate the first entry of the Vite config's `plugins` array";e.appendLeft(o.getStart(),`${T}, `)},je=e=>{const t=pr(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);hr(t)||fr(a,t);const n=mr(a,r);return n!==void 0?{changed:!1,code:e,reason:n}:{changed:!0,code:a.toString()}},gr=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,vr=/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 vr.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}`}:gr.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}},Be=[{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"}],ie=Be.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(`
275
+ ${ie}`)},vr=(e,t)=>{const r=t.getProperty("plugins");if(r===void 0){const s=t.getProperties(),i=t.getStart()+1;if(s.length===0){e.appendLeft(i,` plugins: [${O}] `);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: [${O}],
276
+ `);return}const n=r.getDescendantsOfKind(y.ArrayLiteralExpression)[0];if(n===void 0)return"the Vite config's `plugins` is not an array literal — add `lunora()` to it by hand";const a=n.getElements();if(a.length===0){e.appendLeft(n.getStart()+1,O);return}const o=a[0];if(o===void 0)return"could not locate the first entry of the Vite config's `plugins` array";e.appendLeft(o.getStart(),`${O}, `)},Ve=e=>{const t=mr(e);if(hr(t))return{changed:!1,code:e,reason:"lunora plugin already present"};const r=dr(t)??ur(t);if(r===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const n=new It(e);pr(t)||fr(n,t);const a=vr(n,r);return a!==void 0?{changed:!1,code:e,reason:a}:{changed:!0,code:n.toString()}},gr=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,wr=/404|not found|could not find|no such/u,yr=(e,t)=>{const r=e instanceof Error?e.message:String(e),n=r.toLowerCase(),a=`failed to download template "${t.templateType}" from ${t.remote}: ${r}`;return wr.test(n)?{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}`}:gr.test(n)?{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:a}:{hints:["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],message:a}},Be=[{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"}],se=Be.map(e=>e.value),ee={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(`
115
277
  `),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(`
116
278
  `),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(`
117
- `),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 ie.includes(r)?r:(t(`init: unknown --auth "${e}" — expected ${ie.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",Lr=["lunora.config.ts","lunora.config.mts","lunora.config.js","lunora.config.mjs"],Sr=["src","app","pages","plugins"],Ar=/\.(?:[jt]sx?|svelte|vue)$/u,H="new LunoraClient({",se=/\n([\t ]*)\.build(?:FrameworkWorker)?\(/uy,Cr=new Set(["(","[","{"]),Er=new Set([")","]","}"]),Mr=(e,t)=>{const r=e[t];if(r==="/"&&e[t+1]==="/"){const n=e.indexOf(`
118
- `,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 o=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&&o===";")return{at:a,indent:" "};r+=Cr.has(o)?1:0,r-=Er.has(o)?1:0,a+=1}},_r=(e,t,r)=>{const a=D(S(u(e,t)),u(e,"lunora","identity",r.identityFile));return`${a.startsWith(".")?a:`./${a}`}.js`},Nr=/\bresolveIdentity\b/u,Tr=/^import[^"']*["'][^"'\n]*["'][^\n]*\n/u,Rr=(e,t,r,a)=>{const n=r.indexOf("defineApp<"),o=n===-1?void 0:Ir(r,n);if(o===void 0)return;if(r.includes(`${a.identity}(env)`))return{outcome:"already-wired"};if(Nr.test(r))return{outcome:"has-resolver"};const{at:s,indent:i}=o,l=`
279
+ `),envVars:["WORKOS_CLIENT_ID"],identity:"workosIdentity",identityFile:"workos",item:"auth-workos-jwt"}},br=e=>Object.hasOwn(ee,e),kr=(e,t)=>{const r=e.trim().toLowerCase();return se.includes(r)?r:(t(`init: unknown --auth "${e}" — expected ${se.join(" | ")}; skipping auth.`),"none")},xr=["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"],Er="virtual:lunora/worker",_r=["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({",le=/\n([\t ]*)\.build(?:FrameworkWorker)?\(/uy,Sr=new Set(["(","[","{"]),Ar=new Set([")","]","}"]),Ir=(e,t)=>{const r=e[t];if(r==="/"&&e[t+1]==="/"){const a=e.indexOf(`
280
+ `,t);return a===-1?e.length:a}if(r==="/"&&e[t+1]==="*"){const a=e.indexOf("*/",t+2);return a===-1?e.length:a+2}if(r!=='"'&&r!=="'"&&r!=="`")return t;let n=t+1;for(;n<e.length&&e[n]!==r;)n+=e[n]==="\\"?2:1;return n+1},Rr=(e,t)=>{let r=0,n=t;for(;n<e.length;){const a=Ir(e,n);if(a!==n){n=a;continue}const o=e[n]??"";le.lastIndex=n;const s=r===0?le.exec(e)??void 0:void 0;if(s!==void 0)return{at:n,indent:s[1]??" "};if(r===0&&o===";")return{at:n,indent:" "};r+=Sr.has(o)?1:0,r-=Ar.has(o)?1:0,n+=1}},Tr=(e,t,r)=>{const n=U(C(u(e,t)),u(e,"lunora","identity",r.identityFile));return`${n.startsWith(".")?n:`./${n}`}.js`},$r=/\bresolveIdentity\b/u,Mr=/^import[^"']*["'][^"'\n]*["'][^\n]*\n/u,Or=(e,t,r,n)=>{const a=r.indexOf("defineApp<"),o=a===-1?void 0:Rr(r,a);if(o===void 0)return;if(r.includes(`${n.identity}(env)`))return{outcome:"already-wired"};if($r.test(r))return{outcome:"has-resolver"};const{at:s,indent:i}=o,l=`
119
281
  ${i}// Verify the provider's token on every request and feed it into ctx.auth (memoized for 5 s).
120
- ${i}.extend((env) => ({ resolveIdentity: ${a.identity}(env) }))`,c=`import { ${a.identity} } from "${_r(e,t,a)}";
282
+ ${i}.extend((env) => ({ resolveIdentity: ${n.identity}(env) }))`,c=`import { ${n.identity} } from "${Tr(e,t,n)}";
121
283
  `,d=r.lastIndexOf(`
122
- import `,n),p=d===-1?void 0:Tr.exec(r.slice(d+1)),f=p==null?0:d+1+p[0].length;return{outcome:"wired",patched:r.slice(0,f)+c+r.slice(f,s)+l+r.slice(s)}},Or=(e,t)=>{for(const r of kr){const a=u(e,r),n=m(a)?Rr(e,r,x(a,"utf8"),t):void 0;if(n?.outcome==="wired"&&g(a,n.patched),n!==void 0)return{file:r,outcome:n.outcome}}},$r=e=>{const t=Gt(e);return t!==void 0&&Yt(t).parsed?.main===xr},Pr=(e,t)=>{if(!(!$r(e)||Lr.some(r=>m(u(e,r)))))return g(u(e,"lunora.config.ts"),`import type { AppBuilder, LunoraConfig } from "./lunora/_generated/app";
284
+ import `,a),p=d===-1?void 0:Mr.exec(r.slice(d+1)),m=p==null?0:d+1+p[0].length;return{outcome:"wired",patched:r.slice(0,m)+c+r.slice(m,s)+l+r.slice(s)}},Nr=(e,t)=>{for(const r of xr){const n=u(e,r),a=f(n)?Or(e,r,E(n,"utf8"),t):void 0;if(a?.outcome==="wired"&&v(n,a.patched),a!==void 0)return{file:r,outcome:a.outcome}}},Pr=e=>{const t=Yt(e);return t!==void 0&&Jt(t).parsed?.main===Er},Dr=(e,t)=>{if(!(!Pr(e)||_r.some(r=>f(u(e,r)))))return v(u(e,"lunora.config.ts"),`import type { AppBuilder, LunoraConfig } from "./lunora/_generated/app";
123
285
  import { ${t.identity} } from "./lunora/identity/${t.identityFile}";
124
286
 
125
287
  export default {
126
288
  // Verify the provider's token on every request and feed it into ctx.auth (memoized for 5 s).
127
289
  app: (app: AppBuilder<object>): AppBuilder<object> => app.extend((env) => ({ resolveIdentity: ${t.identity}(env) })),
128
290
  } satisfies LunoraConfig<object>;
129
- `),"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):Ar.test(r.name)?[a]:[]}),Dr=e=>Sr.flatMap(t=>Ve(u(e,t))).filter(t=>{const r=x(t,"utf8");return!r.includes(H)||r.includes("authTokenOnUpgrade")?!1:(g(t,r.replaceAll(H,`${H} authTokenOnUpgrade: true,`)),!0)}),Ur=(e,t)=>{const r=u(e,be),a=u(e,dt),n=m(r)?x(r,"utf8"):"",o=m(a)?x(a,"utf8").split(`
130
- `):[],s=t.envVars.filter(c=>!n.split(`
131
- `).some(d=>d.startsWith(`${c}=`)));if(s.length===0)return!1;const i=s.map(c=>o.find(d=>d.startsWith(`${c}=`))??`${c}=`),l=n.length===0||n.endsWith(`
291
+ `),"lunora.config.ts"},Fe=(e,t=0)=>t>3||!f(e)?[]:J(e,{withFileTypes:!0}).flatMap(r=>{const n=u(e,r.name);return r.isDirectory()?r.name==="node_modules"?[]:Fe(n,t+1):Lr.test(r.name)?[n]:[]}),Ur=e=>Cr.flatMap(t=>Fe(u(e,t))).filter(t=>{const r=E(t,"utf8");return!r.includes(H)||r.includes("authTokenOnUpgrade")?!1:(v(t,r.replaceAll(H,`${H} authTokenOnUpgrade: true,`)),!0)}),jr=(e,t)=>{const r=u(e,ke),n=u(e,ut),a=f(r)?E(r,"utf8"):"",o=f(n)?E(n,"utf8").split(`
292
+ `):[],s=t.envVars.filter(c=>!a.split(`
293
+ `).some(d=>d.startsWith(`${c}=`)));if(s.length===0)return!1;const i=s.map(c=>o.find(d=>d.startsWith(`${c}=`))??`${c}=`),l=a.length===0||a.endsWith(`
132
294
  `)?"":`
133
- `;return it(r,`${l}# ${t.item}: the identity provider the Worker verifies tokens from.
295
+ `;return st(r,`${l}# ${t.item}: the identity provider the Worker verifies tokens from.
134
296
  ${i.join(`
135
297
  `)}
136
- `),!0},jr=(e,t,r)=>{const a=Z[t],n=()=>{const s=Pr(e,a);return s===void 0?void 0:{file:s,outcome:"wired"}},o=Or(e,a)??n();o===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.`):o.outcome==="already-wired"?r.info(`auth: ${o.file} already wires ${a.identity}; left as is.`):o.outcome==="has-resolver"?r.warn(`auth: ${o.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 ${o.file}`),Ur(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):
137
- ${a.clientSnippet}
138
- Fill in the env vars the item wrote to .dev.vars.`)},P=async(e,t,r)=>{if(b()){await Rt(v[e],t,r);return}if(process.stdout.write(`
139
- `),r===void 0||r===""){ae(e,t);return}const a=r.split(`
140
- `).map(n=>ft(n)).join(`
298
+ `),!0},Vr=(e,t,r)=>{const n=ee[t],a=()=>{const s=Dr(e,n);return s===void 0?void 0:{file:s,outcome:"wired"}},o=Nr(e,n)??a();o===void 0?r.warn(`auth: add \`.extend((env) => ({ resolveIdentity: ${n.identity}(env) }))\` to your app builder (lunora.config.ts \`app\` hook or the Worker entry) — ${n.identity} is in lunora/identity/${n.identityFile}.ts.`):o.outcome==="already-wired"?r.info(`auth: ${o.file} already wires ${n.identity}; left as is.`):o.outcome==="has-resolver"?r.warn(`auth: ${o.file} already sets resolveIdentity, so it was left as is. Compose the two: \`resolveIdentity: composeIdentityResolvers([${n.identity}(env), <your resolver>])\` — ${n.identity} is in lunora/identity/${n.identityFile}.ts.`):r.success(`auth: wired ${n.identity} as resolveIdentity in ${o.file}`),jr(e,n)&&r.success(`auth: listed ${n.envVars.join(", ")} in ${ke}`);for(const s of Ur(e))r.success(`auth: turned on authTokenOnUpgrade in ${U(e,s)}`);r.info(`auth: hand the provider's token to Lunora once signed in (setAuthTokenProvider from lunorash/client or @lunora/client):
299
+ ${n.clientSnippet}
300
+ Fill in the env vars the item wrote to .dev.vars.`)},D=async(e,t,r)=>{if(b()){await Ot(w[e],t,r);return}if(process.stdout.write(`
301
+ `),r===void 0||r===""){ae(e,t);return}const n=r.split(`
302
+ `).map(a=>ft(a)).join(`
141
303
  `);ae(e,`${t}
142
- ${a}`)},Br=async e=>{if(b()){await Tt();return}e.info(`
143
- ${ut}
144
- ${ht}: ${pt}`)},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"?$e: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:[$e],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: ${Oe}`);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 jt(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:r=>Bt(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 o=He(e);if(o===void 0){e.logger.error(`init: ${Oe}`),a=!0;continue}r.push({label:n,names:[o]})}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:o,refused:s}=qr(e,n);return t!==void 0&&o.unshift(t),await e.applyAll(o)&&!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?",Be,{default:"none"})??"none",r=ze(t),a=t==="lunora"?ce:ce.filter(i=>!We.has(i.value)),n=await e.multiSelect("Which features do you want to add?",a,{defaults:[]}),o=t==="lunora"&&!n.includes("auth")?["auth",...n]:n;if(o.length===0&&r===void 0)return!0;const s=r===void 0?[]:[r];for(const i of o){const l=Gr[i],c=l?await l(e,o):{label:i,names:[i]};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},N="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",I=`/* The welcome page is a full-bleed starter — reset the browser's default
304
+ ${n}`)},Br=async e=>{if(b()){await Mt();return}e.info(`
305
+ ${ht}
306
+ ${pt}: ${mt}`)},We=[{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"}],ce=We.map(e=>e.value),de=We.filter(e=>e.value!=="auth"),qe=new Set(["auth","auth-ui"]),Fr=e=>e==="email"?Pe:e,Wr=(e,t)=>{const r=[];for(const n of e.split(",").map(a=>a.trim()).filter(Boolean))ce.includes(n)?r.includes(n)||r.push(n):t(`init: unknown --add feature "${n}" — expected ${ce.join(" | ")}; skipping.`);return r},He=e=>e.resolveAuthUiItem===void 0?"auth-ui-react":e.resolveAuthUiItem(),qr=async e=>{const t=await Ht(e.select),r=await De(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:n=>Ue(n,r)}},Hr=async e=>{const t=await e.text(Ft,{placeholder:"you@yourdomain.com"}),r=Wt(t,n=>{e.logger.warn(n)});return{label:"email",names:[Pe],transformManifest:r===void 0?void 0:n=>qt(n,r)}},Kr=async(e,t)=>{const r=He(e);if(r===void 0){e.logger.error(`init: ${Ne}`);return}if(t)return{label:"auth-ui",names:[r]};const n=await De(e.text,e.projectName);return{label:"auth-ui",names:[r],transformManifest:a=>Ue(a,n)}},zr=async e=>{const t=await Vt(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:r=>Bt(r,t)}},Gr=(e,t)=>{const r=[];let n=!1;for(const a of t){if(a!=="auth-ui"){r.push({label:a,names:[Fr(a)]});continue}const o=He(e);if(o===void 0){e.logger.error(`init: ${Ne}`),n=!0;continue}r.push({label:a,names:[o]})}return{plans:r,refused:n}},Ke=e=>e!==void 0&&br(e)?{externalAuth:e,label:e,names:[ee[e].item]}:void 0,Yr={auth:qr,"auth-ui":async(e,t)=>Kr(e,t.includes("auth")),email:Hr,storage:zr},Jr=async e=>{const t=Ke(e.auth),r=e.auth!==void 0&&e.auth!=="lunora",n=new Set(r?(e.preselected??[]).filter(l=>qe.has(l)):[]),a=(e.preselected??[]).filter(l=>!n.has(l));for(const l of n)e.logger.warn(`--auth ${String(e.auth)} rules out Lunora auth; ignoring \`${l}\` from --add.`);e.auth==="lunora"&&!a.includes("auth")&&a.unshift("auth");const{plans:o,refused:s}=Gr(e,a);return t!==void 0&&o.unshift(t),await e.applyAll(o)&&!s&&n.size===0},ue=async e=>{if(e.preselected!==void 0&&e.preselected.length>0||e.auth!==void 0&&!e.interactive)return Jr(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?",Be,{default:"none"})??"none",r=Ke(t),n=t==="lunora"?de:de.filter(i=>!qe.has(i.value)),a=await e.multiSelect("Which features do you want to add?",n,{defaults:[]}),o=t==="lunora"&&!a.includes("auth")?["auth",...a]:a;if(o.length===0&&r===void 0)return!0;const s=r===void 0?[]:[r];for(const i of o){const l=Yr[i],c=l?await l(e,o):{label:i,names:[i]};c!==void 0&&s.push(c)}return await e.applyAll(s),!0},Qr=[{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.",Zr=async e=>{const t=e.interactive?await e.multiSelect(Xr,Qr,{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",R=`/* The welcome page is a full-bleed starter — reset the browser's default
145
307
  body margin/padding so it sits flush; everything else is scoped under
146
308
  .lunora-welcome (collision-safe). */
147
309
  body {
@@ -246,7 +408,7 @@ body {
246
408
  .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); }
247
409
 
248
410
  @media (prefers-reduced-motion: reduce) { .lunora-welcome * { transition: none !important; } }
249
- `,Zr=`import { useEffect, useState } from "react";
411
+ `,en=`import { useEffect, useState } from "react";
250
412
 
251
413
  type Theme = "dark" | "light";
252
414
 
@@ -288,7 +450,7 @@ export default function App() {
288
450
  <div className="lw-wrap">
289
451
  <div className="brand">
290
452
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
291
- <path d="${N}" fill="currentColor" fillRule="evenodd" />
453
+ <path d="${$}" fill="currentColor" fillRule="evenodd" />
292
454
  </svg>
293
455
  <span className="word">Lunora</span>
294
456
  </div>
@@ -407,7 +569,7 @@ export default function App() {
407
569
  </div>
408
570
  );
409
571
  }
410
- `,ea=`<script setup lang="ts">
572
+ `,tn=`<script setup lang="ts">
411
573
  import { onMounted, ref } from "vue";
412
574
 
413
575
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -447,7 +609,7 @@ const toggle = (): void => {
447
609
  <div class="lw-wrap">
448
610
  <div class="brand">
449
611
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
450
- <path d="${N}" fill="currentColor" fill-rule="evenodd" />
612
+ <path d="${$}" fill="currentColor" fill-rule="evenodd" />
451
613
  </svg>
452
614
  <span class="word">Lunora</span>
453
615
  </div>
@@ -563,7 +725,7 @@ const toggle = (): void => {
563
725
  </div>
564
726
  </div>
565
727
  </template>
566
- `,ta=`import { createSignal, onMount } from "solid-js";
728
+ `,rn=`import { createSignal, onMount } from "solid-js";
567
729
 
568
730
  export default function App() {
569
731
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -603,7 +765,7 @@ export default function App() {
603
765
  <div class="lw-wrap">
604
766
  <div class="brand">
605
767
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
606
- <path d="${N}" fill="currentColor" fill-rule="evenodd" />
768
+ <path d="${$}" fill="currentColor" fill-rule="evenodd" />
607
769
  </svg>
608
770
  <span class="word">Lunora</span>
609
771
  </div>
@@ -722,7 +884,7 @@ export default function App() {
722
884
  </div>
723
885
  );
724
886
  }
725
- `,ra=`<script lang="ts">
887
+ `,nn=`<script lang="ts">
726
888
  import { onMount } from "svelte";
727
889
 
728
890
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -765,7 +927,7 @@ export default function App() {
765
927
  <div class="lw-wrap">
766
928
  <div class="brand">
767
929
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
768
- <path d="${N}" fill="currentColor" fill-rule="evenodd" />
930
+ <path d="${$}" fill="currentColor" fill-rule="evenodd" />
769
931
  </svg>
770
932
  <span class="word">Lunora</span>
771
933
  </div>
@@ -880,7 +1042,7 @@ export default function App() {
880
1042
  <div class="lw-foot">Running on Lunora · Vite + Svelte</div>
881
1043
  </div>
882
1044
  </div>
883
- `,aa=`import "./style.css";
1045
+ `,an=`import "./style.css";
884
1046
 
885
1047
  import { LunoraClient } from "lunorash/client";
886
1048
 
@@ -908,7 +1070,7 @@ const welcomeHtml = \`
908
1070
  <div class="lw-wrap">
909
1071
  <div class="brand">
910
1072
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
911
- <path d="${N}" fill="currentColor" fill-rule="evenodd" />
1073
+ <path d="${$}" fill="currentColor" fill-rule="evenodd" />
912
1074
  </svg>
913
1075
  <span class="word">Lunora</span>
914
1076
  </div>
@@ -1047,7 +1209,7 @@ const count = document.querySelector<HTMLSpanElement>("#lw-count")!;
1047
1209
  client.subscribe(api.messages.list, { channelId: "channel:demo" }, (result) => {
1048
1210
  count.textContent = String(result.messages.length);
1049
1211
  });
1050
- `,j="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",na=`import "./index.css";
1212
+ `,V="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",on=`import "./index.css";
1051
1213
 
1052
1214
  import { LunoraProvider } from "@lunora/react";
1053
1215
  import { LunoraClient } from "lunorash/client";
@@ -1059,7 +1221,7 @@ import App from "./App.tsx";
1059
1221
  // \`@lunora/vite\` runs the Worker on the same origin as Vite, so default to
1060
1222
  // \`location.origin\`. Point \`VITE_LUNORA_URL\` at a deployed Worker to develop
1061
1223
  // the client against production data.
1062
- ${j}
1224
+ ${V}
1063
1225
  const client = new LunoraClient({ url });
1064
1226
 
1065
1227
  const root = document.getElementById("root");
@@ -1075,7 +1237,7 @@ createRoot(root).render(
1075
1237
  </LunoraProvider>
1076
1238
  </StrictMode>,
1077
1239
  );
1078
- `,oa=`import "./style.css";
1240
+ `,sn=`import "./style.css";
1079
1241
 
1080
1242
  import { createLunora } from "@lunora/vue";
1081
1243
  import { LunoraClient } from "lunorash/client";
@@ -1084,9 +1246,9 @@ import { createApp } from "vue";
1084
1246
  import App from "./App.vue";
1085
1247
 
1086
1248
  // Provide one LunoraClient at the app root via the Vue plugin form.
1087
- ${j}
1249
+ ${V}
1088
1250
  createApp(App).use(createLunora(new LunoraClient({ url }))).mount("#app");
1089
- `,ia=`import "./index.css";
1251
+ `,ln=`import "./index.css";
1090
1252
 
1091
1253
  import { LunoraProvider } from "@lunora/solid";
1092
1254
  import { LunoraClient } from "lunorash/client";
@@ -1094,7 +1256,7 @@ import { render } from "solid-js/web";
1094
1256
 
1095
1257
  import App from "./App";
1096
1258
 
1097
- ${j}
1259
+ ${V}
1098
1260
  const client = new LunoraClient({ url });
1099
1261
  const root = document.getElementById("root");
1100
1262
 
@@ -1106,18 +1268,18 @@ render(
1106
1268
  ),
1107
1269
  root!,
1108
1270
  );
1109
- `,sa=`<script lang="ts">
1271
+ `,cn=`<script lang="ts">
1110
1272
  import { setLunoraClient } from "@lunora/svelte";
1111
1273
  import { LunoraClient } from "lunorash/client";
1112
1274
 
1113
1275
  import App from "./App.svelte";
1114
1276
 
1115
- ${j}
1277
+ ${V}
1116
1278
  setLunoraClient(new LunoraClient({ url }));
1117
1279
  <\/script>
1118
1280
 
1119
1281
  <App />
1120
- `,la=`import "./app.css";
1282
+ `,dn=`import "./app.css";
1121
1283
 
1122
1284
  import { mount } from "svelte";
1123
1285
 
@@ -1127,7 +1289,7 @@ import Root from "./Root.svelte";
1127
1289
  const app = mount(Root, { target: document.getElementById("app")! });
1128
1290
 
1129
1291
  export default app;
1130
- `,B={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:na,path:"src/main.tsx"},{contents:Zr,path:"src/App.tsx"},{contents:I,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:ia,path:"src/index.tsx"},{contents:ta,path:"src/App.tsx"},{contents:I,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:I,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:aa,path:"src/main.ts"},{contents:I,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:oa,path:"src/main.ts"},{contents:ea,path:"src/App.vue"},{contents:I,path:"src/style.css"}],label:"Vue"}},V=e=>Object.hasOwn(B,e),ca=`/**
1292
+ `,B={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:on,path:"src/main.tsx"},{contents:en,path:"src/App.tsx"},{contents:R,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:ln,path:"src/index.tsx"},{contents:rn,path:"src/App.tsx"},{contents:R,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:cn,path:"src/Root.svelte"},{contents:dn,path:"src/main.ts"},{contents:nn,path:"src/App.svelte"},{contents:R,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:an,path:"src/main.ts"},{contents:R,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:sn,path:"src/main.ts"},{contents:tn,path:"src/App.vue"},{contents:R,path:"src/style.css"}],label:"Vue"}},F=e=>Object.hasOwn(B,e),un=`/**
1131
1293
  * Rate-limit schema extension + plugin.
1132
1294
  *
1133
1295
  * Defines the \`ratelimit_buckets\` table used by \`createDbStore\` for durable,
@@ -1203,7 +1365,7 @@ export const ratelimit = definePlugin("ratelimit", {
1203
1365
  }),
1204
1366
  middleware,
1205
1367
  });
1206
- `,da=`import { ratelimit } from "./ratelimit/schema.js";
1368
+ `,hn=`import { ratelimit } from "./ratelimit/schema.js";
1207
1369
  import { defineSchema, defineTable, v } from "lunorash/server";
1208
1370
 
1209
1371
  export default defineSchema({
@@ -1214,7 +1376,7 @@ export default defineSchema({
1214
1376
  .shardBy("channelId")
1215
1377
  .index("by_channel", ["channelId"]),
1216
1378
  }).extend(ratelimit.extension);
1217
- `,ua=`import { rateLimit } from "lunorash/ratelimit";
1379
+ `,pn=`import { rateLimit } from "lunorash/ratelimit";
1218
1380
 
1219
1381
  import { makeRateLimiter } from "./ratelimit/schema.js";
1220
1382
  import type { MutationCtx } from "#lunora/_generated/server.js";
@@ -1263,7 +1425,7 @@ export const send = mutation
1263
1425
 
1264
1426
  return { channelId: args.channelId, id, text: args.text };
1265
1427
  });
1266
- `,ha=`import type { ShardNamespaceLike } from "lunorash/runtime";
1428
+ `,mn=`import type { ShardNamespaceLike } from "lunorash/runtime";
1267
1429
 
1268
1430
  import { defineApp } from "../lunora/_generated/app.js";
1269
1431
 
@@ -1277,7 +1439,7 @@ const app = defineApp<Env>()
1277
1439
 
1278
1440
  export const ShardDO = app.ShardDO;
1279
1441
  export default app;
1280
- `,pa=`{ ${Object.entries(Jt).map(([e,t])=>`${JSON.stringify(e)}: ${JSON.stringify(t)}`).join(", ")} }`,fa=`{
1442
+ `,fn=`{ ${Object.entries(Qt).map(([e,t])=>`${JSON.stringify(e)}: ${JSON.stringify(t)}`).join(", ")} }`,vn=`{
1281
1443
  "$schema": "node_modules/wrangler/config-schema.json",
1282
1444
  "name": "__NAME__",
1283
1445
  "main": "src/server.ts",
@@ -1287,25 +1449,25 @@ export default app;
1287
1449
  "bindings": [{ "name": "SHARD", "class_name": "ShardDO" }],
1288
1450
  },
1289
1451
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ShardDO"] }],
1290
- "observability": ${pa},
1452
+ "observability": ${fn},
1291
1453
  }
1292
- `,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.
1454
+ `,he=[".wrangler",".env",".env.*","!.env.example",".dev.vars",".dev.vars.*","!.dev.vars.example",".lunora/",".lunora-cache","lunora/_generated"],gn=`# Lunora endpoint for the browser client.
1293
1455
  # Vite statically replaces \`import.meta.env.VITE_LUNORA_URL\` at \`vite dev\` / build.
1294
1456
  # Leave it unset to use the page origin; set it to point at a deployed Worker:
1295
1457
  #
1296
1458
  # VITE_LUNORA_URL=https://my-app.example.workers.dev
1297
- `,ga={"@cloudflare/workers-types":re["@cloudflare/workers-types"],wrangler:re.wrangler},A=(e,t,r,a)=>{const n=u(e,t);E(S(n),{recursive:!0}),g(n,r,"utf8"),a.push(n)},va=/\r?\n/,wa=e=>{const t=u(e,".gitignore"),r=m(t)?x(t,"utf8"):"",a=new Set(r.split(va)),n=ue.filter(i=>!a.has(i));if(n.length===0)return;const o=n.some(i=>!i.startsWith("!"))?[...n.filter(i=>!i.startsWith("!")),...ue.filter(i=>i.startsWith("!"))]:n,s=r.length>0&&!r.endsWith(`
1459
+ `,wn={"@cloudflare/workers-types":ne["@cloudflare/workers-types"],wrangler:ne.wrangler},L=(e,t,r,n)=>{const a=u(e,t);A(C(a),{recursive:!0}),v(a,r,"utf8"),n.push(a)},yn=/\r?\n/,bn=e=>{const t=u(e,".gitignore"),r=f(t)?E(t,"utf8"):"",n=new Set(r.split(yn)),a=he.filter(i=>!n.has(i));if(a.length===0)return;const o=a.some(i=>!i.startsWith("!"))?[...a.filter(i=>!i.startsWith("!")),...he.filter(i=>i.startsWith("!"))]:a,s=r.length>0&&!r.endsWith(`
1298
1460
  `)?`
1299
- `:"";g(t,`${r}${s}
1461
+ `:"";v(t,`${r}${s}
1300
1462
  # Lunora
1301
1463
  ${o.join(`
1302
1464
  `)}
1303
- `,"utf8")},F=e=>e==="lunorash"||e.startsWith("@lunora/"),ya=(e,t,r,a)=>F(e)?a.get(e)??r:t,C=(e,t,r)=>({...e,[t]:r}),he=(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"),o=wt(n);let s=C(o.dependencies??{},"lunorash",a);s=C(s,"@lunora/ratelimit",a),r.adapter.startsWith("@lunora/")&&(s=C(s,r.adapter,a));for(const[d,p]of Object.entries(r.extraDependencies??{}))s=C(s,d,p);let i=C(o.devDependencies??{},"@lunora/vite",a);i=C(i,"@lunora/studio",a);for(const[d,p]of Object.entries(ga))i=C(i,d,p);const l=[...Object.keys(s),...Object.keys(i)].filter(d=>F(d)),c=await Ae(l,a);o.name=t,o.imports={...o.imports,"#lunora/*":"./lunora/*"},o.dependencies=he(s,a,c),o.devDependencies=he(i,a,c),o.scripts={...o.scripts,codegen:"lunora codegen",deploy:"lunora deploy"},g(n,`${JSON.stringify(o,void 0,4)}
1304
- `,"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=je(x(r,"utf8"));a.changed&&g(r,a.code,"utf8")},La=async e=>{const{adapter:t,distTag:r,logger:a,name:n,target:o}=e,s=[];A(o,u("lunora","ratelimit","schema.ts"),ca,s),A(o,u("lunora","schema.ts"),da,s),A(o,u("lunora","messages.ts"),ua,s),A(o,u("src","server.ts"),ha,s),A(o,"wrangler.jsonc",fa.replaceAll("__NAME__",n),s),A(o,".env.example",ma,s);for(const i of t.files)A(o,i.path,i.contents,s);return xa(o,a),await ba(o,n,t,r),wa(o),s},Sa=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],Aa=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],pe=e=>e[Math.floor(Math.random()*e.length)],Ca=()=>`${pe(Sa)}-${pe(Aa)}`,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),L={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"]),Na=`import { defineConfig } from "vite";
1465
+ `,"utf8")},W=e=>e==="lunorash"||e.startsWith("@lunora/"),kn=(e,t,r,n)=>W(e)?n.get(e)??r:t,S=(e,t,r)=>({...e,[t]:r}),pe=(e,t,r)=>Object.fromEntries(Object.entries(e).map(([n,a])=>[n,kn(n,a,t,r)])),xn=async(e,t,r,n)=>{const a=u(e,"package.json"),o=yt(a);let s=S(o.dependencies??{},"lunorash",n);s=S(s,"@lunora/ratelimit",n),r.adapter.startsWith("@lunora/")&&(s=S(s,r.adapter,n));for(const[d,p]of Object.entries(r.extraDependencies??{}))s=S(s,d,p);let i=S(o.devDependencies??{},"@lunora/vite",n);i=S(i,"@lunora/studio",n);for(const[d,p]of Object.entries(wn))i=S(i,d,p);const l=[...Object.keys(s),...Object.keys(i)].filter(d=>W(d)),c=await Le(l,n);o.name=t,o.imports={...o.imports,"#lunora/*":"./lunora/*"},o.dependencies=pe(s,n,c),o.devDependencies=pe(i,n,c),o.scripts={...o.scripts,codegen:"lunora codegen",deploy:"lunora deploy"},v(a,`${JSON.stringify(o,void 0,4)}
1466
+ `,"utf8")},En=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],ze=e=>En.map(t=>u(e,t)).find(t=>f(t)),_n=(e,t)=>{const r=ze(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 n=Ve(E(r,"utf8"));n.changed&&v(r,n.code,"utf8")},Cn=async e=>{const{adapter:t,distTag:r,logger:n,name:a,target:o}=e,s=[];L(o,u("lunora","ratelimit","schema.ts"),un,s),L(o,u("lunora","schema.ts"),hn,s),L(o,u("lunora","messages.ts"),pn,s),L(o,u("src","server.ts"),mn,s),L(o,"wrangler.jsonc",vn.replaceAll("__NAME__",a),s),L(o,".env.example",gn,s);for(const i of t.files)L(o,i.path,i.contents,s);return _n(o,n),await xn(o,a,t,r),bn(o),s},Ln=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],Sn=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],me=e=>e[Math.floor(Math.random()*e.length)],An=()=>`${me(Ln)}-${me(Sn)}`,In=async()=>Zt.lookup("github.com").then(()=>!0,()=>!1),Rn=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,Ge=e=>{const t=Rn.exec(e);if(t===null)return;const[,r,n,a]=t;if(!(r===void 0||n===void 0))return{owner:r,ref:a??"HEAD",repo:n}},Tn=async e=>{const t=Ge(e);if(t===void 0)return;const r=`https://codeload.github.com/${t.owner}/${t.repo}/tar.gz/${t.ref}`;try{const n=await fetch(r,{method:"HEAD"});return n.status===404?!1:n.ok?!0:void 0}catch{return}},Ye=async e=>e.isLocal||!(e.source===void 0||Ge(e.source)!==void 0)?!0:await In()?e.source!==void 0&&await Tn(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),_={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?"},$n=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),Mn=`import { defineConfig } from "vite";
1305
1467
  import { lunora } from "@lunora/vite";
1306
1468
 
1307
1469
  export default defineConfig({ plugins: [lunora()] });
1308
- `,Ta=`import { defineSchema, defineTable, v } from "@lunora/server";
1470
+ `,On=`import { defineSchema, defineTable, v } from "@lunora/server";
1309
1471
 
1310
1472
  export default defineSchema({
1311
1473
  messages: defineTable({
@@ -1315,7 +1477,7 @@ export default defineSchema({
1315
1477
  .shardBy("channelId")
1316
1478
  .index("by_channel", ["channelId"]),
1317
1479
  });
1318
- `,Ra=`import { mutation, query, v } from "./_generated/server";
1480
+ `,Nn=`import { mutation, query, v } from "./_generated/server";
1319
1481
 
1320
1482
  export const list = query
1321
1483
  .input({ channelId: v.string(), limit: v.optional(v.number()) })
@@ -1328,8 +1490,8 @@ export const send = mutation
1328
1490
  .mutation(async ({ args }) => {
1329
1491
  return { channelId: args.channelId, text: args.text };
1330
1492
  });
1331
- `,Oa="gh:anolilab/lunora/templates",$a=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,Ua=/[^a-z0-9_]/gu,ja=e=>{const t=e.replaceAll(Da,"$1-$2").toLowerCase().replaceAll(Ua,"-").split("-").filter(r=>r.length>0);return t.length>0?t.join("-"):"my-app"},Ba=(e,t)=>e.replaceAll("{{name}}",t),Va=async(e,t)=>{const r=new Set;for(const a of e)if(_(a)==="package.json")for(const n of Object.keys(ke(S(a))))F(n)&&r.add(n);return Ae(r,t)},Fa=(e,t,r)=>{let a;try{a=JSON.parse(e)}catch{return e}let n=e;for(const o of["dependencies","devDependencies"])for(const s of Object.keys(a[o]??{})){if(!F(s))continue;const i=r.get(s)??t,l=bt(n,[o,s],i,{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(`
1332
- `),Je=e=>{const t=u(e,Ye);m(t)||g(t,za(),"utf8")},W=e=>{const t=[];for(const r of yt(e,{includeDirs:!1,includeFiles:!0}))ve(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));E(S(a),{recursive:!0}),st(r,a)}},Xe=async(e,t,r)=>{const a=W(e),n=[],o=Ce(),s=await Va(a,o);for(const i of a){const l=D(e,i),c=u(t,l);E(S(c),{recursive:!0});const d=x(i);let p=$a(i)?Ba(d.toString("utf8"),r):void 0;p!==void 0&&_(i)==="package.json"&&(p=Fa(p,o,s)),p===void 0?g(c,d):g(c,p,"utf8"),n.push(c)}return n},q=(e,t,r)=>t!==void 0&&t.length>0?t:`${Oa}/${e}#${Ee(r)}`,Ka=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),M=(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(`
1333
- `),e.success(`scaffolded ${String(t.length)} files into ${r}`)},qa=(e,t)=>{const{args:r,command:a}=Ct(e,t);return`${a} ${r.join(" ")}`},et=(e,t)=>{let r=xe(e);for(;;){if(t(r))return!0;const a=S(r);if(a===r)return!1;r=a}},Ga=e=>m(u(e,Ye))?!0:vt(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(S(t)))return;if(!await Ne(L.git,{badge:v.git,defaultYes:!1})){await Te("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){M(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:At(r,"dev"),lead:"Run",tail:" to start the dev server."},{code:"lunora add",lead:"Add features like auth or storage using"});const o=[{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(v.next,L.nextHeader,n,o);return}const s=n.map(i=>`${i.lead} ${i.code}${i.tail??""}`);s.push("",...o.map(i=>`${i.lead} ${i.code}${i.tail??""}`)),await P("next",L.nextHeader,s.join(`
1334
- `))},Qa=e=>e.yes!==!0&&(e.installPrompt!==void 0||b()),Za=async(e,t)=>{if(!Qa(e)||te(S(t)))return;const r=St(e.packageManagerProbe),[a]=r;if(a===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>Ne(L.install,{badge:v.deps,defaultYes:!0})))()){await Te("No problem! Remember to install dependencies after setup.");return}let o=a;if(r.length>1&&(o=e.installPrompt?await e.installPrompt.selectManager(r):await O(L.packageManager,r.map(d=>({label:d,value:d})),{badge:v.deps,default:a})??a),e.dryRun===!0){M(e.logger,`install dependencies with ${o}`);return}o==="pnpm"&&Je(t);const s=e.spawner??Me,{args:i,command:l}=Se(o);await P("deps",`Installing dependencies with ${o}…`);const c=await s({args:i,command:l,cwd:t});if(c.code!==0){e.logger.warn(`\`${l} install\` exited with code ${String(c.code)} — run it yourself in ${_(t)}/.`);return}return await P("deps",`Dependencies installed with ${o}.`),o},en=async(e,t,r,a,n,o)=>{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 i=await Xe(s,r,a);return i.length===0?Qe(n,r,s):(o(),ee(n,i,r),{code:0,files:i,target:r})},tn=async e=>{const{logger:t,markComplete:r,name:a,ref:n,source:o,target:s,templateType:i}=e,l=we(u(ye(),"lunora-init-fetch-")),c=u(l,"template");try{const d=o!==void 0&&o.length>0?n:await Nt(n,t),p=q(i,o,d);let f,h=[];if(await Re([{label:`${i} template fetched`,run:async()=>{f=await Le(p,{cwd:l,dir:c,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{h=await Xe(c,s,a)}}],{end:Ze,start:"Project initializing…"}),h.length===0)return Qe(t,s,f?.source??p);r();const k=W(c);return b()&&process.stdout.write(`
1335
- `),t.info(f?.commit?`template: ${f.source} @ ${f.commit} (${String(k.length)} files)`:`template: ${f?.source??p} (${String(k.length)} files)`),ee(t,h,s),{code:0,files:h,target:s}}catch(d){if(d instanceof X)throw d;const{hints:p,message:f}=wr(d,{ref:Ee(n),remote:q(i,o,n),templateType:i});t.error(f);for(const h of p)t.warn(h);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:o,target:s}=e,i=B[t],l=we(u(ye(),"lunora-vite-base-"));try{let c;if(o!==void 0&&(c=u(o,`template-${i.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"),h=await _t(fe,"main",r),k=`github:${fe}/packages/create-vite/template-${i.createViteTemplate}#${h}`;await Le(k,{cwd:l,dir:f,force:!0,install:!1,silent:!0}),rn(f),me(f,s)};let p=[];return await Re([{label:`create-vite (${i.label}) base ready`,run:d},{label:`Lunora overlay applied (${i.label})`,run:async()=>{p=await La({adapter:i,distTag:Ce(),logger:r,name:n,target:s})}}],{end:Ze,start:"Project initializing…"}),a(),ee(r,p,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 ${i.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{g(r,Na,"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(o){return G("read",e,o,t,r)}const n=je(a);if(!n.changed)return r.info(`${e}: ${n.reason??"no changes needed"}`),{code:0,files:[],target:t};try{g(e,n.code,"utf8")}catch(o){return G("write",e,o,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{E(r,{recursive:!0}),g(a,Ta,"utf8"),n.push(a);const o=u(r,"messages.ts");m(o)||(g(o,Ra,"utf8"),n.push(o)),t.success(`scaffolded lunora/ (${String(n.length)} file(s))`)}catch(o){const s=o instanceof Error?o.message:String(o);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:o}=e;r.info(""),r.info(`detected framework: ${o} (class ${n})`),r.info("next steps:");const s=[a,"@lunora/client","@lunora/runtime","@lunora/server"];tt(o)||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(` (${o} 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=ir(e),a=cn(e,r.framework,t);if(a.code!==0)return a;const n=sn(e,t);return ln(r,U(e),t),{code:0,files:[...a.files,...n],target:e}},un=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??b())),ge=async(e,t,r)=>{r.dryRun!==!0&&await Qr({apply:a=>gt(e,a),detected:mt(e),interactive:t,logger:r.logger,multiSelect:r.lintPrompt??((a,n,o)=>_e(a,n,{...o,badge:v.add}))})},hn=async(e,t)=>{const r=un(e),a=e.add===void 0?[]:Fr(e.add,i=>{e.logger.warn(i)}),n=async i=>{if(i.length===0)return!0;if(e.dryRun===!0)return M(e.logger,`add ${i.map(h=>h.externalAuth===void 0?h.label:`${h.label} (and wire resolveIdentity)`).join(", ")}`),!0;const l=[],c=b()?{error:h=>{l.push({level:"error",message:h})},info:()=>{},success:()=>{},warn:h=>{l.push({level:"warn",message:h})}}:e.logger,d=i.map(h=>({running:`adding ${h.label}…`,task:()=>qt({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:c,names:[...h.names],ref:e.ref,source:e.registrySource,transformManifest:h.transformManifest,yes:!0})})),p=`added ${i.map(h=>h.label).join(", ")}`,f=await Ut(v.add,d,p);for(const{level:h,message:k}of l)e.logger[h](k);for(const[h,k]of i.entries())k.externalAuth!==void 0&&f[h]?.code===0&&jr(t,k.externalAuth,e.logger);return f.every(h=>h.code===0)},o=e.auth===void 0?void 0:br(e.auth,i=>{e.logger.warn(i)}),s={applyAll:n,auth:o,interactive:r,logger:e.logger,multiSelect:e.prompt?.multiSelect??((i,l,c)=>_e(i,l,{...c,badge:v.add})),preselected:a.length>0?a:void 0,projectName:_(t),resolveAuthUiItem:()=>{const i=ke(t);if(!zt(i))return Kt(i)??"auth-ui-react"},select:e.prompt?.select??((i,l,c)=>O(i,l,{...c,badge:v.add})),selectAuth:e.prompt===void 0?(i,l,c)=>O(i,l,{...c,badge:v.add}):e.prompt.selectAuth??(()=>Promise.resolve("none")),text:e.prompt?.text??((i,l)=>Ie(i,{...l,badge:v.add}))};if(a.length>0||o!==void 0&&!r){const i=await de(s);return await ge(t,r,e),i}return b()&&await $t(L.extras),await de(s),await ge(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(B).join("|"),nt=rt.filter(e=>!V(e.value)).map(e=>e.value),ot=nt.join("|"),pn=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"}:pn(await O(L.framework,rt,{badge:v.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 <${ot}>\` 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.`},gn=async(e,t,r,a,n)=>V(t)?await Ge({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(E(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(B).join(", ")}.`),{code:w.USAGE,files:[],target:a}),vn=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=U(e)}catch{return}r==="pnpm"&&Je(e)},yn=async(e,t,r)=>{await Ot("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=Ca(),o=e.name??await Ie(L.name,{badge:v.dir,default:n,placeholder:n}),s=await fn(e),i=o.trim();if(i.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(i.includes("/")||i.includes("\\")||i===".."||i===".")return e.logger.error(`init: refusing project name "${i}" — must not contain path separators or be "." / "..".`),{code:w.USAGE,files:[],target:""};if(!Pa.test(i))return e.logger.error(`init: refusing project name "${i}" — a Cloudflare Worker name must be lowercase letters, digits, "-" or "_" (starting with a letter, digit or "_"), and wrangler rejects anything else. Try \`${ja(i)}\`.`),{code:w.USAGE,files:[],target:""};const l=xe(t,i),c=ve(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 M(e.logger,`scaffold ${f} into ${l}`),{code:0,files:[],target:l}}r.record(l,d);const p=s.kind==="overlay"?await gn(e,s.framework,i,l,r.complete):await vn(e,s.templateType,i,l,r.complete);return p.code===0&&wn(l,t),p},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?(M(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):dn(t,e.logger),kn=async(e,t,r)=>{const a=await hn(e,t.target),n=e.inPlace===!0?void 0:await Za(e,t.target);if(e.inPlace!==!0){await Ja(e,t.target);const o=n??U(t.target);await Xa(_(t.target),n,o,te(r)),await Br(e.logger)}return a},xn=(e,t,r)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){M(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const a=e.inPlace===!0?r:t.target;try{const n=U(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.`)}},Ln=async e=>{const t=e.cwd??process.cwd(),r={};let a;try{a=await bn(e,t,{complete:()=>{r.target=void 0},record:(n,o)=>{r.target=n,r.targetPreExisted=o}}),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},Sn=e=>typeof e=="string"&&nt.includes(e),An=(e,t)=>{if(e!==void 0){if(rr(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},Cn=e=>e===void 0?{}:Sn(e)?{templateType:e}:V(e)?{vite:e}:{error:`init: unknown --template "${e}" — expected a bespoke template (${ot}) or an overlay framework (${at}).`},Jn=Et(({argument:e,cwd:t,logger:r,options:a})=>{const n=Cn(a.template);return"error"in n?(r.error(n.error),{code:w.USAGE}):Ln({add:a.add,auth:a.auth,allowUnsafeSource:a.allowUnsafeSource===!0,cwd:t,ci:An(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,Sn as isTemplate,Cn as resolveTemplateFlag,q as resolveTemplateSource,Ln as runInitCommand};
1493
+ `,Pn="gh:anolilab/lunora/templates",Dn=e=>{const t=e.lastIndexOf(".");return t===-1?!1:$n.has(e.slice(t))},Un=/^[a-z0-9_][a-z0-9\-_]*$/u,jn=/([a-z0-9])([A-Z])/gu,Vn=/[^a-z0-9_]/gu,Bn=e=>{const t=e.replaceAll(jn,"$1-$2").toLowerCase().replaceAll(Vn,"-").split("-").filter(r=>r.length>0);return t.length>0?t.join("-"):"my-app"},Fn=(e,t)=>e.replaceAll("{{name}}",t),Wn=async(e,t)=>{const r=new Set;for(const n of e)if(T(n)==="package.json")for(const a of Object.keys(xe(C(n))))W(a)&&r.add(a);return Le(r,t)},qn=(e,t,r)=>{let n;try{n=JSON.parse(e)}catch{return e}let a=e;for(const o of["dependencies","devDependencies"])for(const s of Object.keys(n[o]??{})){if(!W(s))continue;const i=r.get(s)??t,l=kt(a,[o,s],i,{formattingOptions:{insertSpaces:!0,tabSize:4}});a=xt(a,l)}return a},Hn=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],Kn=["cpu-features","protobufjs","ssh2"],Je="pnpm-workspace.yaml",zn=()=>["# 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:",...Hn.map(e=>` '${e}': true`),...Kn.map(e=>` '${e}': false`),""].join(`
1494
+ `),Qe=e=>{const t=u(e,Je);f(t)||v(t,zn(),"utf8")},q=e=>{const t=[];for(const r of bt(e,{includeDirs:!1,includeFiles:!0}))we(r.path).isSymbolicLink()||t.push(r.path);return t},fe="vitejs/vite",ve=(e,t)=>{for(const r of q(e)){const n=u(t,U(e,r));A(C(n),{recursive:!0}),lt(r,n)}},Xe=async(e,t,r)=>{const n=q(e),a=[],o=Se(),s=await Wn(n,o);for(const i of n){const l=U(e,i),c=u(t,l);A(C(c),{recursive:!0});const d=E(i);let p=Dn(i)?Fn(d.toString("utf8"),r):void 0;p!==void 0&&T(i)==="package.json"&&(p=qn(p,o,s)),p===void 0?v(c,d):v(c,p,"utf8"),a.push(c)}return a},G=(e,t,r)=>t!==void 0&&t.length>0?t:`${Pn}/${e}#${Ae(r)}`,Gn=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),I=(e,t)=>{e.info(`[dry-run] would ${t}`)},Ze=(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:g.NOT_FOUND,files:[],target:t}),et="Template files copied.",te=(e,t,r)=>{b()&&process.stdout.write(`
1495
+ `),e.success(`scaffolded ${String(t.length)} files into ${r}`)},Yn=(e,t)=>{const{args:r,command:n}=St(e,t);return`${n} ${r.join(" ")}`},tt=(e,t)=>{let r=Ee(e);for(;;){if(t(r))return!0;const n=C(r);if(n===r)return!1;r=n}},Jn=e=>f(u(e,Je))?!0:wt(e)?.workspaces!==void 0,re=e=>tt(e,Jn),Qn=e=>tt(e,t=>f(u(t,".git"))),Xn=async(e,t)=>{if(e.yes===!0||!b()||Qn(C(t)))return;if(!await $e(_.git,{badge:w.git,defaultYes:!1})){await Me("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??Ie;(await Dt("Initializing a git repository…",()=>r({args:["init"],command:"git",cwd:t}))).code===0?await D("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},Zn=async(e,t,r,n)=>{const a=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&a.push({code:`${r} install`,lead:"Install dependencies with",tail:n?" from the workspace root":void 0}),a.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 o=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(b()){await Ut(w.next,_.nextHeader,a,o);return}const s=a.map(i=>`${i.lead} ${i.code}${i.tail??""}`);s.push("",...o.map(i=>`${i.lead} ${i.code}${i.tail??""}`)),await D("next",_.nextHeader,s.join(`
1496
+ `))},ea=e=>e.yes!==!0&&(e.installPrompt!==void 0||b()),ta=async(e,t)=>{if(!ea(e)||re(C(t)))return;const r=Ct(e.packageManagerProbe),[n]=r;if(n===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>$e(_.install,{badge:w.deps,defaultYes:!0})))()){await Me("No problem! Remember to install dependencies after setup.");return}let o=n;if(r.length>1&&(o=e.installPrompt?await e.installPrompt.selectManager(r):await P(_.packageManager,r.map(d=>({label:d,value:d})),{badge:w.deps,default:n})??n),e.dryRun===!0){I(e.logger,`install dependencies with ${o}`);return}o==="pnpm"&&Qe(t);const s=e.spawner??Ie,{args:i,command:l}=Ce(o);await D("deps",`Installing dependencies with ${o}…`);const c=await s({args:i,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 D("deps",`Dependencies installed with ${o}.`),o},ra=async(e,t,r,n,a,o)=>{const s=u(e,t);if(!f(s))return a.error(`template not found in local source: ${s}`),{code:g.NOT_FOUND,files:[],target:r};const i=await Xe(s,r,n);return i.length===0?Ze(a,r,s):(o(),te(a,i,r),{code:0,files:i,target:r})},na=async e=>{const{logger:t,markComplete:r,name:n,ref:a,source:o,target:s,templateType:i}=e,l=ye(u(be(),"lunora-init-fetch-")),c=u(l,"template");try{const d=o!==void 0&&o.length>0?a:await $t(a,t),p=G(i,o,d);let m,h=[];if(await Oe([{label:`${i} template fetched`,run:async()=>{m=await _e(p,{cwd:l,dir:c,force:!0,install:!1,silent:!0})}},{label:`files copied into ${n}/`,run:async()=>{h=await Xe(c,s,n)}}],{end:et,start:"Project initializing…"}),h.length===0)return Ze(t,s,m?.source??p);r();const k=q(c);return b()&&process.stdout.write(`
1497
+ `),t.info(m?.commit?`template: ${m.source} @ ${m.commit} (${String(k.length)} files)`:`template: ${m?.source??p} (${String(k.length)} files)`),te(t,h,s),{code:0,files:h,target:s}}catch(d){if(d instanceof X)throw d;const{hints:p,message:m}=yr(d,{ref:Ae(a),remote:G(i,o,a),templateType:i});t.error(m);for(const h of p)t.warn(h);return{code:1,files:[],target:s}}finally{N(l,{force:!0,recursive:!0})}},aa=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const r=u(e,t);f(r)&&ct(r,u(e,`.${t.slice(1)}`))}},oa=async e=>{const{framework:t,logger:r,markComplete:n,name:a,overlayBaseFrom:o,target:s}=e,i=B[t],l=ye(u(be(),"lunora-vite-base-"));try{let c;if(o!==void 0&&(c=u(o,`template-${i.createViteTemplate}`),!f(c)))return r.error(`create-vite base not found on disk: ${c}`),{code:g.NOT_FOUND,files:[],target:s};const d=async()=>{if(c!==void 0){ve(c,s);return}const m=u(l,"base"),h=await Tt(fe,"main",r),k=`github:${fe}/packages/create-vite/template-${i.createViteTemplate}#${h}`;await _e(k,{cwd:l,dir:m,force:!0,install:!1,silent:!0}),aa(m),ve(m,s)};let p=[];return await Oe([{label:`create-vite (${i.label}) base ready`,run:d},{label:`Lunora overlay applied (${i.label})`,run:async()=>{p=await Cn({adapter:i,distTag:Se(),logger:r,name:a,target:s})}}],{end:et,start:"Project initializing…"}),n(),te(r,p,s),{code:0,files:[...q(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 ${i.label} base: ${d}`),{code:1,files:[],target:s}}finally{N(l,{force:!0,recursive:!0})}},Y=(e,t,r,n,a)=>(a.error(`init --in-place: could not ${e} ${t}: ${r instanceof Error?r.message:String(r)}`),{code:1,files:[],target:n}),ia=(e,t)=>{const r=u(e,"vite.config.ts");try{v(r,Mn,"utf8")}catch(n){return Y("write",r,n,e,t)}return t.success(`created ${r} with lunora() plugin`),{code:0,files:[r],target:e}},sa=(e,t,r)=>{let n;try{n=E(e,"utf8")}catch(o){return Y("read",e,o,t,r)}const a=Ve(n);if(!a.changed)return r.info(`${e}: ${a.reason??"no changes needed"}`),{code:0,files:[],target:t};try{v(e,a.code,"utf8")}catch(o){return Y("write",e,o,t,r)}return r.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},la=(e,t)=>{const r=u(e,"lunora"),n=u(r,"schema.ts");if(f(n))return t.info(`lunora/ already present — left ${n} untouched`),[];const a=[];try{A(r,{recursive:!0}),v(n,On,"utf8"),a.push(n);const o=u(r,"messages.ts");f(o)||(v(o,Nn,"utf8"),a.push(o)),t.success(`scaffolded lunora/ (${String(a.length)} file(s))`)}catch(o){const s=o instanceof Error?o.message:String(o);t.error(`init --here: could not scaffold lunora/: ${s}`)}return a},rt=e=>e==="sveltekit"||e==="nuxt"||e==="astro",ca=(e,t,r)=>{const{adapter:n,class:a,framework:o}=e;r.info(""),r.info(`detected framework: ${o} (class ${a})`),r.info("next steps:");const s=[n,"@lunora/client","@lunora/runtime","@lunora/server"];rt(o)||s.push("@lunora/vite"),r.info(` 1. install the adapter: ${Yn(t,s)}`),r.info(" 2. run codegen: lunora codegen"),a==="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 ${n} 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")):a==="B"?(r.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),r.info(` (${o} owns its Cloudflare adapter — Lunora composes into its server entry)`),r.info(` 4. add the provider: mount the ${n} 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("")},da=(e,t,r)=>{if(rt(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 n=ze(e);return n===void 0?ia(e,r):sa(n,e,r)},ua=(e,t)=>{const r=sr(e),n=da(e,r.framework,t);if(n.code!==0)return n;const a=la(e,t);return ca(r,j(e),t),{code:0,files:[...n.files,...a],target:e}},ha=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??b())),ge=async(e,t,r)=>{r.dryRun!==!0&&await Zr({apply:n=>gt(e,n),detected:vt(e),interactive:t,logger:r.logger,multiSelect:r.lintPrompt??((n,a,o)=>Te(n,a,{...o,badge:w.add}))})},pa=async(e,t)=>{const r=ha(e),n=e.add===void 0?[]:Wr(e.add,i=>{e.logger.warn(i)}),a=async i=>{if(i.length===0)return!0;if(e.dryRun===!0)return I(e.logger,`add ${i.map(h=>h.externalAuth===void 0?h.label:`${h.label} (and wire resolveIdentity)`).join(", ")}`),!0;const l=[],c=b()?{error:h=>{l.push({level:"error",message:h})},info:()=>{},success:()=>{},warn:h=>{l.push({level:"warn",message:h})}}:e.logger,d=i.map(h=>({running:`adding ${h.label}…`,task:()=>Gt({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:c,names:[...h.names],ref:e.ref,source:e.registrySource,transformManifest:h.transformManifest,yes:!0})})),p=`added ${i.map(h=>h.label).join(", ")}`,m=await jt(w.add,d,p);for(const{level:h,message:k}of l)e.logger[h](k);for(const[h,k]of i.entries())k.externalAuth!==void 0&&m[h]?.code===0&&Vr(t,k.externalAuth,e.logger);return m.every(h=>h.code===0)},o=e.auth===void 0?void 0:kr(e.auth,i=>{e.logger.warn(i)}),s={applyAll:a,auth:o,interactive:r,logger:e.logger,multiSelect:e.prompt?.multiSelect??((i,l,c)=>Te(i,l,{...c,badge:w.add})),preselected:n.length>0?n:void 0,projectName:T(t),resolveAuthUiItem:()=>{const i=xe(t);if(!Kt(i))return zt(i)??"auth-ui-react"},select:e.prompt?.select??((i,l,c)=>P(i,l,{...c,badge:w.add})),selectAuth:e.prompt===void 0?(i,l,c)=>P(i,l,{...c,badge:w.add}):e.prompt.selectAuth??(()=>Promise.resolve("none")),text:e.prompt?.text??((i,l)=>Re(i,{...l,badge:w.add}))};if(n.length>0||o!==void 0&&!r){const i=await ue(s);return await ge(t,r,e),i}return b()&&await Pt(_.extras),await ue(s),await ge(t,r,e),!0},K="react",nt=[{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(B).join("|"),ot=nt.filter(e=>!F(e.value)).map(e=>e.value),it=ot.join("|"),ma=e=>F(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},fa=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:K,kind:"overlay"}:ma(await P(_.framework,nt,{badge:w.tmpl,default:K})??K),va=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.`},ga=async(e,t,r,n,a)=>F(t)?await Ye({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(A(n,{recursive:!0}),oa({framework:t,logger:e.logger,markComplete:a,name:r,overlayBaseFrom:e.overlayBaseFrom,target:n})):{code:1,files:[],target:n}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(B).join(", ")}.`),{code:g.USAGE,files:[],target:n}),wa=async(e,t,r,n,a)=>e.from!==void 0?await ra(e.from,t,n,r,e.logger,a):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!Gn(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:g.USAGE,files:[],target:n}):await Ye({isLocal:!1,logger:e.logger,source:G(t,e.source,e.ref)})?na({logger:e.logger,markComplete:a,name:r,ref:e.ref,source:e.source,target:n,templateType:t}):{code:1,files:[],target:n},ya=(e,t)=>{if(re(t))return;let r;try{r=j(e)}catch{return}r==="pnpm"&&Qe(e)},ba=async(e,t,r)=>{await Nt("realtime backend on Cloudflare Workers + Durable Objects");const n=va(e);if(n!==void 0)return e.logger.error(n),{code:g.USAGE,files:[],target:""};const a=An(),o=e.name??await Re(_.name,{badge:w.dir,default:a,placeholder:a}),s=await fa(e),i=o.trim();if(i.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:g.USAGE,files:[],target:""};if(i.includes("/")||i.includes("\\")||i===".."||i===".")return e.logger.error(`init: refusing project name "${i}" — must not contain path separators or be "." / "..".`),{code:g.USAGE,files:[],target:""};if(!Un.test(i))return e.logger.error(`init: refusing project name "${i}" — a Cloudflare Worker name must be lowercase letters, digits, "-" or "_" (starting with a letter, digit or "_"), and wrangler rejects anything else. Try \`${Bn(i)}\`.`),{code:g.USAGE,files:[],target:""};const l=Ee(t,i),c=we(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:g.CONFLICT,files:[],target:l};const d=c!==void 0;if(d&&J(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:g.CONFLICT,files:[],target:l};if(e.dryRun===!0){const m=s.kind==="overlay"?`the ${s.framework} create-vite overlay`:`the ${s.templateType} template`;return I(e.logger,`scaffold ${m} into ${l}`),{code:0,files:[],target:l}}r.record(l,d);const p=s.kind==="overlay"?await ga(e,s.framework,i,l,r.complete):await wa(e,s.templateType,i,l,r.complete);return p.code===0&&ya(l,t),p},z=(e,t)=>{const{target:r,targetPreExisted:n}=e;if(!(r===void 0||!f(r))){if(n===!0)for(const a of J(r))N(u(r,a),{force:!0,recursive:!0});else N(r,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${r}`)}},ka=async(e,t,r)=>e.inPlace!==!0?ba(e,t,r):e.dryRun===!0?(I(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):ua(t,e.logger),xa=async(e,t,r)=>{const n=await pa(e,t.target),a=e.inPlace===!0?void 0:await ta(e,t.target);if(e.inPlace!==!0){await Xn(e,t.target);const o=a??j(t.target);await Zn(T(t.target),a,o,re(r)),await Br(e.logger)}return n},Ea=(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 n=e.inPlace===!0?r:t.target;try{const a=j(n);or(n,e.ci,a,e.logger)}catch{e.logger.warn(`--ci ${e.ci}: could not detect a package manager for this project — skipped the CI pipeline.`)}},_a=async e=>{const t=e.cwd??process.cwd(),r={};let n;try{n=await ka(e,t,{complete:()=>{r.target=void 0},record:(a,o)=>{r.target=a,r.targetPreExisted=o}}),n.code===0&&n.target!==""?(r.target=void 0,await xa(e,n,t)||(n={...n,code:1})):n.code!==0&&z(r,e.logger)}catch(a){if(a instanceof X)return z(r,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw z(r,e.logger),a}return Ea(e,n,t),n},Ca=e=>typeof e=="string"&&ot.includes(e),La=(e,t)=>{if(e!==void 0){if(nr(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},Sa=e=>e===void 0?{}:Ca(e)?{templateType:e}:F(e)?{vite:e}:{error:`init: unknown --template "${e}" — expected a bespoke template (${it}) or an overlay framework (${at}).`},Qa=At(({argument:e,cwd:t,logger:r,options:n})=>{const a=Sa(n.template);return"error"in a?(r.error(a.error),{code:g.USAGE}):_a({add:n.add,auth:n.auth,allowUnsafeSource:n.allowUnsafeSource===!0,cwd:t,ci:La(n.ci,r),dryRun:n.dryRun===!0,from:n.from,inPlace:n.here===!0,interactive:n.interactive===!0?!0:void 0,logger:r,name:e[0],ref:n.ref,source:n.source,templateType:a.templateType,vite:n.vite??a.vite,yes:n.yes===!0})});export{nt as FRAMEWORK_CHOICES,Qa as execute,Ca as isTemplate,Sa as resolveTemplateFlag,G as resolveTemplateSource,_a as runInitCommand};