UNPKG

@lunora/cli

Version:

The Lunora CLI: init, dev, deploy, codegen, migrate, seed, doctor, insights, logs, registry, and the rest of the project commands

14 lines (8 loc) • 12.1 kB
import{existsSync as F,readFileSync as L,writeFileSync as P}from"node:fs";import{parseSchemaSnapshot as H,SchemaSnapshotParseError as B,evaluateSchemaDrift as q,serializeSchemaSnapshot as I}from"@lunora/codegen";import{decodeWire as y}from"@lunora/wire";import{f as S}from"./export-rows-EzdNDYpa.mjs";const D=new Set(["addedRequiredField","changedFieldKind","changedFieldShape","fieldOptionalToRequired","removedField"]),R=e=>e.table!==void 0&&(e.uniqueOn!==void 0||e.field!==void 0&&D.has(e.type)),E=10,O=e=>e.kind==="id"||e.kind==="storage"||[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})].some(t=>t!==void 0&&O(t)),f=e=>e===null?"null":Array.isArray(e)?"array":e instanceof ArrayBuffer||ArrayBuffer.isView(e)?"bytes":typeof e,b=e=>f(e)==="object",V=/^-?\d+n$/u,K=/\$\{/u,T=e=>{const t=e.trim(),r=t[0];if(t.length>=2&&(r==="'"||r==="`")&&t.endsWith(r)){const n=t.slice(1,-1);return n.includes("\\")||K.test(n)||r==="'"&&n.includes("'")?void 0:{value:n}}if(V.test(t))return{value:BigInt(t.slice(0,-1))};try{return{value:JSON.parse(t)}}catch{return}},m=e=>typeof e=="number"&&Number.isFinite(e),w=(e,t)=>m(e)&&Math.abs(e)<=t,A={any:()=>!0,bigint:e=>typeof e=="bigint",boolean:e=>typeof e=="boolean",bytes:e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),date:m,geoPoint:e=>b(e)&&w(e.lat,90)&&w(e.lng,180),id:e=>typeof e=="string",null:e=>e===null,number:m,storage:e=>typeof e=="string",string:e=>typeof e=="string",timestamp:m},p=(e,t,r)=>{if(t!==void 0)for(const[n,o]of e){const s=g(o,t,r(n));if(s!==void 0)return s}},M={array:(e,t,r)=>Array.isArray(e)?p(e.map((n,o)=>[String(o),n]),t.inner,n=>`${r}[${n}]`):[r,`expected array, found ${f(e)}`],literal:(e,t,r)=>e===T(t.literalValue??"")?.value?void 0:[r,`expected the literal ${t.literalValue??"?"}, found a different ${f(e)}`],object:(e,t,r)=>b(e)?G(e,t.shape??{},`${r}.`):[r,`expected object, found ${f(e)}`],record:(e,t,r)=>b(e)?p(Object.keys(e).map(n=>[n,n]),t.keyType,()=>`${r}[*]`)??p(Object.entries(e),t.valueType,()=>`${r}[*]`):[r,`expected record, found ${f(e)}`],union:(e,t,r)=>(t.members??[]).some(n=>g(e,n,r)===void 0)?void 0:[r,`matches no member of the union (found ${f(e)})`]},W=(e,t,r,n)=>n(e)?typeof e=="string"&&t.stringMaxLength!==void 0&&e.length>t.stringMaxLength?[r,`longer than ${String(t.stringMaxLength)} characters`]:void 0:[r,`expected ${t.kind}, found ${f(e)}`],g=(e,t,r)=>{if(e===null&&t.column?.notNull===!1)return;if(t.kind==="optional")return e===void 0||t.inner===void 0?void 0:g(e,t.inner,r);const n=A[t.kind];if(e===void 0)return n?.(e)===!0?void 0:[r,"required, but missing"];if(n!==void 0)return W(e,t,r,n);const o=M[t.kind];return o===void 0?[r,`has a \`${t.kind}\` validator this check does not know`]:o(e,t,r)},G=(e,t,r)=>{if(Object.keys(e).some(n=>!Object.hasOwn(t,n)))return[`${r}*`,"holds a property the schema does not declare"];for(const[n,o]of Object.entries(t)){const s=g(e[n],o,`${r}${n}`);if(s!==void 0)return s}},x=(e,t)=>{if(e.sourceText!==void 0||e.unmodelledRefinement===!0||e.unresolvedShape===!0||e.hasRefinement===!0&&e.stringMaxLength===void 0)return`${t} has a validator or refinement that cannot be checked outside the worker`;if(e.kind==="literal"&&T(e.literalValue??"")===void 0)return`${t} is a \`v.literal()\` whose value is not a plain literal, so rows cannot be compared to it outside the worker`;if(e.kind==="from")return`${t} is a \`v.from()\` schema, which cannot be checked outside the worker`;if(e.kind!=="optional"&&A[e.kind]===void 0&&M[e.kind]===void 0)return`${t} has a \`${e.kind}\` validator this check does not know`;const r=[e.inner,e.keyType,e.valueType,...e.members??[],...Object.values(e.shape??{})];for(const n of r){const o=n===void 0?void 0:x(n,t);if(o!==void 0)return o}},J=(e,t,r,n)=>{const o=y(n[t]);return e.shardMode==="global"&&o===null&&r.kind==="optional"&&r.column?.notNull!==!1?void 0:o},U=(e,t)=>{const r=o=>t[o]===void 0||e.table.shardMode==="global"&&t[o]===null,n=e.removed.find(o=>!r(o));if(n!==void 0)return[n,"is no longer declared, but the row still holds it"];for(const[o,s]of e.validated){const a=g(J(e.table,o,s,t),s,o);if(a!==void 0)return a}},k=e=>typeof e=="boolean"?e?"n:1":"n:0":typeof e=="number"||typeof e=="bigint"?`n:${e.toString()}`:typeof e=="string"?`s:${e}`:`j:${JSON.stringify(e)}`,z=(e,t,r)=>{const n=typeof e.table.shardMode=="object"?k(y(t[e.table.shardMode.field])):"",o=typeof t._id=="string"?t._id:"(no _id)";for(const s of e.unique){const a=s.map(c=>y(t[c]));if(a.some(c=>c==null))continue;const d=JSON.stringify([e.table.name,s,n,a.map(c=>k(c))]),i=r.get(d);if(i===void 0)r.set(d,o);else return[s.join(" + "),i]}},Y=(e,t)=>{if(t.length===0||t.some(r=>e.table.shape[r]===void 0))return`the unique constraint on ${e.table.name} names a field the current schema does not declare`;e.unique.push(t)},Q=(e,t)=>{if(t.uniqueOn!==void 0)return Y(e,t.uniqueOn);const{field:r}=t;if(r===void 0)return`"${t.summary}" is not something stored rows can confirm`;const n=e.table.shape[r];if(t.type==="removedField"||n===void 0){e.removed.push(r);return}const o=(t.type==="changedFieldKind"||t.type==="changedFieldShape")&&O(n)?`${t.table}.${r} now references a different table or bucket, which a stored id cannot show`:x(n,`${t.table}.${r}`);return o===void 0&&e.validated.push([r,n]),o},X=(e,t)=>{const r=new Map;for(const n of e){if(!R(n))return{reason:`"${n.summary}" is not something stored rows can confirm`};const o=t.get(n.table);if(o===void 0)return{reason:`table ${n.table} is not in the current schema`};const s=r.get(n.table)??{removed:[],table:o,unique:[],validated:[]};r.set(n.table,s);const a=Q(s,n);if(a!==void 0)return{reason:a}}return{plans:r}},me=async e=>{const t=X(e.changes,new Map(e.tables.map(i=>[i.name,i])));if("reason"in t)return{kind:"inconclusive",reason:t.reason};const{plans:r}=t;if(e.target===void 0)return{kind:"inconclusive",reason:"no deployed worker to read the stored rows from — pass --migrate-url (or record one with `lunora link`) and set LUNORA_ADMIN_TOKEN"};const n=[...r.keys()].toSorted((i,c)=>i.localeCompare(c)),o=[],s=new Map;let a=0,d=!1;try{await S(e.target,n,i=>{const c=r.get(i.table);if(c===void 0)return;a+=1;const l=z(c,i.doc,s),h=l===void 0?U(c,i.doc):[l[0],`duplicates ${l[1]}`];if(h!==void 0){if(o.length===E)return d=!0,!1;o.push({field:h[0],id:typeof i.doc._id=="string"?i.doc._id:"(no _id)",reason:h[1],table:i.table})}})}catch(i){return{kind:"inconclusive",reason:i instanceof Error?i.message:String(i)}}return o.length===0?{kind:"conforms",rows:a,tables:n}:{failures:o,kind:"fails",rows:a,truncated:d}},Z=e=>[`${String(e.failures.length)}${e.truncated?"+":""} stored row(s) do not fit the new schema${e.truncated?` (the first ${String(E)} shown)`:""}:`,...e.failures.map(t=>` - ${t.table} ${t.id}: ${t.field} ${t.reason}`)].join(` `),$=(e,t,r)=>{const n=e[t];return typeof n=="number"&&n<r},pe=async e=>{const t=new Map;for(const n of e.changes)n.table!==void 0&&n.expiry!==void 0&&t.set(n.table,n.expiry);if(e.target===void 0)return"no deployed worker to read the stored rows from";const r=new Map([...t.keys()].map(n=>[n,0]));try{await S(e.target,[...t.keys()].toSorted((n,o)=>n.localeCompare(o)),n=>{const o=t.get(n.table);if(o===void 0||!$(n.doc,o.field,e.now-(o.after??0)))return;const{previous:s}=o;s!==void 0&&$(n.doc,s.field,e.now-(s.after??0))||r.set(n.table,(r.get(n.table)??0)+1)})}catch(n){return n instanceof Error?n.message:String(n)}return r},ee=e=>{if(!F(e))return{status:"absent"};let t;try{t=L(e,"utf8")}catch{return{status:"corrupt"}}try{const r=H(t);return r===void 0?{status:"corrupt"}:{snapshot:r,status:"ok"}}catch(r){if(r instanceof B)return{status:"corrupt"};throw r}},te=(e,t)=>{P(e,I(t),"utf8")},ne=e=>{const t=`schema-drift gate: the committed baseline ${e.snapshotPath} is unreadable or malformed, so schema drift cannot be checked. Fix it (e.g. resolve a merge conflict in lunora/.lunora-schema.json), or delete it: the next run captures a fresh baseline from the current schema, checking nothing against the old one.`;return e.readOnly||e.logger.error(t),{blocked:!0,changes:[],reason:t}},re=(e,t,r)=>e!==void 0?` — ${String(e)} stored row(s) are past the new cutoff and are deleted on the next sweep`:typeof t=="string"?` (the affected rows could not be counted: ${t})`:r?"":" (the affected rows are counted by `lunora deploy`, which reads the deployed worker)",oe=async(e,t)=>{const r=e.filter(o=>o.expiry!==void 0);if(r.length===0)return"";if(t.readOnly||t.countExpiringRows===void 0)return` The rows the next sweep would delete were not counted: \`lunora ${t.command??"prepare"}\` does not read a deployment; \`lunora deploy\` counts them.`;const n=await t.countExpiringRows(r);return typeof n=="string"?` The rows the next sweep would delete could not be counted: ${n}.`:` ${r.map(o=>`Next sweep would delete ${String(n.get(o.table??"")??0)} stored row(s) of ${o.table??"?"}, which are past the new cutoff.`).join(` `)}`},_=async(e,t)=>{if(t.readOnly)return;const r=e.filter(s=>s.warning===!0),n=r.filter(s=>s.expiry!==void 0),o=n.length>0&&t.countExpiringRows!==void 0?await t.countExpiringRows(n):void 0;for(const s of r){const a=typeof o=="object"&&s.table!==void 0?o.get(s.table):void 0,d=s.expiry===void 0?"":re(a,o,t.countExpiringRows!==void 0);t.logger.warn(`schema-drift warning: ${s.summary}${d}`)}},se=(e,t)=>(t.readOnly||t.logger.warn(`schema baseline left at its committed shape — --allow-schema-drift overrides this run only: ${t.snapshotPath}`),{blocked:!1,changes:e.changes,reason:e.reason}),ie=e=>e?.kind==="fails"?` ${Z(e)}`:e?.kind==="inconclusive"?` The stored rows were not checked: ${e.reason}.`:"",ae=async(e,t)=>{const r=e.uncovered.filter(o=>R(o));if(!(!(r.length>0&&r.length===e.uncovered.length)||t.readOnly))return t.checkStoredRows===void 0?{kind:"inconclusive",reason:`\`lunora ${t.command??"prepare"}\` does not read a deployment; run \`lunora deploy\`, which checks the stored rows first`}:t.checkStoredRows(r)},ce=async(e,t)=>{const r=await ae(e,t);if(r?.kind==="conforms")return t.logger.success(`schema-drift gate: all ${String(r.rows)} stored row(s) of ${r.tables.join(", ")} fit the new schema — the change needs no backfill`),await _(e.changes,t),{blocked:!1,changes:e.changes,reason:e.reason,rebless:t.rebless};const n=`${e.reason}${ie(r)}${await oe(e.uncovered,t)}`;return t.readOnly||t.logger.error(n),{blocked:!0,changes:e.changes,reason:n}},ye=async e=>{const{allowDrift:t,checkStoredRows:r,codegen:n,command:o,countExpiringRows:s,logger:a,readOnly:d=!1}=e,i=n.schemaSnapshotPath,c=ee(i),l={checkStoredRows:r,command:o,countExpiringRows:s,logger:a,readOnly:d,rebless:()=>{te(i,n.schemaSnapshot)},snapshotPath:i};if(c.status==="corrupt")return ne(l);const h=C=>q({allowDrift:C,baseline:c.status==="ok"?c.snapshot:void 0,command:o,current:n.schemaSnapshot,indexReferences:n.indexReferences,migrations:n.migrations}),u=h(t);if(u.blocked)return ce(u,l);const N=t&&u.changes.length>0&&h(!1).blocked;return u.changes.length>0?(d||a.info(u.reason),N?se(u,l):(await _(u.changes,l),{blocked:!1,changes:u.changes,reason:u.reason,rebless:d?void 0:l.rebless})):{blocked:!1,changes:u.changes,reason:u.reason}},j="/_lunora/health",be="/_lunora/health/ready",de=(e,t=j)=>(e.endsWith("/")?e.slice(0,-1):e)+t,v=async(e,t,r)=>{let n={error:`health probe failed: no health path configured for ${e}`,url:e};for(const[o,s]of t.entries()){const a=de(e,s);let d;try{d=await r(a)}catch(i){const c=i instanceof Error?i.message:String(i);return{error:`health probe failed: could not reach ${a} (${c})`,url:a}}if(d.ok)return{url:a};if(n={error:`health probe failed: ${a} returned HTTP ${String(d.status)}`,url:a},d.status!==404||o===t.length-1)return n}return n},le=async e=>new Promise(t=>{setTimeout(t,e)}),we=async({attempts:e=1,baseUrl:t,delayMs:r=2e3,fetchImpl:n,paths:o=[j],sleep:s=le,timeoutMs:a=1e4})=>{const d=n??(l=>fetch(l,{signal:AbortSignal.timeout(a)})),i=Math.max(1,e);let c=await v(t,o,d);for(let l=1;l<i&&c.error!==void 0;l+=1)await s(r),c=await v(t,o,d);return c};export{be as H,j as a,me as b,pe as c,we as p,ye as r};