@lunora/cli 1.0.0-alpha.49 → 1.0.0-alpha.490

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/LICENSE.md +234 -104
  2. package/README.md +6 -4
  3. package/dist/bin.mjs +3 -10
  4. package/dist/cli.d.mts +31 -0
  5. package/dist/cli.d.ts +31 -0
  6. package/dist/cli.mjs +1 -0
  7. package/dist/index.d.mts +1181 -427
  8. package/dist/index.d.ts +1181 -427
  9. package/dist/index.mjs +1 -19
  10. package/dist/packem_chunks/cli.mjs +2 -0
  11. package/dist/packem_chunks/dispatch.mjs +1 -0
  12. package/dist/packem_chunks/handler.mjs +61 -157
  13. package/dist/packem_chunks/handler10.mjs +1 -16
  14. package/dist/packem_chunks/handler11.mjs +1 -22
  15. package/dist/packem_chunks/handler12.mjs +1 -192
  16. package/dist/packem_chunks/handler13.mjs +3 -131
  17. package/dist/packem_chunks/handler14.mjs +1 -65
  18. package/dist/packem_chunks/handler15.mjs +1 -58
  19. package/dist/packem_chunks/handler16.mjs +1 -80
  20. package/dist/packem_chunks/handler17.mjs +1 -43
  21. package/dist/packem_chunks/handler18.mjs +1 -105
  22. package/dist/packem_chunks/handler19.mjs +1 -170
  23. package/dist/packem_chunks/handler2.mjs +1 -114
  24. package/dist/packem_chunks/handler20.mjs +1 -94
  25. package/dist/packem_chunks/handler21.mjs +7 -94
  26. package/dist/packem_chunks/handler22.mjs +1 -0
  27. package/dist/packem_chunks/handler23.mjs +3 -0
  28. package/dist/packem_chunks/handler24.mjs +3 -0
  29. package/dist/packem_chunks/handler25.mjs +2 -0
  30. package/dist/packem_chunks/handler26.mjs +1 -0
  31. package/dist/packem_chunks/handler27.mjs +2 -0
  32. package/dist/packem_chunks/handler28.mjs +99 -0
  33. package/dist/packem_chunks/handler29.mjs +3 -0
  34. package/dist/packem_chunks/handler3.mjs +1 -204
  35. package/dist/packem_chunks/handler30.mjs +15 -0
  36. package/dist/packem_chunks/handler31.mjs +1 -0
  37. package/dist/packem_chunks/handler32.mjs +1 -0
  38. package/dist/packem_chunks/handler4.mjs +1 -33
  39. package/dist/packem_chunks/handler5.mjs +3 -49
  40. package/dist/packem_chunks/handler6.mjs +1 -91
  41. package/dist/packem_chunks/handler7.mjs +1 -42
  42. package/dist/packem_chunks/handler8.mjs +1 -174
  43. package/dist/packem_chunks/handler9.mjs +2 -315
  44. package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
  45. package/dist/packem_chunks/runDevCommand.mjs +8 -0
  46. package/dist/packem_chunks/runInitCommand.mjs +423 -1452
  47. package/dist/packem_chunks/runResetCommand.mjs +1 -41
  48. package/dist/packem_chunks/runRpcCommand.mjs +1 -68
  49. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck9tABfr.mjs +1 -0
  50. package/dist/packem_shared/EXIT_CODE-DQVhSE-1.mjs +1 -0
  51. package/dist/packem_shared/admin-token-VdUnvnKW.mjs +1 -0
  52. package/dist/packem_shared/admin-url-DJB8P6Jh.mjs +1 -0
  53. package/dist/packem_shared/api-spec-lYyq4vL6.mjs +1 -0
  54. package/dist/packem_shared/binding-manifest-file-BZyQFSTF.mjs +2 -0
  55. package/dist/packem_shared/buildRegistryIndex-Dc8D8AR6.mjs +1 -0
  56. package/dist/packem_shared/cap-error-body-YBKO32BF.mjs +1 -0
  57. package/dist/packem_shared/catalog-CahzmDLV.mjs +1 -0
  58. package/dist/packem_shared/cli-manifest-DoQ_3bzs.mjs +1 -0
  59. package/dist/packem_shared/cloudflare-credentials-BVmZnDZk.mjs +1 -0
  60. package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
  61. package/dist/packem_shared/command-BpMv2n0o.mjs +1 -0
  62. package/dist/packem_shared/commands-CkuCMUP_.mjs +13 -0
  63. package/dist/packem_shared/createLogger-4TujevyB.mjs +2 -0
  64. package/dist/packem_shared/createRecordingSpawner-DchLi0gR.mjs +1 -0
  65. package/dist/packem_shared/deploy-target-resolve-BTCW1Iv4.mjs +1 -0
  66. package/dist/packem_shared/diffSnapshots-DcE-jQUz.mjs +9 -0
  67. package/dist/packem_shared/docker-DpVxvYpL.mjs +1 -0
  68. package/dist/packem_shared/export-rows-EzdNDYpa.mjs +3 -0
  69. package/dist/packem_shared/free-port-DjbFhaaT.mjs +1 -0
  70. package/dist/packem_shared/health-probe-By9T5x2y.mjs +13 -0
  71. package/dist/packem_shared/import-3Y59Ry9F.mjs +13 -0
  72. package/dist/packem_shared/index-oHZBGBwB.mjs +1 -0
  73. package/dist/packem_shared/insertSchemaExtension-CbTH3lCQ.mjs +10 -0
  74. package/dist/packem_shared/js-literal-FWLi94Lh.mjs +1 -0
  75. package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
  76. package/dist/packem_shared/mcp-config-file-GR1Y_CVw.mjs +2 -0
  77. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  78. package/dist/packem_shared/output-format-DWe_tkTR.mjs +2 -0
  79. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  80. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  81. package/dist/packem_shared/plan-BF2E-dq4.mjs +5 -0
  82. package/dist/packem_shared/planDevCommand-C8QHZzEJ.mjs +1 -0
  83. package/dist/packem_shared/platform-diagnostics-Cn2g6Jh-.mjs +4 -0
  84. package/dist/packem_shared/prompt-cancelled-BvsNxg_Q.mjs +1 -0
  85. package/dist/packem_shared/render-lunora-error-JsLelWwR.mjs +2 -0
  86. package/dist/packem_shared/resolve-Bdc9KEUv.mjs +5 -0
  87. package/dist/packem_shared/resolve-target-C_ZloTvd.mjs +1 -0
  88. package/dist/packem_shared/runAddCommand-gThKW-ZB.mjs +1 -0
  89. package/dist/packem_shared/runDeployCommand-DhgZz8Sj.mjs +1 -0
  90. package/dist/packem_shared/runExportCommand-_PtkJJDT.mjs +5 -0
  91. package/dist/packem_shared/runMigrateGenerateCommand-DHdSMKbu.mjs +11 -0
  92. package/dist/packem_shared/schemaIrToSnapshot-CbWOjany.mjs +1 -0
  93. package/dist/packem_shared/shared-CV7ESvuj.mjs +2 -0
  94. package/dist/packem_shared/sql-u1MSmopg.mjs +3 -0
  95. package/dist/packem_shared/storage-3GOIFVZm.mjs +1 -0
  96. package/dist/packem_shared/tui-prompts-B3YwUhGw.mjs +4 -0
  97. package/dist/packem_shared/variables-CPYyJtsL.mjs +1 -0
  98. package/dist/packem_shared/vectorize-metadata-DK61NmVx.mjs +2 -0
  99. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  100. package/dist/packem_shared/wrangler-secrets-C9siMBwN.mjs +1 -0
  101. package/package.json +46 -20
  102. package/skills/README.md +36 -17
  103. package/skills/lunora/SKILL.md +158 -65
  104. package/skills/lunora-cloudflare-audit/SKILL.md +164 -0
  105. package/skills/lunora-create-package/SKILL.md +98 -84
  106. package/skills/lunora-deploy/SKILL.md +212 -102
  107. package/skills/lunora-functions/SKILL.md +367 -60
  108. package/skills/lunora-migration-helper/SKILL.md +194 -149
  109. package/skills/lunora-performance-audit/SKILL.md +137 -95
  110. package/skills/lunora-quickstart/SKILL.md +136 -136
  111. package/skills/lunora-realtime/SKILL.md +219 -97
  112. package/skills/lunora-setup-auth/SKILL.md +203 -101
  113. package/skills/lunora-setup-hyperdrive/SKILL.md +153 -110
  114. package/skills/lunora-setup-hyperdrive-global/SKILL.md +152 -94
  115. package/skills/lunora-setup-mail/SKILL.md +97 -113
  116. package/skills/lunora-setup-scheduler/SKILL.md +133 -97
  117. package/skills/lunora-setup-storage/SKILL.md +189 -95
  118. package/dist/packem_chunks/planDevCommand.mjs +0 -541
  119. package/dist/packem_chunks/runDeployCommand.mjs +0 -594
  120. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +0 -397
  121. package/dist/packem_shared/COMMANDS-B0ftFD_3.mjs +0 -948
  122. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  123. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  124. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  125. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  126. package/dist/packem_shared/codegen-error-DJG-ghs_.mjs +0 -31
  127. package/dist/packem_shared/command-D3lB_4Az.mjs +0 -19
  128. package/dist/packem_shared/commands-B-gR09Z_.mjs +0 -845
  129. package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
  130. package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
  131. package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
  132. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  133. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  134. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  135. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  136. package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
  137. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  138. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  139. package/dist/packem_shared/prompt-cancelled-APzX1Im-.mjs +0 -9
  140. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  141. package/dist/packem_shared/runAddCommand-bnY6-HKb.mjs +0 -4
  142. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  143. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  144. package/dist/packem_shared/storage-BIsph-Vk.mjs +0 -84
  145. package/dist/packem_shared/tui-prompts-BjEN8XgP.mjs +0 -658
  146. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
  147. package/dist/packem_shared/wrangler-secrets-P2_ZUR-k.mjs +0 -47
@@ -1,42 +1,50 @@
1
- import { existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync, mkdtempSync, cpSync, renameSync } from 'node:fs';
2
- import { tmpdir } from 'node:os';
3
- import { detectFramework as detectFramework$1, isInteractive, LUNA_ART, LUNA_NAME, LUNA_SIGNOFF, paintAnswer, BADGES } from '@lunora/config';
4
- import { walkSync } from '@visulima/fs';
5
- import { join as join$1, dirname as dirname$1, basename, resolve, relative } from '@visulima/path';
6
- import { downloadTemplate } from 'giget';
7
- import { modify, applyEdits } from 'jsonc-parser';
8
- import { join, dirname } from 'node:path';
9
- import { d as defineHandler } from '../packem_shared/command-D3lB_4Az.mjs';
10
- import { a as detectInstalledManagers, i as installArgsFor } from '../packem_shared/detect-package-manager-DYp7n3mJ.mjs';
11
- import MagicString from 'magic-string';
12
- import { Project, SyntaxKind } from 'ts-morph';
13
- import { P as PromptCancelledError } from '../packem_shared/prompt-cancelled-APzX1Im-.mjs';
14
- import { c as resolveTagVersions, d as resolveSourceRef, e as resolveDistTag, r as runAddCommand } from '../packem_shared/commands-B-gR09Z_.mjs';
15
- import { defaultSpawner } from '../packem_shared/createRecordingSpawner-DxI3mebw.mjs';
16
- import { d as tuiMascot, e as tuiStep, f as tuiMoonrise, t as tuiText, g as tuiHeadline, h as tuiInfo, a as tuiSelect, b as tuiConfirm, w as withTuiSpinner, i as tuiNextSteps, j as tuiTasks, k as tuiMultiSelect, l as withTuiBadgeProgress } from '../packem_shared/tui-prompts-BjEN8XgP.mjs';
17
- import { logStep } from '../packem_shared/createLogger-B40gPzQo.mjs';
18
- import { E as EMAIL_ITEM, p as promptBucketName, w as withStorageBucketName, M as MAIL_DESTINATION_PROMPT, r as resolveTypedDestination, f as withMailDestination, e as promptAuthProvider, c as promptDatabaseName, g as withAuthDatabaseName } from '../packem_shared/storage-BIsph-Vk.mjs';
19
- import dns from 'node:dns/promises';
20
-
21
- const GITHUB_CONTENT = `name: Deploy
1
+ import{existsSync as f,mkdirSync as I,writeFileSync as v,readFileSync as _,appendFileSync as lt,readdirSync as J,rmSync as P,lstatSync as ye,mkdtempSync as be,copyFileSync as ct,renameSync as dt}from"node:fs";import{tmpdir as ke}from"node:os";import{detectFramework as ut,DEV_VARS_EXAMPLE_FILE as xe,DEV_VARS_FILE as ht,isInteractive as k,LUNA_ART as pt,LUNA_NAME as mt,LUNA_SIGNOFF as ft,BADGES as w,paintAnswer as vt,detectLintTools as gt,readProjectDependencies as Ee,applyLintIgnores as wt,readProjectManifest as yt}from"@lunora/config";import{readJsonSync as bt,walkSync as kt}from"@visulima/fs";import{relative as j,join as u,dirname as S,basename as T,resolve as _e}from"@visulima/path";import{downloadTemplate as Ce}from"giget";import{modify as xt,applyEdits as Et}from"jsonc-parser";import{join as Q,dirname as _t}from"node:path";import{EXIT_CODE as g}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{installArgsFor as Se,execArgsFor as Ct,detectPackageManager as V,detectInstalledManagers as St,runScriptCommand as Lt,addArgsFor as At}from"@lunora/config/cli";import{d as It}from"../packem_shared/command-BpMv2n0o.mjs";import Rt from"magic-string";import{Project as Ot,SyntaxKind as b,ts 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 Ae,o as Ie,a as $t}from"../packem_shared/resolve-Bdc9KEUv.mjs";import{defaultSpawner as Re}from"../packem_shared/createRecordingSpawner-DchLi0gR.mjs";import{d as Mt,e as Nt,f as Pt,a as Oe,t as D,g as Te,h as Dt,b as $e,i as Me,w as Ut,j as jt,k as Ne,l as Vt}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{A as Pe,p as Bt,w as Ft,M as Wt,r as qt,E as De,k as Ht,e as Kt,c as Ue,l as je,i as zt,f as Gt}from"../packem_shared/storage-3GOIFVZm.mjs";import{r as Yt}from"../packem_shared/commands-CkuCMUP_.mjs";import{findWranglerFile as Jt,readWranglerJsonc as Qt,DEFAULT_OBSERVABILITY as Xt,CLOUDFLARE_TOOLCHAIN_VERSIONS as ne}from"@lunora/config/cloudflare";import{logStep as ae}from"../packem_shared/createLogger-4TujevyB.mjs";import{r as Zt}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import er from"node:dns/promises";const Z={bun:{githubCacheKey:void 0,githubSetupStep:` - uses: oven-sh/setup-bun@v2
2
+ `,gitlabImage:"oven/bun:1",gitlabProvisionScript:[],installCmd:"bun install --frozen-lockfile",lockfile:"bun.lockb"},npm:{githubCacheKey:"npm",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:[],installCmd:"npm ci",lockfile:"package-lock.json"},pnpm:{githubCacheKey:"pnpm",githubSetupStep:` - uses: pnpm/action-setup@v4
3
+ with:
4
+ version: latest
5
+ `,gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"pnpm install --frozen-lockfile",lockfile:"pnpm-lock.yaml"},yarn:{githubCacheKey:"yarn",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:["corepack enable"],installCmd:"yarn install --frozen-lockfile",lockfile:"yarn.lock"}},E=(e,t)=>{const r=Ct(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
9
+ with:
10
+ node-version: 22
11
+ ${e.githubCacheKey===void 0?"":` cache: ${e.githubCacheKey}
12
+ `} - run: ${e.installCmd}${r}`,tr=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
22
13
 
23
14
  on:
24
15
  push:
25
16
  branches: [main]
26
17
  pull_request:
18
+ types: [opened, synchronize, reopened, closed]
27
19
  workflow_dispatch:
28
20
 
29
- # Prerequisite: commit your pnpm-lock.yaml. \`pnpm install --frozen-lockfile\`
30
- # (below) and the pnpm cache both require it — run \`pnpm install\` locally and
21
+ # Prerequisite: commit your ${t.lockfile}. \`${t.installCmd}\`
22
+ ${r}
31
23
  # commit the lockfile before pushing, or the first CI run fails.
32
24
  #
33
25
  # Set these repository secrets (Settings → Secrets and variables → Actions):
34
- # 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.
35
34
  # CLOUDFLARE_ACCOUNT_ID — your Cloudflare account id
