@lunora/codegen 1.0.0-alpha.184 → 1.0.0-alpha.186
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.mjs +1 -1
- package/dist/packem_shared/{GENERATED_HEADER-DOoZbn9A.mjs → GENERATED_HEADER-DicwKMVV.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-BzT38i2u.mjs → OPENRPC_VERSION-BPs1hq5Q.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-C3lMTxfR.mjs → SCHEMA_SNAPSHOT_FILENAME-BiHpdo7a.mjs} +1 -1
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-CBMD1pia.mjs +2 -0
- package/dist/packem_shared/{SchemaSnapshotParseError-yrVM8bTa.mjs → SchemaSnapshotParseError-D_n90pDd.mjs} +1 -1
- package/dist/packem_shared/{buildOpenApiDocument-6swU6A67.mjs → buildOpenApiDocument-BaDsKuhs.mjs} +1 -1
- package/dist/packem_shared/{emit-DVA2ykxi.mjs → emit-wC8dZkgS.mjs} +1 -1
- package/dist/packem_shared/{emitApp-DjsY5wOK.mjs → emitApp-BpcEHPGo.mjs} +1 -1
- package/package.json +9 -9
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-CWESEYLi.mjs +0 -2
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-
|
|
1
|
+
import{SCHEMA_SNAPSHOT_VERSION as t,diffSchemaSnapshots as s,serializeSchemaSnapshot as a}from"./packem_shared/SCHEMA_SNAPSHOT_VERSION-CBMD1pia.mjs";import{formatAdvisories as m,lintSchema as d,toAdvisorContext as f}from"./packem_shared/formatAdvisories-CkEu1eye.mjs";import{describeErrorLevelFindings as c,errorAdvisoryNames as n,errorPlatformDiagnosticNames as l}from"./packem_shared/describeErrorLevelFindings-D23VSkFP.mjs";import{CodegenDiagnosticError as x,diagnosticAt as E}from"./packem_shared/CodegenDiagnosticError-BUXlG3P-.mjs";import{AGENTS_FILENAME as u,discoverAgents as v}from"./packem_shared/AGENTS_FILENAME-B78F7DuQ.mjs";import{listLunoraSourceFiles as g}from"./packem_shared/listLunoraSourceFiles-D4xthUf-.mjs";import{default as O}from"./packem_shared/discoverAuthApiCalls-DoblmzUW.mjs";import{CONTAINERS_FILENAME as M,discoverContainers as T}from"./packem_shared/CONTAINERS_FILENAME-CQoUu7n7.mjs";import{default as h}from"./packem_shared/discoverCrons-CMu0sA8k.mjs";import{FLAGS_FILENAME as F,discoverFlags as I}from"./packem_shared/FLAGS_FILENAME-CoTJH0-7.mjs";import{default as D}from"./packem_shared/discoverFunctions-DB9G_XrW.mjs";import{default as U}from"./packem_shared/discoverHttpRoutes-S81Iv_iB.mjs";import{default as H}from"./packem_shared/discoverHyperdriveCalls-DgAYcZRD.mjs";import{default as y}from"./packem_shared/discoverInserts-COk-Sm_n.mjs";import{d as W}from"./packem_shared/index-D_Z8rX-f.mjs";import{default as V}from"./packem_shared/discoverMigrations-B_sYrTyE.mjs";import{MUTATORS_FILENAME as Q,discoverMutators as w}from"./packem_shared/MUTATORS_FILENAME-CTHlZ1j6.mjs";import{default as q}from"./packem_shared/discoverNondeterministicCalls-DkVVHe3U.mjs";import{NOTIFY_FILENAME as Y,discoverNotifyCalls as X,discoverNotifyConfig as Z}from"./packem_shared/NOTIFY_FILENAME-CZh4jN4q.mjs";import{default as ee}from"./packem_shared/readPackageDependencies-C6h6FZuP.mjs";import{d as oe}from"./packem_shared/queries-CPlxXagL.mjs";import{QUEUES_FILENAME as se,discoverQueues as ae}from"./packem_shared/QUEUES_FILENAME-Q3CF3uYr.mjs";import{default as me}from"./packem_shared/discoverR2sqlCalls-6u0OKy2N.mjs";import{default as fe}from"./packem_shared/discoverRlsProcedures-vJZq3yhb.mjs";import{default as ce}from"./packem_shared/discoverRlsMetadata-CwWRPb8N.mjs";import{discoverSandboxUsage as le}from"./packem_shared/discoverSandboxUsage-DskdDbkM.mjs";import{default as xe}from"./packem_shared/discoverSchema-DoZtXwLg.mjs";import{SHAPES_FILENAME as Ae,discoverShapes as ue}from"./packem_shared/SHAPES_FILENAME-Bvd5kgsF.mjs";import{default as Ne}from"./packem_shared/discoverStorageRulesMetadata-xhxu-mkS.mjs";import{WORKFLOWS_FILENAME as Ce,discoverWorkflows as Oe}from"./packem_shared/WORKFLOWS_FILENAME-BaSbufF2.mjs";import{G as Me,e as Te,a as _e,b as he,c as Le,d as Fe,f as Ie,g as Pe,h as De,i as Ge,j as Ue,k as be,l as He,m as je,n as ye}from"./packem_shared/emit-wC8dZkgS.mjs";import{emitApp as We}from"./packem_shared/emitApp-BpcEHPGo.mjs";import{isD1GlobalTable as Ve,isHyperdriveGlobalTable as ze}from"./packem_shared/isD1GlobalTable-udvHAAzD.mjs";import{buildOpenApiDocument as we,emitOpenApi as Je,emitOpenApiModule as qe}from"./packem_shared/buildOpenApiDocument-BaDsKuhs.mjs";import{OPENRPC_VERSION as Ye,buildOpenRpcDocument as Xe,emitOpenRpc as Ze,emitOpenRpcModule as $e}from"./packem_shared/OPENRPC_VERSION-BPs1hq5Q.mjs";import{DEFAULT_TARGET as rr,platformMatrixIds as or,readProjectTarget as tr,resolveCodegenTarget as sr}from"./packem_shared/DEFAULT_TARGET-DtzlGawL.mjs";import{PROJECT_CONFIG_FILENAMES as ir,findProjectConfigFile as mr,loadProjectConfig as dr,readProjectConfigLiterals as fr}from"./packem_shared/PROJECT_CONFIG_FILENAMES-D29yBg5X.mjs";import{SCHEMA_SNAPSHOT_FILENAME as cr,createCodegenProject as nr,findTsconfig as lr,refreshCodegenProject as Sr,runCodegen as xr}from"./packem_shared/SCHEMA_SNAPSHOT_FILENAME-BiHpdo7a.mjs";import{SchemaSnapshotParseError as Ar,buildSchemaSnapshot as ur,evaluateSchemaDrift as vr,parseSchemaSnapshot as Nr}from"./packem_shared/SchemaSnapshotParseError-D_n90pDd.mjs";import{schemaFromIr as Cr}from"./packem_shared/schemaFromIr-BWFnvCVg.mjs";import{LUNORA_ERROR_CODES as Rr,validatorIrToJsonSchema as Mr}from"./packem_shared/LUNORA_ERROR_CODES-C2s0xWQD.mjs";import{SDK_LANGUAGES as _r,SDK_TARGETS as hr,generateSdk as Lr}from"./packem_shared/SDK_LANGUAGES-CFyux-74.mjs";import{redact as Ir,secretKindOf as Pr}from"./packem_shared/redact-Cy14LEnc.mjs";import{MESSAGE_SOLUTIONS as Gr,findSolutionByMessage as Ur}from"@lunora/errors";import{isTypedSchema as Hr}from"./packem_shared/isTypedSchema-B_qlBbE-.mjs";const e="0.0.0";export{u as AGENTS_FILENAME,M as CONTAINERS_FILENAME,x as CodegenDiagnosticError,rr as DEFAULT_TARGET,F as FLAGS_FILENAME,Me as GENERATED_HEADER,Rr as LUNORA_ERROR_CODES,Gr as LUNORA_SOLUTION_RULES,Q as MUTATORS_FILENAME,Y as NOTIFY_FILENAME,Ye as OPENRPC_VERSION,ir as PROJECT_CONFIG_FILENAMES,se as QUEUES_FILENAME,cr as SCHEMA_SNAPSHOT_FILENAME,t as SCHEMA_SNAPSHOT_VERSION,_r as SDK_LANGUAGES,hr as SDK_TARGETS,Ae as SHAPES_FILENAME,Ar as SchemaSnapshotParseError,e as VERSION,Ce as WORKFLOWS_FILENAME,we as buildOpenApiDocument,Xe as buildOpenRpcDocument,ur as buildSchemaSnapshot,nr as createCodegenProject,c as describeErrorLevelFindings,E as diagnosticAt,s as diffSchemaSnapshots,v as discoverAgents,O as discoverAuthApiCalls,T as discoverContainers,h as discoverCrons,I as discoverFlags,D as discoverFunctions,U as discoverHttpRoutes,H as discoverHyperdriveCalls,y as discoverInserts,W as discoverMaskProcedures,V as discoverMigrations,w as discoverMutators,q as discoverNondeterministicCalls,X as discoverNotifyCalls,Z as discoverNotifyConfig,oe as discoverQueries,ae as discoverQueues,me as discoverR2sqlCalls,ce as discoverRlsMetadata,fe as discoverRlsProcedures,le as discoverSandboxUsage,xe as discoverSchema,ue as discoverShapes,Ne as discoverStorageRulesMetadata,Oe as discoverWorkflows,Te as emitAgents,_e as emitApi,We as emitApp,he as emitCollections,Le as emitContainers,Fe as emitCrons,Ie as emitDataModel,Pe as emitDrizzleSchema,De as emitFunctions,Je as emitOpenApi,qe as emitOpenApiModule,Ze as emitOpenRpc,$e as emitOpenRpcModule,Ge as emitScheduler,Ue as emitServer,be as emitShard,He as emitVectors,je as emitWorkflows,ye as emitWranglerCronTriggers,n as errorAdvisoryNames,l as errorPlatformDiagnosticNames,vr as evaluateSchemaDrift,Ur as findLunoraSolution,mr as findProjectConfigFile,lr as findTsconfig,m as formatAdvisories,Lr as generateSdk,Ve as isD1GlobalTable,ze as isHyperdriveGlobalTable,Hr as isTypedSchema,d as lintSchema,g as listLunoraSourceFiles,dr as loadProjectConfig,Nr as parseSchemaSnapshot,or as platformMatrixIds,ee as readPackageDependencies,fr as readProjectConfigLiterals,tr as readProjectTarget,Ir as redact,Sr as refreshCodegenProject,sr as resolveCodegenTarget,xr as runCodegen,Cr as schemaFromIr,Pr as secretKindOf,a as serializeSchemaSnapshot,f as toAdvisorContext,Mr as validatorIrToJsonSchema};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./SCHEMA_SNAPSHOT_VERSION-
|
|
1
|
+
import"./SCHEMA_SNAPSHOT_VERSION-CBMD1pia.mjs";import{G as r,U as o,o as n,e as l,a as A,b as E,c as S,d as p,f as c,g as d,h as g,p as u,i as C,q as h,j as D,k as f,l as G,m as R,n as _}from"./emit-wC8dZkgS.mjs";import"./isD1GlobalTable-udvHAAzD.mjs";import"./paths-C-9fwEgQ.mjs";import"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";export{r as GENERATED_HEADER,o as UMBRELLA_BASE_PACKAGES,n as buildStorageColumns,l as emitAgents,A as emitApi,E as emitCollections,S as emitContainers,p as emitCrons,c as emitDataModel,d as emitDrizzleSchema,g as emitFunctions,u as emitQueues,C as emitScheduler,h as emitSeed,D as emitServer,f as emitShard,G as emitVectors,R as emitWorkflows,_ as emitWranglerCronTriggers};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{G as c}from"./emit-
|
|
1
|
+
import{G as c}from"./emit-wC8dZkgS.mjs";import{s as u}from"./paths-C-9fwEgQ.mjs";import{validatorIrToJsonSchema as m,objectSchema as p,LUNORA_ERROR_CODES as i}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";const l="1.3.2",d={description:"Result is TS-inferred from the function's return type (no `.output()` declared); best-effort — any JSON."},R=e=>{const n=u(e.filePath),o=`${n}:${e.exportName}`;return{description:`Invoke the \`${e.kind}\` \`${o}\` over the Lunora RPC envelope (POST /_lunora/rpc, body \`{ "functionPath": "${o}", "args": { … } }\`).`,errors:i.map((r,s)=>({code:-32e3-s,data:{code:r},message:r})),name:o,params:[{description:"The function's argument object (the RPC envelope's `args`).",name:"args",required:Object.keys(e.args).length>0,schema:p(e.args)}],result:{name:"result",schema:e.output?m(e.output):d},summary:`${e.kind}: ${o}`,"x-lunora-function-kind":e.kind,"x-tags":[{name:n}]}},g=e=>{const n=e.version??"0.0.0",r=e.functions.filter(t=>t.visibility!=="internal"&&t.kind!=="stream").map(t=>R(t)).toSorted((t,a)=>t.name.localeCompare(a.name));return{info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora RPC",version:n},methods:r,openrpc:l}},S=e=>`${JSON.stringify(g(e),void 0,2)}
|
|
2
2
|
`,v=e=>`${c}export const openRpcSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
|
|
3
3
|
`;export{l as OPENRPC_VERSION,g as buildOpenRpcDocument,S as emitOpenRpc,v as emitOpenRpcModule};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync as b,mkdirSync as Ps,readFileSync as Mt,writeFileSync as Is,rmSync as ws}from"node:fs";import{join as f,dirname as te}from"node:path";import{performance as Ee}from"node:perf_hooks";import{runAdvisor as Ts}from"@lunora/advisor";import{LunoraError as D}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as at}from"ts-morph";import{serializeSchemaSnapshot as Cs}from"./SCHEMA_SNAPSHOT_VERSION-
|
|
1
|
+
import{existsSync as b,mkdirSync as Ps,readFileSync as Mt,writeFileSync as Is,rmSync as ws}from"node:fs";import{join as f,dirname as te}from"node:path";import{performance as Ee}from"node:perf_hooks";import{runAdvisor as Ts}from"@lunora/advisor";import{LunoraError as D}from"@lunora/errors";import{SyntaxKind as l,Node as i,Project as at}from"ts-morph";import{serializeSchemaSnapshot as Cs}from"./SCHEMA_SNAPSHOT_VERSION-CBMD1pia.mjs";import{toAdvisorContext as Fs}from"./formatAdvisories-CkEu1eye.mjs";import{s as Os}from"./paths-C-9fwEgQ.mjs";import{C as se,o as _t,j as Rs,f as Ls,k as Ds,b as ks,c as Ms,m as _s,e as Ks,p as zs,d as $s,i as Us,l as qs,g as Bs,q as Vs,n as Ws,a as js,h as Hs}from"./emit-wC8dZkgS.mjs";import{isD1GlobalTable as Kt,isHyperdriveGlobalTable as zt}from"./isD1GlobalTable-udvHAAzD.mjs";import{discoverAgents as Gs}from"./AGENTS_FILENAME-B78F7DuQ.mjs";import{discoverContainers as Ys}from"./CONTAINERS_FILENAME-CQoUu7n7.mjs";import Qs from"./discoverCrons-CMu0sA8k.mjs";import{diagnosticAt as ce}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{b as le}from"./module-specifiers-WF8iAydP.mjs";import{listLunoraSourceFiles as h,unwrapExpression as H,listSecurityScanFiles as Te,objectLiteralFromCallbackBody as $t,propertyInitializer as N,lunoraRelativePath as E,collectCallRows as I,collectSecurityCallRows as Xs,limitNameOf as Ut,isContextIdentifier as Ne,handlerOf as Zs,isDatabaseAccessor as k,readTargetOf as qt,enclosingExportName as Js}from"./listLunoraSourceFiles-D4xthUf-.mjs";import en from"./readPackageDependencies-C6h6FZuP.mjs";import{discoverQueues as tn}from"./QUEUES_FILENAME-Q3CF3uYr.mjs";import{discoverSandboxUsage as sn}from"./discoverSandboxUsage-DskdDbkM.mjs";import nn from"./discoverStorageRulesMetadata-xhxu-mkS.mjs";import{a as y,c as M,d as Bt,e as rn}from"./classify-procedure-call-C8jbo0IJ.mjs";import{discoverWorkflows as on}from"./WORKFLOWS_FILENAME-BaSbufF2.mjs";import{gatePlatformFeatures as an,resolveCodegenTarget as cn,readTargetDiagnostics as ln}from"./DEFAULT_TARGET-DtzlGawL.mjs";import{i as L,a as z,e as S,r as un,b as dn,s as ue,c as fn,f as gn,d as pn}from"./queries-CPlxXagL.mjs";import{r as de,s as mn}from"./parse-validator-tdRHHDzh.mjs";import hn from"./discoverAuthApiCalls-DoblmzUW.mjs";import ct from"./discoverFunctions-DB9G_XrW.mjs";import{i as xn,r as vn,e as En}from"./unwrap-handler-return-CmIWbykC.mjs";import lt from"./discoverHttpRoutes-S81Iv_iB.mjs";import Sn from"./discoverHyperdriveCalls-DgAYcZRD.mjs";import yn from"./discoverInserts-COk-Sm_n.mjs";import{m as Ce,a as re,s as Vt,d as An}from"./index-D_Z8rX-f.mjs";import{e as Wt}from"./exported-procedure-chains-C9FHwphy.mjs";import Nn from"./discoverMigrations-B_sYrTyE.mjs";import{MUTATORS_FILENAME as bn,isDefineMutatorCallee as Pn,discoverMutators as ut}from"./MUTATORS_FILENAME-CTHlZ1j6.mjs";import In from"./discoverNondeterministicCalls-DkVVHe3U.mjs";import{discoverNotifyConfig as wn,discoverNotifyCalls as Tn}from"./NOTIFY_FILENAME-CZh4jN4q.mjs";import Cn from"./discoverR2sqlCalls-6u0OKy2N.mjs";import Fn from"./discoverRlsProcedures-vJZq3yhb.mjs";import On from"./discoverRlsMetadata-CwWRPb8N.mjs";import Rn from"./discoverSchema-DoZtXwLg.mjs";import{secretKindOf as Ln,redact as Dn,isHeuristicSecretKind as kn,isSecretishName as Mn}from"./redact-Cy14LEnc.mjs";import{discoverShapes as _n}from"./SHAPES_FILENAME-Bvd5kgsF.mjs";import{emitApp as Kn}from"./emitApp-BpcEHPGo.mjs";import{buildOpenApiDocument as zn,emitOpenApiModule as $n}from"./buildOpenApiDocument-BaDsKuhs.mjs";import{buildOpenRpcDocument as Un,emitOpenRpcModule as qn}from"./OPENRPC_VERSION-BPs1hq5Q.mjs";import{buildSchemaSnapshot as Bn}from"./SchemaSnapshotParseError-D_n90pDd.mjs";const dt=(e,t="api")=>{const s=new Map;for(const n of e){const o=Os(n),r=s.get(o);if(r===void 0){s.set(o,n);continue}if(r!==n){const a=t==="api"?`the generated api.ts would declare "${o}" twice and the dispatch key "${o}:<fn>" would be ambiguous`:`the generated api.ts would declare "${o}" twice in HttpStreamsRef and again in the httpStreams object literal`;throw new D("INTERNAL",`@lunora/codegen: "${r}" and "${n}" both map to the ${t} namespace "${o}" — ${a}. Rename one file so the two differ by more than a non-identifier character (\`-\`, \`.\`, \`/\` and \`_\` all sanitize to \`_\`).`,{status:500})}}},Vn=(e,t={})=>{const{hasVectors:s=!0,scheduler:n=!1,storage:o=!1,usage:r}=t,a=[];e.tables.some(c=>Kt(c))&&a.push({name:"@lunora/d1",reason:"`.global()` tables are D1-backed, so `_generated/app.ts` imports the D1 `ctx.db` adapter"}),e.tables.some(c=>zt(c))&&a.push({name:"@lunora/hyperdrive",reason:'`.global({ backend: "hyperdrive" })` tables route through `@lunora/hyperdrive/global`'},{name:"@lunora/sql-store",reason:'`.global({ backend: "hyperdrive" })` makes `_generated/app.ts` import the `SqlCtxDbOptions` / `SqlExec` types'}),n&&a.push({name:"@lunora/scheduler",reason:"a declared cron (or `ctx.scheduler` use) makes `_generated/app.ts` import `createScheduler`"}),o&&a.push({name:"@lunora/storage",reason:"a `v.storage()` column, a storage access rule (or `ctx.storage` use) makes `_generated/app.ts` import `createStorage`"}),e.vectorIndexes.length>0&&s&&a.push({name:"@lunora/bindings",reason:"`.vectorize()` indexes make `_generated/shard.ts` import `@lunora/bindings/vectors`"});for(const c of r===void 0?[]:se)c.requiredPackage!==void 0&&r?.[c.key]===!0&&a.push({name:c.requiredPackage,reason:`\`ctx.${c.contextProperty??c.key}\` usage makes \`_generated/\` import \`${c.moduleSpecifier}\``});return a.filter((c,u)=>a.findIndex(d=>d.name===c.name)===u)},Wn=(e,t,s={})=>{if(t===void 0)return;const n=Vn(e,s).filter(r=>!t.has(r.name));if(n.length===0)return;const o=n.map(r=>` - ${r.name} — ${r.reason}`).join(`
|
|
2
2
|
`);throw new D("INTERNAL",`@lunora/codegen: this schema's generated code imports packages the project does not declare:
|
|
3
3
|
${o}
|
|
4
4
|
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const p=(e,i=2166136261)=>{let t=i;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")},m=e=>`${p(e,2166136261)}${p(e,16777619)}`,I=1;function g(e){const i={},t=Object.keys(e);t.sort();for(const n of t)i[n]=e[n];return i}const v=e=>`${JSON.stringify(e,void 0,2)}
|
|
2
|
+
`,E=e=>m(v(e)),a=e=>typeof e=="object"&&e!==null,$=e=>a(e)&&a(e.fields)&&a(e.indexes)&&a(e.relations)&&typeof e.shardMode=="string",_=e=>{if(e===void 0||e.trim()==="")return{status:"absent"};let i;try{i=JSON.parse(e)}catch(n){return{error:`baseline is not valid JSON: ${n instanceof Error?n.message:String(n)}`,status:"invalid"}}if(!a(i)||i.version!==1||!a(i.tables))return{error:`baseline is malformed or written by an incompatible version (expected version ${String(1)})`,status:"invalid"};for(const[n,o]of Object.entries(i.tables))if(!$(o))return{error:`baseline table "${n}" has an invalid structure`,status:"invalid"};return{snapshot:{jurisdiction:typeof i.jurisdiction=="string"?i.jurisdiction:void 0,migrationIds:Array.isArray(i.migrationIds)?i.migrationIds:[],tables:i.tables,version:1},status:"ok"}},b=(e,i)=>e.unique===i.unique&&e.fields.length===i.fields.length&&e.fields.every((t,n)=>t===i.fields[n]),f=e=>e.unique!==void 0,u=({nullable:e,optional:i,refined:t,unique:n,...o})=>JSON.stringify(g(o)),h=e=>({form:JSON.stringify([u(e),e.optional===!0,e.nullable===!0]),refined:e.refined===!0}),y=e=>e.kind==="union"&&e.members?e.members.map(i=>h(i)):[h({...e,nullable:!1,optional:!1})],S=(e,i)=>{if(i.kind!=="union")return!1;const t=y(i);return y(e).every(n=>t.some(o=>o.form===n.form&&(n.refined||!o.refined)))},d=e=>{switch(e.kind){case"array":return`array(${e.of?d(e.of):"?"})`;case"id":return`id(${e.ref??"?"})`;case"literal":return`literal(${e.literal??"?"})`;case"object":return`object({ ${Object.keys(e.fields??{}).join(", ")} })`;case"record":return`record(${e.key?d(e.key):"?"}, ${e.of?d(e.of):"?"})`;case"union":return(e.members??[]).map(i=>d(i)).join(" | ");default:return e.kind}},c=(e,i,t)=>({remediation:"backfill",scope:"table",severity:"breaking",summary:t,table:e,type:i}),l=(e,i,t)=>({remediation:"none",scope:"table",severity:"safe",summary:t,table:e,type:i}),k=(e,i,t,n,o)=>{if(!(t.kind===n.kind&&(!o||u(t)===u(n))))return o&&S(t,n)?l(e,"widenedFieldShape",`field ${e}.${i} widened: ${d(t)} → ${d(n)} — every stored value stays valid`):t.kind!==n.kind?c(e,"changedFieldKind",`field ${e}.${i} changed type: ${t.kind} → ${n.kind} — add a data migration to convert existing values`):c(e,"changedFieldShape",`field ${e}.${i} changed shape: ${d(t)} → ${d(n)} — stored values were written against the old shape; add a data migration to convert them`)},x=(e,i,t,n)=>{const o=[];return t.unique!==n.unique&&o.push(n.unique===!0?c(e,"addedFieldConstraint",`field ${e}.${i} became unique — existing duplicates would violate it; add a data migration to de-duplicate first`):l(e,"relaxedFieldConstraint",`field ${e}.${i} is no longer unique`)),t.nullable!==n.nullable&&o.push(n.nullable===!0?l(e,"relaxedFieldConstraint",`field ${e}.${i} became nullable`):c(e,"addedFieldConstraint",`field ${e}.${i} is no longer nullable — rows holding NULL would be invalid; add a data migration to backfill them`)),t.refined!==n.refined&&o.push(n.refined===!0?c(e,"addedFieldConstraint",`field ${e}.${i} gained a validation refinement — stored values were never checked against it; add a data migration if any could fail`):l(e,"relaxedFieldConstraint",`field ${e}.${i} dropped its validation refinement`)),o},O=(e,i,t,n)=>{const o=[],s=f(t)&&f(n),r=k(e,i,t,n,s);return r&&o.push(r),s&&o.push(...x(e,i,t,n)),t.optional&&!n.optional?o.push({remediation:"backfill",severity:"breaking",summary:`field ${e}.${i} became required — rows missing it would be invalid; add a data migration to backfill it`,table:e,scope:"table",type:"fieldOptionalToRequired"}):!t.optional&&n.optional&&o.push({remediation:"none",scope:"table",severity:"safe",summary:`field ${e}.${i} became optional`,table:e,type:"fieldRequiredToOptional"}),o},F=(e,i,t)=>t.optional?{remediation:"none",scope:"table",severity:"safe",summary:`added optional field ${e}.${i}`,table:e,type:"addedOptionalField"}:{remediation:"backfill",severity:"breaking",summary:`added required field ${e}.${i} — existing rows have no value; add a data migration to backfill it`,table:e,scope:"table",type:"addedRequiredField"},j=(e,i,t,n)=>{for(const[o,s]of Object.entries(t.fields)){const r=i.fields[o];r===void 0?n.push(F(e,o,s)):n.push(...O(e,o,r,s))}for(const o of Object.keys(i.fields))t.fields[o]===void 0&&n.push({remediation:"backfill",severity:"breaking",summary:`removed field ${e}.${o} — add a data migration if stored data must be cleaned up`,table:e,scope:"table",type:"removedField"})},w=(e,i,t,n)=>{for(const[o,s]of Object.entries(t.indexes)){const r=i.indexes[o];if(r===void 0){n.push(s.unique?{remediation:"backfill",scope:"table",severity:"breaking",summary:`added unique index ${o} on ${e} — existing duplicates would violate it; add a data migration to de-duplicate first`,table:e,type:"addedIndex"}:{remediation:"none",scope:"table",severity:"safe",summary:`added index ${o} on ${e}`,table:e,type:"addedIndex"});continue}b(r,s)||n.push({remediation:"code",severity:"breaking",summary:`index ${o} on ${e} changed shape — a query may have relied on the old index`,table:e,scope:"table",type:"changedIndex"})}for(const o of Object.keys(i.indexes))t.indexes[o]===void 0&&n.push({remediation:"code",severity:"breaking",summary:`removed index ${o} on ${e} — a query that used \`.withIndex("${o}")\` would break`,table:e,scope:"table",type:"removedIndex"})},A=(e,i,t,n)=>{for(const o of Object.keys(t.relations))i.relations[o]===void 0&&n.push({remediation:"none",scope:"schema",severity:"safe",summary:`added relation ${e}.${o}`,table:e,type:"addedRelation"});for(const o of Object.keys(i.relations))t.relations[o]===void 0&&n.push({remediation:"code",scope:"schema",severity:"breaking",summary:`removed relation ${e}.${o}`,table:e,type:"removedRelation"})},q=(e,i,t,n)=>{i.shardMode!==t.shardMode&&n.push({remediation:"rehome",severity:"breaking",summary:`table ${e} changed shard mode: ${i.shardMode} → ${t.shardMode} — its physical storage moves, and existing rows do NOT follow the schema; re-home them with an export/import round trip (https://lunora.sh/docs/concepts/sharding#migrating-a-populated-table)`,table:e,scope:"table",type:"changedShardMode"}),j(e,i,t,n),w(e,i,t,n),A(e,i,t,n)},C=(e,i)=>{const t=[],n=e?.tables??{};for(const[o,s]of Object.entries(i.tables)){const r=n[o];if(r===void 0){t.push({remediation:"none",scope:"table",severity:"safe",summary:`added table ${o}`,table:o,type:"addedTable"});continue}q(o,r,s,t)}for(const o of Object.keys(n))i.tables[o]===void 0&&t.push({remediation:"rehome",scope:"table",severity:"breaking",summary:`removed table ${o} — its rows stay in each shard's SQLite, unreachable through the schema; export the shard first if the data must be kept`,table:o,type:"removedTable"});if(e!==void 0&&e.jurisdiction!==i.jurisdiction){const o=e.jurisdiction??"(none)",s=i.jurisdiction??"(none)";t.push({remediation:"rehome",scope:"schema",severity:"breaking",summary:`Durable Object jurisdiction changed from ${o} to ${s} — this re-homes every DO and strands all existing shard, scheduler, and session-DO data in the old region (no in-place migration; export then import to move it). Revert the change, or override the gate to proceed intentionally.`,type:"changedJurisdiction"})}return{changes:t}};export{I as SCHEMA_SNAPSHOT_VERSION,d as describeShape,O as diffExistingField,C as diffSchemaSnapshots,E as hashSchemaSnapshot,$ as isValidTableSnapshot,_ as parseSnapshotJson,v as serializeSchemaSnapshot,g as sortKeys};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as E}from"@lunora/errors";import{SCHEMA_SNAPSHOT_VERSION as I,sortKeys as f,diffSchemaSnapshots as A,parseSnapshotJson as L}from"./SCHEMA_SNAPSHOT_VERSION-
|
|
1
|
+
import{LunoraError as E}from"@lunora/errors";import{SCHEMA_SNAPSHOT_VERSION as I,sortKeys as f,diffSchemaSnapshots as A,parseSnapshotJson as L}from"./SCHEMA_SNAPSHOT_VERSION-CBMD1pia.mjs";import{serializeSchemaSnapshot as V}from"./SCHEMA_SNAPSHOT_VERSION-CBMD1pia.mjs";const _=e=>e==="global"||e==="root"?e:`shardBy:${e.field}`,N=(e,t)=>{const s=JSON.stringify(e),i=JSON.stringify(t);return s===i?0:s<i?-1:1},l=e=>{const t=e.kind==="optional",s=t?e.inner:void 0,i=s??e,n={kind:t?s?.kind??"unknown":e.kind,nullable:i.column?.notNull===!1||e.column?.notNull===!1,optional:t,unique:i.column?.unique===!0||e.column?.unique===!0,...v[i.kind]?.(i)};return(i.hasRefinement===!0||e.hasRefinement===!0)&&(n.refined=!0),n},j=e=>{const t={};for(const[s,i]of Object.entries(e))t[s]=l(i);return f(t)},v={array:e=>e.inner?{of:l(e.inner)}:{},id:e=>e.tableName===void 0?{}:{ref:e.tableName},literal:e=>e.literalValue===void 0?{}:{literal:e.literalValue},object:e=>e.shape?{fields:j(e.shape)}:{},record:e=>({...e.keyType?{key:l(e.keyType)}:{},...e.valueType?{of:l(e.valueType)}:{}}),union:e=>e.members?{members:e.members.map(t=>l(t)).toSorted(N)}:{}},D=e=>{const t={};for(const[n,a]of Object.entries(e.shape))t[n]=l(a);const s={};for(const n of e.indexes)s[n.name]={fields:[...n.fields],unique:n.unique??!1};const i={};for(const n of e.relations)i[n.name]={field:n.field,kind:n.kind,table:n.table};return{fields:f(t),indexes:f(s),relations:f(i),shardMode:_(e.shardMode)}},U=(e,t)=>{const s={};for(const n of e.tables)s[n.name]=D(n);const i=[...t].sort();return{jurisdiction:e.jurisdiction,migrationIds:i,tables:f(s),version:I}};class O extends E{constructor(t){super("SCHEMA_SNAPSHOT_PARSE",t,{name:"SchemaSnapshotParseError"})}}const C=e=>{const t=L(e);if(t.status==="invalid")throw new O(t.error);return t.status==="ok"?t.snapshot:void 0},R={build:{allowDrift:!0,updateBaseline:!1},deploy:{allowDrift:!0,updateBaseline:!0},prepare:{allowDrift:!0,updateBaseline:!0},verify:{allowDrift:!0,updateBaseline:!1}},y=" • For backward-compatible changes (e.g. adding an optional field): pass `--allow-schema-drift` to skip the block.",k=" • To accept the new shape without a migration (you know data is compatible): pass `--update-schema-baseline`.",M=e=>{const t=e===void 0?void 0:R[e];if(e===void 0||t===void 0)return`${y}
|
|
2
2
|
${k}
|
|
3
3
|
`;const s=t.updateBaseline?k:` • To accept the new shape without a migration, run \`lunora prepare --update-schema-baseline\` — \`lunora ${e}\` does not take that flag.`;return`${y}
|
|
4
4
|
${s}
|
package/dist/packem_shared/{buildOpenApiDocument-6swU6A67.mjs → buildOpenApiDocument-BaDsKuhs.mjs}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{G as S}from"./emit-
|
|
1
|
+
import{G as S}from"./emit-wC8dZkgS.mjs";import{s as p}from"./paths-C-9fwEgQ.mjs";import{LUNORA_ERROR_CODES as O,objectSchema as h,validatorIrToJsonSchema as u}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";const E="/_lunora/rest",A=["authorization","cf-access-jwt-assertion","cookie","x-payment"],f=["x-d1-bookmark","x-lunora-shard-key"],P=e=>[...A,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],g=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,y=(...e)=>{const t=[];for(const r of e)for(const o of r?.split(",")??[]){const s=o.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},T=(e,t)=>{const r=[t,`max-age=${String(g(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(g(e.staleWhileRevalidate))}`),r.join(", ")},b=e=>e.scope==="public"?y(e.vary,...P(e),...f):y(e.vary,...f),x=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},N=e=>{const t=x(e);if(t!==void 0)return`${E}/${t.namespace}/${t.name}`},k=e=>e==="query"?"GET":"POST",m="#/components/responses/LunoraError",v=/:([A-Za-z_$][\w$]*)/gu,q=e=>[...e.matchAll(v)].map(t=>t[1]),_=e=>e.replaceAll(v,"{$1}"),l=e=>e.kind==="optional"?e.inner??e:e,j=e=>{const t=new Set(q(e.path)),r=[];for(const[o,s]of Object.entries(e.searchParams)){const c=l(s);r.push({description:`Query parameter \`${o}\``,in:"query",name:o,required:s.kind!=="optional",schema:u(c)})}for(const[o,s]of Object.entries(e.params)){const c=l(s);r.push({description:`Path parameter \`${o}\``,in:t.has(o)?"path":"query",name:o,required:t.has(o)?!0:s.kind!=="optional",schema:u(c)})}return r},$=e=>e?{content:{"application/json":{schema:u(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},C=e=>{const t=p(e.filePath),r=j(e),o={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${p(e.path)}`,responses:{200:$(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:m}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(o.parameters=r),Object.keys(e.body).length>0&&(o.requestBody={content:{"application/json":{schema:h(e.body)}},required:!0}),e.stream&&(o["x-lunora-stream"]="text/event-stream"),o},w=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o={additionalProperties:!1,properties:{args:h(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:o}},required:!0},responses:{200:$(e.output),default:{$ref:m}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},D=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},o={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:T(r,r.scope),type:"string"}}};r.tag!==void 0&&(o["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=b(r);return s!==void 0&&(o.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:o}},L=e=>{const t=p(e.filePath),r=`${t}:${e.exportName}`,o=N(r);if(o===void 0)return;const s=k(e.kind),c=s==="GET",d={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${p(o)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",...D(e.expose?.cache,c?"get":"post")},default:{$ref:m}},summary:`${s} ${o}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const n=Object.entries(e.args).map(([a,i])=>{const R=l(i);return{description:`Argument \`${a}\` (JSON-encoded for non-string values).`,in:"query",name:a,required:i.kind!=="optional",schema:u(R)}});return n.length>0&&(d.parameters=n),{method:"get",operation:d,path:o}}return d.requestBody={content:{"application/json":{schema:h(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:d,path:o}},I=e=>{const t=e.version??"0.0.0",r={},o=new Set;for(const n of e.httpRoutes){const a=_(n.path),i=r[a]??{};i[n.method.toLowerCase()]=C(n),r[a]=i,o.add(p(n.filePath))}const s=e.functions.filter(n=>n.visibility!=="internal"&&n.kind!=="stream");for(const n of s){const{operation:a,pathKey:i}=w(n);r[i]={post:a},o.add(p(n.filePath))}for(const n of s){if(n.expose?.rest!==!0)continue;const a=L(n);if(a===void 0)continue;const i=r[a.path]??{};i[a.method]=a.operation,r[a.path]=i}const c=[...o].toSorted((n,a)=>n.localeCompare(a)).map(n=>({description:`Operations declared in \`lunora/${n}\`.`,name:n}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:O,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:r,tags:c}},J=e=>`${JSON.stringify(I(e),void 0,2)}
|
|
2
2
|
`,U=e=>`${S}export const openApiSpec: Record<string, unknown> = ${JSON.stringify(e,void 0,4)};
|
|
3
3
|
`;export{I as buildOpenApiDocument,J as emitOpenApi,U as emitOpenApiModule};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{agentComponent as pt}from"@lunora/agent/component";import{LunoraError as X}from"@lunora/errors";import{serializeSchemaSnapshot as $n,hashSchemaSnapshot as Tn}from"./SCHEMA_SNAPSHOT_VERSION-
|
|
1
|
+
import{agentComponent as pt}from"@lunora/agent/component";import{LunoraError as X}from"@lunora/errors";import{serializeSchemaSnapshot as $n,hashSchemaSnapshot as Tn}from"./SCHEMA_SNAPSHOT_VERSION-CBMD1pia.mjs";import{isHyperdriveGlobalTable as Nn,isD1GlobalTable as An}from"./isD1GlobalTable-udvHAAzD.mjs";import{s as N}from"./paths-C-9fwEgQ.mjs";import{acceptsAbsentIr as On}from"./LUNORA_ERROR_CODES-C2s0xWQD.mjs";const mt=[{contextProperty:"access",key:"access",moduleSpecifier:"@lunora/cloudflare-access",requiredPackage:"@lunora/cloudflare-access"},{appMethod:{configKey:"ai",doc:"Override the Workers AI binding backing `ctx.ai` (defaults to `env.AI`).",method:"ai"},contextProperty:"ai",key:"ai",moduleSpecifier:"@lunora/ai",requiredPackage:"@lunora/ai"},{appMethod:{configKey:"analytics",doc:"Override the Analytics Engine dataset backing `ctx.analytics` (defaults to `env.ANALYTICS`).",method:"analytics"},contextProperty:"analytics",key:"analytics",moduleSpecifier:"@lunora/bindings/analytics",requiredPackage:"@lunora/bindings",serverCtxField:{field:`
|
|
2
2
|
/** Analytics Engine telemetry sink. Fire-and-forget and sampled; do not read it back in-handler. */
|
|
3
3
|
readonly analytics: import("@lunora/bindings/analytics").AnalyticsClient;`,tier:"every"}},{appMethod:{configKey:"browser",doc:"Override the Browser Rendering binding backing `ctx.browser` (defaults to `env.BROWSER`).",method:"browser"},contextProperty:"browser",key:"browser",moduleSpecifier:"@lunora/browser",requiredPackage:"@lunora/browser",serverCtxField:{field:`
|
|
4
4
|
/** Browser Rendering (screenshots/PDF/scrape). Non-deterministic — available only in actions. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{A as w,G as k}from"./emit-
|
|
1
|
+
import{A as w,G as k}from"./emit-wC8dZkgS.mjs";const y=e=>`has${e.charAt(0).toUpperCase()}${e.slice(1)}`,b=w.map(({appMethod:e,key:t})=>[y(t),e.method,e.configKey,e.doc]),m=e=>b.some(([t])=>e[t]),S=e=>e?['import * as lunoraIdentityContract from "../identity.js";']:[],E=(e,t)=>e?['import type { CreateAccessResolverOptions } from "@lunora/cloudflare-access";',`import { createAccessResolver${t?", composeResolvers":""} } from "@lunora/cloudflare-access";`]:[],D=e=>e?['import { createKvIntrospectorFromEnv } from "@lunora/bindings/kv";']:[],x=e=>e?['import { createVectorAdminIntrospector } from "@lunora/bindings/vectors";']:[],R=e=>e?['import type { D1CtxDbOptions, D1DatabaseLike, D1Exec } from "@lunora/d1";','import { applyCdcChanges, createD1CtxDb, emitD1QueryCost, exportGlobalRows, facetGlobalColumn, importGlobalRows, listGlobalTables, readD1CdcChanges, readGlobalTablePage, retryingExec } from "@lunora/d1";']:[],A=e=>e?['import notifyConfig from "../notify.js";']:[],g=e=>(e.emailAgents?.length??0)>0,C=e=>g(e)?['import { dispatchAgentEmail } from "@lunora/agent/inbound";']:[],O=e=>g(e)?['import * as lunoraAgentDefinitions from "../agents.js";']:[],T=e=>{const{hasFramework:t,hasGlobal:a,hasHyperdriveGlobal:r,hasQueue:n,useUmbrella:i}=e,o=i?"lunorash/runtime":"@lunora/runtime",l=["ExecutionContextLike","HttpRouterLike","LunoraWorker","Route","ScheduledControllerLike","ShardNamespaceLike","WorkerOptions",...n?["TriggerTrace"]:[],...a?["GlobalIntrospector","AdminTableResolver"]:[],...t?["FrameworkHostHandler"]:[]],s=[...a||r?["createCrossShardRelationCapabilities"]:[],"createWorker","resolveLogArchiveFromEnv",...t?["withFrameworkWorker"]:[]].join(", ");return[`import type { ${[...l].toSorted((c,d)=>c.localeCompare(d)).join(", ")} } from "${o}";`,`import { ${s} } from "${o}";`]},I=e=>{const{hasAccess:t,hasAuth:a,hasGlobal:r,hasHyperdriveGlobal:n,hasKvIntrospector:i,hasQueue:o,hasScheduler:l,hasStorage:s,hasWorkflow:c,wantsOpenApi:d,wantsOpenRpc:h}=e;return[...a?['import type { AuthNamespaceLike, LunoraAuth, LunoraAuthOptions } from "@lunora/auth";','import { createAuth, createAuthAdmin, createAuthAuditReader, createDoAuthWiring, d1Executor, ensureMigrated, handleAuthRequest, lunoraD1Adapter } from "@lunora/auth";']:[],...E(t,a),...R(r),...n?['import type { HyperdriveEngine } from "@lunora/hyperdrive/global";','import { createHyperdriveGlobalCtxDb } from "@lunora/hyperdrive/global";','import type { SqlCtxDbOptions, SqlExec } from "@lunora/sql-store";']:[],...D(i),...x(e.hasVectors===!0),...l?['import type { DurableObjectNamespaceLike } from "@lunora/scheduler";','import { createScheduler } from "@lunora/scheduler";']:[],...s?['import type { R2BucketLike, R2S3Credentials, Storage } from "@lunora/storage";','import { createBucketStorage, createStorage } from "@lunora/storage";']:[],...c?['import { createWorkflowsRestClient } from "@lunora/workflow";']:[],...C(e),...T(e),"",...S(e.identity),...O(e),...r||n?['import schema from "../schema.js";']:[],...A(e.hasNotify),'import { LUNORA_CRONS } from "./crons.js";','import { LUNORA_FUNCTIONS } from "./functions.js";',...o?['import { createQueueCaptureSink, dispatchQueueBatch, shouldCaptureQueue } from "@lunora/queue";','import { LUNORA_QUEUE_REGISTRY } from "./queues.js";']:[],...d?['import { openApiSpec } from "./openapi.js";']:[],...h?['import { openRpcSpec } from "./openrpc.js";']:[],'import { createShardDO } from "./shard.js";',...e.hasVectors===!0?['import { LUNORA_VECTOR_INDEXES } from "./vectors.js";']:[]]},L=e=>[...e.hasStorage?['/** `.storage(...)` declaration — one bucket (required) plus optional extra named buckets and signed-URL config. Backs `ctx.storage` AND the studio file browser. */\ninterface StorageDeclaration<Env> {\n /** The default R2 bucket binding (the bare `ctx.storage`). */\n bucket: Selector<Env, R2BucketLike>;\n /** Extra named buckets, reached via `ctx.storage.bucket("name")` and the studio\'s bucket picker. */\n buckets?: Record<string, Selector<Env, R2BucketLike>>;\n /** Public base URL signed/public object URLs resolve against. */\n publicBaseUrl?: Selector<Env, string>;\n /** R2 S3-API credentials (`{ accountId, accessKeyId, secretAccessKey, bucket, jurisdiction? }`) enabling `ctx.storage.getPresignedUrl` — native S3 presigned URLs that hit R2 directly, bypassing the worker. Omit to use only the worker-signed `getSignedUrl` path. */\n s3?: Selector<Env, R2S3Credentials>;\n /** HMAC secret for signed URLs. */\n signingSecret?: Selector<Env, string>;\n}']:[],...e.hasScheduler?["/** `.scheduler(...)` declaration — the `SchedulerDO` namespace. Backs `ctx.scheduler` AND the studio's scheduled-jobs view. The origin its callbacks dispatch back to is not declared here: the DO reads `env.LUNORA_ORIGIN_URL` at fire time, because a caller-supplied dispatch target would be an SSRF vector. */\ninterface SchedulerDeclaration<Env> {\n /** The `SchedulerDO` namespace binding (typically `env.SCHEDULER`). */\n namespace: Selector<Env, DurableObjectNamespaceLike & ShardNamespaceLike>;\n}"]:[],...e.hasGlobal?["/** `.global(...)` declaration — the D1 binding backing `.global()` tables. Backs cross-tenant `ctx.db` reads/writes AND the studio's global data browser. */\ninterface GlobalDeclaration<Env> {\n /** The D1 binding (typically `env.DB`). */\n d1: Selector<Env, D1DatabaseLike>;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}"]:[],...e.hasHyperdriveGlobal?['/** `.hyperdriveGlobal(...)` declaration — backs `.global({ backend: "hyperdrive" })` tables on a Postgres/MySQL database via Hyperdrive. Stays reactive: the writer is injected as `globalDb` and the broadcast hook drives live queries. */\ninterface HyperdriveGlobalDeclaration<Env> {\n /** The Hyperdrive engine — selects the Postgres or MySQL dialect. */\n engine: HyperdriveEngine;\n /** Build the `SqlExec` from `env` — e.g. `buildPgExec(fromPostgresJs(postgres(env.HYPERDRIVE.connectionString)))`. Cache the driver on the DO instance; rebuild lazily after hibernation. */\n exec: (env: Env) => SqlExec;\n /** The worker origin used to fan reverse cross-backend relations across shards. Without it, such a relation throws a clear error. */\n origin?: Selector<Env, string>;\n}']:[],...e.hasAuth?['/** `.auth(...)` declaration — better-auth options plus the storage the adapter reads. Give it `d1` (the default) or `namespace` (a Durable Object that hosts the auth tables), never both. The builder owns the lazy build + `ensureMigrated` dance and wires `authHandler` / `resolveIdentity` / `authAdmin`. */\ninterface AuthDeclaration<Env> {\n /** The D1 binding the auth SQL adapter is wired over (via `lunoraD1Adapter`). Omit only when using `namespace`. */\n d1?: Selector<Env, unknown>;\n /** Shared secret the worker presents on the object\'s internal session route. REQUIRED with `namespace`: the binding is reachable from any worker bound to it, so the secret — not the binding — is the authorization boundary. Without it identity resolution fails closed. */\n internalSecret?: Selector<Env, string>;\n /** Name of the Durable Object instance holding the auth tables. Defaults to `"auth"`. Set it to run separate auth objects (per deployment, per tenant) off one namespace. */\n objectName?: Selector<Env, string>;\n /** The auth Durable Object namespace — the DO-backed mode. Needed for `@better-auth/scim`, which requires native transactions that D1 has none of. The object owns the auth tables, so `/api/auth/*` and identity resolution both go through it. Typed as `AuthNamespaceLike` because `createDoAuthWiring` resolves through `idFromName` + `get` and has no `getByName` fallback — both members are load-bearing here, and `ShardNamespaceLike` leaves both optional. */\n namespace?: Selector<Env, AuthNamespaceLike>;\n /** Build the better-auth options from `env` (secret, plugins, email/password, …). */\n options: (env: Env) => LunoraAuthOptions;\n}']:[]],N=e=>[...e.hasAccess?[" private accessSelector?: Selector<Env, CreateAccessResolverOptions | undefined>;"]:[]," private adminToken?: Selector<Env, string>;",...e.hasAuth?[" private authDeclaration?: AuthDeclaration<Env>;"]:[]," private cdcEnabled = false;"," private reactiveCacheConfig: boolean | { maxBytes?: number; maxEntries?: number } = false;",' private maxRelationKeysLimit?: ShardConfig["maxRelationKeys"];',' private observabilitySink?: ShardConfig["observability"];',' private relationExistsPushDownMode?: ShardConfig["relationExistsPushDown"];'," private readonly extendFns: ((env: Env, derived: Readonly<WorkerOptions>) => Partial<WorkerOptions>)[] = [];",...e.hasGlobal?[" private globalDeclaration?: GlobalDeclaration<Env>;"]:[],...e.hasHyperdriveGlobal?[" private hyperdriveGlobalDeclaration?: HyperdriveGlobalDeclaration<Env>;"]:[]," private httpRouterApp?: HttpRouterLike;"," private readonly routeMap: Record<string, Route> = {};",...e.hasScheduler?[" private schedulerDeclaration?: SchedulerDeclaration<Env>;"]:[],...m(e)?[" private readonly shardExtras: Partial<ShardConfig> = {};"]:[]," private shardSelector?: Selector<Env, ShardNamespaceLike>;",...e.hasStorage?[" private storageDeclaration?: StorageDeclaration<Env>;"]:[]],q=e=>b.filter(([t])=>e[t]).map(([,t,a,r])=>` /** ${r} */
|
|
2
2
|
public ${t}(factory: (env: Env) => ReturnType<NonNullable<ShardConfig["${a}"]>>): this {
|
|
3
3
|
this.shardExtras.${a} = factory as NonNullable<ShardConfig["${a}"]>;
|
|
4
4
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/codegen",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.186",
|
|
4
4
|
"description": "Code generator for Lunora: emits _generated/{api,server,dataModel}.ts from your schema",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -46,15 +46,15 @@
|
|
|
46
46
|
"access": "public"
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
50
|
-
"@lunora/agent": "1.0.0-alpha.
|
|
51
|
-
"@lunora/container": "1.0.0-alpha.
|
|
52
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
49
|
+
"@lunora/advisor": "1.0.0-alpha.136",
|
|
50
|
+
"@lunora/agent": "1.0.0-alpha.114",
|
|
51
|
+
"@lunora/container": "1.0.0-alpha.50",
|
|
52
|
+
"@lunora/errors": "1.0.0-alpha.37",
|
|
53
53
|
"@lunora/platform": "1.0.0-alpha.32",
|
|
54
|
-
"@lunora/queue": "1.0.0-alpha.
|
|
55
|
-
"@lunora/scheduler": "1.0.0-alpha.
|
|
56
|
-
"@lunora/values": "1.0.0-alpha.
|
|
57
|
-
"@lunora/workflow": "1.0.0-alpha.
|
|
54
|
+
"@lunora/queue": "1.0.0-alpha.57",
|
|
55
|
+
"@lunora/scheduler": "1.0.0-alpha.74",
|
|
56
|
+
"@lunora/values": "1.0.0-alpha.47",
|
|
57
|
+
"@lunora/workflow": "1.0.0-alpha.53",
|
|
58
58
|
"jiti": "^2.7.0",
|
|
59
59
|
"quicktype-core": "^26.0.0",
|
|
60
60
|
"ts-morph": "^28.0.0"
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const f=(e,i=2166136261)=>{let t=i;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")},m=e=>`${f(e,2166136261)}${f(e,16777619)}`,I=1;function g(e){const i={},t=Object.keys(e);t.sort();for(const n of t)i[n]=e[n];return i}const v=e=>`${JSON.stringify(e,void 0,2)}
|
|
2
|
-
`,q=e=>m(v(e)),d=e=>typeof e=="object"&&e!==null,$=e=>d(e)&&d(e.fields)&&d(e.indexes)&&d(e.relations)&&typeof e.shardMode=="string",_=e=>{if(e===void 0||e.trim()==="")return{status:"absent"};let i;try{i=JSON.parse(e)}catch(n){return{error:`baseline is not valid JSON: ${n instanceof Error?n.message:String(n)}`,status:"invalid"}}if(!d(i)||i.version!==1||!d(i.tables))return{error:`baseline is malformed or written by an incompatible version (expected version ${String(1)})`,status:"invalid"};for(const[n,o]of Object.entries(i.tables))if(!$(o))return{error:`baseline table "${n}" has an invalid structure`,status:"invalid"};return{snapshot:{jurisdiction:typeof i.jurisdiction=="string"?i.jurisdiction:void 0,migrationIds:Array.isArray(i.migrationIds)?i.migrationIds:[],tables:i.tables,version:1},status:"ok"}},b=(e,i)=>e.unique===i.unique&&e.fields.length===i.fields.length&&e.fields.every((t,n)=>t===i.fields[n]),p=e=>e.unique!==void 0,u=({nullable:e,optional:i,refined:t,unique:n,...o})=>JSON.stringify(g(o)),h=e=>({form:JSON.stringify([u(e),e.optional===!0,e.nullable===!0]),refined:e.refined===!0}),y=e=>e.kind==="union"&&e.members?e.members.map(i=>h(i)):[h({...e,nullable:!1,optional:!1})],S=(e,i)=>{if(i.kind!=="union")return!1;const t=y(i);return y(e).every(n=>t.some(o=>o.form===n.form&&(n.refined||!o.refined)))},a=e=>{switch(e.kind){case"array":return`array(${e.of?a(e.of):"?"})`;case"id":return`id(${e.ref??"?"})`;case"literal":return`literal(${e.literal??"?"})`;case"object":return`object({ ${Object.keys(e.fields??{}).join(", ")} })`;case"record":return`record(${e.key?a(e.key):"?"}, ${e.of?a(e.of):"?"})`;case"union":return(e.members??[]).map(i=>a(i)).join(" | ");default:return e.kind}},c=(e,i,t)=>({remediation:"backfill",scope:"table",severity:"breaking",summary:t,table:e,type:i}),l=(e,i,t)=>({remediation:"none",scope:"table",severity:"safe",summary:t,table:e,type:i}),k=(e,i,t,n,o)=>{if(!(t.kind===n.kind&&(!o||u(t)===u(n))))return o&&S(t,n)?l(e,"widenedFieldShape",`field ${e}.${i} widened: ${a(t)} → ${a(n)} — every stored value stays valid`):t.kind!==n.kind?c(e,"changedFieldKind",`field ${e}.${i} changed type: ${t.kind} → ${n.kind} — add a data migration to convert existing values`):c(e,"changedFieldShape",`field ${e}.${i} changed shape: ${a(t)} → ${a(n)} — stored values were written against the old shape; add a data migration to convert them`)},O=(e,i,t,n)=>{const o=[];return t.unique!==n.unique&&o.push(n.unique===!0?c(e,"addedFieldConstraint",`field ${e}.${i} became unique — existing duplicates would violate it; add a data migration to de-duplicate first`):l(e,"relaxedFieldConstraint",`field ${e}.${i} is no longer unique`)),t.nullable!==n.nullable&&o.push(n.nullable===!0?l(e,"relaxedFieldConstraint",`field ${e}.${i} became nullable`):c(e,"addedFieldConstraint",`field ${e}.${i} is no longer nullable — rows holding NULL would be invalid; add a data migration to backfill them`)),t.refined!==n.refined&&o.push(n.refined===!0?c(e,"addedFieldConstraint",`field ${e}.${i} gained a validation refinement — stored values were never checked against it; add a data migration if any could fail`):l(e,"relaxedFieldConstraint",`field ${e}.${i} dropped its validation refinement`)),o},F=(e,i,t,n)=>{const o=[],s=p(t)&&p(n),r=k(e,i,t,n,s);return r&&o.push(r),s&&o.push(...O(e,i,t,n)),t.optional&&!n.optional?o.push({remediation:"backfill",severity:"breaking",summary:`field ${e}.${i} became required — rows missing it would be invalid; add a data migration to backfill it`,table:e,scope:"table",type:"fieldOptionalToRequired"}):!t.optional&&n.optional&&o.push({remediation:"none",scope:"table",severity:"safe",summary:`field ${e}.${i} became optional`,table:e,type:"fieldRequiredToOptional"}),o},x=(e,i,t)=>t.optional?{remediation:"none",scope:"table",severity:"safe",summary:`added optional field ${e}.${i}`,table:e,type:"addedOptionalField"}:{remediation:"backfill",severity:"breaking",summary:`added required field ${e}.${i} — existing rows have no value; add a data migration to backfill it`,table:e,scope:"table",type:"addedRequiredField"},j=(e,i,t,n)=>{for(const[o,s]of Object.entries(t.fields)){const r=i.fields[o];r===void 0?n.push(x(e,o,s)):n.push(...F(e,o,r,s))}for(const o of Object.keys(i.fields))t.fields[o]===void 0&&n.push({remediation:"backfill",severity:"breaking",summary:`removed field ${e}.${o} — add a data migration if stored data must be cleaned up`,table:e,scope:"table",type:"removedField"})},A=(e,i,t,n)=>{for(const[o,s]of Object.entries(t.indexes)){const r=i.indexes[o];if(r===void 0){n.push({remediation:"none",scope:"table",severity:"safe",summary:`added index ${o} on ${e}`,table:e,type:"addedIndex"});continue}b(r,s)||n.push({remediation:"code",severity:"breaking",summary:`index ${o} on ${e} changed shape — a query may have relied on the old index`,table:e,scope:"table",type:"changedIndex"})}for(const o of Object.keys(i.indexes))t.indexes[o]===void 0&&n.push({remediation:"code",severity:"breaking",summary:`removed index ${o} on ${e} — a query that used \`.withIndex("${o}")\` would break`,table:e,scope:"table",type:"removedIndex"})},w=(e,i,t,n)=>{for(const o of Object.keys(t.relations))i.relations[o]===void 0&&n.push({remediation:"none",scope:"schema",severity:"safe",summary:`added relation ${e}.${o}`,table:e,type:"addedRelation"});for(const o of Object.keys(i.relations))t.relations[o]===void 0&&n.push({remediation:"code",scope:"schema",severity:"breaking",summary:`removed relation ${e}.${o}`,table:e,type:"removedRelation"})},E=(e,i,t,n)=>{i.shardMode!==t.shardMode&&n.push({remediation:"rehome",severity:"breaking",summary:`table ${e} changed shard mode: ${i.shardMode} → ${t.shardMode} — its physical storage moves, and existing rows do NOT follow the schema; re-home them with an export/import round trip (https://lunora.sh/docs/concepts/sharding#migrating-a-populated-table)`,table:e,scope:"table",type:"changedShardMode"}),j(e,i,t,n),A(e,i,t,n),w(e,i,t,n)},C=(e,i)=>{const t=[],n=e?.tables??{};for(const[o,s]of Object.entries(i.tables)){const r=n[o];if(r===void 0){t.push({remediation:"none",scope:"table",severity:"safe",summary:`added table ${o}`,table:o,type:"addedTable"});continue}E(o,r,s,t)}for(const o of Object.keys(n))i.tables[o]===void 0&&t.push({remediation:"rehome",scope:"table",severity:"breaking",summary:`removed table ${o} — its rows stay in each shard's SQLite, unreachable through the schema; export the shard first if the data must be kept`,table:o,type:"removedTable"});if(e!==void 0&&e.jurisdiction!==i.jurisdiction){const o=e.jurisdiction??"(none)",s=i.jurisdiction??"(none)";t.push({remediation:"rehome",scope:"schema",severity:"breaking",summary:`Durable Object jurisdiction changed from ${o} to ${s} — this re-homes every DO and strands all existing shard, scheduler, and session-DO data in the old region (no in-place migration; export then import to move it). Revert the change, or override the gate to proceed intentionally.`,type:"changedJurisdiction"})}return{changes:t}};export{I as SCHEMA_SNAPSHOT_VERSION,a as describeShape,F as diffExistingField,C as diffSchemaSnapshots,q as hashSchemaSnapshot,$ as isValidTableSnapshot,_ as parseSnapshotJson,v as serializeSchemaSnapshot,g as sortKeys};
|