@lunora/cli 1.0.0-alpha.469 → 1.0.0-alpha.470
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +12 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/cli.mjs +2 -2
- package/dist/packem_chunks/dispatch.mjs +1 -1
- package/dist/packem_chunks/handler.mjs +2 -2
- package/dist/packem_chunks/handler10.mjs +2 -1
- package/dist/packem_chunks/handler11.mjs +1 -1
- package/dist/packem_chunks/handler12.mjs +1 -1
- package/dist/packem_chunks/handler13.mjs +1 -3
- package/dist/packem_chunks/handler14.mjs +3 -1
- package/dist/packem_chunks/handler15.mjs +1 -1
- package/dist/packem_chunks/handler16.mjs +1 -1
- package/dist/packem_chunks/handler17.mjs +1 -1
- package/dist/packem_chunks/handler18.mjs +1 -1
- package/dist/packem_chunks/handler19.mjs +1 -1
- package/dist/packem_chunks/handler20.mjs +1 -7
- package/dist/packem_chunks/handler21.mjs +7 -2
- package/dist/packem_chunks/handler24.mjs +1 -1
- package/dist/packem_chunks/handler25.mjs +2 -1
- package/dist/packem_chunks/handler26.mjs +1 -2
- package/dist/packem_chunks/handler27.mjs +2 -99
- package/dist/packem_chunks/handler28.mjs +99 -3
- package/dist/packem_chunks/handler29.mjs +3 -15
- package/dist/packem_chunks/handler3.mjs +1 -1
- package/dist/packem_chunks/handler30.mjs +15 -1
- package/dist/packem_chunks/handler31.mjs +1 -1
- package/dist/packem_chunks/handler32.mjs +1 -0
- package/dist/packem_chunks/handler4.mjs +1 -1
- package/dist/packem_chunks/handler5.mjs +1 -3
- package/dist/packem_chunks/handler6.mjs +3 -1
- package/dist/packem_chunks/handler7.mjs +1 -1
- package/dist/packem_chunks/handler8.mjs +1 -1
- package/dist/packem_chunks/handler9.mjs +1 -2
- package/dist/packem_chunks/runDevCommand.mjs +1 -1
- package/dist/packem_chunks/runInitCommand.mjs +37 -27
- package/dist/packem_chunks/runRpcCommand.mjs +1 -1
- package/dist/packem_shared/createRecordingSpawner-DchLi0gR.mjs +1 -0
- package/dist/packem_shared/{plan-KTxWYvt_.mjs → plan-pog5AvMk.mjs} +1 -1
- package/dist/packem_shared/{planDevCommand-CEDLRkjW.mjs → planDevCommand-Bl6OrwXm.mjs} +1 -1
- package/dist/packem_shared/{resolve-target-C_ZloTvd.mjs → resolve-target-BRvw8Pf7.mjs} +1 -1
- package/dist/packem_shared/{runDeployCommand-5ng8LjBN.mjs → runDeployCommand-CNgOUx91.mjs} +1 -1
- package/dist/packem_shared/{vectorize-metadata-BVSF8z2h.mjs → vectorize-metadata-DK61NmVx.mjs} +1 -1
- package/dist/packem_shared/{wrangler-secrets-DlSlWvRH.mjs → wrangler-secrets-C9siMBwN.mjs} +1 -1
- package/package.json +8 -8
- package/dist/packem_shared/createRecordingSpawner-01ZngIwK.mjs +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync as f,mkdirSync as
|
|
1
|
+
import{existsSync as f,mkdirSync as L,writeFileSync as v,readFileSync as E,appendFileSync as st,readdirSync as J,rmSync as N,lstatSync as we,mkdtempSync as ye,copyFileSync as lt,renameSync as ct}from"node:fs";import{tmpdir as be}from"node:os";import{detectFramework as dt,DEV_VARS_EXAMPLE_FILE as ke,DEV_VARS_FILE as ut,isInteractive as b,LUNA_ART as ht,LUNA_NAME as pt,LUNA_SIGNOFF as mt,BADGES as w,paintAnswer as ft,detectLintTools as vt,readProjectDependencies as xe,applyLintIgnores as gt,readProjectManifest as wt}from"@lunora/config";import{readJsonSync as yt,walkSync as bt}from"@visulima/fs";import{relative as U,join as u,dirname as C,basename as O,resolve as Ee}from"@visulima/path";import{downloadTemplate as _e}from"giget";import{modify as kt,applyEdits as xt}from"jsonc-parser";import{join as Q,dirname as Et}from"node:path";import{EXIT_CODE as g}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{installArgsFor as Ce,execArgsFor as _t,detectPackageManager as j,detectInstalledManagers as Ct,runScriptCommand as At,addArgsFor as St}from"@lunora/config/cli";import{d as Lt}from"../packem_shared/command-BpMv2n0o.mjs";import It from"magic-string";import{Project as Rt,SyntaxKind as y}from"ts-morph";import{P as X}from"../packem_shared/prompt-cancelled-BvsNxg_Q.mjs";import{l as Ae,m as Ot,n as Se,o as Le,a as Tt}from"../packem_shared/resolve-Bdc9KEUv.mjs";import{defaultSpawner as Ie}from"../packem_shared/createRecordingSpawner-DchLi0gR.mjs";import{d as Mt,e as $t,f as Nt,a as Re,t as P,g as Oe,h as Pt,b as Te,i as Me,w as Dt,j as Ut,k as $e,l as jt}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{A as Ne,p as Vt,w as Bt,M as Ft,r as Wt,E as Pe,k as qt,e as Ht,c as De,l as Ue,i as Kt,f as zt}from"../packem_shared/storage-3GOIFVZm.mjs";import{r as Gt}from"../packem_shared/commands-CkuCMUP_.mjs";import{findWranglerFile as Yt,readWranglerJsonc as Jt,DEFAULT_OBSERVABILITY as Qt,CLOUDFLARE_TOOLCHAIN_VERSIONS as ne}from"@lunora/config/cloudflare";import{logStep as ae}from"../packem_shared/createLogger-4TujevyB.mjs";import{r as Xt}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import Zt from"node:dns/promises";const Z={bun:{githubCacheKey:void 0,githubSetupStep:` - uses: oven-sh/setup-bun@v2
|
|
2
2
|
`,gitlabImage:"oven/bun:1",gitlabProvisionScript:[],installCmd:"bun install --frozen-lockfile",lockfile:"bun.lockb"},npm:{githubCacheKey:"npm",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:[],installCmd:"npm ci",lockfile:"package-lock.json"},pnpm:{githubCacheKey:"pnpm",githubSetupStep:` - uses: pnpm/action-setup@v4
|
|
3
3
|
with:
|
|
4
4
|
version: latest
|
|
@@ -270,25 +270,25 @@ check:
|
|
|
270
270
|
- if: $CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_SOURCE_PROJECT_ID != $CI_PROJECT_ID
|
|
271
271
|
script:
|
|
272
272
|
- ${x(e,["deploy","--dry-run"])}
|
|
273
|
-
`},je={github:{file:Q(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{file:".gitlab-ci.yml",secretsHint:"CI/CD variables, Masked and Protected, scoped to the production environment (Settings → CI/CD → Variables)"}},rr=(e,t)=>e==="github"?er(t):tr(t),nr=e=>e==="github"||e==="gitlab",ar=(e,t,r,n={})=>{const a=Q(e,je[t].file);return f(a)&&n.overwrite!==!0?{path:a,skipped:!0,written:!1}:(
|
|
273
|
+
`},je={github:{file:Q(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{file:".gitlab-ci.yml",secretsHint:"CI/CD variables, Masked and Protected, scoped to the production environment (Settings → CI/CD → Variables)"}},rr=(e,t)=>e==="github"?er(t):tr(t),nr=e=>e==="github"||e==="gitlab",ar=(e,t,r,n={})=>{const a=Q(e,je[t].file);return f(a)&&n.overwrite!==!0?{path:a,skipped:!0,written:!1}:(L(Et(a),{recursive:!0}),v(a,rr(t,r),"utf8"),{path:a,skipped:!1,written:!0})},or=(e,t,r,n,a={})=>{const o=je[t];try{const s=ar(e,t,r,a);if(s.skipped)n.info(`--ci ${t}: ${o.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const i=Ce(r),l=[i.command,...i.args].join(" "),{installCmd:c,lockfile:d}=Z[r];n.success(`--ci ${t}: wrote ${o.file}`),n.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${o.secretsHint} to enable deploys.`),n.info(`--ci ${t}: run \`${l}\` and commit ${d} before pushing — the pipeline runs \`${c}\`.`)}return s}catch(s){const i=s instanceof Error?s.message:String(s);return n.warn(`--ci ${t}: could not write ${o.file} (${i})`),{path:Q(e,o.file),skipped:!1,written:!1}}},ir={astro:"@lunora/react",none:"@lunora/react",nuxt:"@lunora/vue","react-router":"@lunora/react","solid-start":"@lunora/solid",sveltekit:"@lunora/svelte","tanstack-start":"@lunora/react","tanstack-start-solid":"@lunora/solid",vinext:"@lunora/react"},sr=e=>{const t=dt(e);return{...t,adapter:ir[t.framework]}},$="lunora()",ie='import { lunora } from "@lunora/vite";',lr="@lunora/vite",cr="lunora",dr=e=>{for(const t of e.getStatements()){if(t.getKind()!==y.ExportAssignment)continue;const r=t.asKindOrThrow(y.ExportAssignment).getExpression();if(r.getKind()!==y.CallExpression)continue;const n=r.asKindOrThrow(y.CallExpression);if(n.getExpression().getText()!=="defineConfig")continue;const a=n.getArguments()[0];if(a?.getKind()===y.ObjectLiteralExpression)return a.asKindOrThrow(y.ObjectLiteralExpression)}},ur=e=>{for(const t of e.getStatements()){if(t.getKind()!==y.ExportAssignment)continue;const r=t.asKindOrThrow(y.ExportAssignment).getExpression();if(r.getKind()===y.ObjectLiteralExpression)return r.asKindOrThrow(y.ObjectLiteralExpression)}},hr=e=>e.getDescendantsOfKind(y.CallExpression).some(t=>t.getExpression().getText()===cr),pr=e=>e.getImportDeclarations().some(t=>t.getModuleSpecifierValue()===lr),mr=e=>new Rt({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}),fr=(e,t)=>{const r=t.getImportDeclarations().at(-1)?.getEnd()??0;r===0?e.prepend(`${ie}
|
|
274
274
|
`):e.appendLeft(r,`
|
|
275
|
-
${ie}`)},vr=(e,t)=>{const r=t.getProperty("plugins");if(r===void 0){const s=t.getProperties(),i=t.getStart()+1;if(s.length===0){e.appendLeft(i,` plugins: [${
|
|
276
|
-
`);return}const n=r.getDescendantsOfKind(y.ArrayLiteralExpression)[0];if(n===void 0)return"the Vite config's `plugins` is not an array literal — add `lunora()` to it by hand";const a=n.getElements();if(a.length===0){e.appendLeft(n.getStart()+1
|
|
275
|
+
${ie}`)},vr=(e,t)=>{const r=t.getProperty("plugins");if(r===void 0){const s=t.getProperties(),i=t.getStart()+1;if(s.length===0){e.appendLeft(i,` plugins: [${$}] `);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: [${$}],
|
|
276
|
+
`);return}const n=r.getDescendantsOfKind(y.ArrayLiteralExpression)[0];if(n===void 0)return"the Vite config's `plugins` is not an array literal — add `lunora()` to it by hand";const a=n.getElements();if(a.length===0){e.appendLeft(n.getStart()+1,$);return}const o=a[0];if(o===void 0)return"could not locate the first entry of the Vite config's `plugins` array";e.appendLeft(o.getStart(),`${$}, `)},Ve=e=>{const t=mr(e);if(hr(t))return{changed:!1,code:e,reason:"lunora plugin already present"};const r=dr(t)??ur(t);if(r===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const n=new It(e);pr(t)||fr(n,t);const a=vr(n,r);return a!==void 0?{changed:!1,code:e,reason:a}:{changed:!0,code:n.toString()}},gr=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,wr=/404|not found|could not find|no such/u,yr=(e,t)=>{const r=e instanceof Error?e.message:String(e),n=r.toLowerCase(),a=`failed to download template "${t.templateType}" from ${t.remote}: ${r}`;return wr.test(n)?{hints:[`Check the template name "${t.templateType}" and the ref "${t.ref}".`,"List/inspect available templates, or target a branch/tag with `--ref <branch>`."],message:`template "${t.templateType}" not found at ${t.remote}: ${r}`}:gr.test(n)?{hints:["You appear to be offline or unable to reach GitHub.","To scaffold without a network, point at a local template root: `lunora init --from <dir>`."],message:a}:{hints:["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],message:a}},Be=[{description:"No sign-in yet; add it later with `lunora add auth`",label:"None",value:"none"},{description:"Users and sessions in your own D1, via better-auth (@lunora/auth)",label:"Lunora auth",value:"lunora"},{description:"Clerk owns the session; the Worker verifies its session token",label:"Clerk",value:"clerk"},{description:"WorkOS AuthKit owns the session; the Worker verifies its access token",label:"WorkOS AuthKit",value:"workos"},{description:"Auth0 owns the session; the Worker verifies its access token",label:"Auth0",value:"auth0"}],se=Be.map(e=>e.value),ee={auth0:{clientSnippet:["// @auth0/auth0-react: <Auth0Provider authorizationParams={{ audience: AUTH0_AUDIENCE }} useRefreshTokens>","// const { getAccessTokenSilently, isLoading, user } = useAuth0();","// In a useEffect over [client, getAccessTokenSilently, isLoading, user?.sub]:","if (isLoading) return;","if (!user) return client.setAuthToken(null);","const fetchToken = () => getAccessTokenSilently().catch((error) => {",' if (["login_required", "missing_refresh_token"].includes(error?.error)) return null; // signed out'," throw error;","});","return setAuthTokenProvider(client, fetchToken, { subject: user.sub });"].join(`
|
|
277
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
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"}},br=e=>Object.hasOwn(ee,e),kr=(e,t)=>{const r=e.trim().toLowerCase();return se.includes(r)?r:(t(`init: unknown --auth "${e}" — expected ${se.join(" | ")}; skipping auth.`),"none")},xr=["lunora/app.ts","src/app.ts","lunora/server.ts","src/server.ts","src/server/index.ts","src/server/index.tsx","src/index.ts","src/worker.ts"],Er="virtual:lunora/worker",_r=["lunora.config.ts","lunora.config.mts","lunora.config.js","lunora.config.mjs"],Cr=["src","app","pages","plugins"],
|
|
280
|
-
`,t);return a===-1?e.length:a}if(r==="/"&&e[t+1]==="*"){const a=e.indexOf("*/",t+2);return a===-1?e.length:a+2}if(r!=='"'&&r!=="'"&&r!=="`")return t;let n=t+1;for(;n<e.length&&e[n]!==r;)n+=e[n]==="\\"?2:1;return n+1},Rr=(e,t)=>{let r=0,n=t;for(;n<e.length;){const a=Ir(e,n);if(a!==n){n=a;continue}const o=e[n]??"";le.lastIndex=n;const s=r===0?le.exec(e)??void 0:void 0;if(s!==void 0)return{at:n,indent:s[1]??" "};if(r===0&&o===";")return{at:n,indent:" "};r+=Sr.has(o)?1:0,r-=
|
|
279
|
+
`),envVars:["WORKOS_CLIENT_ID"],identity:"workosIdentity",identityFile:"workos",item:"auth-workos-jwt"}},br=e=>Object.hasOwn(ee,e),kr=(e,t)=>{const r=e.trim().toLowerCase();return se.includes(r)?r:(t(`init: unknown --auth "${e}" — expected ${se.join(" | ")}; skipping auth.`),"none")},xr=["lunora/app.ts","src/app.ts","lunora/server.ts","src/server.ts","src/server/index.ts","src/server/index.tsx","src/index.ts","src/worker.ts"],Er="virtual:lunora/worker",_r=["lunora.config.ts","lunora.config.mts","lunora.config.js","lunora.config.mjs"],Cr=["src","app","pages","plugins"],Ar=/\.(?:[jt]sx?|svelte|vue)$/u,H="new LunoraClient({",le=/\n([\t ]*)\.build(?:FrameworkWorker)?\(/uy,Sr=new Set(["(","[","{"]),Lr=new Set([")","]","}"]),Ir=(e,t)=>{const r=e[t];if(r==="/"&&e[t+1]==="/"){const a=e.indexOf(`
|
|
280
|
+
`,t);return a===-1?e.length:a}if(r==="/"&&e[t+1]==="*"){const a=e.indexOf("*/",t+2);return a===-1?e.length:a+2}if(r!=='"'&&r!=="'"&&r!=="`")return t;let n=t+1;for(;n<e.length&&e[n]!==r;)n+=e[n]==="\\"?2:1;return n+1},Rr=(e,t)=>{let r=0,n=t;for(;n<e.length;){const a=Ir(e,n);if(a!==n){n=a;continue}const o=e[n]??"";le.lastIndex=n;const s=r===0?le.exec(e)??void 0:void 0;if(s!==void 0)return{at:n,indent:s[1]??" "};if(r===0&&o===";")return{at:n,indent:" "};r+=Sr.has(o)?1:0,r-=Lr.has(o)?1:0,n+=1}},Or=(e,t,r)=>{const n=U(C(u(e,t)),u(e,"lunora","identity",r.identityFile));return`${n.startsWith(".")?n:`./${n}`}.js`},Tr=/\bresolveIdentity\b/u,Mr=/^import[^"']*["'][^"'\n]*["'][^\n]*\n/u,$r=(e,t,r,n)=>{const a=r.indexOf("defineApp<"),o=a===-1?void 0:Rr(r,a);if(o===void 0)return;if(r.includes(`${n.identity}(env)`))return{outcome:"already-wired"};if(Tr.test(r))return{outcome:"has-resolver"};const{at:s,indent:i}=o,l=`
|
|
281
281
|
${i}// Verify the provider's token on every request and feed it into ctx.auth (memoized for 5 s).
|
|
282
|
-
${i}.extend((env) => ({ resolveIdentity: ${n.identity}(env) }))`,c=`import { ${n.identity} } from "${
|
|
282
|
+
${i}.extend((env) => ({ resolveIdentity: ${n.identity}(env) }))`,c=`import { ${n.identity} } from "${Or(e,t,n)}";
|
|
283
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)}},Nr=(e,t)=>{for(const r of xr){const n=u(e,r),a=f(n)
|
|
284
|
+
import `,a),p=d===-1?void 0:Mr.exec(r.slice(d+1)),m=p==null?0:d+1+p[0].length;return{outcome:"wired",patched:r.slice(0,m)+c+r.slice(m,s)+l+r.slice(s)}},Nr=(e,t)=>{for(const r of xr){const n=u(e,r),a=f(n)?$r(e,r,E(n,"utf8"),t):void 0;if(a?.outcome==="wired"&&v(n,a.patched),a!==void 0)return{file:r,outcome:a.outcome}}},Pr=e=>{const t=Yt(e);return t!==void 0&&Jt(t).parsed?.main===Er},Dr=(e,t)=>{if(!(!Pr(e)||_r.some(r=>f(u(e,r)))))return v(u(e,"lunora.config.ts"),`import type { AppBuilder, LunoraConfig } from "./lunora/_generated/app";
|
|
285
285
|
import { ${t.identity} } from "./lunora/identity/${t.identityFile}";
|
|
286
286
|
|
|
287
287
|
export default {
|
|
288
288
|
// Verify the provider's token on every request and feed it into ctx.auth (memoized for 5 s).
|
|
289
289
|
app: (app: AppBuilder<object>): AppBuilder<object> => app.extend((env) => ({ resolveIdentity: ${t.identity}(env) })),
|
|
290
290
|
} satisfies LunoraConfig<object>;
|
|
291
|
-
`),"lunora.config.ts"},Fe=(e,t=0)=>t>3||!f(e)?[]:J(e,{withFileTypes:!0}).flatMap(r=>{const n=u(e,r.name);return r.isDirectory()?r.name==="node_modules"?[]:Fe(n,t+1):
|
|
291
|
+
`),"lunora.config.ts"},Fe=(e,t=0)=>t>3||!f(e)?[]:J(e,{withFileTypes:!0}).flatMap(r=>{const n=u(e,r.name);return r.isDirectory()?r.name==="node_modules"?[]:Fe(n,t+1):Ar.test(r.name)?[n]:[]}),Ur=e=>Cr.flatMap(t=>Fe(u(e,t))).filter(t=>{const r=E(t,"utf8");return!r.includes(H)||r.includes("authTokenOnUpgrade")?!1:(v(t,r.replaceAll(H,`${H} authTokenOnUpgrade: true,`)),!0)}),jr=(e,t)=>{const r=u(e,ke),n=u(e,ut),a=f(r)?E(r,"utf8"):"",o=f(n)?E(n,"utf8").split(`
|
|
292
292
|
`):[],s=t.envVars.filter(c=>!a.split(`
|
|
293
293
|
`).some(d=>d.startsWith(`${c}=`)));if(s.length===0)return!1;const i=s.map(c=>o.find(d=>d.startsWith(`${c}=`))??`${c}=`),l=a.length===0||a.endsWith(`
|
|
294
294
|
`)?"":`
|
|
@@ -297,13 +297,13 @@ ${i.join(`
|
|
|
297
297
|
`)}
|
|
298
298
|
`),!0},Vr=(e,t,r)=>{const n=ee[t],a=()=>{const s=Dr(e,n);return s===void 0?void 0:{file:s,outcome:"wired"}},o=Nr(e,n)??a();o===void 0?r.warn(`auth: add \`.extend((env) => ({ resolveIdentity: ${n.identity}(env) }))\` to your app builder (lunora.config.ts \`app\` hook or the Worker entry) — ${n.identity} is in lunora/identity/${n.identityFile}.ts.`):o.outcome==="already-wired"?r.info(`auth: ${o.file} already wires ${n.identity}; left as is.`):o.outcome==="has-resolver"?r.warn(`auth: ${o.file} already sets resolveIdentity, so it was left as is. Compose the two: \`resolveIdentity: composeIdentityResolvers([${n.identity}(env), <your resolver>])\` — ${n.identity} is in lunora/identity/${n.identityFile}.ts.`):r.success(`auth: wired ${n.identity} as resolveIdentity in ${o.file}`),jr(e,n)&&r.success(`auth: listed ${n.envVars.join(", ")} in ${ke}`);for(const s of Ur(e))r.success(`auth: turned on authTokenOnUpgrade in ${U(e,s)}`);r.info(`auth: hand the provider's token to Lunora once signed in (setAuthTokenProvider from lunorash/client or @lunora/client):
|
|
299
299
|
${n.clientSnippet}
|
|
300
|
-
Fill in the env vars the item wrote to .dev.vars.`)},D=async(e,t,r)=>{if(b()){await
|
|
300
|
+
Fill in the env vars the item wrote to .dev.vars.`)},D=async(e,t,r)=>{if(b()){await $t(w[e],t,r);return}if(process.stdout.write(`
|
|
301
301
|
`),r===void 0||r===""){ae(e,t);return}const n=r.split(`
|
|
302
302
|
`).map(a=>ft(a)).join(`
|
|
303
303
|
`);ae(e,`${t}
|
|
304
304
|
${n}`)},Br=async e=>{if(b()){await Mt();return}e.info(`
|
|
305
305
|
${ht}
|
|
306
|
-
${pt}: ${mt}`)},We=[{description:"LLMs via Workers AI (summarize, generate, stream)",label:"AI",value:"ai"},{description:"Sign-up / sign-in with @lunora/auth (asks which provider)",label:"Authentication",value:"auth"},{description:"Copy-in auth screens for your framework (sign in/up, reset, 2FA)",label:"Auth UI",value:"auth-ui"},{description:"Snapshot + restore your Durable Object data",label:"Backups",value:"backup"},{description:"Headless browser screenshots + PDFs",label:"Browser rendering",value:"browser"},{description:"Zero Trust identity via Cloudflare Access",label:"Cloudflare Access",value:"cloudflare-access"},{description:"Scheduled jobs via Cron Triggers (@lunora/scheduler)",label:"Cron jobs",value:"crons"},{description:"Cloudflare Email Workers + a dev mail catcher",label:"Transactional email",value:"email"},{description:"OpenFeature feature flags (ctx.flags)",label:"Feature flags",value:"flags"},{description:"External Postgres/MySQL via Hyperdrive",label:"Hyperdrive",value:"hyperdrive"},{description:"Stripe-first payments (checkout, subscription, webhooks)",label:"Payments",value:"payment"},{description:"Live presence / who's-online over hibernated WebSockets",label:"Presence",value:"presence"},{description:"Async message queues (push/pull consumers)",label:"Queues",value:"queue"},{description:"Typed R2 buckets + signed URLs (@lunora/storage)",label:"File storage",value:"storage"},{description:"Durable long-running workflows (step.do, sleep, branch)",label:"Workflows",value:"workflow"}],ce=We.map(e=>e.value),de=We.filter(e=>e.value!=="auth"),qe=new Set(["auth","auth-ui"]),Fr=e=>e==="email"?Pe:e,Wr=(e,t)=>{const r=[];for(const n of e.split(",").map(a=>a.trim()).filter(Boolean))ce.includes(n)?r.includes(n)||r.push(n):t(`init: unknown --add feature "${n}" — expected ${ce.join(" | ")}; skipping.`);return r},He=e=>e.resolveAuthUiItem===void 0?"auth-ui-react":e.resolveAuthUiItem(),qr=async e=>{const t=await Ht(e.select),r=await De(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:n=>Ue(n,r)}},Hr=async e=>{const t=await e.text(Ft,{placeholder:"you@yourdomain.com"}),r=Wt(t,n=>{e.logger.warn(n)});return{label:"email",names:[Pe],transformManifest:r===void 0?void 0:n=>qt(n,r)}},Kr=async(e,t)=>{const r=He(e);if(r===void 0){e.logger.error(`init: ${Ne}`);return}if(t)return{label:"auth-ui",names:[r]};const n=await De(e.text,e.projectName);return{label:"auth-ui",names:[r],transformManifest:a=>Ue(a,n)}},zr=async e=>{const t=await Vt(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:r=>Bt(r,t)}},Gr=(e,t)=>{const r=[];let n=!1;for(const a of t){if(a!=="auth-ui"){r.push({label:a,names:[Fr(a)]});continue}const o=He(e);if(o===void 0){e.logger.error(`init: ${Ne}`),n=!0;continue}r.push({label:a,names:[o]})}return{plans:r,refused:n}},Ke=e=>e!==void 0&&br(e)?{externalAuth:e,label:e,names:[ee[e].item]}:void 0,Yr={auth:qr,"auth-ui":async(e,t)=>Kr(e,t.includes("auth")),email:Hr,storage:zr},Jr=async e=>{const t=Ke(e.auth),r=e.auth!==void 0&&e.auth!=="lunora",n=new Set(r?(e.preselected??[]).filter(l=>qe.has(l)):[]),a=(e.preselected??[]).filter(l=>!n.has(l));for(const l of n)e.logger.warn(`--auth ${String(e.auth)} rules out Lunora auth; ignoring \`${l}\` from --add.`);e.auth==="lunora"&&!a.includes("auth")&&a.unshift("auth");const{plans:o,refused:s}=Gr(e,a);return t!==void 0&&o.unshift(t),await e.applyAll(o)&&!s&&n.size===0},ue=async e=>{if(e.preselected!==void 0&&e.preselected.length>0||e.auth!==void 0&&!e.interactive)return Jr(e);if(!e.interactive)return e.logger.info("tip: add features later with `lunora add <ai|auth|backup|browser|cloudflare-access|crons|email|flags|hyperdrive|payment|presence|queue|storage|workflow>`."),!0;const t=e.auth??await e.selectAuth("Which auth do you want?",Be,{default:"none"})??"none",r=Ke(t),n=t==="lunora"?de:de.filter(i=>!qe.has(i.value)),a=await e.multiSelect("Which features do you want to add?",n,{defaults:[]}),o=t==="lunora"&&!a.includes("auth")?["auth",...a]:a;if(o.length===0&&r===void 0)return!0;const s=r===void 0?[]:[r];for(const i of o){const l=Yr[i],c=l?await l(e,o):{label:i,names:[i]};c!==void 0&&s.push(c)}return await e.applyAll(s),!0},Qr=[{description:"Adds an ignores entry to eslint.config.js",label:"ESLint",value:"eslint"},{description:"Writes .prettierignore",label:"Prettier",value:"prettier"},{description:"Adds negated patterns to biome.json",label:"Biome",value:"biome"},{description:"Writes ignorePatterns to .oxlintrc.json",label:"oxlint (oxc)",value:"oxlint"}],Xr="Which linter/formatter do you use? We'll tell it to skip Lunora's generated files.",Zr=async e=>{const t=e.interactive?await e.multiSelect(Xr,Qr,{defaults:e.detected}):[...e.detected];if(t.length===0)return[];const r=e.apply(t);return Xt(r,e.logger),r}
|
|
306
|
+
${pt}: ${mt}`)},We=[{description:"LLMs via Workers AI (summarize, generate, stream)",label:"AI",value:"ai"},{description:"Sign-up / sign-in with @lunora/auth (asks which provider)",label:"Authentication",value:"auth"},{description:"Copy-in auth screens for your framework (sign in/up, reset, 2FA)",label:"Auth UI",value:"auth-ui"},{description:"Snapshot + restore your Durable Object data",label:"Backups",value:"backup"},{description:"Headless browser screenshots + PDFs",label:"Browser rendering",value:"browser"},{description:"Zero Trust identity via Cloudflare Access",label:"Cloudflare Access",value:"cloudflare-access"},{description:"Scheduled jobs via Cron Triggers (@lunora/scheduler)",label:"Cron jobs",value:"crons"},{description:"Cloudflare Email Workers + a dev mail catcher",label:"Transactional email",value:"email"},{description:"OpenFeature feature flags (ctx.flags)",label:"Feature flags",value:"flags"},{description:"External Postgres/MySQL via Hyperdrive",label:"Hyperdrive",value:"hyperdrive"},{description:"Stripe-first payments (checkout, subscription, webhooks)",label:"Payments",value:"payment"},{description:"Live presence / who's-online over hibernated WebSockets",label:"Presence",value:"presence"},{description:"Async message queues (push/pull consumers)",label:"Queues",value:"queue"},{description:"Typed R2 buckets + signed URLs (@lunora/storage)",label:"File storage",value:"storage"},{description:"Durable long-running workflows (step.do, sleep, branch)",label:"Workflows",value:"workflow"}],ce=We.map(e=>e.value),de=We.filter(e=>e.value!=="auth"),qe=new Set(["auth","auth-ui"]),Fr=e=>e==="email"?Pe:e,Wr=(e,t)=>{const r=[];for(const n of e.split(",").map(a=>a.trim()).filter(Boolean))ce.includes(n)?r.includes(n)||r.push(n):t(`init: unknown --add feature "${n}" — expected ${ce.join(" | ")}; skipping.`);return r},He=e=>e.resolveAuthUiItem===void 0?"auth-ui-react":e.resolveAuthUiItem(),qr=async e=>{const t=await Ht(e.select),r=await De(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:n=>Ue(n,r)}},Hr=async e=>{const t=await e.text(Ft,{placeholder:"you@yourdomain.com"}),r=Wt(t,n=>{e.logger.warn(n)});return{label:"email",names:[Pe],transformManifest:r===void 0?void 0:n=>qt(n,r)}},Kr=async(e,t)=>{const r=He(e);if(r===void 0){e.logger.error(`init: ${Ne}`);return}if(t)return{label:"auth-ui",names:[r]};const n=await De(e.text,e.projectName);return{label:"auth-ui",names:[r],transformManifest:a=>Ue(a,n)}},zr=async e=>{const t=await Vt(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:r=>Bt(r,t)}},Gr=(e,t)=>{const r=[];let n=!1;for(const a of t){if(a!=="auth-ui"){r.push({label:a,names:[Fr(a)]});continue}const o=He(e);if(o===void 0){e.logger.error(`init: ${Ne}`),n=!0;continue}r.push({label:a,names:[o]})}return{plans:r,refused:n}},Ke=e=>e!==void 0&&br(e)?{externalAuth:e,label:e,names:[ee[e].item]}:void 0,Yr={auth:qr,"auth-ui":async(e,t)=>Kr(e,t.includes("auth")),email:Hr,storage:zr},Jr=async e=>{const t=Ke(e.auth),r=e.auth!==void 0&&e.auth!=="lunora",n=new Set(r?(e.preselected??[]).filter(l=>qe.has(l)):[]),a=(e.preselected??[]).filter(l=>!n.has(l));for(const l of n)e.logger.warn(`--auth ${String(e.auth)} rules out Lunora auth; ignoring \`${l}\` from --add.`);e.auth==="lunora"&&!a.includes("auth")&&a.unshift("auth");const{plans:o,refused:s}=Gr(e,a);return t!==void 0&&o.unshift(t),await e.applyAll(o)&&!s&&n.size===0},ue=async e=>{if(e.preselected!==void 0&&e.preselected.length>0||e.auth!==void 0&&!e.interactive)return Jr(e);if(!e.interactive)return e.logger.info("tip: add features later with `lunora add <ai|auth|backup|browser|cloudflare-access|crons|email|flags|hyperdrive|payment|presence|queue|storage|workflow>`."),!0;const t=e.auth??await e.selectAuth("Which auth do you want?",Be,{default:"none"})??"none",r=Ke(t),n=t==="lunora"?de:de.filter(i=>!qe.has(i.value)),a=await e.multiSelect("Which features do you want to add?",n,{defaults:[]}),o=t==="lunora"&&!a.includes("auth")?["auth",...a]:a;if(o.length===0&&r===void 0)return!0;const s=r===void 0?[]:[r];for(const i of o){const l=Yr[i],c=l?await l(e,o):{label:i,names:[i]};c!==void 0&&s.push(c)}return await e.applyAll(s),!0},Qr=[{description:"Adds an ignores entry to eslint.config.js",label:"ESLint",value:"eslint"},{description:"Writes .prettierignore",label:"Prettier",value:"prettier"},{description:"Adds negated patterns to biome.json",label:"Biome",value:"biome"},{description:"Writes ignorePatterns to .oxlintrc.json",label:"oxlint (oxc)",value:"oxlint"}],Xr="Which linter/formatter do you use? We'll tell it to skip Lunora's generated files.",Zr=async e=>{const t=e.interactive?await e.multiSelect(Xr,Qr,{defaults:e.detected}):[...e.detected];if(t.length===0)return[];const r=e.apply(t);return Xt(r,e.logger),r},T="M 259.500 10.552 C 220.080 15.859, 182.424 32.566, 152.500 58.025 C 110.179 94.031, 85.380 137.183, 77.518 188.500 C 75.410 202.255, 74.569 225.677, 75.796 236.466 C 76.757 244.917, 76.683 245.692, 74.518 249.966 C 63.118 272.466, 53.141 303.876, 51.382 322.799 L 50.718 329.943 71.960 320.471 C 83.643 315.262, 93.326 311, 93.478 311 C 93.630 311, 96.547 316.063, 99.959 322.250 C 103.371 328.438, 107.249 334.850, 108.577 336.500 L 110.990 339.500 110.981 336 C 110.977 334.075, 111.499 324.991, 112.143 315.813 L 113.312 299.127 121.406 293.336 C 132.495 285.403, 149.593 271.554, 161 261.268 C 171.556 251.748, 189.116 235, 188.540 235 C 188.337 235, 183.069 238.648, 176.835 243.106 C 142.318 267.789, 68.537 314, 63.646 314 C 61.843 314, 72.791 281.179, 80.905 262.259 C 92.233 235.845, 107.473 212.389, 132.106 183.453 L 138.451 176 148.268 176 C 176.192 176, 197.512 187.154, 212.868 209.797 C 216.470 215.108, 217.035 216.595, 216.477 219.297 C 211.386 243.968, 202.359 274.496, 193.797 296 C 183.898 320.861, 167.147 352.101, 152.395 373.215 L 147.004 380.930 152.891 385.830 C 161.400 392.911, 165.563 396, 166.594 395.998 C 167.092 395.998, 168.772 391.641, 170.327 386.317 C 176.279 365.934, 188.422 338.749, 200.942 317.778 C 223.060 280.731, 256.432 244.369, 294.500 215.836 C 309.956 204.252, 313.937 201.603, 314.719 202.385 C 315.116 202.783, 315.449 213.096, 315.460 225.304 C 315.474 241.855, 315.021 250.405, 313.680 258.924 C 307.009 301.272, 291.175 336.677, 263.112 372 C 255.259 381.883, 227.182 410.673, 218.516 417.727 L 213.532 421.783 223.439 424.880 C 281.705 443.093, 349.165 436.018, 398.616 406.508 C 446.728 377.797, 483.322 331.466, 497.366 281.481 C 503.381 260.075, 504.480 250.741, 504.491 221 C 504.501 191.997, 503.598 184.047, 497.987 163.732 C 484.768 115.871, 452.505 72.708, 407.718 42.964 C 381.051 25.254, 352.818 14.828, 319.695 10.460 C 305.932 8.645, 273.298 8.695, 259.500 10.552",R=`/* The welcome page is a full-bleed starter — reset the browser's default
|
|
307
307
|
body margin/padding so it sits flush; everything else is scoped under
|
|
308
308
|
.lunora-welcome (collision-safe). */
|
|
309
309
|
body {
|
|
@@ -450,7 +450,7 @@ export default function App() {
|
|
|
450
450
|
<div className="lw-wrap">
|
|
451
451
|
<div className="brand">
|
|
452
452
|
<svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
|
|
453
|
-
<path d="${
|
|
453
|
+
<path d="${T}" fill="currentColor" fillRule="evenodd" />
|
|
454
454
|
</svg>
|
|
455
455
|
<span className="word">Lunora</span>
|
|
456
456
|
</div>
|
|
@@ -609,7 +609,7 @@ const toggle = (): void => {
|
|
|
609
609
|
<div class="lw-wrap">
|
|
610
610
|
<div class="brand">
|
|
611
611
|
<svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
|
|
612
|
-
<path d="${
|
|
612
|
+
<path d="${T}" fill="currentColor" fill-rule="evenodd" />
|
|
613
613
|
</svg>
|
|
614
614
|
<span class="word">Lunora</span>
|
|
615
615
|
</div>
|
|
@@ -765,7 +765,7 @@ export default function App() {
|
|
|
765
765
|
<div class="lw-wrap">
|
|
766
766
|
<div class="brand">
|
|
767
767
|
<svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
|
|
768
|
-
<path d="${
|
|
768
|
+
<path d="${T}" fill="currentColor" fill-rule="evenodd" />
|
|
769
769
|
</svg>
|
|
770
770
|
<span class="word">Lunora</span>
|
|
771
771
|
</div>
|
|
@@ -927,7 +927,7 @@ export default function App() {
|
|
|
927
927
|
<div class="lw-wrap">
|
|
928
928
|
<div class="brand">
|
|
929
929
|
<svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
|
|
930
|
-
<path d="${
|
|
930
|
+
<path d="${T}" fill="currentColor" fill-rule="evenodd" />
|
|
931
931
|
</svg>
|
|
932
932
|
<span class="word">Lunora</span>
|
|
933
933
|
</div>
|
|
@@ -1070,7 +1070,7 @@ const welcomeHtml = \`
|
|
|
1070
1070
|
<div class="lw-wrap">
|
|
1071
1071
|
<div class="brand">
|
|
1072
1072
|
<svg viewBox="0 0 543 446" role="img" aria-label="Lunora">
|
|
1073
|
-
<path d="${
|
|
1073
|
+
<path d="${T}" fill="currentColor" fill-rule="evenodd" />
|
|
1074
1074
|
</svg>
|
|
1075
1075
|
<span class="word">Lunora</span>
|
|
1076
1076
|
</div>
|
|
@@ -1430,14 +1430,18 @@ export const send = mutation
|
|
|
1430
1430
|
import { defineApp } from "../lunora/_generated/app.js";
|
|
1431
1431
|
|
|
1432
1432
|
interface Env extends Record<string, unknown> {
|
|
1433
|
+
ADMIN_REVOCATIONS: ShardNamespaceLike;
|
|
1433
1434
|
SHARD: ShardNamespaceLike;
|
|
1434
1435
|
}
|
|
1435
1436
|
|
|
1436
1437
|
const app = defineApp<Env>()
|
|
1437
1438
|
.shard((env) => env.SHARD)
|
|
1439
|
+
.adminRevocations((env) => env.ADMIN_REVOCATIONS)
|
|
1438
1440
|
.build();
|
|
1439
1441
|
|
|
1440
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";
|
|
1441
1445
|
export default app;
|
|
1442
1446
|
`,fn=`{ ${Object.entries(Qt).map(([e,t])=>`${JSON.stringify(e)}: ${JSON.stringify(t)}`).join(", ")} }`,vn=`{
|
|
1443
1447
|
"$schema": "node_modules/wrangler/config-schema.json",
|
|
@@ -1446,9 +1450,15 @@ export default app;
|
|
|
1446
1450
|
"compatibility_date": "2026-10-01",
|
|
1447
1451
|
"compatibility_flags": ["nodejs_compat"],
|
|
1448
1452
|
"durable_objects": {
|
|
1449
|
-
"bindings": [
|
|
1453
|
+
"bindings": [
|
|
1454
|
+
{ "name": "SHARD", "class_name": "ShardDO" },
|
|
1455
|
+
{ "name": "ADMIN_REVOCATIONS", "class_name": "AdminRevocationDO" },
|
|
1456
|
+
],
|
|
1450
1457
|
},
|
|
1451
|
-
"migrations": [
|
|
1458
|
+
"migrations": [
|
|
1459
|
+
{ "tag": "v1", "new_sqlite_classes": ["ShardDO"] },
|
|
1460
|
+
{ "tag": "v2", "new_sqlite_classes": ["AdminRevocationDO"] },
|
|
1461
|
+
],
|
|
1452
1462
|
"observability": ${fn},
|
|
1453
1463
|
}
|
|
1454
1464
|
`,he=[".wrangler",".env",".env.*","!.env.example",".dev.vars",".dev.vars.*","!.dev.vars.example",".lunora/",".lunora-cache","lunora/_generated"],gn=`# Lunora endpoint for the browser client.
|
|
@@ -1456,18 +1466,18 @@ export default app;
|
|
|
1456
1466
|
# Leave it unset to use the page origin; set it to point at a deployed Worker:
|
|
1457
1467
|
#
|
|
1458
1468
|
# VITE_LUNORA_URL=https://my-app.example.workers.dev
|
|
1459
|
-
`,wn={"@cloudflare/workers-types":ne["@cloudflare/workers-types"],wrangler:ne.wrangler},
|
|
1469
|
+
`,wn={"@cloudflare/workers-types":ne["@cloudflare/workers-types"],wrangler:ne.wrangler},A=(e,t,r,n)=>{const a=u(e,t);L(C(a),{recursive:!0}),v(a,r,"utf8"),n.push(a)},yn=/\r?\n/,bn=e=>{const t=u(e,".gitignore"),r=f(t)?E(t,"utf8"):"",n=new Set(r.split(yn)),a=he.filter(i=>!n.has(i));if(a.length===0)return;const o=a.some(i=>!i.startsWith("!"))?[...a.filter(i=>!i.startsWith("!")),...he.filter(i=>i.startsWith("!"))]:a,s=r.length>0&&!r.endsWith(`
|
|
1460
1470
|
`)?`
|
|
1461
1471
|
`:"";v(t,`${r}${s}
|
|
1462
1472
|
# Lunora
|
|
1463
1473
|
${o.join(`
|
|
1464
1474
|
`)}
|
|
1465
|
-
`,"utf8")},W=e=>e==="lunorash"||e.startsWith("@lunora/"),kn=(e,t,r,n)=>W(e)?n.get(e)??r:t,S=(e,t,r)=>({...e,[t]:r}),pe=(e,t,r)=>Object.fromEntries(Object.entries(e).map(([n,a])=>[n,kn(n,a,t,r)])),xn=async(e,t,r,n)=>{const a=u(e,"package.json"),o=yt(a);let s=S(o.dependencies??{},"lunorash",n);s=S(s,"@lunora/ratelimit",n),r.adapter.startsWith("@lunora/")&&(s=S(s,r.adapter,n));for(const[d,p]of Object.entries(r.extraDependencies??{}))s=S(s,d,p);let i=S(o.devDependencies??{},"@lunora/vite",n);i=S(i,"@lunora/studio",n);for(const[d,p]of Object.entries(wn))i=S(i,d,p);const l=[...Object.keys(s),...Object.keys(i)].filter(d=>W(d)),c=await
|
|
1466
|
-
`,"utf8")},En=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],ze=e=>En.map(t=>u(e,t)).find(t=>f(t)),_n=(e,t)=>{const r=ze(e);if(r===void 0){t.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");return}const n=Ve(E(r,"utf8"));n.changed&&v(r,n.code,"utf8")},Cn=async e=>{const{adapter:t,distTag:r,logger:n,name:a,target:o}=e,s=[];
|
|
1475
|
+
`,"utf8")},W=e=>e==="lunorash"||e.startsWith("@lunora/"),kn=(e,t,r,n)=>W(e)?n.get(e)??r:t,S=(e,t,r)=>({...e,[t]:r}),pe=(e,t,r)=>Object.fromEntries(Object.entries(e).map(([n,a])=>[n,kn(n,a,t,r)])),xn=async(e,t,r,n)=>{const a=u(e,"package.json"),o=yt(a);let s=S(o.dependencies??{},"lunorash",n);s=S(s,"@lunora/ratelimit",n),r.adapter.startsWith("@lunora/")&&(s=S(s,r.adapter,n));for(const[d,p]of Object.entries(r.extraDependencies??{}))s=S(s,d,p);let i=S(o.devDependencies??{},"@lunora/vite",n);i=S(i,"@lunora/studio",n);for(const[d,p]of Object.entries(wn))i=S(i,d,p);const l=[...Object.keys(s),...Object.keys(i)].filter(d=>W(d)),c=await Ae(l,n);o.name=t,o.imports={...o.imports,"#lunora/*":"./lunora/*"},o.dependencies=pe(s,n,c),o.devDependencies=pe(i,n,c),o.scripts={...o.scripts,codegen:"lunora codegen",deploy:"lunora deploy"},v(a,`${JSON.stringify(o,void 0,4)}
|
|
1476
|
+
`,"utf8")},En=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],ze=e=>En.map(t=>u(e,t)).find(t=>f(t)),_n=(e,t)=>{const r=ze(e);if(r===void 0){t.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");return}const n=Ve(E(r,"utf8"));n.changed&&v(r,n.code,"utf8")},Cn=async e=>{const{adapter:t,distTag:r,logger:n,name:a,target:o}=e,s=[];A(o,u("lunora","ratelimit","schema.ts"),un,s),A(o,u("lunora","schema.ts"),hn,s),A(o,u("lunora","messages.ts"),pn,s),A(o,u("src","server.ts"),mn,s),A(o,"wrangler.jsonc",vn.replaceAll("__NAME__",a),s),A(o,".env.example",gn,s);for(const i of t.files)A(o,i.path,i.contents,s);return _n(o,n),await xn(o,a,t,r),bn(o),s},An=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],Sn=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],me=e=>e[Math.floor(Math.random()*e.length)],Ln=()=>`${me(An)}-${me(Sn)}`,In=async()=>Zt.lookup("github.com").then(()=>!0,()=>!1),Rn=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,Ge=e=>{const t=Rn.exec(e);if(t===null)return;const[,r,n,a]=t;if(!(r===void 0||n===void 0))return{owner:r,ref:a??"HEAD",repo:n}},On=async e=>{const t=Ge(e);if(t===void 0)return;const r=`https://codeload.github.com/${t.owner}/${t.repo}/tar.gz/${t.ref}`;try{const n=await fetch(r,{method:"HEAD"});return n.status===404?!1:n.ok?!0:void 0}catch{return}},Ye=async e=>e.isLocal||!(e.source===void 0||Ge(e.source)!==void 0)?!0:await In()?e.source!==void 0&&await On(e.source)===!1?(e.logger.error(`template source not found: ${e.source} — double-check --ref / --source, or browse the templates at https://lunora.sh/docs.`),!1):!0:(e.logger.error("you appear to be offline — connect to the internet and try again, or scaffold from a local template with `--from <dir>`."),!1),_={extras:"Let's finish setting up your app.",framework:"Which framework should we launch?",git:"Initialize a new git repository? (optional)",install:"Install dependencies now?",name:"Where should we land your project?",nextHeader:"Liftoff confirmed — explore your project!",packageManager:"Which package manager?"},Tn=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),Mn=`import { defineConfig } from "vite";
|
|
1467
1477
|
import { lunora } from "@lunora/vite";
|
|
1468
1478
|
|
|
1469
1479
|
export default defineConfig({ plugins: [lunora()] });
|
|
1470
|
-
|
|
1480
|
+
`,$n=`import { defineSchema, defineTable, v } from "@lunora/server";
|
|
1471
1481
|
|
|
1472
1482
|
export default defineSchema({
|
|
1473
1483
|
messages: defineTable({
|
|
@@ -1490,8 +1500,8 @@ export const send = mutation
|
|
|
1490
1500
|
.mutation(async ({ args }) => {
|
|
1491
1501
|
return { channelId: args.channelId, text: args.text };
|
|
1492
1502
|
});
|
|
1493
|
-
`,Pn="gh:anolilab/lunora/templates",Dn=e=>{const t=e.lastIndexOf(".");return t===-1?!1
|
|
1494
|
-
`),Qe=e=>{const t=u(e,Je);f(t)||v(t,zn(),"utf8")},q=e=>{const t=[];for(const r of bt(e,{includeDirs:!1,includeFiles:!0}))we(r.path).isSymbolicLink()||t.push(r.path);return t},fe="vitejs/vite",ve=(e,t)=>{for(const r of q(e)){const n=u(t,U(e,r));
|
|
1495
|
-
`),e.success(`scaffolded ${String(t.length)} files into ${r}`)},Yn=(e,t)=>{const{args:r,command:n}=St(e,t);return`${n} ${r.join(" ")}`},tt=(e,t)=>{let r=Ee(e);for(;;){if(t(r))return!0;const n=C(r);if(n===r)return!1;r=n}},Jn=e=>f(u(e,Je))?!0:wt(e)?.workspaces!==void 0,re=e=>tt(e,Jn),Qn=e=>tt(e,t=>f(u(t,".git"))),Xn=async(e,t)=>{if(e.yes===!0||!b()||Qn(C(t)))return;if(!await
|
|
1496
|
-
`))},ea=e=>e.yes!==!0&&(e.installPrompt!==void 0||b()),ta=async(e,t)=>{if(!ea(e)||re(C(t)))return;const r=Ct(e.packageManagerProbe),[n]=r;if(n===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()
|
|
1497
|
-
`),t.info(m?.commit?`template: ${m.source} @ ${m.commit} (${String(k.length)} files)`:`template: ${m?.source??p} (${String(k.length)} files)`),te(t,h,s),{code:0,files:h,target:s}}catch(d){if(d instanceof X)throw d;const{hints:p,message:m}=yr(d,{ref:Ae(a),remote:G(i,o,a),templateType:i});t.error(m);for(const h of p)t.warn(h);return{code:1,files:[],target:s}}finally{N(l,{force:!0,recursive:!0})}},aa=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const r=u(e,t);f(r)&&ct(r,u(e,`.${t.slice(1)}`))}},oa=async e=>{const{framework:t,logger:r,markComplete:n,name:a,overlayBaseFrom:o,target:s}=e,i=B[t],l=ye(u(be(),"lunora-vite-base-"));try{let c;if(o!==void 0&&(c=u(o,`template-${i.createViteTemplate}`),!f(c)))return r.error(`create-vite base not found on disk: ${c}`),{code:g.NOT_FOUND,files:[],target:s};const d=async()=>{if(c!==void 0){ve(c,s);return}const m=u(l,"base"),h=await Tt(fe,"main",r),k=`github:${fe}/packages/create-vite/template-${i.createViteTemplate}#${h}`;await _e(k,{cwd:l,dir:m,force:!0,install:!1,silent:!0}),aa(m),ve(m,s)};let p=[];return await Oe([{label:`create-vite (${i.label}) base ready`,run:d},{label:`Lunora overlay applied (${i.label})`,run:async()=>{p=await Cn({adapter:i,distTag:Se(),logger:r,name:a,target:s})}}],{end:et,start:"Project initializing…"}),n(),te(r,p,s),{code:0,files:[...q(s)],target:s}}catch(c){if(c instanceof X)throw c;const d=c instanceof Error?c.message:String(c);return r.error(`failed to scaffold the ${i.label} base: ${d}`),{code:1,files:[],target:s}}finally{N(l,{force:!0,recursive:!0})}},Y=(e,t,r,n,a)=>(a.error(`init --in-place: could not ${e} ${t}: ${r instanceof Error?r.message:String(r)}`),{code:1,files:[],target:n}),ia=(e,t)=>{const r=u(e,"vite.config.ts");try{v(r,Mn,"utf8")}catch(n){return Y("write",r,n,e,t)}return t.success(`created ${r} with lunora() plugin`),{code:0,files:[r],target:e}},sa=(e,t,r)=>{let n;try{n=E(e,"utf8")}catch(o){return Y("read",e,o,t,r)}const a=Ve(n);if(!a.changed)return r.info(`${e}: ${a.reason??"no changes needed"}`),{code:0,files:[],target:t};try{v(e,a.code,"utf8")}catch(o){return Y("write",e,o,t,r)}return r.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},la=(e,t)=>{const r=u(e,"lunora"),n=u(r,"schema.ts");if(f(n))return t.info(`lunora/ already present — left ${n} untouched`),[];const a=[];try{A(r,{recursive:!0}),v(n,On,"utf8"),a.push(n);const o=u(r,"messages.ts");f(o)||(v(o,Nn,"utf8"),a.push(o)),t.success(`scaffolded lunora/ (${String(a.length)} file(s))`)}catch(o){const s=o instanceof Error?o.message:String(o);t.error(`init --here: could not scaffold lunora/: ${s}`)}return a},rt=e=>e==="sveltekit"||e==="nuxt"||e==="astro",ca=(e,t,r)=>{const{adapter:n,class:a,framework:o}=e;r.info(""),r.info(`detected framework: ${o} (class ${a})`),r.info("next steps:");const s=[n,"@lunora/client","@lunora/runtime","@lunora/server"];rt(o)||s.push("@lunora/vite"),r.info(` 1. install the adapter: ${Yn(t,s)}`),r.info(" 2. run codegen: lunora codegen"),a==="A"?(r.info(" 3. compose one worker: wrap your worker entry with"),r.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),r.info(` 4. add the provider: mount the ${n} provider in your root layout/route`),r.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),r.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):a==="B"?(r.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),r.info(` (${o} owns its Cloudflare adapter — Lunora composes into its server entry)`),r.info(` 4. add the provider: mount the ${n} provider in your root layout`),r.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(r.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),r.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),r.info("")},da=(e,t,r)=>{if(rt(t))return r.info(`${t} wires Lunora through its server entry, not a lunora() Vite plugin — leaving the Vite config alone (see next steps)`),{code:0,files:[],target:e};const n=ze(e);return n===void 0?ia(e,r):sa(n,e,r)},ua=(e,t)=>{const r=sr(e),n=da(e,r.framework,t);if(n.code!==0)return n;const a=la(e,t);return ca(r,j(e),t),{code:0,files:[...n.files,...a],target:e}},ha=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??b())),ge=async(e,t,r)=>{r.dryRun!==!0&&await Zr({apply:n=>gt(e,n),detected:vt(e),interactive:t,logger:r.logger,multiSelect:r.lintPrompt??((n,a,o)=>Te(n,a,{...o,badge:w.add}))})},pa=async(e,t)=>{const r=ha(e),n=e.add===void 0?[]:Wr(e.add,i=>{e.logger.warn(i)}),a=async i=>{if(i.length===0)return!0;if(e.dryRun===!0)return I(e.logger,`add ${i.map(h=>h.externalAuth===void 0?h.label:`${h.label} (and wire resolveIdentity)`).join(", ")}`),!0;const l=[],c=b()?{error:h=>{l.push({level:"error",message:h})},info:()=>{},success:()=>{},warn:h=>{l.push({level:"warn",message:h})}}:e.logger,d=i.map(h=>({running:`adding ${h.label}…`,task:()=>Gt({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:c,names:[...h.names],ref:e.ref,source:e.registrySource,transformManifest:h.transformManifest,yes:!0})})),p=`added ${i.map(h=>h.label).join(", ")}`,m=await jt(w.add,d,p);for(const{level:h,message:k}of l)e.logger[h](k);for(const[h,k]of i.entries())k.externalAuth!==void 0&&m[h]?.code===0&&Vr(t,k.externalAuth,e.logger);return m.every(h=>h.code===0)},o=e.auth===void 0?void 0:kr(e.auth,i=>{e.logger.warn(i)}),s={applyAll:a,auth:o,interactive:r,logger:e.logger,multiSelect:e.prompt?.multiSelect??((i,l,c)=>Te(i,l,{...c,badge:w.add})),preselected:n.length>0?n:void 0,projectName:T(t),resolveAuthUiItem:()=>{const i=xe(t);if(!Kt(i))return zt(i)??"auth-ui-react"},select:e.prompt?.select??((i,l,c)=>P(i,l,{...c,badge:w.add})),selectAuth:e.prompt===void 0?(i,l,c)=>P(i,l,{...c,badge:w.add}):e.prompt.selectAuth??(()=>Promise.resolve("none")),text:e.prompt?.text??((i,l)=>Re(i,{...l,badge:w.add}))};if(n.length>0||o!==void 0&&!r){const i=await ue(s);return await ge(t,r,e),i}return b()&&await Pt(_.extras),await ue(s),await ge(t,r,e),!0},K="react",nt=[{description:"React SPA — official create-vite base + the Lunora layer (the default)",label:"React",value:"react"},{description:"Vue SPA — create-vite base + Lunora",label:"Vue",value:"vue"},{description:"Solid SPA — create-vite base + Lunora",label:"Solid",value:"solid"},{description:"Solid 2.0 SPA — the Solid 2 line (@solidjs/web, vite-plugin-solid 3)",label:"Solid 2",value:"solid-v2"},{description:"Svelte SPA — create-vite base + Lunora",label:"Svelte",value:"svelte"},{description:"React SPA on Rsbuild — the Worker runs under wrangler dev behind the dev server",label:"React · Rsbuild",value:"rspack-react"},{description:"Next.js (App Router) — OpenNext on Cloudflare + a standalone Lunora worker",label:"Next.js",value:"next"},{description:"TanStack Start (React) — SSR with live-loader routes",label:"TanStack Start · React",value:"tanstack-start-react"},{description:"TanStack Start (React) on Rsbuild — SSR composed into the Lunora worker",label:"TanStack Start · React · Rsbuild",value:"tanstack-start-react-rspack"},{description:"SaaS kit — multi-tenant app on TanStack Start: organizations, projects, activity, admin",label:"SaaS kit",value:"saas"},{description:"TanStack Start (Solid)",label:"TanStack Start · Solid",value:"tanstack-start-solid"},{description:"Next.js App Router on Vite (vinext) — composed into the Lunora worker (experimental)",label:"vinext · App Router",value:"vinext"},{description:"Next.js Pages Router on Vite (vinext) — composed into one worker (experimental)",label:"vinext · Pages Router",value:"vinext-pages"},{description:"Astro (islands) — single-worker, Lunora composed into the adapter worker",label:"Astro",value:"astro"},{description:"AnalogJS (Angular) — single-worker, Lunora mounted in Nitro",label:"Analog",value:"analog"},{description:"Nuxt (Vue) — single-worker, Lunora mounted in Nitro",label:"Nuxt",value:"nuxt"},{description:"SvelteKit — single-worker, Lunora composed into the adapter worker",label:"SvelteKit",value:"sveltekit"},{description:"React Native (Expo) — an iOS/Android/web app + a Lunora worker backend",label:"React Native · Expo",value:"expo"},{description:"Worker only — no frontend",label:"Standalone",value:"standalone"}],at=Object.keys(B).join("|"),ot=nt.filter(e=>!F(e.value)).map(e=>e.value),it=ot.join("|"),ma=e=>F(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},fa=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!b()||e.yes===!0?{framework:K,kind:"overlay"}:ma(await P(_.framework,nt,{badge:w.tmpl,default:K})??K),va=e=>{if(b()||e.yes===!0)return;const t=[];if(e.name===void 0&&t.push("a project name (`lunora init <name>`)"),e.templateType===void 0&&e.vite===void 0&&t.push(`a framework — \`--vite <${at}>\` for an SPA, or \`-t <${it}>\` for a bespoke template`),t.length!==0)return`lunora init can't prompt in a non-interactive terminal — provide ${t.join(" and ")}, or pass --yes to accept the defaults.`},ga=async(e,t,r,n,a)=>F(t)?await Ye({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(A(n,{recursive:!0}),oa({framework:t,logger:e.logger,markComplete:a,name:r,overlayBaseFrom:e.overlayBaseFrom,target:n})):{code:1,files:[],target:n}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(B).join(", ")}.`),{code:g.USAGE,files:[],target:n}),wa=async(e,t,r,n,a)=>e.from!==void 0?await ra(e.from,t,n,r,e.logger,a):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!Gn(e.source)?(e.logger.error(`init: refusing --source ${e.source} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`),{code:g.USAGE,files:[],target:n}):await Ye({isLocal:!1,logger:e.logger,source:G(t,e.source,e.ref)})?na({logger:e.logger,markComplete:a,name:r,ref:e.ref,source:e.source,target:n,templateType:t}):{code:1,files:[],target:n},ya=(e,t)=>{if(re(t))return;let r;try{r=j(e)}catch{return}r==="pnpm"&&Qe(e)},ba=async(e,t,r)=>{await Nt("realtime backend on Cloudflare Workers + Durable Objects");const n=va(e);if(n!==void 0)return e.logger.error(n),{code:g.USAGE,files:[],target:""};const a=An(),o=e.name??await Re(_.name,{badge:w.dir,default:a,placeholder:a}),s=await fa(e),i=o.trim();if(i.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:g.USAGE,files:[],target:""};if(i.includes("/")||i.includes("\\")||i===".."||i===".")return e.logger.error(`init: refusing project name "${i}" — must not contain path separators or be "." / "..".`),{code:g.USAGE,files:[],target:""};if(!Un.test(i))return e.logger.error(`init: refusing project name "${i}" — a Cloudflare Worker name must be lowercase letters, digits, "-" or "_" (starting with a letter, digit or "_"), and wrangler rejects anything else. Try \`${Bn(i)}\`.`),{code:g.USAGE,files:[],target:""};const l=Ee(t,i),c=we(l,{throwIfNoEntry:!1});if(c?.isSymbolicLink()===!0)return e.logger.error(`init: refusing to scaffold into "${l}" — it is a symlink. Remove it, or scaffold into a different directory name.`),{code:g.CONFLICT,files:[],target:l};const d=c!==void 0;if(d&&J(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:g.CONFLICT,files:[],target:l};if(e.dryRun===!0){const m=s.kind==="overlay"?`the ${s.framework} create-vite overlay`:`the ${s.templateType} template`;return I(e.logger,`scaffold ${m} into ${l}`),{code:0,files:[],target:l}}r.record(l,d);const p=s.kind==="overlay"?await ga(e,s.framework,i,l,r.complete):await wa(e,s.templateType,i,l,r.complete);return p.code===0&&ya(l,t),p},z=(e,t)=>{const{target:r,targetPreExisted:n}=e;if(!(r===void 0||!f(r))){if(n===!0)for(const a of J(r))N(u(r,a),{force:!0,recursive:!0});else N(r,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${r}`)}},ka=async(e,t,r)=>e.inPlace!==!0?ba(e,t,r):e.dryRun===!0?(I(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):ua(t,e.logger),xa=async(e,t,r)=>{const n=await pa(e,t.target),a=e.inPlace===!0?void 0:await ta(e,t.target);if(e.inPlace!==!0){await Xn(e,t.target);const o=a??j(t.target);await Zn(T(t.target),a,o,re(r)),await Br(e.logger)}return n},Ea=(e,t,r)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){I(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const n=e.inPlace===!0?r:t.target;try{const a=j(n);or(n,e.ci,a,e.logger)}catch{e.logger.warn(`--ci ${e.ci}: could not detect a package manager for this project — skipped the CI pipeline.`)}},_a=async e=>{const t=e.cwd??process.cwd(),r={};let n;try{n=await ka(e,t,{complete:()=>{r.target=void 0},record:(a,o)=>{r.target=a,r.targetPreExisted=o}}),n.code===0&&n.target!==""?(r.target=void 0,await xa(e,n,t)||(n={...n,code:1})):n.code!==0&&z(r,e.logger)}catch(a){if(a instanceof X)return z(r,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw z(r,e.logger),a}return Ea(e,n,t),n},Ca=e=>typeof e=="string"&&ot.includes(e),La=(e,t)=>{if(e!==void 0){if(nr(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},Sa=e=>e===void 0?{}:Ca(e)?{templateType:e}:F(e)?{vite:e}:{error:`init: unknown --template "${e}" — expected a bespoke template (${it}) or an overlay framework (${at}).`},Qa=At(({argument:e,cwd:t,logger:r,options:n})=>{const a=Sa(n.template);return"error"in a?(r.error(a.error),{code:g.USAGE}):_a({add:n.add,auth:n.auth,allowUnsafeSource:n.allowUnsafeSource===!0,cwd:t,ci:La(n.ci,r),dryRun:n.dryRun===!0,from:n.from,inPlace:n.here===!0,interactive:n.interactive===!0?!0:void 0,logger:r,name:e[0],ref:n.ref,source:n.source,templateType:a.templateType,vite:n.vite??a.vite,yes:n.yes===!0})});export{nt as FRAMEWORK_CHOICES,Qa as execute,Ca as isTemplate,Sa as resolveTemplateFlag,G as resolveTemplateSource,_a as runInitCommand};
|
|
1503
|
+
`,Pn="gh:anolilab/lunora/templates",Dn=e=>{const t=e.lastIndexOf(".");return t===-1?!1:Tn.has(e.slice(t))},Un=/^[a-z0-9_][a-z0-9\-_]*$/u,jn=/([a-z0-9])([A-Z])/gu,Vn=/[^a-z0-9_]/gu,Bn=e=>{const t=e.replaceAll(jn,"$1-$2").toLowerCase().replaceAll(Vn,"-").split("-").filter(r=>r.length>0);return t.length>0?t.join("-"):"my-app"},Fn=(e,t)=>e.replaceAll("{{name}}",t),Wn=async(e,t)=>{const r=new Set;for(const n of e)if(O(n)==="package.json")for(const a of Object.keys(xe(C(n))))W(a)&&r.add(a);return Ae(r,t)},qn=(e,t,r)=>{let n;try{n=JSON.parse(e)}catch{return e}let a=e;for(const o of["dependencies","devDependencies"])for(const s of Object.keys(n[o]??{})){if(!W(s))continue;const i=r.get(s)??t,l=kt(a,[o,s],i,{formattingOptions:{insertSpaces:!0,tabSize:4}});a=xt(a,l)}return a},Hn=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],Kn=["cpu-features","protobufjs","ssh2"],Je="pnpm-workspace.yaml",zn=()=>["# pnpm reads its settings from here (the package.json `pnpm` field is no longer read).","# Pre-approve the toolchain's native build scripts so `pnpm install` runs them","# without the interactive `pnpm approve-builds` step; deny the optional native","# builds a scaffold doesn't need (so no C/C++ toolchain is required).","allowBuilds:",...Hn.map(e=>` '${e}': true`),...Kn.map(e=>` '${e}': false`),""].join(`
|
|
1504
|
+
`),Qe=e=>{const t=u(e,Je);f(t)||v(t,zn(),"utf8")},q=e=>{const t=[];for(const r of bt(e,{includeDirs:!1,includeFiles:!0}))we(r.path).isSymbolicLink()||t.push(r.path);return t},fe="vitejs/vite",ve=(e,t)=>{for(const r of q(e)){const n=u(t,U(e,r));L(C(n),{recursive:!0}),lt(r,n)}},Xe=async(e,t,r)=>{const n=q(e),a=[],o=Se(),s=await Wn(n,o);for(const i of n){const l=U(e,i),c=u(t,l);L(C(c),{recursive:!0});const d=E(i);let p=Dn(i)?Fn(d.toString("utf8"),r):void 0;p!==void 0&&O(i)==="package.json"&&(p=qn(p,o,s)),p===void 0?v(c,d):v(c,p,"utf8"),a.push(c)}return a},G=(e,t,r)=>t!==void 0&&t.length>0?t:`${Pn}/${e}#${Le(r)}`,Gn=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),I=(e,t)=>{e.info(`[dry-run] would ${t}`)},Ze=(e,t,r)=>(e.error(`init: the template at ${r} contains no files — nothing was scaffolded. Check the template name, \`--source\` layout and \`--ref\`.`),{code:g.NOT_FOUND,files:[],target:t}),et="Template files copied.",te=(e,t,r)=>{b()&&process.stdout.write(`
|
|
1505
|
+
`),e.success(`scaffolded ${String(t.length)} files into ${r}`)},Yn=(e,t)=>{const{args:r,command:n}=St(e,t);return`${n} ${r.join(" ")}`},tt=(e,t)=>{let r=Ee(e);for(;;){if(t(r))return!0;const n=C(r);if(n===r)return!1;r=n}},Jn=e=>f(u(e,Je))?!0:wt(e)?.workspaces!==void 0,re=e=>tt(e,Jn),Qn=e=>tt(e,t=>f(u(t,".git"))),Xn=async(e,t)=>{if(e.yes===!0||!b()||Qn(C(t)))return;if(!await Te(_.git,{badge:w.git,defaultYes:!1})){await Me("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){I(e.logger,"initialize a git repository");return}const r=e.spawner??Ie;(await Dt("Initializing a git repository…",()=>r({args:["init"],command:"git",cwd:t}))).code===0?await D("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},Zn=async(e,t,r,n)=>{const a=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&a.push({code:`${r} install`,lead:"Install dependencies with",tail:n?" from the workspace root":void 0}),a.push({code:At(r,"dev"),lead:"Run",tail:" to start the dev server."},{code:"lunora add",lead:"Add features like auth or storage using"});const o=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(b()){await Ut(w.next,_.nextHeader,a,o);return}const s=a.map(i=>`${i.lead} ${i.code}${i.tail??""}`);s.push("",...o.map(i=>`${i.lead} ${i.code}${i.tail??""}`)),await D("next",_.nextHeader,s.join(`
|
|
1506
|
+
`))},ea=e=>e.yes!==!0&&(e.installPrompt!==void 0||b()),ta=async(e,t)=>{if(!ea(e)||re(C(t)))return;const r=Ct(e.packageManagerProbe),[n]=r;if(n===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>Te(_.install,{badge:w.deps,defaultYes:!0})))()){await Me("No problem! Remember to install dependencies after setup.");return}let o=n;if(r.length>1&&(o=e.installPrompt?await e.installPrompt.selectManager(r):await P(_.packageManager,r.map(d=>({label:d,value:d})),{badge:w.deps,default:n})??n),e.dryRun===!0){I(e.logger,`install dependencies with ${o}`);return}o==="pnpm"&&Qe(t);const s=e.spawner??Ie,{args:i,command:l}=Ce(o);await D("deps",`Installing dependencies with ${o}…`);const c=await s({args:i,command:l,cwd:t});if(c.code!==0){e.logger.warn(`\`${l} install\` exited with code ${String(c.code)} — run it yourself in ${O(t)}/.`);return}return await D("deps",`Dependencies installed with ${o}.`),o},ra=async(e,t,r,n,a,o)=>{const s=u(e,t);if(!f(s))return a.error(`template not found in local source: ${s}`),{code:g.NOT_FOUND,files:[],target:r};const i=await Xe(s,r,n);return i.length===0?Ze(a,r,s):(o(),te(a,i,r),{code:0,files:i,target:r})},na=async e=>{const{logger:t,markComplete:r,name:n,ref:a,source:o,target:s,templateType:i}=e,l=ye(u(be(),"lunora-init-fetch-")),c=u(l,"template");try{const d=o!==void 0&&o.length>0?a:await Tt(a,t),p=G(i,o,d);let m,h=[];if(await $e([{label:`${i} template fetched`,run:async()=>{m=await _e(p,{cwd:l,dir:c,force:!0,install:!1,silent:!0})}},{label:`files copied into ${n}/`,run:async()=>{h=await Xe(c,s,n)}}],{end:et,start:"Project initializing…"}),h.length===0)return Ze(t,s,m?.source??p);r();const k=q(c);return b()&&process.stdout.write(`
|
|
1507
|
+
`),t.info(m?.commit?`template: ${m.source} @ ${m.commit} (${String(k.length)} files)`:`template: ${m?.source??p} (${String(k.length)} files)`),te(t,h,s),{code:0,files:h,target:s}}catch(d){if(d instanceof X)throw d;const{hints:p,message:m}=yr(d,{ref:Le(a),remote:G(i,o,a),templateType:i});t.error(m);for(const h of p)t.warn(h);return{code:1,files:[],target:s}}finally{N(l,{force:!0,recursive:!0})}},aa=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const r=u(e,t);f(r)&&ct(r,u(e,`.${t.slice(1)}`))}},oa=async e=>{const{framework:t,logger:r,markComplete:n,name:a,overlayBaseFrom:o,target:s}=e,i=B[t],l=ye(u(be(),"lunora-vite-base-"));try{let c;if(o!==void 0&&(c=u(o,`template-${i.createViteTemplate}`),!f(c)))return r.error(`create-vite base not found on disk: ${c}`),{code:g.NOT_FOUND,files:[],target:s};const d=async()=>{if(c!==void 0){ve(c,s);return}const m=u(l,"base"),h=await Ot(fe,"main",r),k=`github:${fe}/packages/create-vite/template-${i.createViteTemplate}#${h}`;await _e(k,{cwd:l,dir:m,force:!0,install:!1,silent:!0}),aa(m),ve(m,s)};let p=[];return await $e([{label:`create-vite (${i.label}) base ready`,run:d},{label:`Lunora overlay applied (${i.label})`,run:async()=>{p=await Cn({adapter:i,distTag:Se(),logger:r,name:a,target:s})}}],{end:et,start:"Project initializing…"}),n(),te(r,p,s),{code:0,files:[...q(s)],target:s}}catch(c){if(c instanceof X)throw c;const d=c instanceof Error?c.message:String(c);return r.error(`failed to scaffold the ${i.label} base: ${d}`),{code:1,files:[],target:s}}finally{N(l,{force:!0,recursive:!0})}},Y=(e,t,r,n,a)=>(a.error(`init --in-place: could not ${e} ${t}: ${r instanceof Error?r.message:String(r)}`),{code:1,files:[],target:n}),ia=(e,t)=>{const r=u(e,"vite.config.ts");try{v(r,Mn,"utf8")}catch(n){return Y("write",r,n,e,t)}return t.success(`created ${r} with lunora() plugin`),{code:0,files:[r],target:e}},sa=(e,t,r)=>{let n;try{n=E(e,"utf8")}catch(o){return Y("read",e,o,t,r)}const a=Ve(n);if(!a.changed)return r.info(`${e}: ${a.reason??"no changes needed"}`),{code:0,files:[],target:t};try{v(e,a.code,"utf8")}catch(o){return Y("write",e,o,t,r)}return r.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},la=(e,t)=>{const r=u(e,"lunora"),n=u(r,"schema.ts");if(f(n))return t.info(`lunora/ already present — left ${n} untouched`),[];const a=[];try{L(r,{recursive:!0}),v(n,$n,"utf8"),a.push(n);const o=u(r,"messages.ts");f(o)||(v(o,Nn,"utf8"),a.push(o)),t.success(`scaffolded lunora/ (${String(a.length)} file(s))`)}catch(o){const s=o instanceof Error?o.message:String(o);t.error(`init --here: could not scaffold lunora/: ${s}`)}return a},rt=e=>e==="sveltekit"||e==="nuxt"||e==="astro",ca=(e,t,r)=>{const{adapter:n,class:a,framework:o}=e;r.info(""),r.info(`detected framework: ${o} (class ${a})`),r.info("next steps:");const s=[n,"@lunora/client","@lunora/runtime","@lunora/server"];rt(o)||s.push("@lunora/vite"),r.info(` 1. install the adapter: ${Yn(t,s)}`),r.info(" 2. run codegen: lunora codegen"),a==="A"?(r.info(" 3. compose one worker: wrap your worker entry with"),r.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),r.info(` 4. add the provider: mount the ${n} provider in your root layout/route`),r.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),r.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):a==="B"?(r.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),r.info(` (${o} owns its Cloudflare adapter — Lunora composes into its server entry)`),r.info(` 4. add the provider: mount the ${n} provider in your root layout`),r.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(r.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),r.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),r.info("")},da=(e,t,r)=>{if(rt(t))return r.info(`${t} wires Lunora through its server entry, not a lunora() Vite plugin — leaving the Vite config alone (see next steps)`),{code:0,files:[],target:e};const n=ze(e);return n===void 0?ia(e,r):sa(n,e,r)},ua=(e,t)=>{const r=sr(e),n=da(e,r.framework,t);if(n.code!==0)return n;const a=la(e,t);return ca(r,j(e),t),{code:0,files:[...n.files,...a],target:e}},ha=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??b())),ge=async(e,t,r)=>{r.dryRun!==!0&&await Zr({apply:n=>gt(e,n),detected:vt(e),interactive:t,logger:r.logger,multiSelect:r.lintPrompt??((n,a,o)=>Oe(n,a,{...o,badge:w.add}))})},pa=async(e,t)=>{const r=ha(e),n=e.add===void 0?[]:Wr(e.add,i=>{e.logger.warn(i)}),a=async i=>{if(i.length===0)return!0;if(e.dryRun===!0)return I(e.logger,`add ${i.map(h=>h.externalAuth===void 0?h.label:`${h.label} (and wire resolveIdentity)`).join(", ")}`),!0;const l=[],c=b()?{error:h=>{l.push({level:"error",message:h})},info:()=>{},success:()=>{},warn:h=>{l.push({level:"warn",message:h})}}:e.logger,d=i.map(h=>({running:`adding ${h.label}…`,task:()=>Gt({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:c,names:[...h.names],ref:e.ref,source:e.registrySource,transformManifest:h.transformManifest,yes:!0})})),p=`added ${i.map(h=>h.label).join(", ")}`,m=await jt(w.add,d,p);for(const{level:h,message:k}of l)e.logger[h](k);for(const[h,k]of i.entries())k.externalAuth!==void 0&&m[h]?.code===0&&Vr(t,k.externalAuth,e.logger);return m.every(h=>h.code===0)},o=e.auth===void 0?void 0:kr(e.auth,i=>{e.logger.warn(i)}),s={applyAll:a,auth:o,interactive:r,logger:e.logger,multiSelect:e.prompt?.multiSelect??((i,l,c)=>Oe(i,l,{...c,badge:w.add})),preselected:n.length>0?n:void 0,projectName:O(t),resolveAuthUiItem:()=>{const i=xe(t);if(!Kt(i))return zt(i)??"auth-ui-react"},select:e.prompt?.select??((i,l,c)=>P(i,l,{...c,badge:w.add})),selectAuth:e.prompt===void 0?(i,l,c)=>P(i,l,{...c,badge:w.add}):e.prompt.selectAuth??(()=>Promise.resolve("none")),text:e.prompt?.text??((i,l)=>Re(i,{...l,badge:w.add}))};if(n.length>0||o!==void 0&&!r){const i=await ue(s);return await ge(t,r,e),i}return b()&&await Pt(_.extras),await ue(s),await ge(t,r,e),!0},K="react",nt=[{description:"React SPA — official create-vite base + the Lunora layer (the default)",label:"React",value:"react"},{description:"Vue SPA — create-vite base + Lunora",label:"Vue",value:"vue"},{description:"Solid SPA — create-vite base + Lunora",label:"Solid",value:"solid"},{description:"Solid 2.0 SPA — the Solid 2 line (@solidjs/web, vite-plugin-solid 3)",label:"Solid 2",value:"solid-v2"},{description:"Svelte SPA — create-vite base + Lunora",label:"Svelte",value:"svelte"},{description:"React SPA on Rsbuild — the Worker runs under wrangler dev behind the dev server",label:"React · Rsbuild",value:"rspack-react"},{description:"Next.js (App Router) — OpenNext on Cloudflare + a standalone Lunora worker",label:"Next.js",value:"next"},{description:"TanStack Start (React) — SSR with live-loader routes",label:"TanStack Start · React",value:"tanstack-start-react"},{description:"TanStack Start (React) on Rsbuild — SSR composed into the Lunora worker",label:"TanStack Start · React · Rsbuild",value:"tanstack-start-react-rspack"},{description:"SaaS kit — multi-tenant app on TanStack Start: organizations, projects, activity, admin",label:"SaaS kit",value:"saas"},{description:"TanStack Start (Solid)",label:"TanStack Start · Solid",value:"tanstack-start-solid"},{description:"Next.js App Router on Vite (vinext) — composed into the Lunora worker (experimental)",label:"vinext · App Router",value:"vinext"},{description:"Next.js Pages Router on Vite (vinext) — composed into one worker (experimental)",label:"vinext · Pages Router",value:"vinext-pages"},{description:"Astro (islands) — single-worker, Lunora composed into the adapter worker",label:"Astro",value:"astro"},{description:"AnalogJS (Angular) — single-worker, Lunora mounted in Nitro",label:"Analog",value:"analog"},{description:"Nuxt (Vue) — single-worker, Lunora mounted in Nitro",label:"Nuxt",value:"nuxt"},{description:"SvelteKit — single-worker, Lunora composed into the adapter worker",label:"SvelteKit",value:"sveltekit"},{description:"React Native (Expo) — an iOS/Android/web app + a Lunora worker backend",label:"React Native · Expo",value:"expo"},{description:"Worker only — no frontend",label:"Standalone",value:"standalone"}],at=Object.keys(B).join("|"),ot=nt.filter(e=>!F(e.value)).map(e=>e.value),it=ot.join("|"),ma=e=>F(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},fa=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!b()||e.yes===!0?{framework:K,kind:"overlay"}:ma(await P(_.framework,nt,{badge:w.tmpl,default:K})??K),va=e=>{if(b()||e.yes===!0)return;const t=[];if(e.name===void 0&&t.push("a project name (`lunora init <name>`)"),e.templateType===void 0&&e.vite===void 0&&t.push(`a framework — \`--vite <${at}>\` for an SPA, or \`-t <${it}>\` for a bespoke template`),t.length!==0)return`lunora init can't prompt in a non-interactive terminal — provide ${t.join(" and ")}, or pass --yes to accept the defaults.`},ga=async(e,t,r,n,a)=>F(t)?await Ye({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(L(n,{recursive:!0}),oa({framework:t,logger:e.logger,markComplete:a,name:r,overlayBaseFrom:e.overlayBaseFrom,target:n})):{code:1,files:[],target:n}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(B).join(", ")}.`),{code:g.USAGE,files:[],target:n}),wa=async(e,t,r,n,a)=>e.from!==void 0?await ra(e.from,t,n,r,e.logger,a):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!Gn(e.source)?(e.logger.error(`init: refusing --source ${e.source} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`),{code:g.USAGE,files:[],target:n}):await Ye({isLocal:!1,logger:e.logger,source:G(t,e.source,e.ref)})?na({logger:e.logger,markComplete:a,name:r,ref:e.ref,source:e.source,target:n,templateType:t}):{code:1,files:[],target:n},ya=(e,t)=>{if(re(t))return;let r;try{r=j(e)}catch{return}r==="pnpm"&&Qe(e)},ba=async(e,t,r)=>{await Nt("realtime backend on Cloudflare Workers + Durable Objects");const n=va(e);if(n!==void 0)return e.logger.error(n),{code:g.USAGE,files:[],target:""};const a=Ln(),o=e.name??await Re(_.name,{badge:w.dir,default:a,placeholder:a}),s=await fa(e),i=o.trim();if(i.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:g.USAGE,files:[],target:""};if(i.includes("/")||i.includes("\\")||i===".."||i===".")return e.logger.error(`init: refusing project name "${i}" — must not contain path separators or be "." / "..".`),{code:g.USAGE,files:[],target:""};if(!Un.test(i))return e.logger.error(`init: refusing project name "${i}" — a Cloudflare Worker name must be lowercase letters, digits, "-" or "_" (starting with a letter, digit or "_"), and wrangler rejects anything else. Try \`${Bn(i)}\`.`),{code:g.USAGE,files:[],target:""};const l=Ee(t,i),c=we(l,{throwIfNoEntry:!1});if(c?.isSymbolicLink()===!0)return e.logger.error(`init: refusing to scaffold into "${l}" — it is a symlink. Remove it, or scaffold into a different directory name.`),{code:g.CONFLICT,files:[],target:l};const d=c!==void 0;if(d&&J(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:g.CONFLICT,files:[],target:l};if(e.dryRun===!0){const m=s.kind==="overlay"?`the ${s.framework} create-vite overlay`:`the ${s.templateType} template`;return I(e.logger,`scaffold ${m} into ${l}`),{code:0,files:[],target:l}}r.record(l,d);const p=s.kind==="overlay"?await ga(e,s.framework,i,l,r.complete):await wa(e,s.templateType,i,l,r.complete);return p.code===0&&ya(l,t),p},z=(e,t)=>{const{target:r,targetPreExisted:n}=e;if(!(r===void 0||!f(r))){if(n===!0)for(const a of J(r))N(u(r,a),{force:!0,recursive:!0});else N(r,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${r}`)}},ka=async(e,t,r)=>e.inPlace!==!0?ba(e,t,r):e.dryRun===!0?(I(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):ua(t,e.logger),xa=async(e,t,r)=>{const n=await pa(e,t.target),a=e.inPlace===!0?void 0:await ta(e,t.target);if(e.inPlace!==!0){await Xn(e,t.target);const o=a??j(t.target);await Zn(O(t.target),a,o,re(r)),await Br(e.logger)}return n},Ea=(e,t,r)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){I(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const n=e.inPlace===!0?r:t.target;try{const a=j(n);or(n,e.ci,a,e.logger)}catch{e.logger.warn(`--ci ${e.ci}: could not detect a package manager for this project — skipped the CI pipeline.`)}},_a=async e=>{const t=e.cwd??process.cwd(),r={};let n;try{n=await ka(e,t,{complete:()=>{r.target=void 0},record:(a,o)=>{r.target=a,r.targetPreExisted=o}}),n.code===0&&n.target!==""?(r.target=void 0,await xa(e,n,t)||(n={...n,code:1})):n.code!==0&&z(r,e.logger)}catch(a){if(a instanceof X)return z(r,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw z(r,e.logger),a}return Ea(e,n,t),n},Ca=e=>typeof e=="string"&&ot.includes(e),Aa=(e,t)=>{if(e!==void 0){if(nr(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},Sa=e=>e===void 0?{}:Ca(e)?{templateType:e}:F(e)?{vite:e}:{error:`init: unknown --template "${e}" — expected a bespoke template (${it}) or an overlay framework (${at}).`},Qa=Lt(({argument:e,cwd:t,logger:r,options:n})=>{const a=Sa(n.template);return"error"in a?(r.error(a.error),{code:g.USAGE}):_a({add:n.add,auth:n.auth,allowUnsafeSource:n.allowUnsafeSource===!0,cwd:t,ci:Aa(n.ci,r),dryRun:n.dryRun===!0,from:n.from,inPlace:n.here===!0,interactive:n.interactive===!0?!0:void 0,logger:r,name:e[0],ref:n.ref,source:n.source,templateType:a.templateType,vite:n.vite??a.vite,yes:n.yes===!0})});export{nt as FRAMEWORK_CHOICES,Qa as execute,Ca as isTemplate,Sa as resolveTemplateFlag,G as resolveTemplateSource,_a as runInitCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{r as S,d as b}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as _,b as N,a as U}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as P}from"../packem_shared/command-BpMv2n0o.mjs";import{EXIT_CODE as i,exitCodeForStatus as E}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{r as S,d as b}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as _,b as N,a as U}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as P}from"../packem_shared/command-BpMv2n0o.mjs";import{EXIT_CODE as i,exitCodeForStatus as E}from"../packem_shared/EXIT_CODE-DQVhSE-1.mjs";import{a as I}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";const y=(r,t="--args")=>{if(r===void 0||r.length===0)return{};let e;try{e=JSON.parse(r)}catch(a){const s=a instanceof Error?a.message:String(a);throw new h("INTERNAL",`failed to parse ${t} as JSON: ${s}`,{cause:a})}if(typeof e!="object"||e===null||Array.isArray(e))throw new h("INTERNAL",`${t} must be a JSON object (e.g. '{"id":1}'), got ${Array.isArray(e)?"an array":typeof e}`);return e},O=/\/$/u,$="__lunora_admin__:runAs",T="__lunora_admin__:",k=async(r,t)=>{const e=await r.text();let a;try{a=JSON.parse(e)}catch{a=e}return t.info(JSON.stringify(a,void 0,2)),a},p=(r,t)=>{const e=t.body?.error?.code;t.runAs||t.status!==403||e!=="FORBIDDEN_SHARD"||r.info("this app authorizes per shard, so an anonymous call is denied — retry with --as <userId> to run as an authenticated user")},R=({args:r,claims:t,options:e,runAs:a})=>{const s=a?{args:{args:r,functionPath:e.functionPath,identity:t,userId:e.as},functionPath:$}:{args:r,functionPath:e.functionPath};return e.shard!==void 0&&(s.shardKey=e.shard),s},w=({cwd:r,logger:t,needsBearer:e,url:a})=>e?_(a,t,r):(I({cwd:r,url:a})??N(r)).replace(O,""),D=({args:r,claims:t},e)=>{try{return{args:y(r),claims:t===void 0?void 0:y(t,"--claims")}}catch(a){e.error(a instanceof Error?a.message:String(a));return}},J=async r=>{const t=r.cwd??process.cwd(),{logger:e}=r,a=r.as!==void 0&&r.as!=="";if(r.claims!==void 0&&!a){const d="--claims requires --as <userId> — extra identity claims only travel inside the admin-gated `runAs` dispatch.";return e.error(d),{body:void 0,code:i.USAGE,error:d,requestUrl:r.url??""}}const s=a||r.functionPath.startsWith(T),n=w({cwd:t,logger:e,needsBearer:s,url:r.url});if(n===void 0)return{body:void 0,code:i.USAGE,error:"could not resolve a usable worker URL",requestUrl:r.url??""};const o=`${n}/_lunora/rpc`,u=r.fetchImpl??U,m=D(r,e);if(m===void 0)return{body:void 0,code:i.USAGE,error:"could not parse --args / --claims as JSON",requestUrl:o};const{source:g,token:l}=s?S({cwd:t,token:r.token,url:n}):{};if(s&&l===void 0){const d="admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)";return e.error(d),{body:void 0,code:i.AUTH,error:d,requestUrl:o}}l!==void 0&&e.debug?.(`admin bearer from ${b(g)}`);const v={"content-type":"application/json",...l===void 0?{}:{authorization:`Bearer ${l}`}},A=R({args:m.args,claims:m.claims,options:r,runAs:a});e.info(`POST ${o} -> ${r.functionPath}${a?` (as ${r.as??""})`:""}`);const c=await u(o,{body:JSON.stringify(A),headers:v,method:"POST"}),f=await k(c,e);return p(e,{body:f,runAs:a,status:c.status}),{body:f,code:c.ok?0:E(c.status),error:c.ok?void 0:`${r.functionPath} failed: HTTP ${String(c.status)}`,requestUrl:o}},j=P(async({argument:r,cwd:t,format:e,logger:a,options:s})=>{const n=r[0];if(!n){const u="missing function path. Usage: lunora run <functionPath> [--args <json>]";return a.error(u),{code:i.USAGE,error:u}}const o=await J({args:s.args,as:s.as,claims:s.claims,cwd:t,format:e,functionPath:n,logger:a,shard:s.shard,token:s.token,url:s.url});return{code:o.code,data:{functionPath:n,requestUrl:o.requestUrl,result:o.body},error:o.error}});export{j as execute,k as readAndLogBody,J as runRpcCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{spawn as C}from"node:child_process";import{StringDecoder as v}from"node:string_decoder";import{LunoraError as g}from"@lunora/errors";const D=/[\s"%&<>^|]/u,L=500,N=e=>{let i="",r=0;for(const o of e)o==="\\"?r+=1:(i+=o==='"'?`${"\\".repeat(r*2+1)}"`:`${"\\".repeat(r)}${o}`,r=0);return i+"\\".repeat(r*2)},_=(e,i,r=process.platform)=>{if(r!=="win32"||e===process.execPath)return{args:[...i],command:e,shell:!1};const o=s=>s===""?'""':D.test(s)?`"${N(s)}"`:s;return{args:i.map(s=>o(s)),command:o(e),shell:!0}},x=e=>new Promise((i,r)=>{const o=typeof e.input=="string",s=e.captureStdout===!0,a=e.captureStdoutSilently===!0;let u="inherit";s||a?u="pipe":e.stdoutToStderr&&(u=2);const c=e.captureStderr===!0||e.captureStderrSilently===!0,d=_(e.command,e.args),t=C(d.command,d.args,{cwd:e.cwd??process.cwd(),env:e.env?{...process.env,...e.env}:process.env,shell:d.shell,detached:e.timeoutMs!==void 0&&process.platform!=="win32",stdio:[o?"pipe":"inherit",u,c?"pipe":"inherit"]}),p=e.timeoutMs===void 0?void 0:setTimeout(()=>{process.platform==="win32"||t.pid===void 0?t.kill("SIGKILL"):process.kill(-t.pid,"SIGKILL")},e.timeoutMs),f=new v("utf8"),m=new v("utf8");let w="",S="";c&&t.stderr&&t.stderr.on("data",n=>{S+=m.write(n),e.captureStderr===!0&&process.stderr.write(n)}),(s||a)&&t.stdout&&t.stdout.on("data",n=>{w+=f.write(n),s&&process.stdout.write(n)});let l=!1;t.on("error",n=>{if(clearTimeout(p),l=!0,n.code==="ENOENT"){r(new g("LOCAL_DEPENDENCY_MISSING",`\`${e.command}\` is not installed or not on your PATH — nothing was run.`,{cause:n}));return}r(n)});let h=0,T;const E=()=>{l||(l=!0,clearTimeout(T),clearTimeout(p),i({code:h,stderr:c?S+m.end():void 0,stdout:s||a?w+f.end():void 0}))};t.on("exit",(n,I)=>{h=n??(I?1:0),T=setTimeout(()=>{t.stdout?.destroy(),t.stderr?.destroy(),E()},L)}),t.on("close",E),o&&t.stdin&&(t.stdin.on("error",()=>{}),t.stdin.end(e.input))}),P=(e=0)=>{const i=[];return{calls:i,spawner:o=>(i.push({descriptor:o}),Promise.resolve({code:e}))}};export{P as createRecordingSpawner,x as defaultSpawner,_ as spawnShellCompat};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync as q,mkdirSync as Te,openSync as J,closeSync as X,statSync as Pe,readFileSync as Q,readSync as be}from"node:fs";import{join as N,dirname as _e}from"node:path";import{readServiceBindings as $e}from"@lunora/codegen";import{readLiveDevServerState as C,discoverContainerInfo as Re,streamContainerLogs as Ne,formatLunoraEvent as Ce,updateDevServerState as b,resolveLazyFunctions as Z,targetRunsOwnDevServer as D,resolveProjectTarget as ee,claimDevServerState as De,DEV_HANDOFF_ENV as Oe,clearDevServerState as E,readDevServerState as O,isDevServerReady as j,detectFramework as re,readProjectDependencyNames as xe,DEV_LOG_FILE_ENV as Ae,DEV_DAEMON_ENV as Me,LAZY_FUNCTIONS_ENV as Ue,readProjectManifest as Ge,isRecordedProcessCurrent as Fe,DEV_LOG_FILE as je,CODEGEN_ENV as te,isCodegenDisabled as Ve,planToolchainInvocation as We,startCelldDevSession as Be,resolveDeployDriver as ne,DEV_VARS_FILE as oe,parseDevVariableEntries as Ke}from"@lunora/config";import{warnCloudflareCliConfigOnce as ze,findWranglerFile as L,readWranglerJsonc as x,materializeDevWranglerConfig as He,materializeServiceDevConfigs as Ye}from"@lunora/config/cloudflare";import{f as qe}from"./free-port-DjbFhaaT.mjs";import{networkInterfaces as Je}from"node:os";import{spawn as ie,spawnSync as T}from"node:child_process";import{setTimeout as w}from"node:timers/promises";import{EXIT_CODE as se}from"./EXIT_CODE-DQVhSE-1.mjs";import{a as h}from"./output-format-DWe_tkTR.mjs";import{spawnShellCompat as ae,defaultSpawner as Xe}from"./createRecordingSpawner-01ZngIwK.mjs";import{isLunoraError as Qe}from"@lunora/errors";import{s as V}from"./index-oHZBGBwB.mjs";import{createInterface as Ze}from"node:readline";import{detectPackageManager as A,execArgsFor as ce,toolchainExecArgs as le,runScriptCommand as er}from"@lunora/config/cli";const rr=12e4,_=250,tr=1e3,nr="LUNORA_DEV_READY_TIMEOUT_MS",or=e=>{if(e!==void 0)return e;const r=Number(process.env[nr]??"");return Number.isFinite(r)&&r>0?r:rr},ir=async(e,r)=>{try{const n=AbortSignal.timeout(tr);return await(await fetch(new URL("/_lunora/status",e),{redirect:"manual",signal:r===void 0?n:AbortSignal.any([r,n])})).body?.cancel(),!0}catch{return!1}},de=async(e,r,n)=>{const t=Date.now()+n.timeoutMs;for(;n.signal?.aborted!==!0;){const o=r(C(e));if(o!==void 0)return o;if(Date.now()>=t)return;try{await w(n.intervalMs??500,void 0,{signal:n.signal})}catch{return}}},W=(e,r)=>{Ze({crlfDelay:Number.POSITIVE_INFINITY,input:e}).on("line",r)},sr=5e3,ue=(e,r,n,t)=>{if(e.length===0)return;const o=Ce(e);if(o){t[o.level](`[lunora] ${o.text}`);return}const i=`[${r}] ${e}`;n==="stderr"?t.warn(i):t.info(i)},ar=(e,r,n=process.platform,t=T)=>{try{if(r==="SIGKILL"&&n==="win32"&&e.pid!==void 0){t("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"});return}e.kill(r)}catch{}},fe=(e,r,n)=>{const t=e.direct===!0?{args:[...e.args],command:e.command,shell:!1}:ae(e.command,e.args),o=ie(t.command,t.args,{cwd:e.cwd??process.cwd(),env:e.env?{...process.env,...e.env}:process.env,shell:t.shell,stdio:[e.direct===!0?"ignore":"inherit","pipe","pipe"]});return W(o.stdout,i=>{r(i,"stdout")}),W(o.stderr,i=>{r(i,"stderr")}),{exited:new Promise(i=>{o.on("error",s=>{n?.(s),i(1)}),o.on("exit",(s,a)=>{i(s??(a?1:0))})}),kill:i=>{ar(o,i)}}},vt=(e,r)=>fe(e,(n,t)=>{ue(n.trimEnd(),e.tag,t,r)},n=>{r.error(`[${e.tag}] failed to start: ${n.message}`)}),gt=(e,r)=>{if(process.env.LUNORA_CONTAINER_LOGS==="0")return;const t=Re(e,"lunora").containers.map(o=>({className:o.className,exportName:o.exportName}));if(t.length!==0)return Ne({containers:t,onLine:o=>{const i=`[container:${o.name}] ${o.text}`;o.level==="error"?r.warn(i):r.info(i)},onUnavailable:o=>{r.warn(`[container] Docker engine unreachable — container logs unavailable (${o})`)}})},pt=async e=>{e.readyProbe?.abort(),await e.tunnel?.close(),await e.codegen?.close().catch(()=>{}),e.containerLogs?.close(),await e.studio?.close().catch(()=>{}),await e.hyperdrive?.stop().catch(()=>{});try{e.remoteCleanup?.(),e.serviceConfigCleanup?.()}catch{}},mt=async e=>await new Promise(r=>{const n={},t=s=>{e.info(`received ${s} — shutting down`),n.sigint&&process.off("SIGINT",n.sigint),n.sigterm&&process.off("SIGTERM",n.sigterm),r(0)},o=()=>{t("SIGINT")},i=()=>{t("SIGTERM")};n.sigint=o,n.sigterm=i,process.on("SIGINT",o),process.on("SIGTERM",i)}),wt=async(e,r,n)=>{let t=0,o;const i=l=>{e.kill(l),r?.kill(l)},s=()=>{t+=1,t===1?(n.info("received SIGINT — shutting down (press Ctrl-C again to force-kill)"),i("SIGTERM"),o=setTimeout(()=>{i("SIGKILL")},sr),o.unref()):i("SIGKILL")},a=()=>{i("SIGTERM")};process.on("SIGINT",s),process.on("SIGTERM",a);const c=await Promise.race([e.exited.then(l=>({code:l,who:"worker"})),...r===void 0?[]:[r.exited.then(l=>({code:l,who:"sidecar"}))]]);return r!==void 0&&(c.who==="sidecar"?(n.warn("[worker] the Lunora sidecar (wrangler dev) exited — shutting down the framework dev server"),e.kill("SIGTERM")):r.kill("SIGTERM"),await Promise.allSettled([e.exited,r.exited])),o&&clearTimeout(o),process.off("SIGINT",s),process.off("SIGTERM",a),c.code},y="2026.9.3",cr="https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/",lr=/version (\S+)/u,B=/https:\/\/[\da-z-]+\.trycloudflare\.com/u,dr="1s",ur=5e3,K=async(e,r)=>await Promise.race([e.then(()=>!0),w(r,!1,{ref:!1})]),fr=6e4,vr='Vite answers 403 for hosts it does not know — add `server: { allowedHosts: [".trycloudflare.com"] }` to vite.config if the URL is blocked.',gr=async e=>{const r=`Install or update it: ${cr} (macOS: \`brew install cloudflared\`).`;let n;try{const o=await e({args:["--version"],captureStdoutSilently:!0,command:"cloudflared"});if(o.code!==0)return{message:`\`cloudflared --version\` exited ${String(o.code)}. ${r}`,ok:!1};n=o.stdout??""}catch(o){return Qe(o)&&o.code==="LOCAL_DEPENDENCY_MISSING"?{message:`--tunnel needs \`cloudflared\` ${y} or newer, and it is not on your PATH. ${r}`,ok:!1}:{message:`\`cloudflared --version\` could not run: ${o instanceof Error?o.message:String(o)}. ${r}`,ok:!1}}const t=V.coerce(lr.exec(n)?.[1])?.version;return t===void 0?{ok:!0,version:void 0}:V.gte(t,y)?{ok:!0,version:t}:{message:`--tunnel needs \`cloudflared\` ${y} or newer (protected quick tunnels); found ${t}. ${r}`,ok:!1}},pr=e=>{const r=[],n=[];for(const t of e??[]){const o=t.split(",").map(i=>i.trim()).filter(i=>i.length>0);o.length>0&&(n.push(...o.filter(i=>!i.includes("@"))),r.push(o.join(",")))}return{entries:r,invalid:n}},mr=(e,r)=>["tunnel","--url",e,"--output","json","--grace-period",dr,...r.flatMap(n=>["--allowed-mail",n])],wr=e=>{let r;try{r=JSON.parse(e)}catch{r=void 0}if(typeof r=="object"&&r!==null){const n=r,t=typeof n.message=="string"?n.message:"";return{level:typeof n.level=="string"?n.level:void 0,text:t,url:B.exec(t)?.[0]}}return{level:void 0,text:e,url:B.exec(e)?.[0]}},hr=e=>{e.warn(" ⚠ PUBLIC TUNNEL: anyone with the tunnel URL can reach this dev server — there is no sign-in in front of it."),e.warn(" Protect it with a one-time-PIN email allow-list: lunora dev --tunnel --allow-mail you@example.com"),e.warn(" (repeat --allow-mail, pass a comma-separated list, or allow a whole domain with '*@example.com')")},Sr=async(e,r,n,{intervalMs:t,timeoutMs:o=fr}={})=>{const i=await de(e,s=>s?.mode==="vite"?{origin:s.url,ownerPid:s.pid}:void 0,{intervalMs:t,signal:n,timeoutMs:o});return i===void 0&&!n.aborted&&r.warn(`--tunnel: the Vite dev server did not report its URL within ${String(o/1e3)}s — continuing without a tunnel.`),i},kr=e=>{const{allowMail:r,cwd:n,logger:t}=e,o=r.length===0,i=new AbortController,{signal:s}=i,a=()=>s.aborted,c=e.closeTimeoutMs??ur;let l;const d=()=>{i.abort()};process.once("SIGINT",d),process.once("SIGTERM",d);const p=(async()=>{const u=await gr(e.spawner??Xe);if(!u.ok){t.error(u.message),t.warn("continuing without a tunnel.");return}u.version===void 0&&t.warn(`could not read the cloudflared version — --tunnel needs ${y} or newer; trying anyway.`);const v=e.origin.kind==="fixed"?{origin:e.origin.origin,ownerPid:process.pid}:await Sr(n,t,s);if(v===void 0||s.aborted)return;o&&hr(t),t.info(`starting a Cloudflare quick tunnel to ${v.origin}${o?"":" (email one-time-PIN protected)"}…`);let S;const U={failedToStart:!1},Le=k=>{if(k.length===0)return;const g=wr(k);if(g.url!==void 0&&S===void 0){S=g.url,t.success(` ➜ Tunnel: ${g.url}${o?" (PUBLIC)":""}`),o||t.info(` Allowed: ${r.join(", ")} — visitors confirm with a one-time PIN; a session lasts up to 4 hours`),e.origin.kind==="vite"&&t.info(` ${vr}`),b(n,{tunnelUrl:g.url},{expectedPid:v.ownerPid});return}g.level==="error"||g.level==="fatal"?t.warn(`[cloudflared] ${g.text}`):t.debug?.(`[cloudflared] ${g.text}`)},P=(e.startChild??fe)({args:mr(v.origin,r),command:"cloudflared",direct:!0},Le,k=>{U.failedToStart=!0,t.error(`could not start cloudflared (${k.message}) — continuing without a tunnel.`)});l=P;const G=()=>{P.kill("SIGTERM")};s.addEventListener("abort",G,{once:!0});const F=await P.exited;s.removeEventListener("abort",G),l=void 0,S!==void 0&&b(n,{tunnelUrl:void 0},{expectedPid:v.ownerPid}),!(a()||U.failedToStart)&&t.warn(S===void 0?`cloudflared exited (${String(F)}) before a tunnel URL was assigned — continuing without a tunnel.`:`cloudflared exited (${String(F)}) — the tunnel is closed; the dev server keeps running.`)})().catch(u=>{t.error(`--tunnel failed (${u instanceof Error?u.message:String(u)}) — continuing without a tunnel.`)});return{close:async()=>{if(process.off("SIGINT",d),process.off("SIGTERM",d),i.abort(),await K(p,c))return;const u=l;u!==void 0&&(t.warn(`cloudflared did not exit within ${String(c/1e3)}s of SIGTERM — force-killing it.`),u.kill("SIGKILL"),!await K(u.exited,c)&&t.error(`could not confirm that cloudflared stopped — ${o?"the PUBLIC tunnel":"the tunnel"} may still be reachable. Stop the \`cloudflared\` process manually.`))}}},ht=e=>{const{cwd:r,logger:n,plan:t,tunnel:o}=e;if(o!==void 0)return kr({allowMail:o.allowMail,cwd:r,logger:n,origin:t.flavor==="wrangler"?{kind:"fixed",origin:t.workerOrigin}:{kind:"vite"},spawner:o.spawner,startChild:o.startChild})},Ir=(e,r)=>{const n=["dev"];if(e.apiSpec!==void 0&&n.push("--api-spec",e.apiSpec),Z(e.lazyFunctions)&&n.push("--lazy-functions"),e.port!==void 0&&n.push("--port",String(e.port)),e.workerPort!==void 0&&n.push("--worker-port",String(e.workerPort)),e.inspectorPort!==void 0&&n.push("--inspector-port",String(e.inspectorPort)),e.emitBindings!==void 0&&n.push("--emit-bindings",e.emitBindings),e.codegen===!1&&n.push("--no-codegen"),e.studio===!1&&n.push("--no-studio"),e.worker===!1&&n.push("--no-worker"),e.target!==void 0&&n.push("--target",e.target),e.tunnel===!0){n.push("--tunnel");for(const t of pr(e.allowMail).entries)n.push("--allow-mail",t)}return r&&n.push("--remote"),e.local===!0&&n.push("--local"),n},yr=1e4,Er=100,Lr=40,I=256*1024,Tr=new Set(["nuxt","sveltekit"]),Pr=["@lunora/rspack","@lunora/vite"],M=e=>{if(Tr.has(re(e).framework))return"framework-worker";const r=xe(e);return Pr.some(n=>r.has(n))?"vite":"wrangler"},ve=e=>{const r=A(e),n=Ge(e)?.scripts,t=typeof n=="object"&&n!==null?n.dev:void 0;if(typeof t!="string"||t.trim()===""||t.includes("lunora")){const o=ce(r,"vite",["dev"]);return{args:o.args,command:o.command}}return{args:["run","dev"],command:r}},br=e=>{Te(_e(e.logPath),{recursive:!0});const r=J(e.logPath,"w",384);let n;const t=ae(e.command,e.args);try{n=ie(t.command,t.args,{cwd:e.cwd,detached:!0,env:e.env,shell:t.shell,stdio:["ignore",r,r],windowsHide:!0})}finally{X(r)}return n.unref(),{exited:new Promise(o=>{n.on("error",()=>{o(1)}),n.on("exit",(i,s)=>{o(i??(s?1:0))})}),pid:n.pid}},_r=e=>{try{const{size:r}=Pe(e);if(r<=I)return Q(e,"utf8");const n=J(e,"r");try{const t=Buffer.alloc(I),o=be(n,t,0,I,r-I),i=t.toString("utf8",0,o);return i.slice(i.indexOf(`
|
|
1
|
+
import{existsSync as q,mkdirSync as Te,openSync as J,closeSync as X,statSync as Pe,readFileSync as Q,readSync as be}from"node:fs";import{join as N,dirname as _e}from"node:path";import{readServiceBindings as $e}from"@lunora/codegen";import{readLiveDevServerState as C,discoverContainerInfo as Re,streamContainerLogs as Ne,formatLunoraEvent as Ce,updateDevServerState as b,resolveLazyFunctions as Z,targetRunsOwnDevServer as D,resolveProjectTarget as ee,claimDevServerState as De,DEV_HANDOFF_ENV as Oe,clearDevServerState as E,readDevServerState as O,isDevServerReady as j,detectFramework as re,readProjectDependencyNames as xe,DEV_LOG_FILE_ENV as Ae,DEV_DAEMON_ENV as Me,LAZY_FUNCTIONS_ENV as Ue,readProjectManifest as Ge,isRecordedProcessCurrent as Fe,DEV_LOG_FILE as je,CODEGEN_ENV as te,isCodegenDisabled as Ve,planToolchainInvocation as We,startCelldDevSession as Be,resolveDeployDriver as ne,DEV_VARS_FILE as oe,parseDevVariableEntries as Ke}from"@lunora/config";import{warnCloudflareCliConfigOnce as ze,findWranglerFile as L,readWranglerJsonc as x,materializeDevWranglerConfig as He,materializeServiceDevConfigs as Ye}from"@lunora/config/cloudflare";import{f as qe}from"./free-port-DjbFhaaT.mjs";import{networkInterfaces as Je}from"node:os";import{spawn as ie,spawnSync as T}from"node:child_process";import{setTimeout as w}from"node:timers/promises";import{EXIT_CODE as se}from"./EXIT_CODE-DQVhSE-1.mjs";import{a as h}from"./output-format-DWe_tkTR.mjs";import{spawnShellCompat as ae,defaultSpawner as Xe}from"./createRecordingSpawner-DchLi0gR.mjs";import{isLunoraError as Qe}from"@lunora/errors";import{s as V}from"./index-oHZBGBwB.mjs";import{createInterface as Ze}from"node:readline";import{detectPackageManager as A,execArgsFor as ce,toolchainExecArgs as le,runScriptCommand as er}from"@lunora/config/cli";const rr=12e4,_=250,tr=1e3,nr="LUNORA_DEV_READY_TIMEOUT_MS",or=e=>{if(e!==void 0)return e;const r=Number(process.env[nr]??"");return Number.isFinite(r)&&r>0?r:rr},ir=async(e,r)=>{try{const n=AbortSignal.timeout(tr);return await(await fetch(new URL("/_lunora/status",e),{redirect:"manual",signal:r===void 0?n:AbortSignal.any([r,n])})).body?.cancel(),!0}catch{return!1}},de=async(e,r,n)=>{const t=Date.now()+n.timeoutMs;for(;n.signal?.aborted!==!0;){const o=r(C(e));if(o!==void 0)return o;if(Date.now()>=t)return;try{await w(n.intervalMs??500,void 0,{signal:n.signal})}catch{return}}},W=(e,r)=>{Ze({crlfDelay:Number.POSITIVE_INFINITY,input:e}).on("line",r)},sr=5e3,ue=(e,r,n,t)=>{if(e.length===0)return;const o=Ce(e);if(o){t[o.level](`[lunora] ${o.text}`);return}const i=`[${r}] ${e}`;n==="stderr"?t.warn(i):t.info(i)},ar=(e,r,n=process.platform,t=T)=>{try{if(r==="SIGKILL"&&n==="win32"&&e.pid!==void 0){t("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"});return}e.kill(r)}catch{}},fe=(e,r,n)=>{const t=e.direct===!0?{args:[...e.args],command:e.command,shell:!1}:ae(e.command,e.args),o=ie(t.command,t.args,{cwd:e.cwd??process.cwd(),env:e.env?{...process.env,...e.env}:process.env,shell:t.shell,stdio:[e.direct===!0?"ignore":"inherit","pipe","pipe"]});return W(o.stdout,i=>{r(i,"stdout")}),W(o.stderr,i=>{r(i,"stderr")}),{exited:new Promise(i=>{o.on("error",s=>{n?.(s),i(1)}),o.on("exit",(s,a)=>{i(s??(a?1:0))})}),kill:i=>{ar(o,i)}}},vt=(e,r)=>fe(e,(n,t)=>{ue(n.trimEnd(),e.tag,t,r)},n=>{r.error(`[${e.tag}] failed to start: ${n.message}`)}),gt=(e,r)=>{if(process.env.LUNORA_CONTAINER_LOGS==="0")return;const t=Re(e,"lunora").containers.map(o=>({className:o.className,exportName:o.exportName}));if(t.length!==0)return Ne({containers:t,onLine:o=>{const i=`[container:${o.name}] ${o.text}`;o.level==="error"?r.warn(i):r.info(i)},onUnavailable:o=>{r.warn(`[container] Docker engine unreachable — container logs unavailable (${o})`)}})},pt=async e=>{e.readyProbe?.abort(),await e.tunnel?.close(),await e.codegen?.close().catch(()=>{}),e.containerLogs?.close(),await e.studio?.close().catch(()=>{}),await e.hyperdrive?.stop().catch(()=>{});try{e.remoteCleanup?.(),e.serviceConfigCleanup?.()}catch{}},mt=async e=>await new Promise(r=>{const n={},t=s=>{e.info(`received ${s} — shutting down`),n.sigint&&process.off("SIGINT",n.sigint),n.sigterm&&process.off("SIGTERM",n.sigterm),r(0)},o=()=>{t("SIGINT")},i=()=>{t("SIGTERM")};n.sigint=o,n.sigterm=i,process.on("SIGINT",o),process.on("SIGTERM",i)}),wt=async(e,r,n)=>{let t=0,o;const i=l=>{e.kill(l),r?.kill(l)},s=()=>{t+=1,t===1?(n.info("received SIGINT — shutting down (press Ctrl-C again to force-kill)"),i("SIGTERM"),o=setTimeout(()=>{i("SIGKILL")},sr),o.unref()):i("SIGKILL")},a=()=>{i("SIGTERM")};process.on("SIGINT",s),process.on("SIGTERM",a);const c=await Promise.race([e.exited.then(l=>({code:l,who:"worker"})),...r===void 0?[]:[r.exited.then(l=>({code:l,who:"sidecar"}))]]);return r!==void 0&&(c.who==="sidecar"?(n.warn("[worker] the Lunora sidecar (wrangler dev) exited — shutting down the framework dev server"),e.kill("SIGTERM")):r.kill("SIGTERM"),await Promise.allSettled([e.exited,r.exited])),o&&clearTimeout(o),process.off("SIGINT",s),process.off("SIGTERM",a),c.code},y="2026.9.3",cr="https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/",lr=/version (\S+)/u,B=/https:\/\/[\da-z-]+\.trycloudflare\.com/u,dr="1s",ur=5e3,K=async(e,r)=>await Promise.race([e.then(()=>!0),w(r,!1,{ref:!1})]),fr=6e4,vr='Vite answers 403 for hosts it does not know — add `server: { allowedHosts: [".trycloudflare.com"] }` to vite.config if the URL is blocked.',gr=async e=>{const r=`Install or update it: ${cr} (macOS: \`brew install cloudflared\`).`;let n;try{const o=await e({args:["--version"],captureStdoutSilently:!0,command:"cloudflared"});if(o.code!==0)return{message:`\`cloudflared --version\` exited ${String(o.code)}. ${r}`,ok:!1};n=o.stdout??""}catch(o){return Qe(o)&&o.code==="LOCAL_DEPENDENCY_MISSING"?{message:`--tunnel needs \`cloudflared\` ${y} or newer, and it is not on your PATH. ${r}`,ok:!1}:{message:`\`cloudflared --version\` could not run: ${o instanceof Error?o.message:String(o)}. ${r}`,ok:!1}}const t=V.coerce(lr.exec(n)?.[1])?.version;return t===void 0?{ok:!0,version:void 0}:V.gte(t,y)?{ok:!0,version:t}:{message:`--tunnel needs \`cloudflared\` ${y} or newer (protected quick tunnels); found ${t}. ${r}`,ok:!1}},pr=e=>{const r=[],n=[];for(const t of e??[]){const o=t.split(",").map(i=>i.trim()).filter(i=>i.length>0);o.length>0&&(n.push(...o.filter(i=>!i.includes("@"))),r.push(o.join(",")))}return{entries:r,invalid:n}},mr=(e,r)=>["tunnel","--url",e,"--output","json","--grace-period",dr,...r.flatMap(n=>["--allowed-mail",n])],wr=e=>{let r;try{r=JSON.parse(e)}catch{r=void 0}if(typeof r=="object"&&r!==null){const n=r,t=typeof n.message=="string"?n.message:"";return{level:typeof n.level=="string"?n.level:void 0,text:t,url:B.exec(t)?.[0]}}return{level:void 0,text:e,url:B.exec(e)?.[0]}},hr=e=>{e.warn(" ⚠ PUBLIC TUNNEL: anyone with the tunnel URL can reach this dev server — there is no sign-in in front of it."),e.warn(" Protect it with a one-time-PIN email allow-list: lunora dev --tunnel --allow-mail you@example.com"),e.warn(" (repeat --allow-mail, pass a comma-separated list, or allow a whole domain with '*@example.com')")},Sr=async(e,r,n,{intervalMs:t,timeoutMs:o=fr}={})=>{const i=await de(e,s=>s?.mode==="vite"?{origin:s.url,ownerPid:s.pid}:void 0,{intervalMs:t,signal:n,timeoutMs:o});return i===void 0&&!n.aborted&&r.warn(`--tunnel: the Vite dev server did not report its URL within ${String(o/1e3)}s — continuing without a tunnel.`),i},kr=e=>{const{allowMail:r,cwd:n,logger:t}=e,o=r.length===0,i=new AbortController,{signal:s}=i,a=()=>s.aborted,c=e.closeTimeoutMs??ur;let l;const d=()=>{i.abort()};process.once("SIGINT",d),process.once("SIGTERM",d);const p=(async()=>{const u=await gr(e.spawner??Xe);if(!u.ok){t.error(u.message),t.warn("continuing without a tunnel.");return}u.version===void 0&&t.warn(`could not read the cloudflared version — --tunnel needs ${y} or newer; trying anyway.`);const v=e.origin.kind==="fixed"?{origin:e.origin.origin,ownerPid:process.pid}:await Sr(n,t,s);if(v===void 0||s.aborted)return;o&&hr(t),t.info(`starting a Cloudflare quick tunnel to ${v.origin}${o?"":" (email one-time-PIN protected)"}…`);let S;const U={failedToStart:!1},Le=k=>{if(k.length===0)return;const g=wr(k);if(g.url!==void 0&&S===void 0){S=g.url,t.success(` ➜ Tunnel: ${g.url}${o?" (PUBLIC)":""}`),o||t.info(` Allowed: ${r.join(", ")} — visitors confirm with a one-time PIN; a session lasts up to 4 hours`),e.origin.kind==="vite"&&t.info(` ${vr}`),b(n,{tunnelUrl:g.url},{expectedPid:v.ownerPid});return}g.level==="error"||g.level==="fatal"?t.warn(`[cloudflared] ${g.text}`):t.debug?.(`[cloudflared] ${g.text}`)},P=(e.startChild??fe)({args:mr(v.origin,r),command:"cloudflared",direct:!0},Le,k=>{U.failedToStart=!0,t.error(`could not start cloudflared (${k.message}) — continuing without a tunnel.`)});l=P;const G=()=>{P.kill("SIGTERM")};s.addEventListener("abort",G,{once:!0});const F=await P.exited;s.removeEventListener("abort",G),l=void 0,S!==void 0&&b(n,{tunnelUrl:void 0},{expectedPid:v.ownerPid}),!(a()||U.failedToStart)&&t.warn(S===void 0?`cloudflared exited (${String(F)}) before a tunnel URL was assigned — continuing without a tunnel.`:`cloudflared exited (${String(F)}) — the tunnel is closed; the dev server keeps running.`)})().catch(u=>{t.error(`--tunnel failed (${u instanceof Error?u.message:String(u)}) — continuing without a tunnel.`)});return{close:async()=>{if(process.off("SIGINT",d),process.off("SIGTERM",d),i.abort(),await K(p,c))return;const u=l;u!==void 0&&(t.warn(`cloudflared did not exit within ${String(c/1e3)}s of SIGTERM — force-killing it.`),u.kill("SIGKILL"),!await K(u.exited,c)&&t.error(`could not confirm that cloudflared stopped — ${o?"the PUBLIC tunnel":"the tunnel"} may still be reachable. Stop the \`cloudflared\` process manually.`))}}},ht=e=>{const{cwd:r,logger:n,plan:t,tunnel:o}=e;if(o!==void 0)return kr({allowMail:o.allowMail,cwd:r,logger:n,origin:t.flavor==="wrangler"?{kind:"fixed",origin:t.workerOrigin}:{kind:"vite"},spawner:o.spawner,startChild:o.startChild})},Ir=(e,r)=>{const n=["dev"];if(e.apiSpec!==void 0&&n.push("--api-spec",e.apiSpec),Z(e.lazyFunctions)&&n.push("--lazy-functions"),e.port!==void 0&&n.push("--port",String(e.port)),e.workerPort!==void 0&&n.push("--worker-port",String(e.workerPort)),e.inspectorPort!==void 0&&n.push("--inspector-port",String(e.inspectorPort)),e.emitBindings!==void 0&&n.push("--emit-bindings",e.emitBindings),e.codegen===!1&&n.push("--no-codegen"),e.studio===!1&&n.push("--no-studio"),e.worker===!1&&n.push("--no-worker"),e.target!==void 0&&n.push("--target",e.target),e.tunnel===!0){n.push("--tunnel");for(const t of pr(e.allowMail).entries)n.push("--allow-mail",t)}return r&&n.push("--remote"),e.local===!0&&n.push("--local"),n},yr=1e4,Er=100,Lr=40,I=256*1024,Tr=new Set(["nuxt","sveltekit"]),Pr=["@lunora/rspack","@lunora/vite"],M=e=>{if(Tr.has(re(e).framework))return"framework-worker";const r=xe(e);return Pr.some(n=>r.has(n))?"vite":"wrangler"},ve=e=>{const r=A(e),n=Ge(e)?.scripts,t=typeof n=="object"&&n!==null?n.dev:void 0;if(typeof t!="string"||t.trim()===""||t.includes("lunora")){const o=ce(r,"vite",["dev"]);return{args:o.args,command:o.command}}return{args:["run","dev"],command:r}},br=e=>{Te(_e(e.logPath),{recursive:!0});const r=J(e.logPath,"w",384);let n;const t=ae(e.command,e.args);try{n=ie(t.command,t.args,{cwd:e.cwd,detached:!0,env:e.env,shell:t.shell,stdio:["ignore",r,r],windowsHide:!0})}finally{X(r)}return n.unref(),{exited:new Promise(o=>{n.on("error",()=>{o(1)}),n.on("exit",(i,s)=>{o(i??(s?1:0))})}),pid:n.pid}},_r=e=>{try{const{size:r}=Pe(e);if(r<=I)return Q(e,"utf8");const n=J(e,"r");try{const t=Buffer.alloc(I),o=be(n,t,0,I,r-I),i=t.toString("utf8",0,o);return i.slice(i.indexOf(`
|
|
2
2
|
`)+1)}finally{X(n)}}catch{return}},ge=(e,r)=>{const n=_r(e);if(n===void 0)return[];const t=n.split(`
|
|
3
3
|
`);return t.at(-1)===""&&t.pop(),r>0?t.slice(-r):t},pe=(e,r)=>r?.logFile??N(e,je),me=e=>{e.info(" Stop: lunora dev stop"),e.info(" Status: lunora dev status"),e.info(" Logs: lunora dev logs")},$r=(e,r)=>{ze(r,n=>{e.warn(n)})},Rr=(e,r)=>{e.warn(`Dev server already running at ${r.url} (pid ${String(r.pid)})`),me(e)},Nr=(e,r)=>{e.success(`Dev server running at ${r.url} (pid ${String(r.pid)})`),r.studioUrl!==void 0&&e.info(` Studio: ${r.studioUrl}`),r.tunnelUrl!==void 0&&e.info(` Tunnel: ${r.tunnelUrl}`),me(e)},Cr=3e4,Dr=async(e,r,n,t)=>{const o=await de(e,i=>i?.tunnelUrl,{intervalMs:n,timeoutMs:t});o===void 0?r.warn(" Tunnel: no URL yet — `lunora dev status` shows it once cloudflared reports one; `lunora dev logs` says why if it does not."):r.success(` Tunnel: ${o}`)},Or=async e=>{const{child:r,cwd:n,deadline:t,pollIntervalMs:o,probe:i}=e,s=r.exited.then(a=>({exitCode:a}));for(;Date.now()<t;){const a=C(n);if(a!==void 0&&a.pid!==process.pid&&await i(a.url))return{state:a,status:"ready"};const c=await Promise.race([s,w(o)]);if(c!==void 0)return{...c,status:"exited"}}return{status:"timeout"}},xr=async e=>{const{cwd:r,logger:n}=e,t=pe(r,void 0),o=or(e.readyTimeoutMs),i=(e.spawnDetached??br)({args:e.command.args,command:e.command.command,cwd:r,env:{...process.env,...e.env,[Me]:"1",[Ae]:t,...process.env.FORCE_COLOR===void 0?{NO_COLOR:"1"}:{},...e.json?{LUNORA_LOG_JSON:"1"}:{}},logPath:t}),s=await Or({child:i,cwd:r,deadline:Date.now()+o,pollIntervalMs:e.pollIntervalMs??_,probe:e.probe??ir});if(s.status==="ready")return Nr(n,s.state),e.tunnel===!0&&s.state.tunnelUrl===void 0&&await Dr(r,n,e.pollIntervalMs??_,e.tunnelUrlTimeoutMs??Cr),{code:0};if(s.status==="exited"){n.error(`dev server exited before becoming ready (exit code ${String(s.exitCode)}). Last output:`);for(const c of ge(t,Lr))n.error(` ${c}`);return E(r,i.pid??process.pid),{code:s.exitCode===0?1:s.exitCode}}i.pid!==void 0&&O(r)?.pid===process.pid&&b(r,{logFile:t,pid:i.pid});const a=i.pid===void 0?"":` (pid ${String(i.pid)})`;return n.warn(`dev server did not confirm ready within ${String(Math.round(o/1e3))}s — it may still be compiling${a}. Check \`lunora dev status\` and \`lunora dev logs\`; \`lunora dev stop\` shuts it down.`),{code:se.UNAVAILABLE}},we=e=>e.codegen!==!1&&!Ve(process.env[te]),he=e=>{const r={...Z(e.lazyFunctions)?{[Ue]:"1"}:{},...e.remote===!0?{LUNORA_REMOTE:"1"}:{},...e.codegen===!1?{[te]:"0"}:{}};return Object.keys(r).length>0?{env:r}:{}},St=async e=>{const{cwd:r,jsonLogs:n,logger:t,options:o,remote:i}=e,s=e.run??xr,a=M(r),c=a==="vite"&&D(o.target??ee(r))?"wrangler":a,l=c==="wrangler"?`http://localhost:${String(o.workerPort??8787)}`:"http://localhost:5173",d=De(r,{background:!0,mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:l});if(!d.ok)return d.existing!==void 0&&Rr(t,d.existing),{code:0};const f={[Oe]:String(process.pid)};$r(t,r);try{return c==="vite"&&o.tunnel!==!0?await s({command:ve(r),cwd:r,env:{...he({...o,remote:i}).env,...f},json:n,logger:t}):await s({command:{args:[process.argv[1]??"lunora",...Ir(o,i)],command:process.execPath},cwd:r,env:f,json:n,logger:t,tunnel:o.tunnel===!0})}finally{E(r,process.pid)}},Ar=e=>{try{const r=T("ps",["-o","pgid=","-p",String(e)],{encoding:"utf8"}),n=Number.parseInt(r.stdout.trim(),10);return Number.isInteger(n)&&n>0?n:void 0}catch{return}},Mr=(e,r,n=process.platform,t=T)=>{if(n==="win32"){try{t("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}return}if(e.background===!0)try{r(-(Ar(e.pid)??e.pid),"SIGKILL");return}catch{}try{r(e.pid,"SIGKILL")}catch{}},Ur=(e,r)=>(r.json?h({pid:e.pid,stopped:!1}):r.logger.error(`dev server (pid ${String(e.pid)}) survived the force-kill — record kept; retry \`lunora dev stop\` or kill the process manually.`),{code:1}),Gr=async e=>{const{cwd:r,logger:n}=e,t=O(r),o=e.alive??(f=>f===t?.pid&&Fe(t)),i=e.signal??((f,p)=>{process.kill(f,p)}),s=e.pollIntervalMs??_,a=e.stopGraceMs??yr,c=e.platform??process.platform,l=e.spawnSyncImpl??T;if(t===void 0||!o(t.pid))return t!==void 0&&E(r,t.pid),e.json?h({running:!1,stopped:!1}):n.info("No dev server running."),{code:0};try{i(t.pid,"SIGTERM")}catch{}const d=Date.now()+a;for(;o(t.pid)&&Date.now()<d;)await w(s);return o(t.pid)&&(Mr(t,i,c,l),await w(s),o(t.pid))?Ur(t,e):(E(r,t.pid),e.json?h({pid:t.pid,stopped:!0}):n.success(`Stopped dev server (pid ${String(t.pid)}).`),{code:0})},Fr=e=>{const{cwd:r,logger:n}=e,t=C(r);if(t===void 0)return e.json?h({running:!1}):n.info("No dev server running."),{code:0};const o=e.now??Date.now,i=t.startedAt===void 0?Number.NaN:Date.parse(t.startedAt),s=Number.isFinite(i)?Math.max(0,Math.round((o()-i)/1e3)):void 0;if(e.json)return h({background:t.background===!0,logFile:t.logFile,mode:t.mode,pid:t.pid,ready:j(t),readyAt:t.readyAt,running:!0,startedAt:t.startedAt,studioUrl:t.studioUrl,tunnelUrl:t.tunnelUrl,uptimeSeconds:s,url:t.url}),{code:0};const a=[`pid ${String(t.pid)}`,...s===void 0?[]:[`uptime ${String(s)}s`],t.background===!0?"background":"foreground",j(t)?"ready":"starting"];return n.success(`Dev server running at ${t.url} (${a.join(", ")})`),t.studioUrl!==void 0&&n.info(` Studio: ${t.studioUrl}`),t.tunnelUrl!==void 0&&n.info(` Tunnel: ${t.tunnelUrl}`),t.logFile!==void 0&&n.info(` Logs: lunora dev logs (${t.logFile})`),{code:0}},jr=e=>{const{cwd:r,logger:n}=e,t=O(r),o=pe(r,t);if(!q(o))return n.info("No dev server logs found — output is captured when the server runs in background mode (`lunora dev --background`)."),{code:0};const i=ge(o,e.lines??Er);return i.length>0&&process.stdout.write(`${i.join(`
|
|
4
4
|
`)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./free-port-DjbFhaaT.mjs";import{g as a,p as s,q as l,u as p}from"./plan-
|
|
1
|
+
import"./free-port-DjbFhaaT.mjs";import{g as a,p as s,q as l,u as p}from"./plan-pog5AvMk.mjs";export{a as buildDevPlan,s as planDevCommand,l as resolveInspectorPort,p as resolveWorkerPort};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readLinkedProject as n}from"@lunora/config";const v=({cwd:e,env:i,url:o})=>{if(o!==void 0&&o!=="")return o;const r=n(e);if(!(r===void 0||r.env!==i))return r.workerUrl},d=({cwd:e,prod:i,url:o})=>{if(o!==void 0&&o!=="")return o;if(!i)return;const r=n(e);if(!(r===void 0||r.env!==void 0&&r.env!=="production"))return r.workerUrl};export{
|
|
1
|
+
import{readLinkedProject as n}from"@lunora/config";const v=({cwd:e,env:i,url:o})=>{if(o!==void 0&&o!=="")return o;const r=n(e);if(!(r===void 0||r.env!==i))return r.workerUrl},d=({cwd:e,prod:i,url:o})=>{if(o!==void 0&&o!=="")return o;if(!i)return;const r=n(e);if(!(r===void 0||r.env!==void 0&&r.env!=="production"))return r.workerUrl};export{v as a,d as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./admin-token-VdUnvnKW.mjs";import"./admin-url-DJB8P6Jh.mjs";import"./platform-diagnostics-Cn2g6Jh-.mjs";import"./api-spec-lYyq4vL6.mjs";import{f,b as x,r as D,a as L,s as P}from"../packem_chunks/handler.mjs";import"./vectorize-metadata-
|
|
1
|
+
import"./admin-token-VdUnvnKW.mjs";import"./admin-url-DJB8P6Jh.mjs";import"./platform-diagnostics-Cn2g6Jh-.mjs";import"./api-spec-lYyq4vL6.mjs";import{f,b as x,r as D,a as L,s as P}from"../packem_chunks/handler.mjs";import"./vectorize-metadata-DK61NmVx.mjs";import"./binding-manifest-file-CQ1eQYy1.mjs";import"./command-BpMv2n0o.mjs";import"./deploy-target-resolve-BTCW1Iv4.mjs";import"./EXIT_CODE-DQVhSE-1.mjs";import"./resolve-target-BRvw8Pf7.mjs";import"./health-probe-BLnoq_oC.mjs";import"./createRecordingSpawner-DchLi0gR.mjs";export{f as execute,x as provisionBindings,D as runDeployCommand,L as runPreDeployPipeline,P as smokeLoadLazyModules};
|
package/dist/packem_shared/{vectorize-metadata-BVSF8z2h.mjs → vectorize-metadata-DK61NmVx.mjs}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{r as _,c as g}from"./cloudflare-credentials-BVmZnDZk.mjs";import{spawnSync as I}from"node:child_process";import{readFileSync as p,writeFileSync as x,existsSync as E}from"node:fs";import{join as w}from"node:path";import{readProjectTarget as P,DEFAULT_TARGET as N}from"@lunora/codegen";import{DEV_VARS_FILE as u,parseDevVariableEntries as k,upsertDevVariableLine as L,generateSecretValue as F,writeDevVariablesFileAtomically as U,isPlaceholderValue as y,isMintableSecretKey as K,mintableSecretKeysFor as M,secretSourcesFromBindings as W,inferLunoraBindings as V,resolveSchemaDirectory as B}from"@lunora/config";import{modify as Y,applyEdits as z,parse as H}from"jsonc-parser";import{r as G}from"./admin-token-VdUnvnKW.mjs";import{defaultSpawner as J}from"./createRecordingSpawner-
|
|
1
|
+
import{r as _,c as g}from"./cloudflare-credentials-BVmZnDZk.mjs";import{spawnSync as I}from"node:child_process";import{readFileSync as p,writeFileSync as x,existsSync as E}from"node:fs";import{join as w}from"node:path";import{readProjectTarget as P,DEFAULT_TARGET as N}from"@lunora/codegen";import{DEV_VARS_FILE as u,parseDevVariableEntries as k,upsertDevVariableLine as L,generateSecretValue as F,writeDevVariablesFileAtomically as U,isPlaceholderValue as y,isMintableSecretKey as K,mintableSecretKeysFor as M,secretSourcesFromBindings as W,inferLunoraBindings as V,resolveSchemaDirectory as B}from"@lunora/config";import{modify as Y,applyEdits as z,parse as H}from"jsonc-parser";import{r as G}from"./admin-token-VdUnvnKW.mjs";import{defaultSpawner as J}from"./createRecordingSpawner-DchLi0gR.mjs";import{toolchainExecArgs as X,detectPackageManager as q}from"@lunora/config/cli";const b=5e3,D=(e,t,s)=>`POST https://api.cloudflare.com/client/v4/accounts/${e}/artifacts/namespaces with body { "namespace": "${t}", "jurisdiction": "${s}" }`,Q=e=>{let t="";try{const{errors:s}=JSON.parse(e.text);t=(s??[]).flatMap(n=>typeof n.message=="string"?[n.message]:[]).slice(0,2).join("; ")}catch{}return t===""?`HTTP ${String(e.status)}`:`HTTP ${String(e.status)}: ${t}`},Z=async(e,t,s)=>{const{jurisdiction:n,namespace:r}=e;try{const a=await g({accountId:t,apiToken:s,...e.fetch===void 0?{}:{fetch:e.fetch},init:{body:JSON.stringify({jurisdiction:n,namespace:r}),method:"POST",signal:AbortSignal.timeout(b)},path:"/artifacts/namespaces"});return a.ok?{}:{reason:Q(a)}}catch(a){return{reason:a instanceof Error?a.message:String(a)}}},ee=async(e,t,s)=>{const n=await g({accountId:t,apiToken:s,...e.fetch===void 0?{}:{fetch:e.fetch},init:{signal:AbortSignal.timeout(b)},path:`/artifacts/namespaces/${encodeURIComponent(e.namespace)}`}).catch(()=>{}),r=n?.ok===!0?n.body.result:void 0;return typeof r=="object"&&r!==null&&"jurisdiction"in r?r.jurisdiction:void 0},j=(e,t,s,n)=>({fix:`A namespace's jurisdiction cannot change: create one with ${D(e,"<name>",s)}, point the binding's "namespace" at it, and move the repos over.`,message:`${t} is in the "${n}" jurisdiction, but the schema pins data to "${s}".`,verdict:"mismatch"}),te=async(e,t,s,n)=>{const{jurisdiction:r,namespace:a}=e;let i;if(e.create===!0){if(i=(await Z(e,t,s)).reason,i===void 0)return{changesAccount:!0,message:`created ${n} in the "${r}" jurisdiction, as the schema pins.`,verdict:"ok"};const l=await ee(e,t,s);if(l===r)return{message:`${n} is in the "${r}" jurisdiction, as the schema pins.`,verdict:"ok"};if(typeof l=="string")return j(t,n,r,l)}if(e.missingOk===!0)return{changesAccount:!0,message:`${n} does not exist yet; it will be created in the "${r}" jurisdiction just before the deploy.`,verdict:"ok"};const c=i===void 0?"":` (${i})`,o=e.create===!0?` and could not be created${c}`:"";return{fix:`Create it before the first repo: ${D(t,a,r)}.`,message:`${n} does not exist${o}, and the first repo create() would make it unrestricted — the schema pins data to "${r}".`,verdict:"missing"}},Ce=async e=>{const{binding:t,jurisdiction:s,namespace:n}=e,r=`Artifacts namespace "${n}" (binding ${t})`,{accountId:a,token:i}=_(e.environment??process.env,e.accountId);if(i===void 0||a===void 0)return{fix:"Set CLOUDFLARE_API_TOKEN (with Artifacts edit access, which creating a missing namespace needs) and CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) to check it.",message:`the jurisdiction of ${r} was not checked against the schema's "${s}".`,verdict:"unchecked"};let c;try{c=await g({accountId:a,apiToken:i,...e.fetch===void 0?{}:{fetch:e.fetch},init:{signal:AbortSignal.timeout(b)},path:`/artifacts/namespaces/${encodeURIComponent(n)}`})}catch(l){return{message:`the jurisdiction of ${r} could not be read (${l instanceof Error?l.message:String(l)}).`,verdict:"unchecked"}}if(!c.ok&&c.status===404)return te(e,a,i,r);if(!c.ok)return{...c.status===401||c.status===403?{fix:`Give CLOUDFLARE_API_TOKEN Artifacts edit access on account ${a}.`}:{},message:`the jurisdiction of ${r} could not be read (HTTP ${String(c.status)}).`,verdict:"unchecked"};const{result:o}=c.body,d=typeof o=="object"&&o!==null&&"jurisdiction"in o?o.jurisdiction:void 0;return typeof d!="string"?{message:`the jurisdiction of ${r} could not be read (the response carried none).`,verdict:"unchecked"}:d===s?{message:`${r} is in the "${d}" jurisdiction, as the schema pins.`,verdict:"ok"}:j(a,r,s,d)},m=100,f=500,S=10,ne=5e3,h="Delete the Workers you no longer need (old preview / staging deploys free their classes), or set `durableObjects: { merge: true }` in lunora.config before an app's first deploy so it spends one class instead of up to three.",re=e=>e>=f?{fix:h,message:`the Cloudflare account has ${String(e)} Durable Object classes — the Workers Paid cap is ${String(f)}, so a deploy that adds one will fail.`,verdict:"full"}:e>=f-S?{fix:h,message:`the Cloudflare account has ${String(e)} of ${String(f)} Durable Object classes (Workers Paid cap).`,verdict:"near"}:e>=m-S&&e<=m?{fix:h,message:`the Cloudflare account has ${String(e)} Durable Object classes — on Workers Free the cap is ${String(m)} (Paid: ${String(f)}).`,verdict:"near"}:{message:`the Cloudflare account has ${String(e)} Durable Object classes (caps: ${String(m)} Free, ${String(f)} Paid).`,verdict:"ok"},Ie=async(e={})=>{const{accountId:t,token:s}=_(e.environment??process.env,e.accountId);if(s===void 0||t===void 0)return{fix:"Set CLOUDFLARE_API_TOKEN (Workers Scripts Read) and CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) to check it.",message:"the account's Durable Object class count was not checked.",verdict:"unchecked"};try{const n=await g({accountId:t,apiToken:s,...e.fetch===void 0?{}:{fetch:e.fetch},init:{signal:AbortSignal.timeout(ne)},path:"/workers/durable_objects/namespaces?per_page=1"}),r=n.ok?n.body.result_info:void 0,a=typeof r=="object"&&r!==null&&"total_count"in r?r.total_count:void 0;return typeof a!="number"?{message:`the account's Durable Object class count could not be read${n.ok?"":` (HTTP ${String(n.status)})`}.`,verdict:"unchecked"}:re(a)}catch(n){return{message:`the account's Durable Object class count could not be read (${n instanceof Error?n.message:String(n)}).`,verdict:"unchecked"}}},$=e=>e.endsWith("S")?e.slice(0,-1):e,T=e=>e.replaceAll(/([a-z\d])([A-Z])/gu,"$1_$2").toUpperCase().split(/[_-]+/u).filter(t=>t.length>0),O=new Set(["CREDENTIAL","DSN","PASSPHRASE","PASSWD","PASSWORD","SECRET","TOKEN"]),R=["ACCESS_KEY","API_KEY","ENCRYPTION_KEY","PRIVATE_KEY","SIGNING_KEY"],se=new RegExp(`(?:${[...O,...R.map(e=>e.replaceAll("_",""))].join("|")})S?$`,"iu"),ae=e=>T(e).some(t=>t==="PUBLIC"||t==="PUBLISHABLE"),ie=e=>{if(ae(e))return!1;const t=T(e);if(t.some(n=>O.has($(n))))return!0;const s=$(t.join("_"));return R.some(n=>s===n||s.endsWith(`_${n}`))||se.test(e)},ce=e=>{const t=e.trim();return t===""||t.startsWith("<")&&t.endsWith(">")},oe=/replace[-_\s]?(?:with|me)(?![a-z])/iu,de=e=>ce(e)||oe.test(e),ue=e=>de(e),C=/\r?\n/u,le=async(e,t,s)=>{const{args:n,command:r}=X(q(t),{args:e,tool:"wrangler"});try{const a=await J({args:n,captureStderr:!0,captureStdoutSilently:!0,command:r,cwd:t,...s===void 0?{}:{env:{CLOUDFLARE_ENV:s}}});return{code:a.code,stderr:a.stderr??"",stdout:a.stdout??""}}catch(a){return{code:1,stderr:a instanceof Error?a.message:String(a),stdout:""}}},v=async(e,t,s)=>{const n=await e(["d1","list","--json"],t,s);if(n.code!==0)return;let r;try{r=JSON.parse(n.stdout)}catch{return}if(!Array.isArray(r))return;const a=new Map;for(const i of r)typeof i.name=="string"&&typeof i.uuid=="string"&&a.set(i.name,i.uuid);return a},fe=(e,t,s)=>(Array.isArray(e)?e:[]).flatMap((r,a)=>{if(r===null||typeof r!="object")return[];const i=r,c=typeof i.database_id=="string"?i.database_id:"";return ue(c)?[{binding:typeof i.binding=="string"&&i.binding!==""?i.binding:"<unnamed>",environment:s,path:[...t,"d1_databases",a],name:typeof i.database_name=="string"&&i.database_name!==""?i.database_name:void 0}]:[]}),me=(e,t)=>{const s=H(e);return[{config:s,environment:void 0,prefix:[]},...Object.entries(t?{}:s?.env??{}).map(([r,a])=>({config:a,environment:r,prefix:["env",r]}))].flatMap(({config:r,environment:a,prefix:i})=>fe(r?.d1_databases,i,a))},ge=async(e,t,s,n)=>{const r=await v(s,t.cwd,e.environment);if(r===void 0){n.skipped.push(`D1 "${e.binding}": could not run \`wrangler d1 list --json\`. Check that wrangler is installed in this project and logged in (\`wrangler login\`), then retry.`);return}const a=r.get(e.name);if(a!==void 0)return a;if(t.dryRun){n.applied.push(`would run \`wrangler d1 create ${e.name}\` and write its id into ${e.binding}`);return}const i=await s(["d1","create",e.name],t.cwd,e.environment);if(i.code!==0){const d=i.stderr.trim()||`exit ${String(i.code)}`;n.skipped.push(`D1 "${e.binding}": \`wrangler d1 create ${e.name}\` failed: ${d}`);return}const o=(await v(s,t.cwd,e.environment))?.get(e.name);return o===void 0&&n.skipped.push(`D1 "${e.binding}": created ${e.name} but could not read back its id.`),o},he=async(e,t)=>{if(e.configPath===void 0)return;const s=e.runner??le,n=p(e.configPath,"utf8"),r=me(n,(P(e.cwd)??N)==="celld");let a=n;for(const i of r){if(i.name===void 0){t.skipped.push(`D1 "${i.binding}" has no database_name, so there is no database to create or reuse.`);continue}const c=await ge({...i,name:i.name},e,s,t);if(c!==void 0){const o=Y(a,[...i.path,"database_id"],c,{formattingOptions:{eol:`
|
|
2
2
|
`,insertSpaces:!0,tabSize:4}});a=z(a,o),t.applied.push(`${i.binding}: database_id set to the id of D1 "${i.name}"`)}}!e.dryRun&&a!==n&&x(e.configPath,a)},pe=e=>{const t=I("git",["check-ignore","-q",u],{cwd:e,stdio:"ignore"});if(t.status===0)return!0;if(t.status===1)return!1;const s=w(e,".gitignore");return E(s)&&p(s,"utf8").split(C).some(n=>n.trim()===u)},be=async(e,t)=>{try{return M(W(await V({projectRoot:e,schemaDir:B(e)})))}catch{t.skipped.push(`${u}: could not read the project's bindings, so the relay key was not checked against its role.`);return}},ye=(e,t,s,n,r)=>{const a=[],i=new Set(t.split(C).flatMap(c=>{const[o]=k(c);return o!==void 0&&!y(o.value)?[o.key]:[]}));G({cwd:e}).source===void 0&&!i.has("LUNORA_ADMIN_TOKEN")&&a.push("LUNORA_ADMIN_TOKEN");for(const c of s)!ie(c.key)||!y(c.value)||i.has(c.key)||(K(c.key,c.value,r)?a.push(c.key):n.skipped.push(`${u}: ${c.key} is a provider key and cannot be minted here; fill it in by hand.`));return a},Se=async(e,t)=>{const s=w(e.cwd,u),n=E(s)?p(s,"utf8"):"",r=ye(e.cwd,n,k(n),t,await be(e.cwd,t));if(r.length===0)return;if(!pe(e.cwd)){t.skipped.push(`${u} is not in .gitignore, so no secret is written there. Add \`${u}\` to .gitignore first.`);return}if(e.dryRun){t.applied.push(`would mint ${r.join(", ")} into ${u}`);return}let a=n;for(const i of r)a=L(a,i,F());U(s,a),t.applied.push(`minted ${r.join(", ")} into ${u}`)},xe=async e=>{const t={applied:[],skipped:[]};return await he(e,t),await Se(e,t),t},Pe=e=>{switch(e){case"boolean":return"boolean";case"date":case"number":case"timestamp":return"number";case"id":case"literal":case"string":return"string";default:return}},$e=/already (?:exists|indexed)|duplicate/iu,A=e=>["vectorize","create-metadata-index",e.index,`--property-name=${e.property}`,`--type=${e.type}`],ve=async(e,t)=>{try{return await e(t)}catch(s){return{code:1,stderr:s instanceof Error?s.message:String(s)}}},Ne=async e=>{const{cwd:t,entries:s,exec:n,logger:r,spawner:a}=e,i=[];for(const c of s){const o=await ve(a,{args:[...n.args,...A(c)],captureStderr:!0,command:n.command,cwd:t,stdoutToStderr:!0});if(o.code===0){i.push({entry:c,status:"created"});continue}const d=`${o.stderr??""}${o.stdout??""}`;if($e.test(d)){i.push({entry:c,status:"exists"});continue}i.push({entry:c,error:d.trim()||`exit code ${String(o.code)}`,status:"failed"}),r.warn(`could not create the Vectorize metadata index for "${c.property}" on "${c.index}" — filters on that property will match nothing until it exists. Run: wrangler ${A(c).join(" ")}`)}return i};export{xe as a,Ie as b,A as c,Ce as d,de as e,ue as f,Ne as g,ie as i,Pe as m};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveDeployDriver as c,resolveProjectTarget as d}from"@lunora/config";import{defaultSpawner as l}from"./createRecordingSpawner-
|
|
1
|
+
import{resolveDeployDriver as c,resolveProjectTarget as d}from"@lunora/config";import{defaultSpawner as l}from"./createRecordingSpawner-DchLi0gR.mjs";import{toolchainExecArgs as i,detectPackageManager as m}from"@lunora/config/cli";const u=async(e,t,o)=>{try{const r=await l({args:t,captureStderr:!0,captureStdoutSilently:!0,command:e,cwd:o});return{code:r.code,stderr:r.stderr??"",stdout:r.stdout??""}}catch(r){return{code:1,stderr:r instanceof Error?r.message:String(r),stdout:""}}},f=e=>{let t;try{t=JSON.parse(e)}catch{return}return Array.isArray(t)?[...t.map(r=>r!==null&&typeof r=="object"?r.name:void 0).filter(r=>typeof r=="string"&&r.length>0)].toSorted((r,a)=>r.localeCompare(a)):void 0},S=async e=>{const t=c(e.target??d(e.cwd)),o=t.toolchain?.secretList?.({environment:e.env,temporary:e.temporary});if(o===void 0)return{error:`deploy target "${t.id}" has no secret store to list`,names:[],ok:!1};const{args:r,command:a}=i(m(e.cwd),o),s=await(e.runner??u)(a,r,e.cwd);if(s.code!==0)return{error:s.stderr.trim()||`wrangler secret list exited ${String(s.code)}`,names:[],ok:!1};const n=f(s.stdout);return n===void 0?{error:"could not parse `wrangler secret list --format json` output",names:[],ok:!1}:{names:n,ok:!0}};export{S as l};
|