36
- env:
37
- CLOUDFLARE_API_TOKEN: \${{ secrets.CLOUDFLARE_API_TOKEN }}
38
- CLOUDFLARE_ACCOUNT_ID: \${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
39
-
35
+ # LUNORA_DEPLOY_URL — the production worker's URL (after the first deploy)
36
+ # LUNORA_ADMIN_TOKEN — the production worker's admin token
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.
40
48
  jobs:
41
49
  # Production deploy on push to the default branch.
42
50
  deploy:
@@ -45,379 +53,257 @@ jobs:
45
53
  permissions:
46
54
  contents: read
47
55
  steps:
48
- - uses: actions/checkout@v4
49
- - uses: pnpm/action-setup@v4
50
- - uses: actions/setup-node@v4
51
- with:
52
- node-version: 22
53
- cache: pnpm
54
- - run: pnpm install --frozen-lockfile
55
- # Codegen + wrangler validation gate (no deploy) — fails fast on drift.
56
- - run: pnpm exec lunora prepare
57
- - run: pnpm exec lunora deploy
58
-
59
- # Preview version on every pull request — uploads a versioned preview URL;
60
- # production traffic is untouched.
56
+ ${M(t)}
57
+ # When a schema change tightens a table, the drift gate reads that table's
58
+ # stored rows from this worker and lets the change ship if every row fits.
59
+ # Unset (a first deploy), the gate blocks as before. A *.workers.dev URL is
60
+ # only trusted when the project is linked and .lunora/ is not committed, so
61
+ # CI has no link: there the gate stays blocked, and a tightening needs a
62
+ # migration or --allow-schema-drift. A custom domain on a declared route works.
63
+ - run: ${E(e,["deploy","--migrate-url",'"${{ secrets.LUNORA_DEPLOY_URL }}"'])}
64
+ env:
65
+ CLOUDFLARE_API_TOKEN: \${{ secrets.CLOUDFLARE_API_TOKEN }}
66
+ CLOUDFLARE_ACCOUNT_ID: \${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
67
+ LUNORA_ADMIN_TOKEN: \${{ secrets.LUNORA_ADMIN_TOKEN }}
68
+
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.
61
72
  preview:
62
- if: github.event_name == 'pull_request'
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]'
63
74
  runs-on: ubuntu-latest
75
+ concurrency: lunora-preview-\${{ github.event.pull_request.number }}
64
76
  permissions:
65
77
  contents: read
66
78
  steps:
67
- - uses: actions/checkout@v4
68
- - uses: pnpm/action-setup@v4
69
- - uses: actions/setup-node@v4
70
- with:
71
- node-version: 22
72
- cache: pnpm
73
- - run: pnpm install --frozen-lockfile
74
- - run: pnpm exec lunora deploy --preview
75
- `;
76
- const GITLAB_CONTENT = `stages:
79
+ ${M(t)}
80
+ - run: ${E(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: ${E(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.
126
+ check:
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]')
128
+ runs-on: ubuntu-latest
129
+ permissions:
130
+ contents: read
131
+ steps:
132
+ ${M(t)}
133
+ - run: ${E(e,["deploy","--dry-run"])}
134
+ `},oe="lunora-preview-$CI_MERGE_REQUEST_IID",rr=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}`,i=[n,` - ${t.installCmd} --ignore-scripts`].filter(s=>s!=="").join(`
138
+ `);return`stages:
77
139
  - deploy
78
140
 
79
- # Prerequisite: commit your pnpm-lock.yaml. \`pnpm install --frozen-lockfile\`
80
- # (below) requires it — run \`pnpm install\` locally and commit the lockfile
141
+ # Prerequisite: commit your ${t.lockfile}. \`${t.installCmd}\`
142
+ # (below) requires it — run \`${e} install\` locally and commit the lockfile
81
143
  # before pushing, or the first pipeline fails.
82
144
  #
83
- # Set these as masked CI/CD variables (Settings → CI/CD → Variables):
145
+ # Set these as CI/CD variables (Settings → CI/CD → Variables), each Masked AND
146
+ # Protected, with Environment scope "production":
84
147
  # CLOUDFLARE_API_TOKEN — a Workers-scoped API token
85
148
  # CLOUDFLARE_ACCOUNT_ID — your Cloudflare account id
149
+ # LUNORA_DEPLOY_URL — the production worker's URL (after the first deploy)
150
+ # LUNORA_ADMIN_TOKEN — the production worker's admin token
151
+ # Protected variables reach only pipelines on protected branches and tags, so a
152
+ # merge-request pipeline from a feature branch, which runs the project's own
153
+ # code, gets none of them. Keep your default branch protected (it is by default).
154
+ # The "production" scope reaches only jobs that declare environment: production,
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.
86
187
  .lunora_base:
87
- image: node:22
188
+ image: ${t.gitlabImage}
88
189
  stage: deploy
89
190
  before_script:
90
- - corepack enable
91
- - pnpm install --frozen-lockfile
191
+ ${r}
92
192
 
93
193
  # Production deploy on the default branch.
94
194
  deploy:
95
195
  extends: .lunora_base
196
+ environment:
197
+ name: production
96
198
  rules:
97
199
  - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
98
200
  script:
99
- # Codegen + wrangler validation gate (no deploy) — fails fast on drift.
100
- - pnpm exec lunora prepare
101
- - pnpm exec lunora deploy
201
+ # When a schema change tightens a table, the drift gate reads that table's
202
+ # stored rows from this worker and lets the change ship if every row fits.
203
+ # Unset (a first deploy), the gate blocks as before. A *.workers.dev URL is
204
+ # only trusted when the project is linked and .lunora/ is not committed, so
205
+ # CI has no link: there the gate stays blocked, and a tightening needs a
206
+ # migration or --allow-schema-drift. A custom domain on a declared route works.
207
+ - ${E(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
102
231
 
103
- # Preview version on every merge request (versioned preview URL; production
104
- # traffic is untouched).
105
232
  preview:
106
233
  extends: .lunora_base
234
+ needs:
235
+ - preview_install
236
+ before_script:${a}
107
237
  rules:
108
- - if: $CI_PIPELINE_SOURCE == "merge_request_event"
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
109
244
  script:
110
- - pnpm exec lunora deploy --preview
111
- `;
112
- const WORKFLOWS = {
113
- github: {
114
- content: GITHUB_CONTENT,
115
- file: join(".github", "workflows", "deploy.yml"),
116
- secretsHint: "repository secrets (Settings → Secrets and variables → Actions)"
117
- },
118
- gitlab: {
119
- content: GITLAB_CONTENT,
120
- file: ".gitlab-ci.yml",
121
- secretsHint: "masked CI/CD variables (Settings → CI/CD → Variables)"
122
- }
123
- };
124
- const isCiProvider = (value) => value === "github" || value === "gitlab";
125
- const writeCiWorkflow = (projectRoot, provider, options = {}) => {
126
- const spec = WORKFLOWS[provider];
127
- const path = join(projectRoot, spec.file);
128
- if (existsSync(path) && options.overwrite !== true) {
129
- return { path, skipped: true, written: false };
130
- }
131
- mkdirSync(dirname(path), { recursive: true });
132
- writeFileSync(path, spec.content, "utf8");
133
- return { path, skipped: false, written: true };
134
- };
135
- const scaffoldCiWorkflow = (projectRoot, provider, logger, options = {}) => {
136
- const spec = WORKFLOWS[provider];
137
- try {
138
- const result = writeCiWorkflow(projectRoot, provider, options);
139
- if (result.skipped) {
140
- logger.info(`--ci ${provider}: ${spec.file} already exists — left unchanged (re-run with overwrite to replace).`);
141
- } else {
142
- logger.success(`--ci ${provider}: wrote ${spec.file}`);
143
- logger.info(`--ci ${provider}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${spec.secretsHint} to enable deploys.`);
144
- logger.info(
145
- `--ci ${provider}: run \`pnpm install\` and commit pnpm-lock.yaml before pushing — the pipeline runs \`pnpm install --frozen-lockfile\`.`
146
- );
147
- }
148
- return result;
149
- } catch (error) {
150
- const message = error instanceof Error ? error.message : String(error);
151
- logger.warn(`--ci ${provider}: could not write ${spec.file} (${message})`);
152
- return { path: join(projectRoot, spec.file), skipped: false, written: false };
153
- }
154
- };
245
+ - ${E(e,["preview","deploy",'"$CI_MERGE_REQUEST_IID"'])}
155
246
 
156
- const ADAPTER_BY_FRAMEWORK = {
157
- astro: "@lunora/react",
158
- none: "@lunora/react",
159
- nuxt: "@lunora/vue",
160
- "react-router": "@lunora/react",
161
- "solid-start": "@lunora/solid",
162
- sveltekit: "@lunora/svelte",
163
- "tanstack-start": "@lunora/react",
164
- "tanstack-start-solid": "@lunora/solid"
165
- };
166
- const detectFramework = (root) => {
167
- const base = detectFramework$1(root);
168
- return { ...base, adapter: ADAPTER_BY_FRAMEWORK[base.framework] };
169
- };
170
-
171
- const LUNORA_CALL = "lunora()";
172
- const LUNORA_IMPORT = 'import { lunora } from "@lunora/vite";';
173
- const LUNORA_CALL_RE = /\blunora\s*\(/u;
174
- const LUNORA_VITE_DOUBLE = '"@lunora/vite"';
175
- const LUNORA_VITE_SINGLE = "'@lunora/vite'";
176
- const findDefineConfigObject = (sf) => {
177
- for (const statement of sf.getStatements()) {
178
- if (statement.getKind() !== SyntaxKind.ExportAssignment) {
179
- continue;
180
- }
181
- const expr = statement.asKindOrThrow(SyntaxKind.ExportAssignment).getExpression();
182
- if (expr.getKind() !== SyntaxKind.CallExpression) {
183
- continue;
184
- }
185
- const call = expr.asKindOrThrow(SyntaxKind.CallExpression);
186
- if (call.getExpression().getText() !== "defineConfig") {
187
- continue;
188
- }
189
- const argument = call.getArguments()[0];
190
- if (argument?.getKind() === SyntaxKind.ObjectLiteralExpression) {
191
- return argument.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);
192
- }
193
- }
194
- return void 0;
195
- };
196
- const findPlainExportObject = (sf) => {
197
- for (const statement of sf.getStatements()) {
198
- if (statement.getKind() !== SyntaxKind.ExportAssignment) {
199
- continue;
200
- }
201
- const expr = statement.asKindOrThrow(SyntaxKind.ExportAssignment).getExpression();
202
- if (expr.getKind() === SyntaxKind.ObjectLiteralExpression) {
203
- return expr.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);
204
- }
205
- }
206
- return void 0;
207
- };
208
- const findConfigObject = (sourceText) => {
209
- const project = new Project({
210
- compilerOptions: { allowJs: true },
211
- useInMemoryFileSystem: true
212
- });
213
- const sf = project.createSourceFile("vite.config.ts", sourceText, { overwrite: true });
214
- return findDefineConfigObject(sf) ?? findPlainExportObject(sf);
215
- };
216
- const importInsertPosition = (sourceText) => {
217
- const project = new Project({
218
- compilerOptions: { allowJs: true },
219
- useInMemoryFileSystem: true
220
- });
221
- const sf = project.createSourceFile("vite.config.ts", sourceText, { overwrite: true });
222
- const imports = sf.getImportDeclarations();
223
- if (imports.length === 0) {
224
- return 0;
225
- }
226
- const last = imports[imports.length - 1];
227
- if (last === void 0) {
228
- return 0;
229
- }
230
- return last.getEnd();
231
- };
232
- const addImport = (ms, source) => {
233
- const insertAt = importInsertPosition(source);
234
- if (insertAt === 0) {
235
- ms.prepend(`${LUNORA_IMPORT}
236
- `);
237
- } else {
238
- ms.appendLeft(insertAt, `
239
- ${LUNORA_IMPORT}`);
240
- }
241
- };
242
- const patchPluginsArray = (ms, configObject) => {
243
- const pluginsProp = configObject.getProperty("plugins");
244
- if (pluginsProp === void 0) {
245
- const properties = configObject.getProperties();
246
- const openBrace = configObject.getStart() + 1;
247
- if (properties.length === 0) {
248
- ms.appendLeft(openBrace, ` plugins: [${LUNORA_CALL}] `);
249
- } else {
250
- const firstProp = properties[0];
251
- if (firstProp !== void 0) {
252
- ms.appendLeft(firstProp.getStart(), `plugins: [${LUNORA_CALL}],
253
- `);
254
- }
255
- }
256
- return;
257
- }
258
- const arrayLit = pluginsProp.getDescendantsOfKind(SyntaxKind.ArrayLiteralExpression)[0];
259
- if (arrayLit === void 0) {
260
- return;
261
- }
262
- const elements = arrayLit.getElements();
263
- if (elements.length === 0) {
264
- ms.appendLeft(arrayLit.getStart() + 1, LUNORA_CALL);
265
- } else {
266
- const firstElement = elements[0];
267
- if (firstElement !== void 0) {
268
- ms.appendLeft(firstElement.getStart(), `${LUNORA_CALL}, `);
269
- }
270
- }
271
- };
272
- const patchViteConfig = (source) => {
273
- if (LUNORA_CALL_RE.test(source)) {
274
- return { changed: false, code: source, reason: "lunora plugin already present" };
275
- }
276
- const configObject = findConfigObject(source);
277
- if (configObject === void 0) {
278
- return { changed: false, code: source, reason: "could not locate a Vite config plugins array to patch" };
279
- }
280
- const ms = new MagicString(source);
281
- const alreadyImported = source.includes(LUNORA_VITE_DOUBLE) || source.includes(LUNORA_VITE_SINGLE);
282
- if (alreadyImported) {
283
- patchPluginsArray(ms, configObject);
284
- } else {
285
- addImport(ms, source);
286
- patchPluginsArray(ms, configObject);
287
- }
288
- return { changed: true, code: ms.toString() };
289
- };
290
-
291
- const NETWORK_ERROR_PATTERN = /enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u;
292
- const NOT_FOUND_ERROR_PATTERN = /404|not found|could not find|no such/u;
293
- const describeDownloadFailure = (error, context) => {
294
- const raw = error instanceof Error ? error.message : String(error);
295
- const lower = raw.toLowerCase();
296
- const genericMessage = `failed to download template "${context.templateType}" from ${context.remote}: ${raw}`;
297
- if (NOT_FOUND_ERROR_PATTERN.test(lower)) {
298
- return {
299
- hints: [
300
- `Check the template name "${context.templateType}" and the ref "${context.ref}".`,
301
- "List/inspect available templates, or target a branch/tag with `--ref <branch>`."
302
- ],
303
- message: `template "${context.templateType}" not found at ${context.remote}: ${raw}`
304
- };
305
- }
306
- if (NETWORK_ERROR_PATTERN.test(lower)) {
307
- return {
308
- hints: [
309
- "You appear to be offline or unable to reach GitHub.",
310
- "To scaffold without a network, point at a local template root: `lunora init --from <dir>`."
311
- ],
312
- message: genericMessage
313
- };
314
- }
315
- return {
316
- hints: ["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],
317
- message: genericMessage
318
- };
319
- };
320
-
321
- const emitStep = async (type, message, answer) => {
322
- if (isInteractive()) {
323
- await tuiStep(BADGES[type], message, answer);
324
- return;
325
- }
326
- process.stdout.write("\n");
327
- if (answer === void 0 || answer === "") {
328
- logStep(type, message);
329
- return;
330
- }
331
- const dimmed = answer.split("\n").map((line) => paintAnswer(line)).join("\n");
332
- logStep(type, `${message}
333
- ${dimmed}`);
334
- };
335
- const emitMascot = async (logger) => {
336
- if (isInteractive()) {
337
- await tuiMascot();
338
- return;
339
- }
340
- logger.info(`
341
- ${LUNA_ART}
342
- ${LUNA_NAME}: ${LUNA_SIGNOFF}`);
343
- };
344
-
345
- const STACK_FEATURE_OPTIONS = [
346
- { description: "Sign-up / sign-in (asks which provider)", label: "Authentication", value: "auth" },
347
- { description: "Cloudflare Email Workers + a dev mail catcher", label: "Transactional email", value: "email" },
348
- { description: "Typed R2 buckets + signed URLs (@lunora/storage)", label: "File storage", value: "storage" },
349
- { description: "Token-bucket / sliding-window limits (@lunora/ratelimit)", label: "Rate limiting", value: "ratelimit" },
350
- { description: "Scheduled jobs via Cron Triggers (@lunora/scheduler)", label: "Cron jobs", value: "crons" },
351
- { description: "Live presence / who's-online over hibernated WebSockets", label: "Presence", value: "presence" },
352
- { description: "Snapshot + restore your Durable Object data", label: "Backups", value: "backup" }
353
- ];
354
- const STACK_FEATURE_VALUES = STACK_FEATURE_OPTIONS.map((option) => option.value);
355
- const featureItem = (feature) => feature === "email" ? EMAIL_ITEM : feature;
356
- const parseFeatureList = (raw, warn) => {
357
- const features = [];
358
- for (const part of raw.split(",").map((entry) => entry.trim()).filter(Boolean)) {
359
- if (STACK_FEATURE_VALUES.includes(part)) {
360
- if (!features.includes(part)) {
361
- features.push(part);
362
- }
363
- } else {
364
- warn(`init: unknown --add feature "${part}" — expected ${STACK_FEATURE_VALUES.join(" | ")}; skipping.`);
365
- }
366
- }
367
- return features;
368
- };
369
- const collectAuthFeature = async (deps) => {
370
- const provider = await promptAuthProvider(deps.select);
371
- const databaseName = await promptDatabaseName(deps.text, deps.projectName);
372
- return { label: "auth", names: [provider], transformManifest: (manifest) => withAuthDatabaseName(manifest, databaseName) };
373
- };
374
- const collectEmailFeature = async (deps) => {
375
- const answer = await deps.text(MAIL_DESTINATION_PROMPT, { placeholder: "you@yourdomain.com" });
376
- const destination = resolveTypedDestination(answer, (message) => {
377
- deps.logger.warn(message);
378
- });
379
- return {
380
- label: "email",
381
- names: [EMAIL_ITEM],
382
- transformManifest: destination === void 0 ? void 0 : (manifest) => withMailDestination(manifest, destination)
383
- };
384
- };
385
- const collectStorageFeature = async (deps) => {
386
- const bucketName = await promptBucketName(deps.text, deps.projectName);
387
- return { label: "storage", names: ["storage"], transformManifest: (manifest) => withStorageBucketName(manifest, bucketName) };
388
- };
389
- const FEATURE_COLLECTORS = {
390
- auth: collectAuthFeature,
391
- email: collectEmailFeature,
392
- storage: collectStorageFeature
393
- };
394
- const offerRegistryExtras = async (deps) => {
395
- if (deps.preselected !== void 0 && deps.preselected.length > 0) {
396
- await deps.applyAll(
397
- deps.preselected.map((feature) => {
398
- return { label: feature, names: [featureItem(feature)] };
399
- })
400
- );
401
- return;
402
- }
403
- if (!deps.interactive) {
404
- deps.logger.info("tip: add features later with `lunora add <auth|email|storage|ratelimit|crons|presence|backup>`.");
405
- return;
406
- }
407
- const picked = await deps.multiSelect("Which features do you want to add?", STACK_FEATURE_OPTIONS, { defaults: [] });
408
- if (picked.length === 0) {
409
- return;
410
- }
411
- const plans = [];
412
- for (const feature of picked) {
413
- const collect = FEATURE_COLLECTORS[feature];
414
- plans.push(collect ? await collect(deps) : { label: feature, names: [feature] });
415
- }
416
- await deps.applyAll(plans);
417
- };
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
+ ${i}
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
+ - ${E(e,["preview","delete",'"$CI_MERGE_REQUEST_IID"'])}
418
264
 
419
- const LOGO_PATH = "M 259.500 10.552 C 220.080 15.859, 182.424 32.566, 152.500 58.025 C 110.179 94.031, 85.380 137.183, 77.518 188.500 C 75.410 202.255, 74.569 225.677, 75.796 236.466 C 76.757 244.917, 76.683 245.692, 74.518 249.966 C 63.118 272.466, 53.141 303.876, 51.382 322.799 L 50.718 329.943 71.960 320.471 C 83.643 315.262, 93.326 311, 93.478 311 C 93.630 311, 96.547 316.063, 99.959 322.250 C 103.371 328.438, 107.249 334.850, 108.577 336.500 L 110.990 339.500 110.981 336 C 110.977 334.075, 111.499 324.991, 112.143 315.813 L 113.312 299.127 121.406 293.336 C 132.495 285.403, 149.593 271.554, 161 261.268 C 171.556 251.748, 189.116 235, 188.540 235 C 188.337 235, 183.069 238.648, 176.835 243.106 C 142.318 267.789, 68.537 314, 63.646 314 C 61.843 314, 72.791 281.179, 80.905 262.259 C 92.233 235.845, 107.473 212.389, 132.106 183.453 L 138.451 176 148.268 176 C 176.192 176, 197.512 187.154, 212.868 209.797 C 216.470 215.108, 217.035 216.595, 216.477 219.297 C 211.386 243.968, 202.359 274.496, 193.797 296 C 183.898 320.861, 167.147 352.101, 152.395 373.215 L 147.004 380.930 152.891 385.830 C 161.400 392.911, 165.563 396, 166.594 395.998 C 167.092 395.998, 168.772 391.641, 170.327 386.317 C 176.279 365.934, 188.422 338.749, 200.942 317.778 C 223.060 280.731, 256.432 244.369, 294.500 215.836 C 309.956 204.252, 313.937 201.603, 314.719 202.385 C 315.116 202.783, 315.449 213.096, 315.460 225.304 C 315.474 241.855, 315.021 250.405, 313.680 258.924 C 307.009 301.272, 291.175 336.677, 263.112 372 C 255.259 381.883, 227.182 410.673, 218.516 417.727 L 213.532 421.783 223.439 424.880 C 281.705 443.093, 349.165 436.018, 398.616 406.508 C 446.728 377.797, 483.322 331.466, 497.366 281.481 C 503.381 260.075, 504.480 250.741, 504.491 221 C 504.501 191.997, 503.598 184.047, 497.987 163.732 C 484.768 115.871, 452.505 72.708, 407.718 42.964 C 381.051 25.254, 352.818 14.828, 319.695 10.460 C 305.932 8.645, 273.298 8.695, 259.500 10.552";
420
- const WELCOME_CSS = `/* The welcome page is a full-bleed starter — reset the browser's default
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.
267
+ check:
268
+ extends: .lunora_base
269
+ rules:
270
+ - if: $CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_SOURCE_PROJECT_ID != $CI_PROJECT_ID
271
+ script:
272
+ - ${E(e,["deploy","--dry-run"])}
273
+ `},Ve={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)"}},nr=(e,t)=>e==="github"?tr(t):rr(t),ar=e=>e==="github"||e==="gitlab",or=(e,t,r,n={})=>{const a=Q(e,Ve[t].file);return f(a)&&n.overwrite!==!0?{path:a,skipped:!0,written:!1}:(I(_t(a),{recursive:!0}),v(a,nr(t,r),"utf8"),{path:a,skipped:!1,written:!0})},ir=(e,t,r,n,a={})=>{const i=Ve[t];try{const s=or(e,t,r,a);if(s.skipped)n.info(`--ci ${t}: ${i.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const o=Se(r),l=[o.command,...o.args].join(" "),{installCmd:c,lockfile:d}=Z[r];n.success(`--ci ${t}: wrote ${i.file}`),n.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${i.secretsHint} to enable deploys.`),n.info(`--ci ${t}: run \`${l}\` and commit ${d} before pushing — the pipeline runs \`${c}\`.`)}return s}catch(s){const o=s instanceof Error?s.message:String(s);return n.warn(`--ci ${t}: could not write ${i.file} (${o})`),{path:Q(e,i.file),skipped:!1,written:!1}}},sr={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"},lr=e=>{const t=ut(e);return{...t,adapter:sr[t.framework]}},N="lunora()",ie='import { lunora } from "@lunora/vite";',cr="@lunora/vite",dr="lunora",ur=e=>{for(const t of e.getStatements()){if(t.getKind()!==b.ExportAssignment)continue;const r=t.asKindOrThrow(b.ExportAssignment).getExpression();if(r.getKind()!==b.CallExpression)continue;const n=r.asKindOrThrow(b.CallExpression);if(n.getExpression().getText()!=="defineConfig")continue;const a=n.getArguments()[0];if(a?.getKind()===b.ObjectLiteralExpression)return a.asKindOrThrow(b.ObjectLiteralExpression)}},hr=e=>{for(const t of e.getStatements()){if(t.getKind()!==b.ExportAssignment)continue;const r=t.asKindOrThrow(b.ExportAssignment).getExpression();if(r.getKind()===b.ObjectLiteralExpression)return r.asKindOrThrow(b.ObjectLiteralExpression)}},pr=e=>e.getDescendantsOfKind(b.CallExpression).some(t=>t.getExpression().getText()===dr),mr=e=>e.getImportDeclarations().some(t=>t.getModuleSpecifierValue()===cr),fr=e=>new Ot({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}),vr=(e,t)=>{const r=t.getImportDeclarations().at(-1)?.getEnd()??0;r===0?e.prepend(`${ie}
274
+ `):e.appendLeft(r,`
275
+ ${ie}`)},gr=(e,t)=>{const r=t.getProperty("plugins");if(r===void 0){const s=t.getProperties(),o=t.getStart()+1;if(s.length===0){e.appendLeft(o,` plugins: [${N}] `);return}const l=s[0];if(l===void 0)return"could not locate the start of the Vite config object's first property";e.appendLeft(l.getStart(),`plugins: [${N}],
276
+ `);return}const n=r.getDescendantsOfKind(b.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,N);return}const i=a[0];if(i===void 0)return"could not locate the first entry of the Vite config's `plugins` array";e.appendLeft(i.getStart(),`${N}, `)},Be=e=>{const t=fr(e);if(pr(t))return{changed:!1,code:e,reason:"lunora plugin already present"};const r=ur(t)??hr(t);if(r===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const n=new Rt(e);mr(t)||vr(n,t);const a=gr(n,r);return a!==void 0?{changed:!1,code:e,reason:a}:{changed:!0,code:n.toString()}},wr=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,yr=/404|not found|could not find|no such/u,br=(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 yr.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}`}:wr.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}},Fe=[{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=Fe.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(`
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(`
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(`
279
+ `),envVars:["WORKOS_CLIENT_ID"],identity:"workosIdentity",identityFile:"workos",item:"auth-workos-jwt"}},kr=e=>Object.hasOwn(ee,e),xr=(e,t)=>{const r=e.trim().toLowerCase();return se.includes(r)?r:(t(`init: unknown --auth "${e}" — expected ${se.join(" | ")}; skipping auth.`),"none")},Er=["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"],_r="virtual:lunora/worker",Cr=["lunora.config.ts","lunora.config.mts","lunora.config.js","lunora.config.mjs"],Sr=["src","app","pages","plugins"],Lr=/\.(?:[jt]sx?|svelte|vue)$/u,le=/\n([\t ]*)\.build(?:FrameworkWorker)?\(/uy,Ar=new Set(["(","[","{"]),Ir=new Set([")","]","}"]),Rr=(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},Or=(e,t)=>{let r=0,n=t;for(;n<e.length;){const a=Rr(e,n);if(a!==n){n=a;continue}const i=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&&i===";")return{at:n,indent:" "};r+=Ar.has(i)?1:0,r-=Ir.has(i)?1:0,n+=1}},Tr=(e,t,r)=>{const n=j(S(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,Nr=(e,t,r,n)=>{const a=r.indexOf("defineApp<"),i=a===-1?void 0:Or(r,a);if(i===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:o}=i,l=`
281
+ ${o}// Verify the provider's token on every request and feed it into ctx.auth (memoized for 5 s).
282
+ ${o}.extend((env) => ({ resolveIdentity: ${n.identity}(env) }))`,c=`import { ${n.identity} } from "${Tr(e,t,n)}";
283
+ `,d=r.lastIndexOf(`
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)}},Pr=(e,t)=>{for(const r of Er){const n=u(e,r),a=f(n)?Nr(e,r,_(n,"utf8"),t):void 0;if(a?.outcome==="wired"&&v(n,a.patched),a!==void 0)return{file:r,outcome:a.outcome}}},Dr=e=>{const t=Jt(e);return t!==void 0&&Qt(t).parsed?.main===_r},Ur=(e,t)=>{if(!(!Dr(e)||Cr.some(r=>f(u(e,r)))))return v(u(e,"lunora.config.ts"),`import type { AppBuilder, LunoraConfig } from "./lunora/_generated/app";
285
+ import { ${t.identity} } from "./lunora/identity/${t.identityFile}";
286
+
287
+ export default {
288
+ // Verify the provider's token on every request and feed it into ctx.auth (memoized for 5 s).
289
+ app: (app: AppBuilder<object>): AppBuilder<object> => app.extend((env) => ({ resolveIdentity: ${t.identity}(env) })),
290
+ } satisfies LunoraConfig<object>;
291
+ `),"lunora.config.ts"},We=(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"?[]:We(n,t+1):Lr.test(r.name)?[n]:[]}),jr=/(<script\b[^>]*>)([\s\S]*?)<\/script\b[^>]*>/giu,Vr=/\.(?:svelte|vue)$/u,Br=(e,t)=>e.properties.some(r=>(y.isPropertyAssignment(r)||y.isShorthandPropertyAssignment(r))&&r.name.getText(t)==="authTokenOnUpgrade"),ce=e=>{const t=y.createSourceFile("client.tsx",e,y.ScriptTarget.Latest,!0,y.ScriptKind.TSX),r=[],n=s=>{if(Br(s,t))return;const o=s.properties.at(-1);r.push(o===void 0?{at:s.getStart(t)+1,text:" authTokenOnUpgrade: true "}:{at:o.getEnd(),text:", authTokenOnUpgrade: true"})},a=s=>{if(y.isNewExpression(s)&&y.isIdentifier(s.expression)&&s.expression.text==="LunoraClient"){const[o]=s.arguments??[];o!==void 0&&y.isObjectLiteralExpression(o)&&n(o)}else if(y.isCallExpression(s)&&y.isIdentifier(s.expression)&&s.expression.text==="provideLunora"){const[o]=s.arguments;o===void 0?r.push({at:s.getEnd()-1,text:"{ authTokenOnUpgrade: true }"}):y.isObjectLiteralExpression(o)&&n(o)}y.forEachChild(s,a)};if(a(t),r.length===0)return;let i=e;for(const{at:s,text:o}of r.toSorted((l,c)=>c.at-l.at))i=`${i.slice(0,s)}${o}${i.slice(s)}`;return i},Fr=(e,t)=>{if(!Vr.test(e))return ce(t);let r="",n=0;for(const a of t.matchAll(jr)){const[,i="",s=""]=a,o=a.index+i.length,l=ce(s);l!==void 0&&(r+=`${t.slice(n,o)}${l}`,n=o+s.length)}if(n!==0)return`${r}${t.slice(n)}`},Wr=e=>Sr.flatMap(t=>We(u(e,t))).filter(t=>{const r=Fr(t,_(t,"utf8"));return r===void 0?!1:(v(t,r),!0)}),qr=(e,t)=>{const r=u(e,xe),n=u(e,ht),a=f(r)?_(r,"utf8"):"",i=f(n)?_(n,"utf8").split(`
292
+ `):[],s=t.envVars.filter(c=>!a.split(`
293
+ `).some(d=>d.startsWith(`${c}=`)));if(s.length===0)return!1;const o=s.map(c=>i.find(d=>d.startsWith(`${c}=`))??`${c}=`),l=a.length===0||a.endsWith(`
294
+ `)?"":`
295
+ `;return lt(r,`${l}# ${t.item}: the identity provider the Worker verifies tokens from.
296
+ ${o.join(`
297
+ `)}
298
+ `),!0},Hr=(e,t,r)=>{const n=ee[t],a=()=>{const o=Ur(e,n);return o===void 0?void 0:{file:o,outcome:"wired"}},i=Pr(e,n)??a();i===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.`):i.outcome==="already-wired"?r.info(`auth: ${i.file} already wires ${n.identity}; left as is.`):i.outcome==="has-resolver"?r.warn(`auth: ${i.file} already sets resolveIdentity, so it was left as is. Compose the two: \`resolveIdentity: composeIdentityResolvers([${n.identity}(env), <your resolver>])\` — ${n.identity} is in lunora/identity/${n.identityFile}.ts.`):r.success(`auth: wired ${n.identity} as resolveIdentity in ${i.file}`),qr(e,n)&&r.success(`auth: listed ${n.envVars.join(", ")} in ${xe}`);const s=Wr(e);for(const o of s)r.success(`auth: turned on authTokenOnUpgrade in ${j(e,o)}`);s.length===0&&r.warn("auth: no client construction found to turn on authTokenOnUpgrade; set it on your client by hand"),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.`)},U=async(e,t,r)=>{if(k()){await Nt(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=>vt(a)).join(`
303
+ `);ae(e,`${t}
304
+ ${n}`)},Kr=async e=>{if(k()){await Mt();return}e.info(`
305
+ ${pt}
306
+ ${mt}: ${ft}`)},qe=[{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"}],de=qe.map(e=>e.value),ue=qe.filter(e=>e.value!=="auth"),He=new Set(["auth","auth-ui"]),zr=e=>e==="email"?De:e,Gr=(e,t)=>{const r=[];for(const n of e.split(",").map(a=>a.trim()).filter(Boolean))de.includes(n)?r.includes(n)||r.push(n):t(`init: unknown --add feature "${n}" — expected ${de.join(" | ")}; skipping.`);return r},Ke=e=>e.resolveAuthUiItem===void 0?"auth-ui-react":e.resolveAuthUiItem(),Yr=async e=>{const t=await Kt(e.select),r=await Ue(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:n=>je(n,r)}},Jr=async e=>{const t=await e.text(Wt,{placeholder:"you@yourdomain.com"}),r=qt(t,n=>{e.logger.warn(n)});return{label:"email",names:[De],transformManifest:r===void 0?void 0:n=>Ht(n,r)}},Qr=async(e,t)=>{const r=Ke(e);if(r===void 0){e.logger.error(`init: ${Pe}`);return}if(t)return{label:"auth-ui",names:[r]};const n=await Ue(e.text,e.projectName);return{label:"auth-ui",names:[r],transformManifest:a=>je(a,n)}},Xr=async e=>{const t=await Bt(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:r=>Ft(r,t)}},Zr=(e,t)=>{const r=[];let n=!1;for(const a of t){if(a!=="auth-ui"){r.push({label:a,names:[zr(a)]});continue}const i=Ke(e);if(i===void 0){e.logger.error(`init: ${Pe}`),n=!0;continue}r.push({label:a,names:[i]})}return{plans:r,refused:n}},ze=e=>e!==void 0&&kr(e)?{externalAuth:e,label:e,names:[ee[e].item]}:void 0,en={auth:Yr,"auth-ui":async(e,t)=>Qr(e,t.includes("auth")),email:Jr,storage:Xr},tn=async e=>{const t=ze(e.auth),r=e.auth!==void 0&&e.auth!=="lunora",n=new Set(r?(e.preselected??[]).filter(l=>He.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:i,refused:s}=Zr(e,a);return t!==void 0&&i.unshift(t),await e.applyAll(i)&&!s&&n.size===0},he=async e=>{if(e.preselected!==void 0&&e.preselected.length>0||e.auth!==void 0&&!e.interactive)return tn(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?",Fe,{default:"none"})??"none",r=ze(t),n=t==="lunora"?ue:ue.filter(o=>!He.has(o.value)),a=await e.multiSelect("Which features do you want to add?",n,{defaults:[]}),i=t==="lunora"&&!a.includes("auth")?["auth",...a]:a;if(i.length===0&&r===void 0)return!0;const s=r===void 0?[]:[r];for(const o of i){const l=en[o],c=l?await l(e,i):{label:o,names:[o]};c!==void 0&&s.push(c)}return await e.applyAll(s),!0},rn=[{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"}],nn="Which linter/formatter do you use? We'll tell it to skip Lunora's generated files.",an=async e=>{const t=e.interactive?await e.multiSelect(nn,rn,{defaults:e.detected}):[...e.detected];if(t.length===0)return[];const r=e.apply(t);return Zt(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",O=`/* The welcome page is a full-bleed starter — reset the browser's default
421
307
  body margin/padding so it sits flush; everything else is scoped under
422
308
  .lunora-welcome (collision-safe). */
