UNPKG

@lunora/cli

Version:

The Lunora CLI: init, dev, deploy, codegen, run, reset, and migrate commands

12 lines (10 loc) 9.72 kB
import{existsSync as m,mkdirSync as S,writeFileSync as h,mkdtempSync as C,rmSync as I,readFileSync as k}from"node:fs";import{tmpdir as A}from"node:os";import{discoverSchema as T,discoverMigrations as N}from"@lunora/codegen";import{isInteractive as M,promptSelect as z,promptText as E}from"@lunora/config";import{LunoraError as y}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as w}from"ts-morph";import{a as F}from"../packem_shared/admin-url-DfVehV3e.mjs";import{i as O}from"../packem_shared/command-Bjv4VmYA.mjs";import{diffSnapshots as R,renderMigrationFile as q}from"../packem_shared/diffSnapshots-9bDd9nOK.mjs";import{s as D}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import L from"../packem_shared/schemaIrToSnapshot-Clwd2A8e.mjs";import{runExportCommand as j,runImportCommand as B}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-DL87PIEl.mjs";const H=".snapshot.json",x=/[^\da-z]+/gu,U=(r,e)=>{let o=0,t=r.length;for(;o<t&&r[o]===e;)o+=1;for(;t>o&&r[t-1]===e;)t-=1;return r.slice(o,t)},J=r=>{const e=U(r.toLowerCase().replaceAll(x,"_"),"_");return e===""?"auto":e},P=r=>{const e=(o,t=2)=>o.toString().padStart(t,"0");return`${String(r.getUTCFullYear())}${e(r.getUTCMonth()+1)}${e(r.getUTCDate())}${e(r.getUTCHours())}${e(r.getUTCMinutes())}${e(r.getUTCSeconds())}`},Z=r=>{if(m(r))try{const e=k(r,"utf8"),o=JSON.parse(e);if(o.version!==1)throw new y("INTERNAL",`unsupported snapshot version: ${o.version}`);return o}catch(e){const o=e instanceof Error?e.message:String(e);throw new y("INTERNAL",`failed to read ${r}: ${o}`,{cause:e})}},K=r=>{const e=r.cwd??process.cwd(),o=c(e,"lunora","schema.ts");if(!m(o))return r.logger.error(`schema not found: ${o} — run \`vis generate lunora-table --name=<name>\` to create one`),{code:1,empty:!0,migrationFile:""};const t=new w({skipAddingFilesFromTsConfig:!0}),n=T(t,o),a=L(n),i=c(e,"lunora","migrations"),s=c(i,H);let d;try{d=Z(s)}catch(p){return r.logger.error(p instanceof Error?p.message:String(p)),{code:1,empty:!0,migrationFile:""}}const l=R(d,a);if(l.empty)return r.logger.info("no schema changes detected — snapshot is already up to date"),{code:0,empty:!0,migrationFile:""};const u=(r.now??(()=>new Date))(),b=J(r.name??"auto"),$=`${P(u)}_${b}.sql`,g=c(i,$);S(i,{recursive:!0});const _=q(b,l,u.toISOString());return h(g,_,"utf8"),h(s,`${JSON.stringify(a,void 0,4)} `,"utf8"),r.logger.success(`wrote ${g}`),l.unsupported.length>0&&r.logger.warn(`${String(l.unsupported.length)} unsupported diff(s) — see the comment block in ${$} and write the SQL manually`),{code:0,empty:!1,migrationFile:g}},Q="migrations.ts",v=/^[A-Za-z_]\w*$/u,V=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),f='import { defineMigration } from "@lunora/server";',W="__lunora_admin__:runMigration",Y="__lunora_admin__:migrationStatus",G="/_lunora/migrate",X=r=>U(r.trim().toLowerCase().replaceAll(x,"-"),"-"),rr=r=>r.split("-").filter(e=>e.length>0).map((e,o)=>o===0?e:e.charAt(0).toUpperCase()+e.slice(1)).join(""),er=r=>{const e=c(r,"lunora","schema.ts");if(!m(e))return[];try{const o=new w({skipAddingFilesFromTsConfig:!0});return T(o,e).tables.map(t=>t.name)}catch{return[]}},tr=async r=>r.length>0?z("Which table does this migration iterate?",r.map(e=>({label:e,value:e}))):E("Target table for the migration: "),or=async(r,e)=>{if(e.table!==void 0)return e.table;const o=e.promptTable??(M()?tr:void 0);if(o===void 0){e.logger.error("migrate create requires a target table when not running interactively — re-run with --table <table>");return}const t=(await o(er(r)))?.trim();if(t===void 0||t===""){e.logger.error("no table selected — re-run with --table <table>");return}return t},nr=async r=>{const e=r.cwd??process.cwd(),o=X(r.name);if(o==="")return r.logger.error(`invalid migration name: "${r.name}" — must contain at least one alphanumeric character`),{code:1,file:""};const t=rr(o);if(!v.test(t)||V.has(t))return r.logger.error(`invalid migration name: "${r.name}" derives the export \`${t}\`, which is not a valid identifier — pick a name that starts with a letter and isn't a reserved word`),{code:1,file:""};const n=await or(e,r);if(n===void 0)return{code:1,file:""};if(!v.test(n))return r.logger.error(`invalid table: "${n}" — must be a valid identifier ([A-Za-z_][A-Za-z0-9_]*)`),{code:1,file:""};const a=c(e,"lunora"),i=c(a,Q);let s=m(i)?k(i,"utf8"):"";if(s.includes(`id: "${o}"`)||new RegExp(String.raw`\bexport const ${t}\b`,"u").test(s))return r.logger.error(`a migration with id "${o}" (export \`${t}\`) already exists in ${i}`),{code:1,file:""};s.trim()===""?s=`${f} `:s.includes(f)||(s=`${f} ${s}`);const d=`export const ${t} = defineMigration({ id: "${o}", table: "${n}", up: (document) => document, });`;return S(a,{recursive:!0}),h(i,`${s.trimEnd()} ${d} `,"utf8"),r.logger.success(`scaffolded migration "${o}" in ${i}`),{code:0,file:i}},ir=(r,e)=>{const o=new w({skipAddingFilesFromTsConfig:!0});return N(o,c(r,"lunora")).find(t=>t.id===e)?.table},ar=(r,e)=>{let o;try{o=ir(r,e.id)}catch(t){e.logger.error(t instanceof Error?t.message:String(t));return}if(o===void 0){e.logger.error(`migration "${e.id}" not found under lunora/ — declare it with defineMigration({ id: "${e.id}", ... })`);return}if(o===""){e.logger.error(`migration "${e.id}" must declare \`table\` as a static string literal`);return}return o},sr=r=>{const e=r.cwd??process.cwd();if(r.prod&&r.url===void 0){r.logger.error("--prod requires an explicit --url (refusing to migrate the implicit localhost worker)");return}if(r.prod&&(r.subcommand==="up"||r.subcommand==="down")&&!r.yes){r.logger.error(`migrate ${r.subcommand} --prod runs the migration against production. Re-run with --yes to confirm.`);return}const o=r.token??process.env.LUNORA_ADMIN_TOKEN;if(!o){r.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}const t=ar(e,r);if(t===void 0)return;const n=F(r.url,r.logger);if(n===void 0)return;const a=r.fetchImpl??globalThis.fetch;if(typeof a!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{fetchImpl:a,requestUrl:`${n}${G}`,table:t,token:o}},cr=r=>{const e={id:r.id};return r.subcommand==="status"||(e.direction=r.subcommand,r.dryRun&&(e.dryRun=!0),r.batchSize!==void 0&&(e.batchSize=r.batchSize),r.maxBatches!==void 0&&(e.maxBatches=r.maxBatches)),e},dr=async r=>{const e=sr(r);if(e===void 0)return{body:void 0,code:1,requestUrl:""};const{fetchImpl:o,requestUrl:t,table:n,token:a}=e,i=r.subcommand==="status"?Y:W,s=cr(r);r.logger.info(`POST ${t} -> ${r.subcommand} ${r.id} (table "${n}")`);const d=await o(t,{body:JSON.stringify({args:s,functionPath:i,table:n}),headers:{authorization:`Bearer ${a}`,"content-type":"application/json"},method:"POST"}),l=await d.text();let u;try{u=JSON.parse(l)}catch{u=l}return r.logger.info(JSON.stringify(u,void 0,2)),{body:u,code:d.ok?0:1,requestUrl:t}},lr=async r=>{const{logger:e}=r,o=r.fromUrl??r.toUrl,t=r.toUrl??r.fromUrl;if(o!==void 0&&o===t)return e.error("source and target are the same deployment — pass distinct --from-url and --to-url so the D1 export and Hyperdrive import don't run against one database"),{code:1};const n=r.out===void 0?C(c(A(),"lunora-d1ps-")):void 0,a=r.out??c(n,"dump.ndjson");try{e.info(`Exporting .global() data from the D1 source (${o??"http://localhost:8787"}) …`);const i=await j({fetchImpl:r.fetchImpl,logger:e,out:a,prod:r.prod,tables:r.tables,token:r.fromToken,url:o});if(i.code!==0)return{code:i.code};e.info(`Exported ${String(i.rows)} row(s) (${String(i.bytes)} bytes).`),e.info(`Importing into the Hyperdrive target (${t??"http://localhost:8787"}) …`);const s=await B({batchSize:r.batchSize,fetchImpl:r.fetchImpl,file:a,logger:e,prod:r.prod,token:r.toToken,url:t});return s.code!==0?{code:s.code}:(s.inserted===i.rows?e.info(`✓ Migrated ${String(i.rows)} row(s) — counts match. Verify your app reads from Hyperdrive, then decommission the D1 binding.`):e.warn(`Imported ${String(s.inserted)} of ${String(i.rows)} exported row(s) — the remainder likely already existed in the target (see conflicts above). Re-run after resolving, or inspect the dump with --out.`),{code:0})}finally{n!==void 0&&I(n,{force:!0,recursive:!0})}},Tr=O(({argument:r,cwd:e,logger:o,options:t})=>{const n=r[0];if(n==="generate")return K({cwd:e,logger:o,name:r[1]??t.name});if(n==="d1-to-hyperdrive")return lr({batchSize:t.batchSize,fromToken:t.fromToken??t.token,fromUrl:t.fromUrl??t.url,logger:o,out:t.out,prod:t.prod===!0,tables:t.tables,toToken:t.toToken??t.token,toUrl:t.toUrl??t.url});if(n==="create"){const a=r[1]??t.name;return a?nr({cwd:e,logger:o,name:a,table:t.table}):(o.error("migrate create requires a name. Usage: lunora migrate create <name> [--table <table>]"),{code:1})}if(n==="up"||n==="down"||n==="status"){const a=r[1]??t.name;return a?dr({batchSize:t.batchSize,cwd:e,dryRun:t.dryRun===!0,id:a,logger:o,maxBatches:t.steps,prod:t.prod===!0,subcommand:n,token:t.token,url:D({cwd:e,prod:t.prod===!0,url:t.url}),yes:t.yes===!0}):(o.error(`migrate ${n} requires a migration id. Usage: lunora migrate ${n} <id>`),{code:1})}return o.error(`unknown migrate subcommand: "${n??""}" — expected generate | create | up | down | status`),{code:1}});export{Tr as execute,nr as runMigrateCreateCommand,dr as runMigrateDataCommand,K as runMigrateGenerateCommand,lr as runMigrateToHyperdriveCommand};