423
309
  body {
@@ -522,8 +408,7 @@ body {
522
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); }
523
409
 
524
410
  @media (prefers-reduced-motion: reduce) { .lunora-welcome * { transition: none !important; } }
525
- `;
526
- const REACT_APP = `import { useEffect, useState } from "react";
411
+ `,on=`import { useEffect, useState } from "react";
527
412
 
528
413
  type Theme = "dark" | "light";
529
414
 
@@ -565,7 +450,7 @@ export default function App() {
565
450
  <div className="lw-wrap">
566
451
  <div className="brand">
567
452
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
568
- <path d="${LOGO_PATH}" fill="currentColor" fillRule="evenodd" />
453
+ <path d="${$}" fill="currentColor" fillRule="evenodd" />
569
454
  </svg>
570
455
  <span className="word">Lunora</span>
571
456
  </div>
@@ -684,8 +569,7 @@ export default function App() {
684
569
  </div>
685
570
  );
686
571
  }
687
- `;
688
- const VUE_APP = `<script setup lang="ts">
572
+ `,sn=`<script setup lang="ts">
689
573
  import { onMounted, ref } from "vue";
690
574
 
691
575
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -725,7 +609,7 @@ const toggle = (): void => {
725
609
  <div class="lw-wrap">
726
610
  <div class="brand">
727
611
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
728
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
612
+ <path d="${$}" fill="currentColor" fill-rule="evenodd" />
729
613
  </svg>
730
614
  <span class="word">Lunora</span>
731
615
  </div>
@@ -841,8 +725,7 @@ const toggle = (): void => {
841
725
  </div>
842
726
  </div>
843
727
  </template>
844
- `;
845
- const SOLID_APP = `import { createSignal, onMount } from "solid-js";
728
+ `,ln=`import { createSignal, onMount } from "solid-js";
846
729
 
847
730
  export default function App() {
848
731
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -882,7 +765,7 @@ export default function App() {
882
765
  <div class="lw-wrap">
883
766
  <div class="brand">
884
767
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
885
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
768
+ <path d="${$}" fill="currentColor" fill-rule="evenodd" />
886
769
  </svg>
887
770
  <span class="word">Lunora</span>
888
771
  </div>
@@ -1001,8 +884,7 @@ export default function App() {
1001
884
  </div>
1002
885
  );
1003
886
  }
1004
- `;
1005
- const SVELTE_APP = `<script lang="ts">
887
+ `,cn=`<script lang="ts">
1006
888
  import { onMount } from "svelte";
1007
889
 
1008
890
  // Default to "dark" for a stable first paint, then reconcile to the OS
@@ -1045,7 +927,7 @@ const SVELTE_APP = `<script lang="ts">
1045
927
  <div class="lw-wrap">
1046
928
  <div class="brand">
1047
929
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
1048
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
930
+ <path d="${$}" fill="currentColor" fill-rule="evenodd" />
1049
931
  </svg>
1050
932
  <span class="word">Lunora</span>
1051
933
  </div>
@@ -1160,8 +1042,7 @@ const SVELTE_APP = `<script lang="ts">
1160
1042
  <div class="lw-foot">Running on Lunora · Vite + Svelte</div>
1161
1043
  </div>
1162
1044
  </div>
1163
- `;
1164
- const VANILLA_MAIN = `import "./style.css";
1045
+ `,dn=`import "./style.css";
1165
1046
 
1166
1047
  import { LunoraClient } from "lunorash/client";
1167
1048
 
@@ -1189,7 +1070,7 @@ const welcomeHtml = \`
1189
1070
  <div class="lw-wrap">
1190
1071
  <div class="brand">
1191
1072
  <svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
1192
- <path d="${LOGO_PATH}" fill="currentColor" fill-rule="evenodd" />
1073
+ <path d="${$}" fill="currentColor" fill-rule="evenodd" />
1193
1074
  </svg>
1194
1075
  <span class="word">Lunora</span>
1195
1076
  </div>
@@ -1325,13 +1206,10 @@ toggleButton.addEventListener("click", () => {
1325
1206
  // Live demo: the message count of a demo channel re-renders on every delta.
1326
1207
  const count = document.querySelector<HTMLSpanElement>("#lw-count")!;
1327
1208
 
1328
- client.onUpdate(api.messages.list, { channelId: "channel:demo" }, (result) => {
1209
+ client.subscribe(api.messages.list, { channelId: "channel:demo" }, (result) => {
1329
1210
  count.textContent = String(result.messages.length);
1330
1211
  });
1331
- `;
1332
-
1333
- const READ_URL = `const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;`;
1334
- const REACT_MAIN = `import "./index.css";
1212
+ `,B="const url = (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? globalThis.location.origin;",un=`import "./index.css";
1335
1213
 
1336
1214
  import { LunoraProvider } from "@lunora/react";
1337
1215
  import { LunoraClient } from "lunorash/client";
@@ -1343,7 +1221,7 @@ import App from "./App.tsx";
1343
1221
  // \`@lunora/vite\` runs the Worker on the same origin as Vite, so default to
1344
1222
  // \`location.origin\`. Point \`VITE_LUNORA_URL\` at a deployed Worker to develop
1345
1223
  // the client against production data.
1346
- ${READ_URL}
1224
+ ${B}
1347
1225
  const client = new LunoraClient({ url });
1348
1226
 
1349
1227
  const root = document.getElementById("root");
@@ -1359,8 +1237,7 @@ createRoot(root).render(
1359
1237
  </LunoraProvider>
1360
1238
  </StrictMode>,
1361
1239
  );
1362
- `;
1363
- const VUE_MAIN = `import "./style.css";
1240
+ `,hn=`import "./style.css";
1364
1241
 
1365
1242
  import { createLunora } from "@lunora/vue";
1366
1243
  import { LunoraClient } from "lunorash/client";
@@ -1369,43 +1246,40 @@ import { createApp } from "vue";
1369
1246
  import App from "./App.vue";
1370
1247
 
1371
1248
  // Provide one LunoraClient at the app root via the Vue plugin form.
1372
- ${READ_URL}
1249
+ ${B}
1373
1250
  createApp(App).use(createLunora(new LunoraClient({ url }))).mount("#app");
1374
- `;
1375
- const SOLID_INDEX = `import "./index.css";
1251
+ `,pn=`import "./index.css";
1376
1252
 
1377
- import { LunoraContext } from "@lunora/solid";
1253
+ import { LunoraProvider } from "@lunora/solid";
1378
1254
  import { LunoraClient } from "lunorash/client";
1379
1255
  import { render } from "solid-js/web";
1380
1256
 
1381
1257
  import App from "./App";
1382
1258
 
1383
- ${READ_URL}
1259
+ ${B}
1384
1260
  const client = new LunoraClient({ url });
1385
1261
  const root = document.getElementById("root");
1386
1262
 
1387
1263
  render(
1388
1264
  () => (
1389
- <LunoraContext.Provider value={client}>
1265
+ <LunoraProvider client={client}>
1390
1266
  <App />
1391
- </LunoraContext.Provider>
1267
+ </LunoraProvider>
1392
1268
  ),
1393
1269
  root!,
1394
1270
  );
1395
- `;
1396
- const SVELTE_ROOT = `<script lang="ts">
1271
+ `,mn=`<script lang="ts">
1397
1272
  import { setLunoraClient } from "@lunora/svelte";
1398
1273
  import { LunoraClient } from "lunorash/client";
1399
1274
 
1400
1275
  import App from "./App.svelte";
1401
1276
 
1402
- ${READ_URL}
1277
+ ${B}
1403
1278
  setLunoraClient(new LunoraClient({ url }));
1404
1279
  <\/script>
1405
1280
 
1406
1281
  <App />
1407
- `;
1408
- const SVELTE_MAIN = `import "./app.css";
1282
+ `,fn=`import "./app.css";
1409
1283
 
1410
1284
  import { mount } from "svelte";
1411
1285
 
@@ -1415,62 +1289,84 @@ import Root from "./Root.svelte";
1415
1289
  const app = mount(Root, { target: document.getElementById("app")! });
1416
1290
 
1417
1291
  export default app;
1418
- `;
1419
- const ADAPTERS = {
1420
- react: {
1421
- adapter: "@lunora/react",
1422
- createViteTemplate: "react-ts",
1423
- files: [
1424
- { contents: REACT_MAIN, path: "src/main.tsx" },
1425
- { contents: REACT_APP, path: "src/App.tsx" },
1426
- { contents: WELCOME_CSS, path: "src/index.css" }
1427
- ],
1428
- label: "React"
1429
- },
1430
- solid: {
1431
- adapter: "@lunora/solid",
1432
- createViteTemplate: "solid",
1433
- files: [
1434
- { contents: SOLID_INDEX, path: "src/index.tsx" },
1435
- { contents: SOLID_APP, path: "src/App.tsx" },
1436
- { contents: WELCOME_CSS, path: "src/index.css" }
1437
- ],
1438
- label: "Solid"
1439
- },
1440
- svelte: {
1441
- adapter: "@lunora/svelte",
1442
- createViteTemplate: "svelte-ts",
1443
- files: [
1444
- { contents: SVELTE_ROOT, path: "src/Root.svelte" },
1445
- { contents: SVELTE_MAIN, path: "src/main.ts" },
1446
- { contents: SVELTE_APP, path: "src/App.svelte" },
1447
- { contents: WELCOME_CSS, path: "src/app.css" }
1448
- ],
1449
- label: "Svelte"
1450
- },
1451
- vanilla: {
1452
- adapter: "lunorash/client",
1453
- createViteTemplate: "vanilla-ts",
1454
- files: [
1455
- { contents: VANILLA_MAIN, path: "src/main.ts" },
1456
- { contents: WELCOME_CSS, path: "src/style.css" }
1457
- ],
1458
- label: "Vanilla"
1459
- },
1460
- vue: {
1461
- adapter: "@lunora/vue",
1462
- createViteTemplate: "vue-ts",
1463
- files: [
1464
- { contents: VUE_MAIN, path: "src/main.ts" },
1465
- { contents: VUE_APP, path: "src/App.vue" },
1466
- { contents: WELCOME_CSS, path: "src/style.css" }
1467
- ],
1468
- label: "Vue"
1469
- }
1470
- };
1471
- const isOverlayFramework = (value) => Object.hasOwn(ADAPTERS, value);
1292
+ `,F={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:un,path:"src/main.tsx"},{contents:on,path:"src/App.tsx"},{contents:O,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:pn,path:"src/index.tsx"},{contents:ln,path:"src/App.tsx"},{contents:O,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:mn,path:"src/Root.svelte"},{contents:fn,path:"src/main.ts"},{contents:cn,path:"src/App.svelte"},{contents:O,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:dn,path:"src/main.ts"},{contents:O,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:hn,path:"src/main.ts"},{contents:sn,path:"src/App.vue"},{contents:O,path:"src/style.css"}],label:"Vue"}},W=e=>Object.hasOwn(F,e),vn=`/**
1293
+ * Rate-limit schema extension + plugin.
1294
+ *
1295
+ * Defines the \`ratelimit_buckets\` table used by \`createDbStore\` for durable,
1296
+ * DO-backed rate limiting. Included automatically in every Lunora project.
1297
+ */
1298
+ import type { RateLimitConfigMap } from "lunorash/ratelimit";
1299
+ import { createDbStore, RateLimiter } from "lunorash/ratelimit";
1300
+ import type { Middleware } from "lunorash/server";
1301
+ import { definePlugin, defineSchemaExtension, defineTable, v } from "lunorash/server";
1302
+
1303
+ /**
1304
+ * Named limits this app enforces. This is the one place they live — add your own
1305
+ * and reference them by name from \`rateLimit(limiter, "<name>", …)\` (see
1306
+ * \`lunora/messages.ts\`).
1307
+ */
1308
+ export const limits = {
1309
+ /** Chat writes: 10 per caller per minute, refilling continuously over 60s. */
1310
+ send: { kind: "token bucket", period: 60_000, rate: 10 },
1311
+ } as const satisfies RateLimitConfigMap;
1472
1312
 
1473
- const LUNORA_SCHEMA = `import { defineSchema, defineTable, v } from "lunorash/server";
1313
+ /** The limit names you've configured above. */
1314
+ export type LimitName = keyof typeof limits;
1315
+
1316
+ /**
1317
+ * Build a durable {@link RateLimiter} bound to this request's \`ctx.db\`. State is
1318
+ * persisted in the \`ratelimit_buckets\` table, so limits survive Durable Object
1319
+ * hibernation/eviction and are shared across every call into the same DO. Each
1320
+ * \`get\`→\`set\` runs under the DO input gate, so the read-modify-write is atomic.
1321
+ */
1322
+ export const makeRateLimiter = (ctx: { db: unknown }): RateLimiter<LimitName> =>
1323
+ new RateLimiter<LimitName>({
1324
+ config: limits,
1325
+ // The merged table name carries the plugin prefix.
1326
+ store: createDbStore({ db: ctx.db as never, table: "ratelimit_buckets" }),
1327
+ });
1328
+
1329
+ /**
1330
+ * Middleware that injects \`ctx.api.ratelimit\` — a per-request limiter helper —
1331
+ * for any procedure that opts in with \`.use(ratelimit.middleware)\`. Convention
1332
+ * (see \`definePlugin\`): helpers hang off \`ctx.api.<key>\`.
1333
+ */
1334
+ const middleware: Middleware<{ api?: Record<string, unknown>; db: unknown }, { api: Record<string, unknown>; db: unknown }> = ({ ctx, next }) =>
1335
+ next({
1336
+ ctx: {
1337
+ ...ctx,
1338
+ api: { ...ctx.api, ratelimit: makeRateLimiter(ctx) },
1339
+ },
1340
+ });
1341
+
1342
+ /**
1343
+ * The rate-limit plugin: a schema extension (\`ratelimit_buckets\`) + middleware
1344
+ * (\`ctx.api.ratelimit\`). \`lunora/schema.ts\` wires the extension in with
1345
+ * \`.extend(ratelimit.extension)\`; attach the middleware yourself with
1346
+ * \`c.mutation.use(ratelimit.middleware)\`.
1347
+ */
1348
+ export const ratelimit = definePlugin("ratelimit", {
1349
+ extension: defineSchemaExtension("ratelimit", {
1350
+ tables: {
1351
+ // Bare name — auto-prefixes to \`ratelimit_buckets\` at merge time.
1352
+ // \`externallyManaged\`: rows are written by \`createDbStore\` (via
1353
+ // \`makeRateLimiter\`), not a discoverable \`ctx.db.insert(...)\`, so the
1354
+ // \`table_without_insert\` advisor correctly skips it.
1355
+ buckets: defineTable({
1356
+ key: v.string(),
1357
+ value: v.number(),
1358
+ ts: v.number(),
1359
+ prev: v.optional(v.number()),
1360
+ })
1361
+ .index("by_key", ["key"])
1362
+ .index("by_ts", ["ts"])
1363
+ .externallyManaged(),
1364
+ },
1365
+ }),
1366
+ middleware,
1367
+ });
1368
+ `,gn=`import { ratelimit } from "./ratelimit/schema.js";
1369
+ import { defineSchema, defineTable, v } from "lunorash/server";
1474
1370
 
1475
1371
  export default defineSchema({
1476
1372
  messages: defineTable({
@@ -1479,25 +1375,40 @@ export default defineSchema({
1479
1375
  })
1480
1376
  .shardBy("channelId")
1481
1377
  .index("by_channel", ["channelId"]),
1482
- });
1483
- `;
1484
- const LUNORA_MESSAGES = `import { RateLimiter, rateLimit } from "@lunora/ratelimit";
1378
+ }).extend(ratelimit.extension);
1379
+ `,wn=`import { rateLimit } from "lunorash/ratelimit";
1485
1380
 
1381
+ import { makeRateLimiter } from "./ratelimit/schema.js";
1382
+ import type { MutationCtx } from "#lunora/_generated/server.js";
1486
1383
  import { mutation, query, v } from "#lunora/_generated/server.js";
1487
1384
 
1488
1385
  /**
1489
- * One in-memory limiter so the public \`send\` mutation isn't an open flood target
1490
- * out of the box. The default store is in-memory (per-isolate, resets on
1491
- * eviction) — fine for a starter; run \`lunora add ratelimit\` for the durable,
1492
- * \`ctx.db\`-backed store when you ship to production.
1386
+ * The limiter comes from \`lunora/ratelimit/schema.ts\` — that file owns the named
1387
+ * limits and the durable store, so tuning \`send\` there is what changes this
1388
+ * procedure's budget. Build it from the generated \`MutationCtx\` so
1389
+ * \`rateLimit(limiter, …)\` infers the full procedure context: \`ctx.auth\`/\`ctx.ip\`
1390
+ * in the key callback and a typed \`ctx.db\` in the handler both depend on it.
1493
1391
  */
1494
- const limiter = new RateLimiter({
1495
- config: {
1496
- send: { kind: "token bucket", period: 60_000, rate: 30 },
1497
- },
1498
- });
1392
+ const limiter = (ctx: MutationCtx) => makeRateLimiter(ctx);
1393
+
1394
+ /**
1395
+ * One bucket per caller, not one bucket for the whole app.
1396
+ *
1397
+ * \`ctx.auth.userId\` is \`null\` until you wire auth (\`lunora registry add auth\`),
1398
+ * so the \`ctx.ip\` fallback is what actually keys the limit in a fresh project.
1399
+ * Keying on \`"anon"\` alone would let one script exhaust the budget for every user.
1400
+ *
1401
+ * \`ctx.ip\` is Cloudflare's server-side \`CF-Connecting-IP\` and is populated ONLY
1402
+ * when the app runs on Cloudflare, where the edge stamps that header over
1403
+ * anything the client sent. Deploy this to another target and \`ctx.ip\` is
1404
+ * \`undefined\` by design — the runtime will not pass on a header the caller can
1405
+ * type — so every anonymous caller falls back to the shared \`"anon"\` bucket.
1406
+ * Off Cloudflare, key on something the caller cannot choose (an API key, a
1407
+ * signed session) before relying on this limit.
1408
+ */
1409
+ const byCaller = { key: (ctx: { auth: { userId?: null | string }; ip?: string }): string => ctx.auth.userId ?? ctx.ip ?? "anon" };
1499
1410
 
1500
- export const list = query.input({ channelId: v.string().meta({ schema: { maxLength: 256 } }), limit: v.optional(v.number()) }).query(async ({ args, ctx }) => {
1411
+ export const list = query.input({ channelId: v.string().max(256), limit: v.optional(v.number()) }).query(async ({ args, ctx }) => {
1501
1412
  const messages = await ctx.db
1502
1413
  .query("messages")
1503
1414
  .withIndex("by_channel", (q) => q.eq("channelId", args.channelId))
@@ -1507,1030 +1418,90 @@ export const list = query.input({ channelId: v.string().meta({ schema: { maxLeng
1507
1418
  });
1508
1419
 
1509
1420
  export const send = mutation
1510
- .input({ channelId: v.string().meta({ schema: { maxLength: 256 } }), text: v.string().meta({ schema: { maxLength: 4096 } }) })
1511
- .use(rateLimit(limiter, "send", { key: (ctx) => ctx.auth.userId ?? "anon" }))
1421
+ .input({ channelId: v.string().max(256), text: v.string().max(4096) })
1422
+ .use(rateLimit(limiter, "send", byCaller))
1512
1423
  .mutation(async ({ args, ctx }) => {
1513
1424
  const id = await ctx.db.insert("messages", { channelId: args.channelId, text: args.text });
1514
1425
 
1515
1426
  return { channelId: args.channelId, id, text: args.text };
1516
1427
  });
1517
- `;
1518
- const SERVER_ENTRY = `import type { ShardNamespaceLike } from "lunorash/runtime";
1428
+ `,yn=`import type { ShardNamespaceLike } from "lunorash/runtime";
1519
1429
 
1520
1430
  import { defineApp } from "../lunora/_generated/app.js";
1521
1431
 
1522
1432
  interface Env extends Record<string, unknown> {
1433
+ ADMIN_REVOCATIONS: ShardNamespaceLike;
1523
1434
  SHARD: ShardNamespaceLike;
1524
1435
  }
1525
1436
 
1526
1437
  const app = defineApp<Env>()
1527
1438
  .shard((env) => env.SHARD)
1439
+ .adminRevocations((env) => env.ADMIN_REVOCATIONS)
1528
1440
  .build();
1529
1441
 
1530
1442
  export const ShardDO = app.ShardDO;
1443
+ // Records revoked named admin tokens where a restore of the shard cannot rewind them.
1444
+ export { AdminRevocationDO } from "../lunora/_generated/adminRevocations.js";
1531
1445
  export default app;
1532
- `;
1533
- const WRANGLER = `{
1446
+ `,bn=`{ ${Object.entries(Xt).map(([e,t])=>`${JSON.stringify(e)}: ${JSON.stringify(t)}`).join(", ")} }`,kn=`{
1534
1447
  "$schema": "node_modules/wrangler/config-schema.json",
1535
1448
  "name": "__NAME__",
1536
1449
  "main": "src/server.ts",
1537
- "compatibility_date": "2026-06-10",
1450
+ "compatibility_date": "2026-10-01",
1538
1451
  "compatibility_flags": ["nodejs_compat"],
1539
1452
  "durable_objects": {
1540
- "bindings": [{ "name": "SHARD", "class_name": "ShardDO" }],
1453
+ "bindings": [
1454
+ { "name": "SHARD", "class_name": "ShardDO" },
1455
+ { "name": "ADMIN_REVOCATIONS", "class_name": "AdminRevocationDO" },
1456
+ ],
1541
1457
  },
1542
- "migrations": [{ "tag": "v1", "new_sqlite_classes": ["ShardDO"] }],
1543
- "observability": { "enabled": true, "head_sampling_rate": 1 },
1458
+ "migrations": [
1459
+ { "tag": "v1", "new_sqlite_classes": ["ShardDO"] },
1460
+ { "tag": "v2", "new_sqlite_classes": ["AdminRevocationDO"] },
1461
+ ],
1462
+ "observability": ${bn},
1544
1463
  }
1545
- `;
1546
- const GITIGNORE_ADDITIONS = [".wrangler", ".env", ".env.*", "!.env.example", ".lunora/", ".lunora-cache", "lunora/_generated"];
1547
- const ENV_EXAMPLE = `# Lunora endpoint for the browser client.
1464
+ `,pe=[".wrangler",".env",".env.*","!.env.example",".dev.vars",".dev.vars.*","!.dev.vars.example",".lunora/",".lunora-cache","lunora/_generated"],xn=`# Lunora endpoint for the browser client.
1548
1465
  # Vite statically replaces \`import.meta.env.VITE_LUNORA_URL\` at \`vite dev\` / build.
1549
1466
  # Leave it unset to use the page origin; set it to point at a deployed Worker:
1550
1467
  #
1551
1468
  # VITE_LUNORA_URL=https://my-app.example.workers.dev
1552
- `;
1553
- const COMMON_DEV_DEPENDENCIES = {
1554
- "@cloudflare/workers-types": "^4.20260611.1",
1555
- wrangler: "^4.100.0"
1556
- };
1557
- const writeFile = (target, relativePath, contents, written) => {
1558
- const destination = join$1(target, relativePath);
1559
- mkdirSync(dirname$1(destination), { recursive: true });
1560
- writeFileSync(destination, contents, "utf8");
1561
- written.push(destination);
1562
- };
1563
- const NEWLINE = /\r?\n/;
1564
- const ensureGitignore = (target) => {
1565
- const path = join$1(target, ".gitignore");
1566
- const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
1567
- const missing = GITIGNORE_ADDITIONS.filter((entry) => !existing.split(NEWLINE).includes(entry));
1568
- if (missing.length === 0) {
1569
- return;
1570
- }
1571
- const prefix = existing.length > 0 && !existing.endsWith("\n") ? "\n" : "";
1572
- writeFileSync(path, `${existing}${prefix}
1469
+ `,En={"@cloudflare/workers-types":ne["@cloudflare/workers-types"],wrangler:ne.wrangler},L=(e,t,r,n)=>{const a=u(e,t);I(S(a),{recursive:!0}),v(a,r,"utf8"),n.push(a)},_n=/\r?\n/,Cn=e=>{const t=u(e,".gitignore"),r=f(t)?_(t,"utf8"):"",n=new Set(r.split(_n)),a=pe.filter(o=>!n.has(o));if(a.length===0)return;const i=a.some(o=>!o.startsWith("!"))?[...a.filter(o=>!o.startsWith("!")),...pe.filter(o=>o.startsWith("!"))]:a,s=r.length>0&&!r.endsWith(`
1470
+ `)?`
1471
+ `:"";v(t,`${r}${s}
1573
1472
  # Lunora
1574
- ${missing.join("\n")}
1575
- `, "utf8");
1576
- };
1577
- const isLunoraDep$1 = (name) => name === "lunorash" || name.startsWith("@lunora/");
1578
- const stampRange = (name, range, distTag, versions) => isLunoraDep$1(name) ? versions?.get(name) ?? distTag : range;
1579
- const withDependency = (map, name, range, distTag) => {
1580
- return { ...map, [name]: stampRange(name, range, distTag) };
1581
- };
1582
- const restampLunora = (map, distTag, versions) => Object.fromEntries(Object.entries(map).map(([name, range]) => [name, stampRange(name, range, distTag, versions)]));
1583
- const patchPackageJson = async (target, name, adapter, distTag) => {
1584
- const path = join$1(target, "package.json");
1585
- const parsed = JSON.parse(readFileSync(path, "utf8"));
1586
- let dependencies = withDependency(parsed.dependencies ?? {}, "lunorash", distTag, distTag);
1587
- dependencies = withDependency(dependencies, "@lunora/ratelimit", distTag, distTag);
1588
- if (adapter.adapter.startsWith("@lunora/")) {
1589
- dependencies = withDependency(dependencies, adapter.adapter, distTag, distTag);
1590
- }
1591
- for (const [depName, range] of Object.entries(adapter.extraDependencies ?? {})) {
1592
- dependencies = withDependency(dependencies, depName, range, distTag);
1593
- }
1594
- let devDependencies = withDependency(parsed.devDependencies ?? {}, "@lunora/vite", distTag, distTag);
1595
- devDependencies = withDependency(devDependencies, "@lunora/studio", distTag, distTag);
1596
- for (const [depName, range] of Object.entries(COMMON_DEV_DEPENDENCIES)) {
1597
- devDependencies = withDependency(devDependencies, depName, range, distTag);
1598
- }
1599
- const lunoraNames = [...Object.keys(dependencies), ...Object.keys(devDependencies)].filter((depName) => isLunoraDep$1(depName));
1600
- const versions = await resolveTagVersions(lunoraNames, distTag);
1601
- parsed.name = name;
1602
- parsed.imports = { ...parsed.imports, "#lunora/*": "./lunora/*" };
1603
- parsed.dependencies = restampLunora(dependencies, distTag, versions);
1604
- parsed.devDependencies = restampLunora(devDependencies, distTag, versions);
1605
- parsed.scripts = { ...parsed.scripts, codegen: "lunora codegen", deploy: "vite build && lunora deploy" };
1606
- writeFileSync(path, `${JSON.stringify(parsed, void 0, 4)}
1607
- `, "utf8");
1608
- };
1609
- const patchBaseViteConfig = (target, logger) => {
1610
- const candidate = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"].map((file) => join$1(target, file)).find((path) => existsSync(path));
1611
- if (candidate === void 0) {
1612
- logger.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");
1613
- return;
1614
- }
1615
- const result = patchViteConfig(readFileSync(candidate, "utf8"));
1616
- if (result.changed) {
1617
- writeFileSync(candidate, result.code, "utf8");
1618
- }
1619
- };
1620
- const applyLunoraOverlay = async (options) => {
1621
- const { adapter, distTag, logger, name, target } = options;
1622
- const written = [];
1623
- writeFile(target, join$1("lunora", "schema.ts"), LUNORA_SCHEMA, written);
1624
- writeFile(target, join$1("lunora", "messages.ts"), LUNORA_MESSAGES, written);
1625
- writeFile(target, join$1("src", "server.ts"), SERVER_ENTRY, written);
1626
- writeFile(target, "wrangler.jsonc", WRANGLER.replaceAll("__NAME__", name), written);
1627
- writeFile(target, ".env.example", ENV_EXAMPLE, written);
1628
- for (const file of adapter.files) {
1629
- writeFile(target, file.path, file.contents, written);
1630
- }
1631
- patchBaseViteConfig(target, logger);
1632
- await patchPackageJson(target, name, adapter, distTag);
1633
- ensureGitignore(target);
1634
- return written;
1635
- };
1636
-
1637
- const ADJECTIVES = [
1638
- "lunar",
1639
- "silver",
1640
- "silent",
1641
- "waning",
1642
- "waxing",
1643
- "crescent",
1644
- "cosmic",
1645
- "stellar",
1646
- "orbital",
1647
- "gibbous",
1648
- "twilight",
1649
- "midnight",
1650
- "shimmering",
1651
- "drifting",
1652
- "weightless"
1653
- ];
1654
- const NOUNS = [
1655
- "moon",
1656
- "tide",
1657
- "crater",
1658
- "comet",
1659
- "eclipse",
1660
- "halo",
1661
- "orbit",
1662
- "nebula",
1663
- "voyager",
1664
- "lander",
1665
- "rover",
1666
- "beacon",
1667
- "harbor",
1668
- "meadow",
1669
- "fox"
1670
- ];
1671
- const pick = (items) => (
1672
- // eslint-disable-next-line sonarjs/pseudo-random -- cosmetic default project name, not a security decision.
1673
- items[Math.floor(Math.random() * items.length)]
1674
- );
1675
- const generateProjectName = () => `${pick(ADJECTIVES)}-${pick(NOUNS)}`;
1676
-
1677
- const isOnline = async () => dns.lookup("github.com").then(
1678
- () => true,
1679
- () => false
1680
- );
1681
- const GITHUB_SOURCE = /^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/;
1682
- const parseGitHubSource = (source) => {
1683
- const match = GITHUB_SOURCE.exec(source);
1684
- if (match === null) {
1685
- return void 0;
1686
- }
1687
- const [, owner, repo, ref] = match;
1688
- if (owner === void 0 || repo === void 0) {
1689
- return void 0;
1690
- }
1691
- return { owner, ref: ref ?? "HEAD", repo };
1692
- };
1693
- const templateRefExists = async (source) => {
1694
- const parsed = parseGitHubSource(source);
1695
- if (parsed === void 0) {
1696
- return void 0;
1697
- }
1698
- const url = `https://codeload.github.com/${parsed.owner}/${parsed.repo}/tar.gz/${parsed.ref}`;
1699
- try {
1700
- const response = await fetch(url, { method: "HEAD" });
1701
- if (response.status === 404) {
1702
- return false;
1703
- }
1704
- return response.ok ? true : void 0;
1705
- } catch {
1706
- return void 0;
1707
- }
1708
- };
1709
- const verifyRemoteTemplate = async (params) => {
1710
- if (params.isLocal) {
1711
- return true;
1712
- }
1713
- const isGitHubBacked = params.source === void 0 || parseGitHubSource(params.source) !== void 0;
1714
- if (!isGitHubBacked) {
1715
- return true;
1716
- }
1717
- if (!await isOnline()) {
1718
- params.logger.error("you appear to be offline — connect to the internet and try again, or scaffold from a local template with `--from <dir>`.");
1719
- return false;
1720
- }
1721
- if (params.source !== void 0 && await templateRefExists(params.source) === false) {
1722
- params.logger.error(`template source not found: ${params.source} — double-check --ref / --source, or browse the templates at https://lunora.sh/docs.`);
1723
- return false;
1724
- }
1725
- return true;
1726
- };
1727
-
1728
- const COPY = {
1729
- extras: "Let's finish setting up your app.",
1730
- framework: "Which framework should we launch?",
1731
- git: "Initialize a new git repository? (optional)",
1732
- install: "Install dependencies now?",
1733
- name: "Where should we land your project?",
1734
- nextHeader: "Liftoff confirmed — explore your project!",
1735
- packageManager: "Which package manager?"
1736
- };
1737
- const TEXT_EXTENSIONS = /* @__PURE__ */ new Set([".gitignore", ".html", ".js", ".json", ".jsonc", ".md", ".mjs", ".ts", ".tsx"]);
1738
- const VITE_CONFIG_CANDIDATES = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs"];
1739
- const MINIMAL_VITE_CONFIG = `import { defineConfig } from "vite";
1473
+ ${i.join(`
1474
+ `)}
1475
+ `,"utf8")},q=e=>e==="lunorash"||e.startsWith("@lunora/"),Sn=(e,t,r,n)=>q(e)?n.get(e)??r:t,A=(e,t,r)=>({...e,[t]:r}),me=(e,t,r)=>Object.fromEntries(Object.entries(e).map(([n,a])=>[n,Sn(n,a,t,r)])),Ln=async(e,t,r,n)=>{const a=u(e,"package.json"),i=bt(a);let s=A(i.dependencies??{},"lunorash",n);s=A(s,"@lunora/ratelimit",n),r.adapter.startsWith("@lunora/")&&(s=A(s,r.adapter,n));for(const[d,p]of Object.entries(r.extraDependencies??{}))s=A(s,d,p);let o=A(i.devDependencies??{},"@lunora/vite",n);o=A(o,"@lunora/studio",n);for(const[d,p]of Object.entries(En))o=A(o,d,p);const l=[...Object.keys(s),...Object.keys(o)].filter(d=>q(d)),c=await Le(l,n);i.name=t,i.imports={...i.imports,"#lunora/*":"./lunora/*"},i.dependencies=me(s,n,c),i.devDependencies=me(o,n,c),i.scripts={...i.scripts,codegen:"lunora codegen",deploy:"lunora deploy"},v(a,`${JSON.stringify(i,void 0,4)}
1476
+ `,"utf8")},An=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Ge=e=>An.map(t=>u(e,t)).find(t=>f(t)),In=(e,t)=>{const r=Ge(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=Be(_(r,"utf8"));n.changed&&v(r,n.code,"utf8")},Rn=async e=>{const{adapter:t,distTag:r,logger:n,name:a,target:i}=e,s=[];L(i,u("lunora","ratelimit","schema.ts"),vn,s),L(i,u("lunora","schema.ts"),gn,s),L(i,u("lunora","messages.ts"),wn,s),L(i,u("src","server.ts"),yn,s),L(i,"wrangler.jsonc",kn.replaceAll("__NAME__",a),s),L(i,".env.example",xn,s);for(const o of t.files)L(i,o.path,o.contents,s);return In(i,n),await Ln(i,a,t,r),Cn(i),s},On=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],Tn=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],fe=e=>e[Math.floor(Math.random()*e.length)],$n=()=>`${fe(On)}-${fe(Tn)}`,Mn=async()=>er.lookup("github.com").then(()=>!0,()=>!1),Nn=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,Ye=e=>{const t=Nn.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}},Pn=async e=>{const t=Ye(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}},Je=async e=>e.isLocal||!(e.source===void 0||Ye(e.source)!==void 0)?!0:await Mn()?e.source!==void 0&&await Pn(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),C={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?"},Dn=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),Un=`import { defineConfig } from "vite";
1740
1477
  import { lunora } from "@lunora/vite";
1741
1478
 
1742
1479
  export default defineConfig({ plugins: [lunora()] });
1743
- `;
1744
- const SAMPLE_SCHEMA = `import { defineSchema, defineTable, v } from "@lunora/server";
1480
+ `,jn=`import { defineSchema, defineTable, v } from "@lunora/server";
1745
1481
 
1746
1482
  export default defineSchema({
1747
1483
  messages: defineTable({
1748
- channelId: v.id("channels"),
1484
+ channelId: v.string(),
1749
1485
  text: v.string(),
1750
1486
  })
1751
1487
  .shardBy("channelId")
1752
1488
  .index("by_channel", ["channelId"]),
1753
1489
  });
1754
- `;
1755
- const SAMPLE_FUNCTION = `import { mutation, query, v } from "./_generated/server";
1490
+ `,Vn=`import { mutation, query, v } from "./_generated/server";
1756
1491
 
1757
1492
  export const list = query
1758
- .input({ channelId: v.id("channels"), limit: v.optional(v.number()) })
1493
+ .input({ channelId: v.string(), limit: v.optional(v.number()) })
1759
1494
  .query(async ({ args }) => {
1760
1495
  return { channelId: args.channelId, limit: args.limit ?? 50, messages: [] };
1761
1496
  });
1762
1497
 
1763
1498
  export const send = mutation
1764
- .input({ channelId: v.id("channels"), text: v.string() })
1499
+ .input({ channelId: v.string(), text: v.string() })
1765
1500
  .mutation(async ({ args }) => {
1766
1501
  return { channelId: args.channelId, text: args.text };
1767
1502
  });
1768
- `;
1769
- const DEFAULT_SOURCE_BASE = "gh:anolilab/lunora/templates";
1770
- const isTextFile = (filePath) => {
1771
- const lastDot = filePath.lastIndexOf(".");
1772
- if (lastDot === -1) {
1773
- return false;
1774
- }
1775
- return TEXT_EXTENSIONS.has(filePath.slice(lastDot));
1776
- };
1777
- const substitute = (content, name) => content.replaceAll("{{name}}", name);
1778
- const isLunoraDep = (name) => name === "lunorash" || name.startsWith("@lunora/");
1779
- const resolveLunoraVersions = async (files, distTag) => {
1780
- const names = /* @__PURE__ */ new Set();
1781
- for (const file of files) {
1782
- if (basename(file) !== "package.json") {
1783
- continue;
1784
- }
1785
- try {
1786
- const parsed = JSON.parse(readFileSync(file, "utf8"));
1787
- for (const section of ["dependencies", "devDependencies"]) {
1788
- for (const name of Object.keys(parsed[section] ?? {})) {
1789
- if (isLunoraDep(name)) {
1790
- names.add(name);
1791
- }
1792
- }
1793
- }
1794
- } catch {
1795
- }
1796
- }
1797
- return resolveTagVersions(names, distTag);
1798
- };
1799
- const stampLunoraDeps = (packageJsonText, distTag, versions) => {
1800
- let parsed;
1801
- try {
1802
- parsed = JSON.parse(packageJsonText);
1803
- } catch {
1804
- return packageJsonText;
1805
- }
1806
- let text = packageJsonText;
1807
- for (const section of ["dependencies", "devDependencies"]) {
1808
- for (const name of Object.keys(parsed[section] ?? {})) {
1809
- if (!isLunoraDep(name)) {
1810
- continue;
1811
- }
1812
- const pin = versions.get(name) ?? distTag;
1813
- const edits = modify(text, [section, name], pin, { formattingOptions: { insertSpaces: true, tabSize: 4 } });
1814
- text = applyEdits(text, edits);
1815
- }
1816
- }
1817
- return text;
1818
- };
1819
- const PNPM_BUILT_DEPENDENCIES = ["esbuild", "sharp", "workerd"];
1820
- const PNPM_WORKSPACE_FILENAME = "pnpm-workspace.yaml";
1821
- const pnpmWorkspaceYaml = () => [
1822
- "# pnpm reads its settings from here (the package.json `pnpm` field is no longer read).",
1823
- "# Pre-approve the toolchain's native build scripts so `pnpm install` runs them",
1824
- "# without the interactive `pnpm approve-builds` step.",
1825
- "allowBuilds:",
1826
- ...PNPM_BUILT_DEPENDENCIES.map((name) => ` ${name}: true`),
1827
- ""
1828
- ].join("\n");
1829
- const collectFiles = (directory) => {
1830
- const out = [];
1831
- for (const entry of walkSync(directory, { includeDirs: false, includeFiles: true })) {
1832
- out.push(entry.path);
1833
- }
1834
- return out;
1835
- };
1836
- const copyTemplate = async (sourceDirectory, target, name) => {
1837
- const files = collectFiles(sourceDirectory);
1838
- const written = [];
1839
- const distTag = resolveDistTag();
1840
- const versions = await resolveLunoraVersions(files, distTag);
1841
- for (const source of files) {
1842
- const relativePath = relative(sourceDirectory, source);
1843
- const destination = join$1(target, relativePath);
1844
- mkdirSync(dirname$1(destination), { recursive: true });
1845
- const raw = readFileSync(source);
1846
- let text = isTextFile(source) ? substitute(raw.toString("utf8"), name) : void 0;
1847
- if (text !== void 0 && basename(source) === "package.json") {
1848
- text = stampLunoraDeps(text, distTag, versions);
1849
- }
1850
- if (text === void 0) {
1851
- writeFileSync(destination, raw);
1852
- } else {
1853
- writeFileSync(destination, text, "utf8");
1854
- }
1855
- written.push(destination);
1856
- }
1857
- return written;
1858
- };
1859
- const resolveTemplateSource = (templateType, source, ref) => {
1860
- if (source !== void 0 && source.length > 0) {
1861
- return source;
1862
- }
1863
- return `${DEFAULT_SOURCE_BASE}/${templateType}#${resolveSourceRef(ref)}`;
1864
- };
1865
- const isSafeSource = (source) => {
1866
- if (source.includes("..")) {
1867
- return false;
1868
- }
1869
- return source.startsWith("gh:") || source.startsWith("github:") || source.startsWith("https://");
1870
- };
1871
- const logWould = (logger, action) => {
1872
- logger.info(`[dry-run] would ${action}`);
1873
- };
1874
- const logScaffoldSuccess = (logger, written, target) => {
1875
- if (isInteractive()) {
1876
- process.stdout.write("\n");
1877
- }
1878
- logger.success(`scaffolded ${String(written.length)} files into ${target}`);
1879
- };
1880
- const runScriptCommand = (manager, script) => {
1881
- if (manager === "npm") {
1882
- return `npm run ${script}`;
1883
- }
1884
- if (manager === "bun") {
1885
- return `bun run ${script}`;
1886
- }
1887
- return `${manager} ${script}`;
1888
- };
1889
- const isInsideMonorepo = (startDirectory) => {
1890
- let directory = resolve(startDirectory);
1891
- for (; ; ) {
1892
- if (existsSync(join$1(directory, "pnpm-workspace.yaml"))) {
1893
- return true;
1894
- }
1895
- const packagePath = join$1(directory, "package.json");
1896
- if (existsSync(packagePath)) {
1897
- try {
1898
- const parsed = JSON.parse(readFileSync(packagePath, "utf8"));
1899
- if (parsed.workspaces !== void 0) {
1900
- return true;
1901
- }
1902
- } catch {
1903
- }
1904
- }
1905
- const parent = dirname$1(directory);
1906
- if (parent === directory) {
1907
- return false;
1908
- }
1909
- directory = parent;
1910
- }
1911
- };
1912
- const isInsideGitRepo = (startDirectory) => {
1913
- let directory = resolve(startDirectory);
1914
- for (; ; ) {
1915
- if (existsSync(join$1(directory, ".git"))) {
1916
- return true;
1917
- }
1918
- const parent = dirname$1(directory);
1919
- if (parent === directory) {
1920
- return false;
1921
- }
1922
- directory = parent;
1923
- }
1924
- };
1925
- const maybeOfferGit = async (options, target) => {
1926
- if (options.yes === true || !isInteractive() || isInsideGitRepo(dirname$1(target))) {
1927
- return;
1928
- }
1929
- if (!await tuiConfirm(COPY.git, { badge: BADGES.git, defaultYes: false })) {
1930
- await tuiInfo("Sounds good! You can always run git init manually.");
1931
- return;
1932
- }
1933
- if (options.dryRun === true) {
1934
- logWould(options.logger, "initialize a git repository");
1935
- return;
1936
- }
1937
- const spawner = options.spawner ?? defaultSpawner;
1938
- const result = await withTuiSpinner("Initializing a git repository…", () => spawner({ args: ["init"], command: "git", cwd: target }));
1939
- if (result.code === 0) {
1940
- await emitStep("git", "Initialized an empty git repository.");
1941
- } else {
1942
- options.logger.warn("`git init` failed — initialize it yourself later with `git init`.");
1943
- }
1944
- };
1945
- const printNextSteps = async (name, installed, insideMonorepo) => {
1946
- const manager = installed ?? "pnpm";
1947
- const steps = [{ code: `cd ./${name}`, lead: "Enter your project directory using" }];
1948
- if (installed === void 0) {
1949
- steps.push({ code: `${manager} install`, lead: "Install dependencies with", tail: insideMonorepo ? " from the workspace root" : void 0 });
1950
- }
1951
- steps.push(
1952
- { code: runScriptCommand(manager, "dev"), lead: "Run", tail: " to start the dev server." },
1953
- { code: "lunora add", lead: "Add features like auth or storage using" }
1954
- );
1955
- const help = [
1956
- { code: "https://lunora.sh/docs", lead: "Read the docs at" },
1957
- { code: "https://lunora.sh/chat", lead: "Stuck? Join the chat at" }
1958
- ];
1959
- if (isInteractive()) {
1960
- await tuiNextSteps(BADGES.next, COPY.nextHeader, steps, help);
1961
- return;
1962
- }
1963
- const lines = steps.map((step) => `${step.lead} ${step.code}${step.tail ?? ""}`);
1964
- lines.push("", ...help.map((line) => `${line.lead} ${line.code}${line.tail ?? ""}`));
1965
- await emitStep("next", COPY.nextHeader, lines.join("\n"));
1966
- };
1967
- const offerInstallIsInteractive = (options) => options.yes !== true && (options.installPrompt !== void 0 || isInteractive());
1968
- const maybeOfferInstall = async (options, target) => {
1969
- if (!offerInstallIsInteractive(options)) {
1970
- return void 0;
1971
- }
1972
- if (isInsideMonorepo(dirname$1(target))) {
1973
- return void 0;
1974
- }
1975
- const managers = detectInstalledManagers(options.packageManagerProbe);
1976
- const [defaultManager] = managers;
1977
- if (defaultManager === void 0) {
1978
- return void 0;
1979
- }
1980
- const confirm = options.installPrompt?.confirmInstall ?? (async () => tuiConfirm(COPY.install, { badge: BADGES.deps, defaultYes: true }));
1981
- if (!await confirm()) {
1982
- await tuiInfo("No problem! Remember to install dependencies after setup.");
1983
- return void 0;
1984
- }
1985
- let manager = defaultManager;
1986
- if (managers.length > 1) {
1987
- manager = options.installPrompt ? await options.installPrompt.selectManager(managers) : await tuiSelect(
1988
- COPY.packageManager,
1989
- managers.map((candidate) => {
1990
- return { label: candidate, value: candidate };
1991
- }),
1992
- { badge: BADGES.deps, default: defaultManager }
1993
- ) ?? defaultManager;
1994
- }
1995
- if (options.dryRun === true) {
1996
- logWould(options.logger, `install dependencies with ${manager}`);
1997
- return void 0;
1998
- }
1999
- if (manager === "pnpm") {
2000
- const workspacePath = join$1(target, PNPM_WORKSPACE_FILENAME);
2001
- if (!existsSync(workspacePath)) {
2002
- writeFileSync(workspacePath, pnpmWorkspaceYaml(), "utf8");
2003
- }
2004
- }
2005
- const spawner = options.spawner ?? defaultSpawner;
2006
- const { args, command } = installArgsFor(manager);
2007
- await emitStep("deps", `Installing dependencies with ${manager}…`);
2008
- const result = await spawner({ args, command, cwd: target });
2009
- if (result.code !== 0) {
2010
- options.logger.warn(`\`${command} install\` exited with code ${String(result.code)} — run it yourself in ${basename(target)}/.`);
2011
- return void 0;
2012
- }
2013
- await emitStep("deps", `Dependencies installed with ${manager}.`);
2014
- return manager;
2015
- };
2016
- const scaffoldFromLocal = async (fromRoot, templateType, target, name, logger) => {
2017
- const templateDirectory = join$1(fromRoot, templateType);
2018
- if (!existsSync(templateDirectory)) {
2019
- logger.error(`template not found in local source: ${templateDirectory}`);
2020
- return { code: 1, files: [], target };
2021
- }
2022
- const written = await copyTemplate(templateDirectory, target, name);
2023
- logScaffoldSuccess(logger, written, target);
2024
- return { code: 0, files: written, target };
2025
- };
2026
- const scaffoldFromRemote = async (options) => {
2027
- const { logger, name, ref, source, target, templateType } = options;
2028
- const stagingRoot = mkdtempSync(join$1(tmpdir(), "lunora-init-fetch-"));
2029
- const stagingDirectory = join$1(stagingRoot, "template");
2030
- try {
2031
- const remote = resolveTemplateSource(templateType, source, ref);
2032
- let downloaded;
2033
- let written = [];
2034
- await tuiTasks(
2035
- [
2036
- {
2037
- label: `${templateType} template fetched`,
2038
- run: async () => {
2039
- downloaded = await downloadTemplate(remote, {
2040
- cwd: stagingRoot,
2041
- dir: stagingDirectory,
2042
- force: true,
2043
- install: false,
2044
- silent: true
2045
- });
2046
- }
2047
- },
2048
- {
2049
- label: `files copied into ${name}/`,
2050
- run: async () => {
2051
- written = await copyTemplate(stagingDirectory, target, name);
2052
- }
2053
- }
2054
- ],
2055
- { end: "Project initialized!", start: "Project initializing…" }
2056
- );
2057
- const staged = collectFiles(stagingDirectory);
2058
- if (isInteractive()) {
2059
- process.stdout.write("\n");
2060
- }
2061
- logger.info(
2062
- downloaded?.commit ? `template: ${downloaded.source} @ ${downloaded.commit} (${String(staged.length)} files)` : `template: ${downloaded?.source ?? remote} (${String(staged.length)} files)`
2063
- );
2064
- logScaffoldSuccess(logger, written, target);
2065
- return { code: 0, files: written, target };
2066
- } catch (error) {
2067
- if (error instanceof PromptCancelledError) {
2068
- throw error;
2069
- }
2070
- const { hints, message } = describeDownloadFailure(error, {
2071
- ref: resolveSourceRef(ref),
2072
- remote: resolveTemplateSource(templateType, source, ref),
2073
- templateType
2074
- });
2075
- logger.error(message);
2076
- for (const hint of hints) {
2077
- logger.warn(hint);
2078
- }
2079
- return { code: 1, files: [], target };
2080
- } finally {
2081
- rmSync(stagingRoot, { force: true, recursive: true });
2082
- }
2083
- };
2084
- const renameCreateViteDotfiles = (directory) => {
2085
- for (const file of ["_gitignore", "_npmrc", "_gitattributes"]) {
2086
- const from = join$1(directory, file);
2087
- if (existsSync(from)) {
2088
- renameSync(from, join$1(directory, `.${file.slice(1)}`));
2089
- }
2090
- }
2091
- };
2092
- const scaffoldViteOverlay = async (options) => {
2093
- const { framework, logger, name, overlayBaseFrom, target } = options;
2094
- const adapter = ADAPTERS[framework];
2095
- const stagingRoot = mkdtempSync(join$1(tmpdir(), "lunora-vite-base-"));
2096
- try {
2097
- let localBase;
2098
- if (overlayBaseFrom !== void 0) {
2099
- localBase = join$1(overlayBaseFrom, `template-${adapter.createViteTemplate}`);
2100
- if (!existsSync(localBase)) {
2101
- logger.error(`create-vite base not found on disk: ${localBase}`);
2102
- return { code: 1, files: [], target };
2103
- }
2104
- }
2105
- const copyBase = async () => {
2106
- if (localBase !== void 0) {
2107
- cpSync(localBase, target, { recursive: true });
2108
- return;
2109
- }
2110
- const stagingDirectory = join$1(stagingRoot, "base");
2111
- const remote = `github:vitejs/vite/packages/create-vite/template-${adapter.createViteTemplate}#main`;
2112
- await downloadTemplate(remote, { cwd: stagingRoot, dir: stagingDirectory, force: true, install: false, silent: true });
2113
- renameCreateViteDotfiles(stagingDirectory);
2114
- cpSync(stagingDirectory, target, { recursive: true });
2115
- };
2116
- let written = [];
2117
- await tuiTasks(
2118
- [
2119
- { label: `create-vite (${adapter.label}) base ready`, run: copyBase },
2120
- {
2121
- label: `Lunora overlay applied (${adapter.label})`,
2122
- run: async () => {
2123
- written = await applyLunoraOverlay({ adapter, distTag: resolveDistTag(), logger, name, target });
2124
- }
2125
- }
2126
- ],
2127
- { end: "Project initialized!", start: "Project initializing…" }
2128
- );
2129
- logScaffoldSuccess(logger, written, target);
2130
- return { code: 0, files: [...collectFiles(target)], target };
2131
- } catch (error) {
2132
- if (error instanceof PromptCancelledError) {
2133
- throw error;
2134
- }
2135
- const message = error instanceof Error ? error.message : String(error);
2136
- logger.error(`failed to scaffold the ${adapter.label} base: ${message}`);
2137
- return { code: 1, files: [], target };
2138
- } finally {
2139
- rmSync(stagingRoot, { force: true, recursive: true });
2140
- }
2141
- };
2142
- const createMinimalViteConfig = (cwd, logger) => {
2143
- const target = join$1(cwd, "vite.config.ts");
2144
- try {
2145
- writeFileSync(target, MINIMAL_VITE_CONFIG, "utf8");
2146
- } catch (error) {
2147
- const message = error instanceof Error ? error.message : String(error);
2148
- logger.error(`init --in-place: could not write ${target}: ${message}`);
2149
- return { code: 1, files: [], target: cwd };
2150
- }
2151
- logger.success(`created ${target} with lunora() plugin`);
2152
- return { code: 0, files: [target], target: cwd };
2153
- };
2154
- const patchExistingViteConfig = (viteConfigPath, cwd, logger) => {
2155
- let source;
2156
- try {
2157
- source = readFileSync(viteConfigPath, "utf8");
2158
- } catch (error) {
2159
- const message = error instanceof Error ? error.message : String(error);
2160
- logger.error(`init --in-place: could not read ${viteConfigPath}: ${message}`);
2161
- return { code: 1, files: [], target: cwd };
2162
- }
2163
- const result = patchViteConfig(source);
2164
- if (!result.changed) {
2165
- logger.info(`${viteConfigPath}: ${result.reason ?? "no changes needed"}`);
2166
- return { code: 0, files: [], target: cwd };
2167
- }
2168
- try {
2169
- writeFileSync(viteConfigPath, result.code, "utf8");
2170
- } catch (error) {
2171
- const message = error instanceof Error ? error.message : String(error);
2172
- logger.error(`init --in-place: could not write ${viteConfigPath}: ${message}`);
2173
- return { code: 1, files: [], target: cwd };
2174
- }
2175
- logger.success(`patched ${viteConfigPath} — added lunora() plugin`);
2176
- return { code: 0, files: [viteConfigPath], target: cwd };
2177
- };
2178
- const scaffoldLunoraDirectory = (cwd, logger) => {
2179
- const lunoraDirectory = join$1(cwd, "lunora");
2180
- const schemaPath = join$1(lunoraDirectory, "schema.ts");
2181
- if (existsSync(schemaPath)) {
2182
- logger.info(`lunora/ already present — left ${schemaPath} untouched`);
2183
- return [];
2184
- }
2185
- const written = [];
2186
- try {
2187
- mkdirSync(lunoraDirectory, { recursive: true });
2188
- writeFileSync(schemaPath, SAMPLE_SCHEMA, "utf8");
2189
- written.push(schemaPath);
2190
- const functionPath = join$1(lunoraDirectory, "messages.ts");
2191
- if (!existsSync(functionPath)) {
2192
- writeFileSync(functionPath, SAMPLE_FUNCTION, "utf8");
2193
- written.push(functionPath);
2194
- }
2195
- logger.success(`scaffolded lunora/ (${String(written.length)} file(s))`);
2196
- } catch (error) {
2197
- const message = error instanceof Error ? error.message : String(error);
2198
- logger.error(`init --here: could not scaffold lunora/: ${message}`);
2199
- }
2200
- return written;
2201
- };
2202
- const printFrameworkNextSteps = (detection, logger) => {
2203
- const { adapter, class: frameworkClass, framework } = detection;
2204
- logger.info("");
2205
- logger.info(`detected framework: ${framework} (class ${frameworkClass})`);
2206
- logger.info("next steps:");
2207
- logger.info(` 1. install the adapter: pnpm add ${adapter} @lunora/client @lunora/runtime @lunora/server`);
2208
- logger.info(" 2. run codegen: lunora codegen");
2209
- if (frameworkClass === "A") {
2210
- logger.info(" 3. compose one worker: wrap your worker entry with");
2211
- logger.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })");
2212
- logger.info(` 4. add the provider: mount the ${adapter} provider in your root layout/route`);
2213
- logger.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component");
2214
- logger.info(" see https://lunora.sh/docs/frameworks/reactive-loaders");
2215
- } else if (frameworkClass === "B") {
2216
- logger.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook");
2217
- logger.info(` (${framework} owns its Cloudflare adapter — Lunora composes into its server entry)`);
2218
- logger.info(` 4. add the provider: mount the ${adapter} provider in your root layout`);
2219
- logger.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy");
2220
- } else {
2221
- logger.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react");
2222
- logger.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework");
2223
- }
2224
- logger.info("");
2225
- };
2226
- const findExistingViteConfig = (cwd) => {
2227
- for (const candidate of VITE_CONFIG_CANDIDATES) {
2228
- const full = join$1(cwd, candidate);
2229
- if (existsSync(full)) {
2230
- return full;
2231
- }
2232
- }
2233
- return void 0;
2234
- };
2235
- const patchOrCreateViteConfig = (cwd, framework, logger) => {
2236
- const viteConfigPath = findExistingViteConfig(cwd);
2237
- if (viteConfigPath === void 0) {
2238
- if (framework === "sveltekit" || framework === "nuxt" || framework === "astro") {
2239
- logger.info(`no Vite config found — ${framework} wires Lunora through its server entry (see next steps)`);
2240
- return { code: 0, files: [], target: cwd };
2241
- }
2242
- return createMinimalViteConfig(cwd, logger);
2243
- }
2244
- return patchExistingViteConfig(viteConfigPath, cwd, logger);
2245
- };
2246
- const runInPlaceInit = (cwd, logger) => {
2247
- const detection = detectFramework(cwd);
2248
- const viteResult = patchOrCreateViteConfig(cwd, detection.framework, logger);
2249
- if (viteResult.code !== 0) {
2250
- return viteResult;
2251
- }
2252
- const scaffolded = scaffoldLunoraDirectory(cwd, logger);
2253
- printFrameworkNextSteps(detection, logger);
2254
- return { code: 0, files: [...viteResult.files, ...scaffolded], target: cwd };
2255
- };
2256
- const offerIsInteractive = (options) => options.yes !== true && (options.prompt !== void 0 || (options.interactive ?? isInteractive()));
2257
- const maybeOfferExtras = async (options, projectDirectory) => {
2258
- const interactive = offerIsInteractive(options);
2259
- const preselected = options.add === void 0 ? [] : parseFeatureList(options.add, (message) => {
2260
- options.logger.warn(message);
2261
- });
2262
- const applyAll = async (plans) => {
2263
- if (plans.length === 0) {
2264
- return true;
2265
- }
2266
- if (options.dryRun === true) {
2267
- logWould(options.logger, `add ${plans.map((plan) => plan.label).join(", ")}`);
2268
- return true;
2269
- }
2270
- const buffered = [];
2271
- const applyLogger = isInteractive() ? {
2272
- error: (message) => {
2273
- buffered.push({ level: "error", message });
2274
- },
2275
- info: () => {
2276
- },
2277
- success: () => {
2278
- },
2279
- warn: (message) => {
2280
- buffered.push({ level: "warn", message });
2281
- }
2282
- } : options.logger;
2283
- const steps = plans.map((plan) => {
2284
- return {
2285
- running: `adding ${plan.label}…`,
2286
- task: () => runAddCommand({
2287
- allowUnsafeSource: options.allowUnsafeSource,
2288
- cwd: projectDirectory,
2289
- from: options.registryFrom,
2290
- logger: applyLogger,
2291
- names: [...plan.names],
2292
- ref: options.ref,
2293
- source: options.registrySource,
2294
- transformManifest: plan.transformManifest,
2295
- yes: true
2296
- })
2297
- };
2298
- });
2299
- const done = `added ${plans.map((plan) => plan.label).join(", ")}`;
2300
- const results = await withTuiBadgeProgress(BADGES.add, steps, done);
2301
- for (const { level, message } of buffered) {
2302
- options.logger[level](message);
2303
- }
2304
- return results.every((result) => result.code === 0);
2305
- };
2306
- const deps = {
2307
- applyAll,
2308
- interactive,
2309
- logger: options.logger,
2310
- multiSelect: options.prompt?.multiSelect ?? ((message, choices, settings) => tuiMultiSelect(message, choices, { ...settings, badge: BADGES.add })),
2311
- preselected: preselected.length > 0 ? preselected : void 0,
2312
- projectName: basename(projectDirectory),
2313
- select: options.prompt?.select ?? ((message, choices, settings) => tuiSelect(message, choices, { ...settings, badge: BADGES.add })),
2314
- text: options.prompt?.text ?? ((message, settings) => tuiText(message, { ...settings, badge: BADGES.add }))
2315
- };
2316
- if (preselected.length > 0) {
2317
- await offerRegistryExtras(deps);
2318
- return;
2319
- }
2320
- if (isInteractive()) {
2321
- await tuiHeadline(COPY.extras);
2322
- }
2323
- await offerRegistryExtras(deps);
2324
- };
2325
- const DEFAULT_FRAMEWORK = "react";
2326
- const FRAMEWORK_CHOICES = [
2327
- { description: "React SPA — official create-vite base + the Lunora layer (the default)", label: "React", value: "react" },
2328
- { description: "Vue SPA — create-vite base + Lunora", label: "Vue", value: "vue" },
2329
- { description: "Solid SPA — create-vite base + Lunora", label: "Solid", value: "solid" },
2330
- { description: "Svelte SPA — create-vite base + Lunora", label: "Svelte", value: "svelte" },
2331
- { description: "TanStack Start (React) — SSR with live-loader routes", label: "TanStack Start · React", value: "tanstack-start-react" },
2332
- { description: "TanStack Start (Solid)", label: "TanStack Start · Solid", value: "tanstack-start-solid" },
2333
- { description: "React Router (v7, framework mode) — SSR composed into the Lunora worker", label: "React Router", value: "react-router" },
2334
- { description: "Astro + a standalone Lunora worker", label: "Astro", value: "astro" },
2335
- { description: "AnalogJS (Angular) — single-worker, Lunora mounted in Nitro", label: "Analog", value: "analog" },
2336
- { description: "Nuxt (Vue) — single-worker, Lunora mounted in Nitro", label: "Nuxt", value: "nuxt" },
2337
- { description: "SvelteKit + a standalone Lunora worker", label: "SvelteKit", value: "sveltekit" },
2338
- { description: "Worker only — no frontend", label: "Standalone", value: "standalone" }
2339
- ];
2340
- const OVERLAY_VALUES = Object.keys(ADAPTERS).join("|");
2341
- const TEMPLATE_VALUES = FRAMEWORK_CHOICES.filter((choice) => !isOverlayFramework(choice.value)).map((choice) => choice.value).join("|");
2342
- const toScaffoldChoice = (value) => isOverlayFramework(value) ? { framework: value, kind: "overlay" } : { kind: "template", templateType: value };
2343
- const resolveScaffoldChoice = async (options) => {
2344
- if (options.vite !== void 0) {
2345
- return { framework: options.vite, kind: "overlay" };
2346
- }
2347
- if (options.templateType !== void 0) {
2348
- return { kind: "template", templateType: options.templateType };
2349
- }
2350
- if (!isInteractive() || options.yes === true) {
2351
- return { framework: DEFAULT_FRAMEWORK, kind: "overlay" };
2352
- }
2353
- return toScaffoldChoice(await tuiSelect(COPY.framework, FRAMEWORK_CHOICES, { badge: BADGES.tmpl, default: DEFAULT_FRAMEWORK }) ?? DEFAULT_FRAMEWORK);
2354
- };
2355
- const nonInteractiveInitError = (options) => {
2356
- if (isInteractive() || options.yes === true) {
2357
- return void 0;
2358
- }
2359
- const missing = [];
2360
- if (options.name === void 0) {
2361
- missing.push("a project name (`lunora init <name>`)");
2362
- }
2363
- if (options.templateType === void 0 && options.vite === void 0) {
2364
- missing.push(`a framework — \`--vite <${OVERLAY_VALUES}>\` for an SPA, or \`-t <${TEMPLATE_VALUES}>\` for a bespoke template`);
2365
- }
2366
- if (missing.length === 0) {
2367
- return void 0;
2368
- }
2369
- return `lunora init can't prompt in a non-interactive terminal — provide ${missing.join(" and ")}, or pass --yes to accept the defaults.`;
2370
- };
2371
- const scaffoldOverlayPath = async (options, framework, name, target) => {
2372
- if (!isOverlayFramework(framework)) {
2373
- options.logger.error(`init: unknown framework "${framework}". Supported overlays: ${Object.keys(ADAPTERS).join(", ")}.`);
2374
- return { code: 1, files: [], target };
2375
- }
2376
- if (!await verifyRemoteTemplate({ isLocal: options.overlayBaseFrom !== void 0, logger: options.logger })) {
2377
- return { code: 1, files: [], target };
2378
- }
2379
- mkdirSync(target, { recursive: true });
2380
- return scaffoldViteOverlay({ framework, logger: options.logger, name, overlayBaseFrom: options.overlayBaseFrom, target });
2381
- };
2382
- const scaffoldTemplatePath = async (options, templateType, name, target) => {
2383
- if (templateType === "next") {
2384
- options.logger.warn('template "next" is not yet available — re-run with `--vite react` or `-t standalone`.');
2385
- return { code: 1, files: [], target };
2386
- }
2387
- if (options.from !== void 0) {
2388
- return await scaffoldFromLocal(options.from, templateType, target, name, options.logger);
2389
- }
2390
- if (options.source !== void 0 && options.source.length > 0 && !options.allowUnsafeSource && !isSafeSource(options.source)) {
2391
- options.logger.error(
2392
- `init: refusing --source ${options.source} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`
2393
- );
2394
- return { code: 1, files: [], target };
2395
- }
2396
- if (!await verifyRemoteTemplate({ isLocal: false, logger: options.logger, source: resolveTemplateSource(templateType, options.source, options.ref) })) {
2397
- return { code: 1, files: [], target };
2398
- }
2399
- return scaffoldFromRemote({ logger: options.logger, name, ref: options.ref, source: options.source, target, templateType });
2400
- };
2401
- const scaffoldNewProject = async (options, cwd, recordTarget) => {
2402
- await tuiMoonrise("realtime backend on Cloudflare Workers + Durable Objects");
2403
- const blocked = nonInteractiveInitError(options);
2404
- if (blocked !== void 0) {
2405
- options.logger.error(blocked);
2406
- return { code: 1, files: [], target: "" };
2407
- }
2408
- const suggestedName = generateProjectName();
2409
- const rawName = options.name ?? await tuiText(COPY.name, { badge: BADGES.dir, default: suggestedName, placeholder: suggestedName });
2410
- const choice = await resolveScaffoldChoice(options);
2411
- const name = rawName.trim();
2412
- if (name.length === 0) {
2413
- options.logger.error(`init: refusing an empty project name — pass a directory name (e.g. \`lunora init my-app\`).`);
2414
- return { code: 1, files: [], target: "" };
2415
- }
2416
- if (name.includes("/") || name.includes("\\") || name === ".." || name === ".") {
2417
- options.logger.error(`init: refusing project name "${name}" — must not contain path separators or be "." / "..".`);
2418
- return { code: 1, files: [], target: "" };
2419
- }
2420
- const target = resolve(cwd, name);
2421
- const targetPreExisted = existsSync(target);
2422
- if (targetPreExisted) {
2423
- const entries = readdirSync(target);
2424
- if (entries.length > 0) {
2425
- options.logger.error(`target directory not empty: ${target}`);
2426
- return { code: 1, files: [], target };
2427
- }
2428
- }
2429
- if (options.dryRun === true) {
2430
- const what = choice.kind === "overlay" ? `the ${choice.framework} create-vite overlay` : `the ${choice.templateType} template`;
2431
- logWould(options.logger, `scaffold ${what} into ${target}`);
2432
- return { code: 0, files: [], target };
2433
- }
2434
- recordTarget(target, targetPreExisted);
2435
- return choice.kind === "overlay" ? scaffoldOverlayPath(options, choice.framework, name, target) : scaffoldTemplatePath(options, choice.templateType, name, target);
2436
- };
2437
- const resetScaffoldOnCancel = (cleanup, logger) => {
2438
- const { target, targetPreExisted } = cleanup;
2439
- if (target === void 0 || !existsSync(target)) {
2440
- return;
2441
- }
2442
- if (targetPreExisted === true) {
2443
- for (const entry of readdirSync(target)) {
2444
- rmSync(join$1(target, entry), { force: true, recursive: true });
2445
- }
2446
- } else {
2447
- rmSync(target, { force: true, recursive: true });
2448
- }
2449
- logger.info(`removed the partially-created project at ${target}`);
2450
- };
2451
- const runScaffoldStep = async (options, cwd, recordTarget) => {
2452
- if (options.inPlace !== true) {
2453
- return scaffoldNewProject(options, cwd, recordTarget);
2454
- }
2455
- if (options.dryRun === true) {
2456
- logWould(options.logger, `configure Lunora into ${cwd}`);
2457
- return { code: 0, files: [], target: cwd };
2458
- }
2459
- return runInPlaceInit(cwd, options.logger);
2460
- };
2461
- const runPostScaffold = async (options, result, cwd) => {
2462
- await maybeOfferExtras(options, result.target);
2463
- const installedManager = options.inPlace === true ? void 0 : await maybeOfferInstall(options, result.target);
2464
- if (options.inPlace !== true) {
2465
- await maybeOfferGit(options, result.target);
2466
- await printNextSteps(basename(result.target), installedManager, isInsideMonorepo(cwd));
2467
- await emitMascot(options.logger);
2468
- }
2469
- };
2470
- const scaffoldCiPipeline = (options, result, cwd) => {
2471
- if (result.code !== 0 || options.ci === void 0) {
2472
- return;
2473
- }
2474
- if (options.dryRun === true) {
2475
- logWould(options.logger, `scaffold a ${options.ci} CI deploy pipeline`);
2476
- return;
2477
- }
2478
- scaffoldCiWorkflow(options.inPlace === true ? cwd : result.target, options.ci, options.logger);
2479
- };
2480
- const runInitCommand = async (options) => {
2481
- const cwd = options.cwd ?? process.cwd();
2482
- const cleanup = {};
2483
- let result;
2484
- try {
2485
- result = await runScaffoldStep(options, cwd, (target, preExisted) => {
2486
- cleanup.target = target;
2487
- cleanup.targetPreExisted = preExisted;
2488
- });
2489
- if (result.code === 0 && result.target !== "") {
2490
- cleanup.target = void 0;
2491
- await runPostScaffold(options, result, cwd);
2492
- }
2493
- } catch (error) {
2494
- if (error instanceof PromptCancelledError) {
2495
- resetScaffoldOnCancel(cleanup, options.logger);
2496
- process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n");
2497
- return { code: 130, files: [], target: "" };
2498
- }
2499
- throw error;
2500
- }
2501
- scaffoldCiPipeline(options, result, cwd);
2502
- return result;
2503
- };
2504
- const isTemplate = (value) => value === "analog" || value === "astro" || value === "next" || value === "nuxt" || value === "react-router" || value === "standalone" || value === "sveltekit" || value === "tanstack-start-react" || value === "tanstack-start-solid";
2505
- const resolveCiProvider = (raw, logger) => {
2506
- if (raw === void 0) {
2507
- return void 0;
2508
- }
2509
- if (isCiProvider(raw)) {
2510
- return raw;
2511
- }
2512
- logger.warn(`init: unknown --ci "${raw}" — expected github | gitlab; skipping CI scaffold.`);
2513
- return void 0;
2514
- };
2515
- const execute = defineHandler(({ argument, cwd, logger, options }) => {
2516
- const templateType = options.template !== void 0 && isTemplate(options.template) ? options.template : void 0;
2517
- return runInitCommand({
2518
- add: options.add,
2519
- allowUnsafeSource: options.allowUnsafeSource === true,
2520
- cwd,
2521
- ci: resolveCiProvider(options.ci, logger),
2522
- dryRun: options.dryRun === true,
2523
- from: options.from,
2524
- inPlace: options.here === true,
2525
- interactive: options.interactive === true ? true : void 0,
2526
- logger,
2527
- name: argument[0],
2528
- ref: options.ref,
2529
- source: options.source,
2530
- templateType,
2531
- vite: options.vite,
2532
- yes: options.yes === true
2533
- });
2534
- });
2535
-
2536
- export { execute, isTemplate, resolveTemplateSource, runInitCommand };
1503
+ `,Bn="gh:anolilab/lunora/templates",Fn=e=>{const t=e.lastIndexOf(".");return t===-1?!1:Dn.has(e.slice(t))},Wn=/^[a-z0-9_][a-z0-9\-_]*$/u,qn=/([a-z0-9])([A-Z])/gu,Hn=/[^a-z0-9_]/gu,Kn=e=>{const t=e.replaceAll(qn,"$1-$2").toLowerCase().replaceAll(Hn,"-").split("-").filter(r=>r.length>0);return t.length>0?t.join("-"):"my-app"},zn=(e,t)=>e.replaceAll("{{name}}",t),Gn=async(e,t)=>{const r=new Set;for(const n of e)if(T(n)==="package.json")for(const a of Object.keys(Ee(S(n))))q(a)&&r.add(a);return Le(r,t)},Yn=(e,t,r)=>{let n;try{n=JSON.parse(e)}catch{return e}let a=e;for(const i of["dependencies","devDependencies"])for(const s of Object.keys(n[i]??{})){if(!q(s))continue;const o=r.get(s)??t,l=xt(a,[i,s],o,{formattingOptions:{insertSpaces:!0,tabSize:4}});a=Et(a,l)}return a},Jn=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],Qn=["cpu-features","protobufjs","ssh2"],Qe="pnpm-workspace.yaml",Xn=()=>["# 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:",...Jn.map(e=>` '${e}': true`),...Qn.map(e=>` '${e}': false`),""].join(`
1504
+ `),Xe=e=>{const t=u(e,Qe);f(t)||v(t,Xn(),"utf8")},H=e=>{const t=[];for(const r of kt(e,{includeDirs:!1,includeFiles:!0}))ye(r.path).isSymbolicLink()||t.push(r.path);return t},ve="vitejs/vite",ge=(e,t)=>{for(const r of H(e)){const n=u(t,j(e,r));I(S(n),{recursive:!0}),ct(r,n)}},Ze=async(e,t,r)=>{const n=H(e),a=[],i=Ae(),s=await Gn(n,i);for(const o of n){const l=j(e,o),c=u(t,l);I(S(c),{recursive:!0});const d=_(o);let p=Fn(o)?zn(d.toString("utf8"),r):void 0;p!==void 0&&T(o)==="package.json"&&(p=Yn(p,i,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:`${Bn}/${e}#${Ie(r)}`,Zn=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),R=(e,t)=>{e.info(`[dry-run] would ${t}`)},et=(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}),tt="Template files copied.",te=(e,t,r)=>{k()&&process.stdout.write(`
1505
+ `),e.success(`scaffolded ${String(t.length)} files into ${r}`)},ea=(e,t)=>{const{args:r,command:n}=At(e,t);return`${n} ${r.join(" ")}`},rt=(e,t)=>{let r=_e(e);for(;;){if(t(r))return!0;const n=S(r);if(n===r)return!1;r=n}},ta=e=>f(u(e,Qe))?!0:yt(e)?.workspaces!==void 0,re=e=>rt(e,ta),ra=e=>rt(e,t=>f(u(t,".git"))),na=async(e,t)=>{if(e.yes===!0||!k()||ra(S(t)))return;if(!await $e(C.git,{badge:w.git,defaultYes:!1})){await Me("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){R(e.logger,"initialize a git repository");return}const r=e.spawner??Re;(await Ut("Initializing a git repository…",()=>r({args:["init"],command:"git",cwd:t}))).code===0?await U("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},aa=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 i=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(k()){await jt(w.next,C.nextHeader,a,i);return}const s=a.map(o=>`${o.lead} ${o.code}${o.tail??""}`);s.push("",...i.map(o=>`${o.lead} ${o.code}${o.tail??""}`)),await U("next",C.nextHeader,s.join(`
1506
+ `))},oa=e=>e.yes!==!0&&(e.installPrompt!==void 0||k()),ia=async(e,t)=>{if(!oa(e)||re(S(t)))return;const r=St(e.packageManagerProbe),[n]=r;if(n===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>$e(C.install,{badge:w.deps,defaultYes:!0})))()){await Me("No problem! Remember to install dependencies after setup.");return}let i=n;if(r.length>1&&(i=e.installPrompt?await e.installPrompt.selectManager(r):await D(C.packageManager,r.map(d=>({label:d,value:d})),{badge:w.deps,default:n})??n),e.dryRun===!0){R(e.logger,`install dependencies with ${i}`);return}i==="pnpm"&&Xe(t);const s=e.spawner??Re,{args:o,command:l}=Se(i);await U("deps",`Installing dependencies with ${i}…`);const c=await s({args:o,command:l,cwd:t});if(c.code!==0){e.logger.warn(`\`${l} install\` exited with code ${String(c.code)} — run it yourself in ${T(t)}/.`);return}return await U("deps",`Dependencies installed with ${i}.`),i},sa=async(e,t,r,n,a,i)=>{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 o=await Ze(s,r,n);return o.length===0?et(a,r,s):(i(),te(a,o,r),{code:0,files:o,target:r})},la=async e=>{const{logger:t,markComplete:r,name:n,ref:a,source:i,target:s,templateType:o}=e,l=be(u(ke(),"lunora-init-fetch-")),c=u(l,"template");try{const d=i!==void 0&&i.length>0?a:await $t(a,t),p=G(o,i,d);let m,h=[];if(await Ne([{label:`${o} template fetched`,run:async()=>{m=await Ce(p,{cwd:l,dir:c,force:!0,install:!1,silent:!0})}},{label:`files copied into ${n}/`,run:async()=>{h=await Ze(c,s,n)}}],{end:tt,start:"Project initializing…"}),h.length===0)return et(t,s,m?.source??p);r();const x=H(c);return k()&&process.stdout.write(`
1507
+ `),t.info(m?.commit?`template: ${m.source} @ ${m.commit} (${String(x.length)} files)`:`template: ${m?.source??p} (${String(x.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}=br(d,{ref:Ie(a),remote:G(o,i,a),templateType:o});t.error(m);for(const h of p)t.warn(h);return{code:1,files:[],target:s}}finally{P(l,{force:!0,recursive:!0})}},ca=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const r=u(e,t);f(r)&&dt(r,u(e,`.${t.slice(1)}`))}},da=async e=>{const{framework:t,logger:r,markComplete:n,name:a,overlayBaseFrom:i,target:s}=e,o=F[t],l=be(u(ke(),"lunora-vite-base-"));try{let c;if(i!==void 0&&(c=u(i,`template-${o.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){ge(c,s);return}const m=u(l,"base"),h=await Tt(ve,"main",r),x=`github:${ve}/packages/create-vite/template-${o.createViteTemplate}#${h}`;await Ce(x,{cwd:l,dir:m,force:!0,install:!1,silent:!0}),ca(m),ge(m,s)};let p=[];return await Ne([{label:`create-vite (${o.label}) base ready`,run:d},{label:`Lunora overlay applied (${o.label})`,run:async()=>{p=await Rn({adapter:o,distTag:Ae(),logger:r,name:a,target:s})}}],{end:tt,start:"Project initializing…"}),n(),te(r,p,s),{code:0,files:[...H(s)],target:s}}catch(c){if(c instanceof X)throw c;const d=c instanceof Error?c.message:String(c);return r.error(`failed to scaffold the ${o.label} base: ${d}`),{code:1,files:[],target:s}}finally{P(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}),ua=(e,t)=>{const r=u(e,"vite.config.ts");try{v(r,Un,"utf8")}catch(n){return Y("write",r,n,e,t)}return t.success(`created ${r} with lunora() plugin`),{code:0,files:[r],target:e}},ha=(e,t,r)=>{let n;try{n=_(e,"utf8")}catch(i){return Y("read",e,i,t,r)}const a=Be(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(i){return Y("write",e,i,t,r)}return r.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},pa=(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{I(r,{recursive:!0}),v(n,jn,"utf8"),a.push(n);const i=u(r,"messages.ts");f(i)||(v(i,Vn,"utf8"),a.push(i)),t.success(`scaffolded lunora/ (${String(a.length)} file(s))`)}catch(i){const s=i instanceof Error?i.message:String(i);t.error(`init --here: could not scaffold lunora/: ${s}`)}return a},nt=e=>e==="sveltekit"||e==="nuxt"||e==="astro",ma=(e,t,r)=>{const{adapter:n,class:a,framework:i}=e;r.info(""),r.info(`detected framework: ${i} (class ${a})`),r.info("next steps:");const s=[n,"@lunora/client","@lunora/runtime","@lunora/server"];nt(i)||s.push("@lunora/vite"),r.info(` 1. install the adapter: ${ea(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(` (${i} 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("")},fa=(e,t,r)=>{if(nt(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=Ge(e);return n===void 0?ua(e,r):ha(n,e,r)},va=(e,t)=>{const r=lr(e),n=fa(e,r.framework,t);if(n.code!==0)return n;const a=pa(e,t);return ma(r,V(e),t),{code:0,files:[...n.files,...a],target:e}},ga=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??k())),we=async(e,t,r)=>{r.dryRun!==!0&&await an({apply:n=>wt(e,n),detected:gt(e),interactive:t,logger:r.logger,multiSelect:r.lintPrompt??((n,a,i)=>Te(n,a,{...i,badge:w.add}))})},wa=async(e,t)=>{const r=ga(e),n=e.add===void 0?[]:Gr(e.add,o=>{e.logger.warn(o)}),a=async o=>{if(o.length===0)return!0;if(e.dryRun===!0)return R(e.logger,`add ${o.map(h=>h.externalAuth===void 0?h.label:`${h.label} (and wire resolveIdentity)`).join(", ")}`),!0;const l=[],c=k()?{error:h=>{l.push({level:"error",message:h})},info:()=>{},success:()=>{},warn:h=>{l.push({level:"warn",message:h})}}:e.logger,d=o.map(h=>({running:`adding ${h.label}…`,task:()=>Yt({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 ${o.map(h=>h.label).join(", ")}`,m=await Vt(w.add,d,p);for(const{level:h,message:x}of l)e.logger[h](x);for(const[h,x]of o.entries())x.externalAuth!==void 0&&m[h]?.code===0&&Hr(t,x.externalAuth,e.logger);return m.every(h=>h.code===0)},i=e.auth===void 0?void 0:xr(e.auth,o=>{e.logger.warn(o)}),s={applyAll:a,auth:i,interactive:r,logger:e.logger,multiSelect:e.prompt?.multiSelect??((o,l,c)=>Te(o,l,{...c,badge:w.add})),preselected:n.length>0?n:void 0,projectName:T(t),resolveAuthUiItem:()=>{const o=Ee(t);if(!zt(o))return Gt(o)??"auth-ui-react"},select:e.prompt?.select??((o,l,c)=>D(o,l,{...c,badge:w.add})),selectAuth:e.prompt===void 0?(o,l,c)=>D(o,l,{...c,badge:w.add}):e.prompt.selectAuth??(()=>Promise.resolve("none")),text:e.prompt?.text??((o,l)=>Oe(o,{...l,badge:w.add}))};if(n.length>0||i!==void 0&&!r){const o=await he(s);return await we(t,r,e),o}return k()&&await Dt(C.extras),await he(s),await we(t,r,e),!0},K="react",at=[{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"}],ot=Object.keys(F).join("|"),it=at.filter(e=>!W(e.value)).map(e=>e.value),st=it.join("|"),ya=e=>W(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},ba=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!k()||e.yes===!0?{framework:K,kind:"overlay"}:ya(await D(C.framework,at,{badge:w.tmpl,default:K})??K),ka=e=>{if(k()||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 <${ot}>\` for an SPA, or \`-t <${st}>\` 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.`},xa=async(e,t,r,n,a)=>W(t)?await Je({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(I(n,{recursive:!0}),da({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(F).join(", ")}.`),{code:g.USAGE,files:[],target:n}),Ea=async(e,t,r,n,a)=>e.from!==void 0?await sa(e.from,t,n,r,e.logger,a):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!Zn(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 Je({isLocal:!1,logger:e.logger,source:G(t,e.source,e.ref)})?la({logger:e.logger,markComplete:a,name:r,ref:e.ref,source:e.source,target:n,templateType:t}):{code:1,files:[],target:n},_a=(e,t)=>{if(re(t))return;let r;try{r=V(e)}catch{return}r==="pnpm"&&Xe(e)},Ca=async(e,t,r)=>{await Pt("realtime backend on Cloudflare Workers + Durable Objects");const n=ka(e);if(n!==void 0)return e.logger.error(n),{code:g.USAGE,files:[],target:""};const a=$n(),i=e.name??await Oe(C.name,{badge:w.dir,default:a,placeholder:a}),s=await ba(e),o=i.trim();if(o.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:g.USAGE,files:[],target:""};if(o.includes("/")||o.includes("\\")||o===".."||o===".")return e.logger.error(`init: refusing project name "${o}" — must not contain path separators or be "." / "..".`),{code:g.USAGE,files:[],target:""};if(!Wn.test(o))return e.logger.error(`init: refusing project name "${o}" — a Cloudflare Worker name must be lowercase letters, digits, "-" or "_" (starting with a letter, digit or "_"), and wrangler rejects anything else. Try \`${Kn(o)}\`.`),{code:g.USAGE,files:[],target:""};const l=_e(t,o),c=ye(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 R(e.logger,`scaffold ${m} into ${l}`),{code:0,files:[],target:l}}r.record(l,d);const p=s.kind==="overlay"?await xa(e,s.framework,o,l,r.complete):await Ea(e,s.templateType,o,l,r.complete);return p.code===0&&_a(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))P(u(r,a),{force:!0,recursive:!0});else P(r,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${r}`)}},Sa=async(e,t,r)=>e.inPlace!==!0?Ca(e,t,r):e.dryRun===!0?(R(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):va(t,e.logger),La=async(e,t,r)=>{const n=await wa(e,t.target),a=e.inPlace===!0?void 0:await ia(e,t.target);if(e.inPlace!==!0){await na(e,t.target);const i=a??V(t.target);await aa(T(t.target),a,i,re(r)),await Kr(e.logger)}return n},Aa=(e,t,r)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){R(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const n=e.inPlace===!0?r:t.target;try{const a=V(n);ir(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.`)}},Ia=async e=>{const t=e.cwd??process.cwd(),r={};let n;try{n=await Sa(e,t,{complete:()=>{r.target=void 0},record:(a,i)=>{r.target=a,r.targetPreExisted=i}}),n.code===0&&n.target!==""?(r.target=void 0,await La(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 Aa(e,n,t),n},Ra=e=>typeof e=="string"&&it.includes(e),Oa=(e,t)=>{if(e!==void 0){if(ar(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},Ta=e=>e===void 0?{}:Ra(e)?{templateType:e}:W(e)?{vite:e}:{error:`init: unknown --template "${e}" — expected a bespoke template (${st}) or an overlay framework (${ot}).`},ro=It(({argument:e,cwd:t,logger:r,options:n})=>{const a=Ta(n.template);return"error"in a?(r.error(a.error),{code:g.USAGE}):Ia({add:n.add,auth:n.auth,allowUnsafeSource:n.allowUnsafeSource===!0,cwd:t,ci:Oa(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{at as FRAMEWORK_CHOICES,ro as execute,Ra as isTemplate,Ta as resolveTemplateFlag,G as resolveTemplateSource,Ia as runInitCommand};