@lunora/server 1.0.0-alpha.94 → 1.0.0-alpha.95

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/index.d.mts +59 -44
  2. package/dist/index.d.ts +59 -44
  3. package/dist/index.mjs +1 -1
  4. package/dist/packem_shared/{ACTION_CACHE_DEFAULT_TTL_MS-BG6A6rHA.mjs → ACTION_CACHE_DEFAULT_TTL_MS-DZ4b4IoT.mjs} +1 -1
  5. package/dist/packem_shared/{DOCUMENT_HISTORY_REDACTED_FIELDS-CXOIUOBE.mjs → DOCUMENT_HISTORY_REDACTED_FIELDS-B5mE3zak.mjs} +1 -1
  6. package/dist/packem_shared/{LunoraEnvError-_BakoYQ3.mjs → LunoraEnvError-CXbrsFI8.mjs} +2 -2
  7. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-DSTJZMfc.mjs +1 -0
  8. package/dist/packem_shared/apply-output-C5wZ5EAL.mjs +1 -0
  9. package/dist/packem_shared/{bindOrm-lWdeDi9P.mjs → bindOrm-ChQydkdL.mjs} +1 -1
  10. package/dist/packem_shared/buildMaskRegistry-DpWMtalG.mjs +1 -0
  11. package/dist/packem_shared/buildRlsReadRegistry-CIGmNx0b.mjs +1 -0
  12. package/dist/packem_shared/compose-middleware-3i5Qk3sb.mjs +1 -0
  13. package/dist/packem_shared/composePluginMiddleware-pe7Ncehp.mjs +1 -0
  14. package/dist/packem_shared/createPolicyDsl-BZa6SqLJ.mjs +1 -0
  15. package/dist/packem_shared/{createSecrets-CyrEddTF.mjs → createSecrets-D6rLB42U.mjs} +1 -1
  16. package/dist/packem_shared/{defineAggregateIndex-C3kWoQ-P.mjs → defineAggregateIndex-DFVCeuX1.mjs} +1 -1
  17. package/dist/packem_shared/defineMigration-CXOS0Bvq.mjs +1 -0
  18. package/dist/packem_shared/{defineShape-DYxbNl5W.mjs → defineShape-BWgwFuMT.mjs} +1 -1
  19. package/dist/packem_shared/defineStorageRule-Dv4nJE0H.mjs +1 -0
  20. package/dist/packem_shared/httpAction-B8X6jXen.mjs +5 -0
  21. package/dist/packem_shared/initLunora-D8WltggT.mjs +1 -0
  22. package/dist/packem_shared/mask-pIhIWBcr.mjs +1 -0
  23. package/dist/packem_shared/middleware-Cz5s6CH-.mjs +1 -0
  24. package/dist/packem_shared/plugin-yKCbHnlj.mjs +1 -0
  25. package/dist/packem_shared/policy-tag-V0lqFzgS.mjs +1 -0
  26. package/dist/packem_shared/protectPublic-Csf6ObbJ.mjs +1 -0
  27. package/dist/packem_shared/rls-BjRa5pMm.mjs +1 -0
  28. package/dist/packem_shared/run-middleware-CuM-Chm3.mjs +1 -0
  29. package/dist/packem_shared/storageRules-DHvF6Fjq.mjs +1 -0
  30. package/dist/rls/testing.mjs +1 -1
  31. package/dist/types.d.mts +83 -22
  32. package/dist/types.d.ts +83 -22
  33. package/package.json +2 -2
  34. package/dist/packem_shared/LunoraError-DcKdk9Ti.mjs +0 -1
  35. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-B6z9BcPN.mjs +0 -1
  36. package/dist/packem_shared/apply-output-D7vpBeeu.mjs +0 -1
  37. package/dist/packem_shared/buildMaskRegistry-72SL8fJn.mjs +0 -1
  38. package/dist/packem_shared/buildRlsReadRegistry-Ct60PLD-.mjs +0 -1
  39. package/dist/packem_shared/composePluginMiddleware-D8I_XMLV.mjs +0 -1
  40. package/dist/packem_shared/createPolicyDsl-DNfByAUX.mjs +0 -1
  41. package/dist/packem_shared/defineMigration-7GI9Qbtd.mjs +0 -1
  42. package/dist/packem_shared/defineStorageRule-BvxHVq3b.mjs +0 -1
  43. package/dist/packem_shared/httpAction-DEN_78Kj.mjs +0 -5
  44. package/dist/packem_shared/initLunora-BxNkWYTz.mjs +0 -1
  45. package/dist/packem_shared/mask-NVloFLLY.mjs +0 -1
  46. package/dist/packem_shared/middleware-EloVU9X1.mjs +0 -1
  47. package/dist/packem_shared/plugin-DfuRhJS1.mjs +0 -1
  48. package/dist/packem_shared/policy-tag-D4RzgQnw.mjs +0 -1
  49. package/dist/packem_shared/protectPublic-Bo4G9xaV.mjs +0 -1
  50. package/dist/packem_shared/rls-B6du_B-q.mjs +0 -1
  51. package/dist/packem_shared/run-middleware-B-JeGGp9.mjs +0 -1
  52. package/dist/packem_shared/storageRules-91NHMDL6.mjs +0 -1
@@ -1 +1 @@
1
- import{LunoraError as r}from"@lunora/errors";import{c as p}from"./context-identity-B2XYGA0B.mjs";import{v as u}from"./functions-B2-H4PQT.mjs";import{toWhereInput as d,deny as m}from"./allowAll-DkRAgItV.mjs";const I=e=>{if(e.table.trim()==="")throw new r("INTERNAL","defineShape: `table` must be a non-empty string");if(e.columns?.length===0)throw new r("INTERNAL","defineShape: `columns` must list at least one column when provided");if(!e.where&&e.owner===void 0)throw new r("INTERNAL",`defineShape: shape on table "${e.table}" needs a \`where\` predicate or an \`owner\` (\`owner: true\` uses the table's .ownedBy(field), \`owner: "field"\` names the column) — a shape with neither would replicate the whole table`);return{__lunoraShape:!0,...e,compileWhere:(a,l,s)=>{const w=u(e.args??{},l),o=e.where?d(e.where(a,w)):void 0;if(e.owner===void 0)return o;const t=e.owner===!0?s?.ownerField:e.owner;if(t===void 0||t==="")throw new r("INTERNAL",`defineShape: shape on table "${e.table}" declares \`owner: true\` but the table has no \`.ownedBy(field)\` — add it to the table, or name the column directly with \`owner: "field"\``);const h=p(a);if(h===void 0)return m();const n={[t]:h};return o===void 0?n:{AND:[n,o]}}}};export{I as defineShape};
1
+ import{LunoraError as r}from"@lunora/errors";import{c as p}from"./context-identity-B2XYGA0B.mjs";import{v as u}from"./functions-B2-H4PQT.mjs";import{toWhereInput as d,deny as m}from"./allowAll-DkRAgItV.mjs";const I=e=>{if(e.table.trim()==="")throw new r("INTERNAL","defineShape: `table` must be a non-empty string");if(e.columns?.length===0)throw new r("INTERNAL","defineShape: `columns` must list at least one column when provided");if(!e.where&&e.owner===void 0)throw new r("INTERNAL",`defineShape: shape on table "${e.table}" needs a \`where\` predicate or an \`owner\` (\`owner: true\` uses the table's .ownedBy(field), \`owner: "field"\` names the column) — a shape with neither would replicate the whole table`);return{__lunoraShape:!0,...e,compileWhere:(a,n,s)=>{const w=u(e.args??{},n),o=e.where?d(e.where(a,w)):void 0;if(e.owner===void 0)return o;const t=e.owner===!0?s?.ownerField:e.owner;if(t===void 0||t==="")throw new r("INTERNAL",`defineShape: shape on table "${e.table}" declares \`owner: true\` but the table has no \`.ownedBy(field)\` — add it to the table, or name the column directly with \`owner: "field"\``);const h=p(a);if(h===void 0)return m();const l={[t]:h};return o===void 0?l:{AND:[l,o]}}}};export{I as defineShape};
@@ -0,0 +1 @@
1
+ import{LunoraError as i}from"@lunora/errors";const s=n=>({bucket:n.bucket,on:n.on,prefix:n.prefix,when:n.when}),f=n=>{const t=new Map;for(const e of n){const o=JSON.stringify([e.bucket,e.on,e.prefix]),r=t.get(o)??new Set;if(r.has(e.when))throw new i("INTERNAL",`defineStorageRules: duplicate rule for (bucket "${e.bucket}", on "${e.on}"${e.prefix===void 0?"":`, prefix "${e.prefix}"`}) — the same decision function is registered more than once. Multiple distinct rules per (bucket, on) are allowed (they OR); remove the duplicate.`);r.add(e.when),t.set(o,r)}return n};export{s as defineStorageRule,f as defineStorageRules};
@@ -0,0 +1,5 @@
1
+ import{LunoraError as y,toErrorBody as k,isLunoraError as x}from"@lunora/errors";import{parseValidatorMap as E,ValidationError as H}from"@lunora/values";import{Hono as C}from"hono";import{a as L}from"./apply-output-C5wZ5EAL.mjs";const Q=e=>async t=>e(t.get("lunora"),t.req.raw),Y=()=>{const e=new C;return e.use("*",async(t,r)=>{const n=t.env.__lunoraCtx;if(!n)throw new y("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");t.set("lunora",n),await r()}),e},O=e=>e.kind==="optional"?e._meta?.inner??e:e,R=(e,t)=>{switch(e){case"bigint":try{return BigInt(t)}catch{return t}case"boolean":return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:t;case"number":return t===""?Number.NaN:Number(t);default:return t}},$=(e,t,r)=>{const n=O(e);if(n.kind==="array"){const a=t.req.queries(r);if(a===void 0)return;const s=n._meta?.inner;return a.map(c=>R(s?.kind??"string",c))}const o=t.req.query(r);return o===void 0?void 0:R(n.kind,o)},N=(e,t)=>{const r={};for(const n of Object.keys(e)){const o=e[n];o&&(r[n]=$(o,t,n))}return E(e,r,"searchParams")},v=(e,t)=>{const r=t.req.param(),n={};for(const o of Object.keys(e)){const a=e[o];if(!a)continue;const s=r[o];n[o]=s===void 0?void 0:R(O(a).kind,s)}return E(e,n,"params")},B=async(e,t)=>{let r;try{r=await t.req.json()}catch{throw new y("BAD_REQUEST","Invalid JSON body")}if(typeof r!="object"||r===null||Array.isArray(r))throw new y("BAD_REQUEST","Expected a JSON object body");return E(e,r,"body")},T=e=>{if(e instanceof H)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(x(e)){const{body:t,redacted:r,status:n}=k(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return r&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:t.code,error:t.message},{status:n})}throw e},j=(e,t)=>{const{method:r}=t.req;if(!(r===e.method||e.method==="GET"&&r==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${r} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},D=(e,t)=>async r=>{const n=j(e,r);if(n)return n;try{const o=r.get("lunora"),a=Object.keys(e.searchParams).length>0?N(e.searchParams,r):{},s=Object.keys(e.params).length>0?v(e.params,r):{},c=Object.keys(e.body).length>0?await B(e.body,r):{},h=await t({body:c,ctx:o,params:s,searchParams:a}),i=e.output?L(e.output,h):h,d={};e.cacheControl&&(d["cache-control"]=e.cacheControl),e.cacheTag&&(d["cache-tag"]=e.cacheTag),e.vary&&(d.vary=e.vary);const f=Object.keys(d).length>0;return i===void 0?new Response(null,{headers:f?d:void 0,status:204}):Response.json(i,{headers:f?d:void 0})}catch(o){return T(o)}},w={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},b=(e,t)=>{const r=JSON.stringify(e);return`${t?`event: ${t}
2
+ `:""}data: ${r}
3
+
4
+ `},I=(e,t)=>(async r=>{const n=j(e,r);if(n)return n;let o,a;try{o=Object.keys(e.searchParams).length>0?N(e.searchParams,r):{},a=Object.keys(e.params).length>0?v(e.params,r):{}}catch(p){return T(p)}const s=r.get("lunora"),c=r.req.raw,h=new TextEncoder,i=new AbortController;if(c.signal.aborted)return i.abort(),new Response("",{headers:w});const d=()=>{i.abort()};c.signal.addEventListener("abort",d,{once:!0});const f=new ReadableStream({cancel(){c.signal.removeEventListener("abort",d),i.abort()},async start(p){try{const m=t({ctx:s,params:a,request:c,searchParams:o,signal:i.signal});for await(const g of m){if(i.signal.aborted)break;p.enqueue(h.encode(b(g)))}i.signal.aborted||p.enqueue(h.encode(b({},"complete")))}catch(m){const{body:g,redacted:q}=k(m,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});q&&console.error("[lunora] unhandled stream handler error:",m),i.signal.aborted||p.enqueue(h.encode(b({code:g.code,message:g.message},"error")))}finally{c.signal.removeEventListener("abort",d);try{p.close()}catch{}}}});return new Response(f,{headers:w})}),u=e=>({body:t=>u({...e,body:{...e.body,...t}}),cacheControl:t=>u({...e,cacheControl:t}),cacheTag:t=>u({...e,cacheTag:t}),handler:t=>D(e,t),output:t=>u({...e,output:t}),params:t=>u({...e,params:{...e.params,...t}}),searchParams:t=>u({...e,searchParams:{...e.searchParams,...t}}),stream:t=>I(e,t),vary:t=>u({...e,vary:t})}),l=e=>t=>u({body:{},method:e,params:{},path:t,searchParams:{}}),z={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")},M=/^bytes=(\d*)-(\d*)$/,A=e=>e.startsWith('"')||e.startsWith('W/"')?e:`"${e}"`,W=e=>!(e.includes("\r")||e.includes(`
5
+ `)||e.includes("\0")),_=(e,t)=>{if(e===null)return{kind:"full"};const r=M.exec(e.trim());if(!r)return{kind:"full"};const n=r[1]??"",o=r[2]??"";if(n===""&&o==="")return{kind:"full"};let a,s;if(n===""){const c=Number(o);if(c===0)return{kind:"unsatisfiable"};a=Math.max(0,t-c),s=t-1}else a=Number(n),s=o===""?t-1:Math.min(Number(o),t-1);return a>s||a>=t?{kind:"unsatisfiable"}:{end:s,kind:"partial",start:a}},P=e=>{const t=e.httpMetadata?.contentType,r={"accept-ranges":"bytes","content-type":t!==void 0&&W(t)?t:"application/octet-stream",etag:A(e.etag)};return e.sha256Base64!==void 0&&(r["repr-digest"]=`sha-256=:${e.sha256Base64}:`),r},V=e=>_(e,0).kind==="full",S=async(e,t)=>{const r=await e.storage.download(t);return r?new Response(r.body,{headers:{...P(r),"content-length":String(r.size)},status:200}):new Response("Not Found",{status:404})},K=async(e,t,r)=>{const n=r.headers.get("range");if(V(n))return S(e,t);const o=await e.storage.head(t);if(!o)return new Response("Not Found",{status:404});const a=_(n,o.size);if(a.kind==="unsatisfiable")return new Response("Range Not Satisfiable",{headers:{"accept-ranges":"bytes","content-range":`bytes */${String(o.size)}`,"content-type":"text/plain; charset=utf-8",etag:A(o.etag)},status:416});if(a.kind==="full")return S(e,t);const s=a.end-a.start+1,c=await e.storage.download(t,{range:{length:s,offset:a.start}});return c?new Response(c.body,{headers:{...P(o),"content-length":String(s),"content-range":`bytes ${String(a.start)}-${String(a.end)}/${String(o.size)}`},status:206}):new Response("Not Found",{status:404})};export{Q as httpAction,z as httpRoute,Y as httpRouter,W as isSafeHeaderValue,K as serveStorageObject};
@@ -0,0 +1 @@
1
+ import{a as h}from"./apply-output-C5wZ5EAL.mjs";import{v as i}from"./functions-B2-H4PQT.mjs";import{unionMaskColumns as w}from"./buildMaskRegistry-DpWMtalG.mjs";import{r as j}from"./policy-tag-V0lqFzgS.mjs";import{r as b}from"./run-middleware-CuM-Chm3.mjs";const y=(e,r)=>r===void 0||typeof e!="object"||e===null?e:Object.assign(Object.create(Object.getPrototypeOf(e)),e,{meta:r}),M=(e,r)=>b(e,r,o=>o),C=(e,r,o,n,t)=>async(s,d)=>{const c=i(e,d),l=await M(r,y(s,t)),m=await o({args:c,ctx:l});return n?h(n,m):m},O=(e,r,o,n)=>(t,s,d)=>{const c=i(e,s);return(async function*(){const m=await M(r,y(t,n)),f=o({args:c,ctx:m,signal:d})[Symbol.asyncIterator]();try{for(;;){if(d.aborted)return;const p=await f.next();if(p.done||d.aborted)return;yield p.value}}finally{await f.return?.()}})()},g=e=>{const r=e.flatMap(o=>j(o));return r.length>0?{tags:r}:void 0},x=e=>{for(const r of["add","clear","delete","set"])typeof e[r]=="function"&&Object.defineProperty(e,r,{configurable:!1,enumerable:!1,value:()=>{throw new TypeError(`Cannot mutate a frozen .meta() declaration (${e.constructor.name}.${r})`)},writable:!1})},u=(e,r)=>{if(e===null||typeof e!="object"||r.has(e))return e;if(r.add(e),e instanceof Map){for(const[o,n]of e)u(o,r),u(n,r);x(e)}else if(e instanceof Set){for(const o of e)u(o,r);x(e)}for(const o of Object.values(e))u(o,r);return Object.freeze(e),e},_=e=>u(structuredClone(e),new WeakSet),a=(e,r,o)=>({__lunoraProcedure:e,...o?{__lunoraVisibility:o}:{},input:n=>a(e,{...r,args:{...r.args,...n}},o),[e]:n=>{const t=g(r.middlewares),s=w(r.middlewares);return{args:r.args,...r.expose?{expose:r.expose}:{},handler:C(r.args,r.middlewares,n,r.output,r.meta),kind:e,...s?{maskedTables:s}:{},...t?{rls:t}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}},meta:n=>a(e,{...r,meta:_({...r.meta,...n})},o),output:n=>a(e,{...r,output:n},o),...e==="query"?{stream:(n,t)=>{const s=g(r.middlewares),d=w(r.middlewares),c=t?.durable===!0?{}:t?.durable;return{args:r.args,...c?{durable:c}:{},...r.expose?{expose:r.expose}:{},handler:O(r.args,r.middlewares,n,r.meta),kind:"stream",...d?{maskedTables:d}:{},...s?{rls:s}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}}}:{},use:n=>a(e,{...r,middlewares:[...r.middlewares,n]},o),...o?{}:{expose:n=>a(e,{...r,expose:n},o)},...o?{}:{x402:n=>a(e,{...r,x402:n},o)}}),H={dataModel:()=>({create:e=>({action:a("action",{args:{},middlewares:[]}),internalAction:a("action",{args:{},middlewares:[]},"internal"),internalMutation:a("mutation",{args:{},middlewares:[]},"internal"),internalQuery:a("query",{args:{},middlewares:[]},"internal"),mutation:a("mutation",{args:{},middlewares:[]}),query:a("query",{args:{},middlewares:[]})})})};export{H as initLunora};
@@ -0,0 +1 @@
1
+ import{LunoraError as P}from"@lunora/errors";import{f as B}from"./fnv1a-D6VtE8WR.mjs";import{bindTableFacade as E,bindOrm as _}from"./bindOrm-ChQydkdL.mjs";import{i as D,a as K,o as v,b as q}from"./middleware-Cz5s6CH-.mjs";import{tagMaskMiddleware as m}from"./buildMaskRegistry-DpWMtalG.mjs";const G=(i,e,c)=>{try{return i==="redact"?null:i==="hash"?e==null?e:typeof e=="bigint"?B(e.toString()):B(typeof e=="string"?e:JSON.stringify(e)):i(e,c)}catch{return null}},a=(i,e,c)=>{const y={...i};for(const[h,g]of Object.entries(e))h in y&&(y[h]=G(g,i[h],{...c,column:h,row:i}));return y},W=(i,e,c)=>({...i,page:i.page.map(y=>a(y,e,c))}),U=(i,e,c,y)=>{if(typeof i!="function")return;const h=new Set,g=()=>new Proxy({},{get:()=>f=>(typeof f=="string"&&h.add(f),g())});i(g());for(const f of h)if(f in e)throw new P("MASK_UNSUPPORTED",`${y}() filtering "${c}" by masked column "${f}" is not supported`)},L=(i,e,c,y)=>{const h=i.rankBefore,g=i.rankPageRows,f=(r,n)=>{const t=e.get(r);return t?n.map(o=>a(o,t,c)):n},p=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?f:(t,o)=>n(t,f(t,o))}},k=(r,n,t,o)=>{const s=e.get(r);if(!s)return;const d=y?.[r]?.[o]?.[n];if(!d)return;const w=d.find($=>$ in s);if(w!==void 0)throw new P("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${w}" — use an index whose declared fields are all unmasked, or unmask the column`)},l=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield a(o,n,c)},collect:async()=>(await r.collect()).map(s=>a(s,n,c)),collectWithScores:async()=>(await r.collectWithScores()).map(s=>{const d=a(s.document,n,c);return"distanceMeters"in s?{distanceMeters:null,document:d}:{document:d,score:s.score}}),filter:o=>l(r.filter(s=>o(a(s,n,c))),n,t),first:async()=>{const o=await r.first();return o?a(o,n,c):null},order:o=>l(r.order(o),n,t),paginate:async o=>W(await r.paginate(o),n,c),take:async o=>(await r.take(o)).map(d=>a(d,n,c)),unique:async()=>{const o=await r.unique();return o?a(o,n,c):null},withIndex:(o,s)=>(k(t,o,"withIndex","index"),U(s,n,t,"withIndex"),l(r.withIndex(o,s),n,t)),withSearchIndex:(o,s)=>(U(s,n,t,"withSearchIndex"),l(r.withSearchIndex(o,s),n,t)),withGeoIndex:(o,s)=>(k(t,o,"withGeoIndex","geo"),l(r.withGeoIndex(o,s),n,t))}),S=async(r,n)=>{if(i.lookupById){const w=await i.lookupById(r,n);return w?{row:w.row,tableName:e.has(w.tableName)?w.tableName:void 0}:{row:null,tableName:void 0}}const t=await i.get(r,n);if(!t)return{row:null,tableName:void 0};const o=n!==void 0&&e.has(n)?[n]:[],s=n===void 0?[...e.keys()]:o,d=await Promise.all(s.map(async w=>(await i.findFirst(w,{limit:1,where:{_id:r}}))?._id===r?w:void 0));return{row:t,tableName:d.find(w=>w!==void 0)}},M=(r,n,t)=>{const o=e.get(r);if(!o)return;const s=n.find(d=>typeof d=="string"&&d in o);if(s!==void 0)throw new P("MASK_UNSUPPORTED",`${t}() over masked column "${s}" on "${r}" is not supported`)},R=(r,n)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[t,o]of Object.entries(r))if(t==="AND"||t==="OR"){if(Array.isArray(o))for(const s of o)R(s,n)}else t==="NOT"?R(o,n):t.startsWith("__")||n.add(t)},u=(r,n,t)=>{const o=e.get(r);if(!o||n===void 0)return;const s=new Set;R(n,s);for(const d of s)if(d in o)throw new P("MASK_UNSUPPORTED",`${t}() filtering "${r}" by masked column "${d}" is not supported`)},I=(r,n,t)=>{const o=e.get(r);if(!(!o||!Array.isArray(n))){for(const s of n)if(s&&typeof s=="object"&&!Array.isArray(s)){for(const d of Object.keys(s))if(d in o)throw new P("MASK_UNSUPPORTED",`${t}() ordering "${r}" by masked column "${d}" is not supported`)}}},F=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,A=(r,n,t)=>{const o=F(n);u(r,o?.where,t),u(r,o?.baseWhere,t)},O={...i,async deleteWhere(r,n,t){if(u(r,n,"deleteMany({ where })"),i.deleteWhere===void 0)throw new P("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return i.deleteWhere(r,n,t)},async patchWhere(r,n,t){if(u(r,n.where,"patchMany({ where })"),i.patchWhere===void 0)throw new P("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return i.patchWhere(r,n,t)},aggregate(r,n){return M(r,[n.field],"aggregate"),u(r,n.where,"aggregate"),i.aggregate(r,n)},count(r,n){const t=F(n),o=t&&("where"in t||"baseWhere"in t||"restrictsCounts"in t)?t.where:n;return u(r,o,"count"),t&&u(r,t.baseWhere,"count"),i.count(r,n)},async findFirst(r,n){u(r,n?.where,"findFirst"),u(r,n?.baseWhere,"findFirst"),I(r,n?.orderBy,"findFirst");const t=await i.findFirst(r,p(n)),o=e.get(r);return t&&o?a(t,o,c):t},async findFirstOrThrow(r,n){u(r,n?.where,"findFirstOrThrow"),u(r,n?.baseWhere,"findFirstOrThrow"),I(r,n?.orderBy,"findFirstOrThrow");const t=await i.findFirstOrThrow(r,p(n)),o=e.get(r);return o?a(t,o,c):t},async findMany(r,n){u(r,n?.where,"findMany"),u(r,n?.baseWhere,"findMany"),I(r,n?.orderBy,"findMany");const t=await i.findMany(r,p(n)),o=e.get(r);return o?W(t,o,c):t},async get(r,n){const{row:t,tableName:o}=await S(r,n),s=o===void 0?void 0:e.get(o);return!t||!s?t:a(t,s,c)},async lookupById(r,n){const t=await i.lookupById?.(r,n);if(!t)return null;const o=e.get(t.tableName);return{row:o?a(t.row,o,c):t.row,tableName:t.tableName}},groupBy(r,n){return M(r,[...n.by,n.agg?.field],"groupBy"),u(r,n.where,"groupBy"),i.groupBy(r,n)},query(r){const n=i.query(r),t=e.get(r);return t?l(n,t,r):n},async rank(r,n,t){return A(r,t,"rank"),k(r,n,"rank","rank"),i.rank(r,n,t)},async rankPage(r,n,t){A(r,t,"rankPage"),k(r,n,"rankPage","rank");const o=await i.rankPage(r,n,t),s=e.get(r);return s?W(o,s,c):o},...v("rankBefore",h,r=>(n,t,o)=>(A(n,o,"rankBefore"),k(n,t,"rankBefore","rank"),r(n,t,o))),...v("rankPageRows",g,r=>async(n,t,o)=>{A(n,o,"rankPageRows"),k(n,t,"rankPageRows","rank");const s=await r(n,t,o),d=e.get(n);return d?{...s,rows:s.rows.map(w=>({...w,doc:a(w.doc,d,c)}))}:s})},j=O;for(const r of e.keys())q(i[r])&&(j[r]=E(O,r));return O},V=(i,e={})=>{const c=new Map(Object.entries(i)),y=D(e.roles),h=async({ctx:f,next:p})=>{const k={auth:await K(f.auth??{},y),ctx:f};if(e.bypass?.(k))return p();const l=L(f.db,c,k,e.indexFields),S={db:l},{orm:M}=f;return M!==null&&typeof M=="object"&&(S.orm=_(l)),p({ctx:S})},g=new Map;for(const[f,p]of c)g.set(f,new Set(Object.keys(p)));return m(h,{columns:g})};export{V as mask};
@@ -0,0 +1 @@
1
+ import{LunoraError as W}from"@lunora/errors";import{bindTableFacade as L,bindOrm as T}from"./bindOrm-ChQydkdL.mjs";import{t as j}from"./policy-tag-V0lqFzgS.mjs";import{deny as $}from"./allowAll-DkRAgItV.mjs";const S=(r,t,i)=>t?{[r]:i(t)}:{},D=500,B=(r,t,i)=>{const a=t??D;if(r>a)throw new W("BATCH_LIMIT_EXCEEDED",`${i}: batch of ${String(r)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},q=$(),N=Symbol.for("lunora.ctxdb.rls-unwrap"),K=r=>{const t=new Map;for(const i of r){const a=t.get(i.table)??[];a.push(i),t.set(i.table,a)}return t},Y=(r,t)=>{const i=[];let a=!1;for(const h of r){if(h.on!=="read")continue;const f=h.when(t);if(f!==void 0){if(f===!0){a=!0;break}f!==!1&&i.push(f)}}if(!a)return i.length===0?q:i.length===1?i[0]:{OR:i}},P=r=>typeof r=="object"&&r!==null&&!Array.isArray(r),z=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],p=r=>{const t=typeof r;return t==="number"||t==="string"||t==="bigint"},H=(r,t)=>!("lt"in t&&(!p(r)||!p(t.lt)||r>=t.lt)||"lte"in t&&(!p(r)||!p(t.lte)||r>t.lte)||"gt"in t&&(!p(r)||!p(t.gt)||r<=t.gt)||"gte"in t&&(!p(r)||!p(t.gte)||r<t.gte)),G=(r,t)=>{if("in"in t){const i=t.in;if(!Array.isArray(i)||!i.includes(r))return!1}if("notIn"in t){const i=t.notIn;if(Array.isArray(i)&&i.includes(r))return!1}if("contains"in t){const i=t.contains;if(typeof r!="string"||typeof i!="string"||!r.includes(i))return!1}return!("isNull"in t&&t.isNull===!0!==(r==null))},Q=(r,t)=>"eq"in t&&r!==t.eq||"ne"in t&&r===t.ne?!1:G(r,t)&&H(r,t),X=(r,t,i,a)=>t==="AND"?Array.isArray(i)&&i.every(h=>a(r,h)):t==="OR"?Array.isArray(i)&&i.some(h=>a(r,h)):!a(r,i??{}),C=r=>r==="AND"||r==="OR"||r==="NOT",J=r=>P(r)&&Object.keys(r).every(t=>z.includes(t)),Z=["every","is","isNot","none","some"],x=r=>P(r)&&Object.keys(r).length>0&&Object.keys(r).every(t=>Z.includes(t)),E=r=>Object.keys(r).some(t=>{const i=r[t];return C(t)?t==="NOT"?E(i??{}):Array.isArray(i)&&i.some(a=>E(a??{})):x(i)}),A=(r,t)=>{for(const i of Object.keys(t)){const a=t[i];if(C(i)){if(!X(r,i,a,A))return!1;continue}const h=r[i];if(J(a)){if(!Q(h,a))return!1;continue}if(h!==a)return!1}return!0},V=(r,t,i)=>{const a=r.when({...t,row:i});if(a===void 0||a===!0)return!0;if(a===!1)return!1;if(E(a))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return A(i,a)},ee=(r,t,i)=>{const a=r.when(t);if(a===void 0||a===!0)return i===void 0||V(r,t,i);if(a===!1)return!1;if(E(a))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!A(t.row,a)?!1:i===void 0||A(i,a)},_=(r,t,i,a)=>{let h=!1;for(const f of r)if(f.on===t&&(h=!0,!ee(f,i,a)))return!1;return h},re=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),te=(r,t)=>t===void 0?!0:r==="restrictsCounts"?typeof t=="boolean":r==="relationBaseWhere"?typeof t=="function":P(t),ne=r=>{const t=Object.keys(r);return t.length===0?!1:t.every(i=>re.has(i)&&te(i,r[i]))},se=r=>r===void 0?{}:P(r)&&ne(r)?r:{where:r},w=(r,t)=>!t||Object.keys(t).length===0?r:!r||Object.keys(r).length===0?t:{AND:[t,r]},ie=r=>{if(typeof r!="object"||r===null||Array.isArray(r))return!1;const t=r;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},oe=(r,t,i,a)=>{const h=new Map,f=e=>{const n=h.get(e);if(n)return n;const s=i.get(e);if(!s||s.length===0||!s.some(l=>l.on==="read")){const l={baseWhere:void 0,restricts:!1};return h.set(e,l),l}const c={baseWhere:Y(s,a),restricts:!0};return h.set(e,c),c},d=e=>f(e).restricts?t:r,y=e=>f(e).baseWhere,O=async(e,n)=>{if(t.lookupById){const u=await t.lookupById(e,n);return u?{row:u.row,tableName:i.has(u.tableName)?u.tableName:void 0}:{row:null,tableName:void 0}}const s=await t.get(e,n);if(!s)return{row:null,tableName:void 0};const o=n!==void 0&&i.has(n)?[n]:[],c=n===void 0?[...i.keys()]:o,l=await Promise.all(c.map(async u=>(await t.findFirst(u,{limit:1,where:{_id:e}}))?._id===e?u:void 0));return{row:s,tableName:l.find(u=>u!==void 0)}},M=async(e,n)=>{const s=await O(e,n);return s.row&&s.tableName!==void 0?{row:s.row,tableName:s.tableName}:void 0},g=async(e,n,s,o,c)=>{const l=await M(e,c);if(!l)return s(r);const u=i.get(l.tableName);if(u){const k=o?o(l.row):void 0;if(!_(u,n,{...a,row:l.row},k))throw new W("FORBIDDEN",`${n} denied by policy`)}return s(t)},b=(e,n)=>{const{baseWhere:s,restricts:o}=f(e);if(o)throw new W("COUNT_RLS_UNSUPPORTED",`${n}() is not supported on "${e}" inside an RLS-restricted context`);return s},v=r.rankBefore,m=r.rankPageRows,R={...r,async count(e,n){const{baseWhere:s,restricts:o}=f(e),c=se(n);return d(e).count(e,{...c,baseWhere:w(c.baseWhere,s),relationBaseWhere:y,restrictsCounts:(c.restrictsCounts??!1)||o})},delete:(e,n,s)=>g(e,"delete",o=>o.delete(e,n,s),void 0,n),async deleteAll(e,n){const s=Math.max(1,n?.chunkSize??D),{baseWhere:o}=f(e);let c=0;for(;;){const u=(await d(e).findMany(e,{baseWhere:o,limit:s,relationBaseWhere:y})).page.map(k=>String(k._id));if(u.length===0)break;for(const k of u)await g(k,"delete",I=>I.delete(k,void 0,n?.hard===void 0?void 0:{hard:n.hard})),c+=1;if(u.length<s)break}return{deleted:c}},async deleteMany(e,n,s){B(e.length,n?.limit,"deleteMany");for(const o of e)await g(o,"delete",c=>c.delete(o,s),void 0,s);return{deleted:e.length}},async deleteWhere(e,n,s){const{baseWhere:o}=f(e),l=(await d(e).findMany(e,{baseWhere:w(n,o),relationBaseWhere:y})).page.map(u=>String(u._id));return B(l.length,s?.limit,"deleteWhere"),R.deleteMany(l,s)},async findFirst(e,n){const{baseWhere:s}=f(e);return d(e).findFirst(e,{...n,baseWhere:w(n?.baseWhere,s),relationBaseWhere:y})},async findFirstOrThrow(e,n){const{baseWhere:s}=f(e);return d(e).findFirstOrThrow(e,{...n,baseWhere:w(n?.baseWhere,s),relationBaseWhere:y})},async findMany(e,n){const{baseWhere:s}=f(e);return d(e).findMany(e,{...n,baseWhere:w(n?.baseWhere,s),relationBaseWhere:y})},async get(e,n){const s=await O(e,n);if(!s.row)return null;if(s.tableName===void 0)return r.get(e,n);const{baseWhere:o,restricts:c}=f(s.tableName);if(!c)return r.get(e,n);if(!o)return s.row;const l=await t.findFirst(s.tableName,{baseWhere:o,limit:1,where:{_id:e}});return l?._id===e?l:null},async lookupById(e,n){const s=await O(e,n);if(!s.row)return null;if(s.tableName===void 0||!f(s.tableName).restricts)return await r.lookupById?.(e,n)??null;const{baseWhere:o}=f(s.tableName);if(!o)return{row:s.row,tableName:s.tableName};const c=await t.findFirst(s.tableName,{baseWhere:o,limit:1,where:{_id:e}});return c?._id===e?{row:c,tableName:s.tableName}:null},async insert(e,n){const s=i.get(e);if(s){if(!_(s,"insert",{...a,row:n}))throw new W("FORBIDDEN",`insert on "${e}" denied by policy`);return t.insert(e,n)}return r.insert(e,n)},async insertMany(e,n,s){B(n.length,s?.limit,"insertMany");const o=i.get(e);if(o){for(const c of n)if(!_(o,"insert",{...a,row:c}))throw new W("FORBIDDEN",`insert on "${e}" denied by policy`);return t.insertMany(e,n,s)}return r.insertMany(e,n,s)},async insertManyUnsafe(e,n,s){B(n.length,s?.limit,"insertManyUnsafe");const o=i.get(e);if(o){for(const c of n)if(!_(o,"insert",{...a,row:c}))throw new W("FORBIDDEN",`insert on "${e}" denied by policy`);return t.insertManyUnsafe(e,n,s)}return r.insertManyUnsafe(e,n,s)},patch:(e,n,s)=>g(e,"update",o=>o.patch(e,n,s),o=>({...o,...n}),s),async patchMany(e,n,s){B(e.length,n?.limit,"patchMany");for(const o of e)await g(o.id,"update",c=>c.patch(o.id,o.patch,s),c=>({...c,...o.patch}),s);return{patched:e.length}},async patchWhere(e,n,s){const{baseWhere:o}=f(e),l=(await d(e).findMany(e,{baseWhere:w(n.where,o),relationBaseWhere:y})).page.map(u=>({id:String(u._id),patch:n.patch}));return B(l.length,s?.limit,"patchWhere"),R.patchMany(l,s)},query(e){const{baseWhere:n}=f(e),s=d(e).query(e);return n?s.filter(o=>A(o,n)):s},restore:(e,n)=>g(e,"update",async s=>{const o=s.restore??t.restore;if(!o)throw new W("BAD_REQUEST","restore is not supported by this writer");await o(e,n)},void 0,n),replace:(e,n,s)=>g(e,"update",o=>o.replace(e,n,s),o=>({...n,_creationTime:n._creationTime??o._creationTime,_id:o._id}),s),aggregate(e,n){const{baseWhere:s}=f(e);return d(e).aggregate(e,{...n,baseWhere:w(n.baseWhere,s),relationBaseWhere:y})},groupBy(e,n){const{baseWhere:s}=f(e);return d(e).groupBy(e,{...n,baseWhere:w(n.baseWhere,s),relationBaseWhere:y})},rank(e,n,s){const o=b(e,"rank");return d(e).rank(e,n,{...s,baseWhere:w(s.baseWhere,o)})},rankPage(e,n,s){const o=b(e,"rankPage");return d(e).rankPage(e,n,{...s,baseWhere:w(s?.baseWhere,o)})},wipeShard(){throw new W("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...S("rankBefore",v,e=>(n,s,o)=>(b(n,"rankBefore"),(d(n).rankBefore??e)(n,s,o))),...S("rankPageRows",m,e=>(n,s,o)=>{const c=b(n,"rankPageRows");return(d(n).rankPageRows??e)(n,s,{...o,baseWhere:w(o?.baseWhere,c)})})},U=R;for(const e of i.keys())ie(r[e])&&(U[e]=L(R,e));return R},F=r=>typeof r=="string"?r:r.name,ae=r=>{const t=new Map;for(const i of r??[])t.set(i.name,new Set((i.permissions??[]).map(a=>F(a))));return t},ce=(r,t)=>{const i=new Set;for(const a of r)for(const h of t.get(a)??[])i.add(h);return a=>i.has(F(a))},fe=async(r,t)=>{const i=r.roles??[];return{can:ce(i,t),identity:await r.getIdentity?.()??null,roles:i,userId:r.userId??null}},ye=(r,t={})=>{const i=K(r),a=ae(t.roles);return j(async({ctx:f,next:d})=>{const y={auth:await fe(f.auth??{},a),ctx:f},O=f.db,M=O[N]??O,g=oe(O,M,i,y),b={db:g},{orm:v}=f;return v!==null&&typeof v=="object"&&(b.orm=T(g)),d({ctx:b})},[{policies:r,roles:t.roles??[]}])};export{fe as a,ie as b,Y as c,ce as d,_ as e,ae as i,A as m,S as o,F as p,ye as r};
@@ -0,0 +1 @@
1
+ import{LunoraError as s}from"@lunora/errors";import{c as K}from"./compose-middleware-3i5Qk3sb.mjs";import{v as R}from"@lunora/values";const j=["de","en","es","fr","it","nl","none","pt"],_=["native","portable"],z=e=>_.includes(e),H=e=>j.includes(e),q=e=>{if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?q(t):e.kind},B=16,Q={many:(e,t)=>({field:t.field,kind:"many",references:t.references??"_id",table:e}),one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},g=(e,t,n)=>({handler:n,op:t,timing:e}),X=()=>({afterDelete:e=>g("after","delete",e),afterInsert:e=>g("after","insert",e),afterUpdate:e=>g("after","update",e),beforeDelete:e=>g("before","delete",e),beforeInsert:e=>g("before","insert",e),beforeUpdate:e=>g("before","update",e)}),F=(e,t)=>{if(!t||t.length===0)throw new s("INTERNAL",`rankIndex "${e}": "sortBy" is required and must list at least one key`);return t.map(n=>({direction:n.direction??"asc",field:n.field}))},le=e=>{const t={...e},n=[],r=[],o=[],d=[],u={},l=[],f={},m=X(),b=[];let y={kind:"root"},$=!1,N=!1,k=!1,T=!1,L,M,A,O;const c={aggregateIndex(i,a){const h=a?.op??"count";if(h!=="count"&&!a?.field)throw new s("INTERNAL",`aggregateIndex "${i}": op "${h}" requires a "field"`);return n.push({by:a?.by,field:a?.field,name:i,on:"",op:h,where:a?.where}),c},get aggregateIndexes(){return n},get externalSource(){return O},commitOrdered(){return $=!0,c},get commitOrderedMode(){return $},externallyManaged(){return N=!0,c},geoIndex(i,a){return r.push({field:a.field,name:i,precision:a.precision}),c},get geoIndexes(){return r},global(i){return y={backend:i?.backend??"d1",kind:"global"},c},get isExternallyManaged(){return N},get isPublic(){return T},index(i,a,h){return o.push({fields:a,name:i,unique:h?.unique??!1}),c},get indexes(){return o},memory(){return k=!0,c},get memoryMode(){return k},ownedBy(i){return L=i,c},get ownerField(){return L},public(){return T=!0,c},rankIndex(i,a){return d.push({name:i,on:"",partitionBy:a.partitionBy,sortBy:F(i,a.sortBy),where:a.where}),c},get rankIndexes(){return d},get relationMap(){return u},relations(i){return Object.assign(u,i(Q)),c},searchIndex(i,a){if(a.filterFields&&a.filterFields.length>B)throw new s("INTERNAL",`searchIndex "${i}": at most ${String(B)} filterFields are supported (got ${String(a.filterFields.length)})`);const{language:h}=a;if(h!==void 0&&!H(h))throw new s("INTERNAL",`searchIndex "${i}": unknown language "${h}" (supported: ${j.join(", ")})`);const{strategy:v}=a;if(v!==void 0&&!z(v))throw new s("INTERNAL",`searchIndex "${i}": unknown strategy "${v}" (supported: ${_.join(", ")})`);return l.push({field:a.field,filterFields:a.filterFields,language:a.language,name:i,staged:a.staged,strategy:a.strategy}),c},get searchIndexes(){return l},shape:t,shardBy(i){return y={field:i,kind:"shardBy"},c},get shardMode(){return y},get softDeleteMode(){return M},source(i){if(!i.binding)throw new s("INTERNAL","source: `binding` is required (the wrangler Hyperdrive binding name)");if(!i.query)throw new s("INTERNAL","source: `query` is required (the tenant-membership SQL)");return O=i,N=!0,c},softDelete(i){const a=i?.field??"deletedAt";return M={field:a},a in t||(t[a]=R.optional(R.number().nullable())),c},get triggerMap(){return f},triggers(i){return Object.assign(f,i(m)),c},ttl(i,a){return A={after:a?.after,field:i},c},get ttlPolicy(){return A},get vectorIndexes(){return b},vectorize(i,a){return b.push({dimensions:a.dimensions,embed:a.embed,field:i,metadata:a.metadata,metric:a.metric,name:a.index}),c}};return c},ce=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,select:e.source.select,table:e.source.table}),ue=(e,t)=>{const n=t.op??"count";if(n!=="count"&&!t.field)throw new s("INTERNAL",`aggregateIndex "${e}": op "${n}" requires a "field"`);return{by:t.by,field:t.field,name:e,on:t.on,op:n,where:t.where}},fe=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:F(e,t.sortBy),where:t.where}),x=e=>({...e,extend(t){return x(C(e,t))},jurisdiction(t){return x(e)},rls(t){return x({...e,rlsMode:t})}}),U=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},V=(e,t,n)=>{for(const r of Object.values(t)){const o=e[r.on];if(!o)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);o.aggregateIndexes.push(r)}for(const r of Object.values(n)){const o=e[r.on];if(!o)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);o.rankIndexes.push(r)}},Y=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},G=(e,t)=>{const n=t.mode==="incremental";if(t.mode!==void 0&&t.mode!=="full-pull"&&!n)throw new s("INTERNAL",`defineSchema: table "${e}" uses \`mode: ${JSON.stringify(t.mode)}\` — supported modes are "full-pull" (default) and "incremental".`);if(!n){const r=Y(t);if(r)throw new s("INTERNAL",`defineSchema: table "${e}" sets \`${r}\` but is not \`mode: "incremental"\` — that knob only applies to incremental ingest. Set \`mode: "incremental"\` or remove \`${r}\`.`);return}if(!t.cursor?.column||!t.cursor.query)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` but has no \`cursor\` — add \`cursor: { column: "updated_at", query: "… WHERE … > $N" }\` binding the watermark as the trailing parameter.`);if(t.reconcileEveryMs===void 0&&t.softDeleteColumn===void 0)throw new s("INTERNAL",`defineSchema: table "${e}" is \`mode: "incremental"\` with no delete-visibility path — an incremental pull never sees upstream deletes, so it would accumulate phantom rows. Add \`reconcileEveryMs\` (a periodic full-pull sweep) or \`softDeleteColumn\` (an upstream tombstone column).`)},J=e=>{for(const[t,n]of Object.entries(e)){const r=n.externalSource;if(r){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" cannot be both .source() and .global() — a sourced table materializes into a shard DO's SQLite, a global table lives in the external tier`);if(n.shardMode.kind==="shardBy"&&!r.tenantBy)throw new s("INTERNAL",`defineSchema: sourced + .shardBy() table "${t}" needs a \`tenantBy\` mapper — without it every tenant's DO would run the same unscoped query and replicate the whole multitenant table (a cross-tenant leak). Add \`tenantBy: (shardKey) => [shardKey]\` binding the shard key into the query's parameters.`);G(t,r)}}},W=["_commitSeq","_creationTime","_id"],D="_commitSeq",Z=new Set(W),w=(e,t,n,r)=>{if(!(Z.has(n)||n in r.shape))throw new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},p=(e,t,n,r)=>{const o=new Set;for(const d of n){if(o.has(d.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${d.name}" more than once`);o.add(d.name),r(d)}},P=e=>{for(const[t,n]of Object.entries(e))p(t,"index",n.indexes,r=>{for(const o of r.fields)w(t,r.name,o,n)}),p(t,"rank index",n.rankIndexes,r=>{for(const o of r.sortBy)w(t,r.name,o.field,n);for(const o of r.partitionBy??[])w(t,r.name,o,n)}),p(t,"geo index",n.geoIndexes,r=>{w(t,r.name,r.field,n)})},E=(e,t,n)=>{if(e.length===0)return;const r={};for(const o of e)r[t(o)]=n(o);return r},ee=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},me=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const o=E(r.geoIndexes,l=>l.name,l=>[l.field]),d=E(r.indexes,l=>l.name,l=>l.fields),u=E(r.rankIndexes,l=>l.name,ee);(o||d||u)&&(t[n]={...o?{geo:o}:{},...d?{index:d}:{},...u?{rank:u}:{}})}return t},te=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const o=[[n.shardMode.kind==="global",".global() — those rows live in D1, which this shard does not own and cannot clear"],[n.commitOrderedMode===!0,".commitOrdered() — the counter resets with the table, so the sequence would restart and a consumer's cursor would silently skip everything after it"],[n.externalSource!==void 0,".source() — the table is materialized by the ingest loop, so wiping it on every eviction would fight the puller"],[n.searchIndexes.length>0,".searchIndex() — the FTS shadow is a separate table that clearing the rows would leave stale"],[n.geoIndexes.length>0,".geoIndex() — the geohash companion is a separate table that clearing the rows would leave stale"],[n.aggregateIndexes.length>0,".aggregateIndex() — the counter companion is a separate table that clearing the rows would leave stale"],[n.rankIndexes.length>0,".rankIndex() — the rank companion is a separate table that clearing the rows would leave stale"],[n.vectorIndexes.length>0,".vectorize() — vectors live in an external index that a shard restart cannot clear"]].find(([d])=>d)?.[1];if(o!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${o}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},ne=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,o]of Object.entries(n.shape))if(q(o)==="bigint")throw new s("INTERNAL",`defineSchema: table "${t}" is .global() and column "${r}" is v.bigint(). A global (D1/Hyperdrive) table stores a bigint as decimal TEXT, which SQL compares lexicographically — "100" sorts before "25" — so \`orderBy\`, range filters and \`aggregate\` on this column would silently return wrong results. Use v.number() if the value fits a double, or v.string() if you only need equality.`)}},re=e=>{for(const[t,n]of Object.entries(e)){if(n.commitOrderedMode){if(n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .commitOrdered(). \`_commitSeq\` is allocated inside the shard's write transaction, which a global (D1/Hyperdrive) table does not share — so the stamp would carry no commit-ordering guarantee. Drop one of the two.`);continue}for(const r of n.indexes)if(r.fields.includes(D))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${D}", but the table is not .commitOrdered() — no row carries that field, so the index would never match. Add .commitOrdered(), or drop the column from the index.`)}},he=(e,t={},n={},r={})=>(U(e),V(e,n,r),J(e),re(e),ne(e),te(e),P(e),x({tables:e,vectorIndexes:t})),I=(e,t)=>`${e}_${t}`,S=(e,t,n)=>n.has(e)?I(t,e):e,ae=(e,t,n,r)=>{const o=I(t,r),d=m=>m===""?o:S(m,t,n),u={};for(const[m,b]of Object.entries(e.relationMap))u[m]={...b,table:S(b.table,t,n)};const l=e.aggregateIndexes.map(m=>({...m,on:d(m.on)})),f=e.rankIndexes.map(m=>({...m,on:d(m.on)}));return{...e,aggregateIndexes:l,rankIndexes:f,relationMap:u}},ge=(e,t)=>{if(!e)throw new s("INTERNAL","defineSchemaExtension: `key` is required and must be a non-empty string");return{key:e,tables:t.tables,...t.vectorIndexes?{vectorIndexes:t.vectorIndexes}:{}}},oe=((e,t)=>{if(!e)throw new s("INTERNAL","definePlugin: `key` is required and must be a non-empty string");if(t.extension&&t.extension.key!==e)throw new s("INTERNAL",`definePlugin("${e}"): extension key "${t.extension.key}" does not match plugin key`);return{key:e,...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}}),be=(e,t)=>({...oe(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),C=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),o={...e.tables};for(const[u,l]of Object.entries(t.tables)){const f=I(n,u);if(Object.hasOwn(o,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): table "${f}" already exists in the base schema — another extension with the same key already contributed it`);o[f]=ae(l,n,r,u)}const d={...e.vectorIndexes};if(t.vectorIndexes)for(const[u,l]of Object.entries(t.vectorIndexes)){const f=I(n,u);if(Object.hasOwn(d,f))throw new s("INTERNAL",`defineSchema(...).extend("${n}"): vector index "${f}" already exists in the base schema — another extension with the same key already contributed it`);d[f]={...l,table:S(l.table,n,r)}}return P(o),{rlsMode:e.rlsMode,tables:o,vectorIndexes:d}},we=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=C(n,r.extension));return n},xe=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return K(t)};export{be as a,oe as b,xe as c,ue as d,fe as e,he as f,ge as g,le as h,ce as i,me as j,we as k,C as m,P as v};
@@ -0,0 +1 @@
1
+ const t=Symbol.for("lunora.rls.middleware-policies"),o=(e,r)=>(Object.defineProperty(e,t,{configurable:!0,enumerable:!1,value:r}),e),n=e=>e===null||typeof e!="function"&&typeof e!="object"?[]:e[t]??[];export{n as r,o as t};
@@ -0,0 +1 @@
1
+ import{c as t}from"./compose-middleware-3i5Qk3sb.mjs";const i=c=>{const e=[c.rateLimit,c.captcha,...c.use??[]].filter(r=>r!==void 0);return t(e)};export{i as protectPublic};
@@ -0,0 +1 @@
1
+ import"./bindOrm-ChQydkdL.mjs";import{c as o,e as m,i as t,b as p,m as l,p as c,d as n,a as d,r as h}from"./middleware-Cz5s6CH-.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{o as computeReadBaseWhere,m as evaluateWrite,t as indexRolePermissions,p as isFacadeEntry,l as matchesWhere,c as permissionName,n as resolveCan,d as resolvePolicyAuth,h as rls};
@@ -0,0 +1 @@
1
+ import{LunoraError as d}from"@lunora/errors";const w=async(s,c,i)=>{let a=-1;const e=async(r,t)=>{if(r<=a)throw new d("INTERNAL","middleware next() called multiple times");a=r;const n=s[r];return n?await n({ctx:t,next:(l=>e(r+1,l?.ctx?{...t,...l.ctx}:t))}):i(t)};return e(0,c)};export{w as r};
@@ -0,0 +1 @@
1
+ import{LunoraError as y}from"@lunora/errors";import{i as U,a as v}from"./middleware-Cz5s6CH-.mjs";const D=(o,e)=>o===void 0||e.startsWith(o),k=o=>{const e=o[1],c=typeof e=="object"&&e!==null?e.method:void 0;return typeof c=="string"&&c.toUpperCase()==="PUT"?"write":"read"},E=[["delete","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",k],["getUrl","read"],["head","read"],["store","write"]],S=(o,e={})=>{const c=U(e.roles);return async({ctx:u,next:f})=>{const w=await v(u.auth??{},c),g=(n,r,s)=>{const i=o.filter(t=>t.on===n&&t.bucket===s);if(i.length===0)return;const a={auth:w,ctx:u,key:r};if(!i.some(t=>D(t.prefix,r)&&t.when(a)===!0))throw new y("FORBIDDEN",`storage ${n} on "${r}" in bucket "${s}" denied by access rule`)},p=n=>{const r=n.bucketName??"default",s={bucketName:r};for(const[a,d]of E){const t=n[a];typeof t=="function"&&(s[a]=(...l)=>{const m=typeof l[0]=="string"?l[0]:"",b=typeof d=="function"?d(l):d;return g(b,m,r),t(...l)})}const{bucket:i}=n;return typeof i=="function"&&(s.bucket=a=>p(i(a))),s},h=u.storage;return h===void 0?f():f({ctx:{storage:p(h)}})}};export{S as storageRules};
@@ -1 +1 @@
1
- import{i as b,d as P,c as W,m as v,e as y}from"../packem_shared/middleware-EloVU9X1.mjs";const C=(d,c={})=>{const m=b(c.roles),h=c.ctx??{};return{as:x=>{const n=x??{},i=n.roles??[],l={auth:{can:P(i,m),identity:n.identity??null,roles:i,userId:n.userId??null},ctx:h},u=(e,o,t,a)=>{const r=d.filter(s=>s.table===o);if(r.length===0)return!0;if(e==="read"){if(!r.some(f=>f.on==="read"))return!0;const s=W(r,l);return s===void 0||v(t??{},s)}return y(r,e,{...l,row:t},a)};return{can:u,cannot:(e,o,t,a)=>!u(e,o,t,a)}}}};export{C as expectPolicy};
1
+ import{i as b,d as P,c as W,m as v,e as y}from"../packem_shared/middleware-Cz5s6CH-.mjs";const C=(d,c={})=>{const m=b(c.roles),h=c.ctx??{};return{as:x=>{const n=x??{},i=n.roles??[],l={auth:{can:P(i,m),identity:n.identity??null,roles:i,userId:n.userId??null},ctx:h},u=(e,o,t,a)=>{const r=d.filter(s=>s.table===o);if(r.length===0)return!0;if(e==="read"){if(!r.some(f=>f.on==="read"))return!0;const s=W(r,l);return s===void 0||v(t??{},s)}return y(r,e,{...l,row:t},a)};return{can:u,cannot:(e,o,t,a)=>!u(e,o,t,a)}}}};export{C as expectPolicy};
package/dist/types.d.mts CHANGED
@@ -575,12 +575,6 @@ interface RegisteredFunction<A extends ArgsValidator, R, Kind extends FunctionKi
575
575
  * Absent on ordinary registrations.
576
576
  */
577
577
  readonly lifecycle?: LifecycleEventKind;
578
- /**
579
- * Static per-procedure metadata declared with `.meta(...)`. Present so
580
- * middleware (via `ctx.meta`) and tooling can read the same object; absent
581
- * when the chain never called `.meta()`.
582
- */
583
- readonly meta?: Readonly<Record<string, unknown>>;
584
578
  readonly visibility?: FunctionVisibility;
585
579
  /**
586
580
  * Set by the `.x402({ price })` builder modifier. Marks the procedure as paid
@@ -747,8 +741,6 @@ interface RegisteredStream<A extends ArgsValidator, R> {
747
741
  readonly durable?: DurableStreamOptions;
748
742
  readonly handler: (context: unknown, args: InferArgs<A>, signal: AbortSignal) => AsyncIterable<R>;
749
743
  readonly kind: "stream";
750
- /** Static per-procedure metadata attached via `.meta()`. See {@link RegisteredFunction.meta}. */
751
- readonly meta?: Readonly<Record<string, unknown>>;
752
744
  readonly visibility?: FunctionVisibility;
753
745
  }
754
746
  /**
@@ -1603,8 +1595,12 @@ interface StorageMetadata {
1603
1595
  interface StorageObjectHead {
1604
1596
  /** Custom metadata set at upload time, if any. */
1605
1597
  customMetadata?: Record<string, string>;
1606
- /** R2's unquoted etag (the MD5 hex for a single-part upload). */
1607
- etag?: string;
1598
+ /**
1599
+ * R2's unquoted etag (the MD5 hex for a single-part upload). Required: R2
1600
+ * reports one on every object, and an HTTP layer built on `head()` (the
1601
+ * `serveStorageObject` helper) needs it to emit a validator.
1602
+ */
1603
+ etag: string;
1608
1604
  /** The already-quoted form of {@link StorageObjectHead.etag}, when the binding reports one. */
1609
1605
  httpEtag?: string;
1610
1606
  /** Recorded HTTP metadata, notably the `Content-Type`. */
@@ -1622,6 +1618,30 @@ interface StorageObjectHead {
1622
1618
  /** When the object was last written. */
1623
1619
  uploaded?: Date;
1624
1620
  }
1621
+ /**
1622
+ * Byte window forwarded to {@link ReadOnlyStorage.download} so R2 resolves the
1623
+ * slice server-side and streams only those bytes back. Mirrors R2's own `range`
1624
+ * option (`@lunora/platform`'s `R2RangeLike`), restated structurally so
1625
+ * `@lunora/server` takes no dependency on the bindings package.
1626
+ */
1627
+ type StorageRange = {
1628
+ length?: number;
1629
+ offset: number;
1630
+ } | {
1631
+ length: number;
1632
+ offset?: number;
1633
+ } | {
1634
+ suffix: number;
1635
+ };
1636
+ /**
1637
+ * A downloaded object: the same metadata {@link StorageObjectHead} carries, plus
1638
+ * the body stream. This is what `download()` resolves to — R2's object, NOT a
1639
+ * bare stream.
1640
+ */
1641
+ interface StorageObjectBody extends StorageObjectHead {
1642
+ /** The object body stream. `null` for a zero-byte object. */
1643
+ body: ReadableStream | null;
1644
+ }
1625
1645
  /**
1626
1646
  * Read-only projection of `Storage` exposed on `QueryCtx` / `MutationCtx`.
1627
1647
  *
@@ -1641,8 +1661,29 @@ interface ReadOnlyStorage<Buckets extends string = string> {
1641
1661
  bucket: (name: Buckets) => ReadOnlyStorage<Buckets>;
1642
1662
  /** The bucket this accessor's operations target (the default for the bare `ctx.storage`). */
1643
1663
  readonly bucketName: string;
1644
- /** Fetch the body of an existing object. Returns `null` when absent. */
1645
- download: (key: string) => Promise<ReadableStream | null>;
1664
+ /**
1665
+ * Fetch an existing object. Returns the R2 object — metadata plus a `body`
1666
+ * stream — or `null` when absent.
1667
+ *
1668
+ * NOT a bare stream: `new Response(await ctx.storage.download(key))` would
1669
+ * stringify the object and serve the literal text `[object Object]`. Reach
1670
+ * for the body explicitly:
1671
+ *
1672
+ * ```ts
1673
+ * const object = await ctx.storage.download(key);
1674
+ *
1675
+ * return object ? new Response(object.body) : new Response("Not found", { status: 404 });
1676
+ * ```
1677
+ *
1678
+ * (`serveStorageObject` from `@lunora/server` does this, plus range/ETag
1679
+ * handling, for the common "serve a stored file over HTTP" case.)
1680
+ *
1681
+ * Pass `range` to have R2 resolve the byte window server-side, so the
1682
+ * unwanted bytes never reach the worker.
1683
+ */
1684
+ download: (key: string, options?: {
1685
+ range?: StorageRange;
1686
+ }) => Promise<StorageObjectBody | null>;
1646
1687
  /**
1647
1688
  * Read a file's metadata (size, content-type, sha256, upload time, custom
1648
1689
  * metadata) without fetching its body. Returns `null` when the object is
@@ -1697,6 +1738,23 @@ interface Storage<Buckets extends string = string> extends ReadOnlyStorage<Bucke
1697
1738
  contentType?: string;
1698
1739
  expiresInSeconds?: number;
1699
1740
  }) => Promise<string>;
1741
+ /**
1742
+ * Mint a native S3 SigV4 URL that hits R2 **directly**, so the bytes never
1743
+ * pass through the Worker — unlike {@link Storage.generateUploadUrl}, whose
1744
+ * signed URL points back at this app so its storage rules still apply.
1745
+ *
1746
+ * Requires `s3` credentials on the `.storage({ s3 })` declaration; without
1747
+ * them the call throws. That is the trade-off: no Worker in the path also
1748
+ * means no rule enforcement in the path.
1749
+ *
1750
+ * Declared structurally rather than imported — `@lunora/server` does not
1751
+ * depend on `@lunora/storage`, and this file mirrors that surface the same
1752
+ * way `head` and `download` do.
1753
+ */
1754
+ getPresignedUrl: (key: string, options?: {
1755
+ expiresInSeconds?: number;
1756
+ method?: "GET" | "PUT";
1757
+ }) => Promise<string>;
1700
1758
  /**
1701
1759
  * Upload `body` to `key` from the server, returning the stored object's key
1702
1760
  * and etag. Mirrors Convex's `storage.store`. Accepts the same guard fields
@@ -2106,9 +2164,10 @@ interface QueryCtx {
2106
2164
  /** Application counters, gauges, and histograms; see {@link LunoraMetrics}. */
2107
2165
  /**
2108
2166
  * Static metadata declared on this procedure with `.meta(...)`, merged
2109
- * across calls. Present so middleware can read the policy it is meant to
2110
- * enforce (`ctx.meta.rateLimit`, …) instead of having it hard-wired at each
2111
- * `.use()` site; absent when the procedure never called `.meta()`.
2167
+ * across calls and deep-frozen. Present so middleware can read the policy it
2168
+ * is meant to enforce (`ctx.meta.rateLimit`, …) instead of having it
2169
+ * hard-wired at each `.use()` site; absent when the procedure never called
2170
+ * `.meta()`.
2112
2171
  */
2113
2172
  readonly meta?: Readonly<Record<string, unknown>>;
2114
2173
  readonly metrics: LunoraMetrics;
@@ -2161,9 +2220,10 @@ interface MutationCtx {
2161
2220
  /** Application counters, gauges, and histograms; see {@link LunoraMetrics}. */
2162
2221
  /**
2163
2222
  * Static metadata declared on this procedure with `.meta(...)`, merged
2164
- * across calls. Present so middleware can read the policy it is meant to
2165
- * enforce (`ctx.meta.rateLimit`, …) instead of having it hard-wired at each
2166
- * `.use()` site; absent when the procedure never called `.meta()`.
2223
+ * across calls and deep-frozen. Present so middleware can read the policy it
2224
+ * is meant to enforce (`ctx.meta.rateLimit`, …) instead of having it
2225
+ * hard-wired at each `.use()` site; absent when the procedure never called
2226
+ * `.meta()`.
2167
2227
  */
2168
2228
  readonly meta?: Readonly<Record<string, unknown>>;
2169
2229
  readonly metrics: LunoraMetrics;
@@ -2234,9 +2294,10 @@ interface ActionCtx {
2234
2294
  /** Application counters, gauges, and histograms; see {@link LunoraMetrics}. */
2235
2295
  /**
2236
2296
  * Static metadata declared on this procedure with `.meta(...)`, merged
2237
- * across calls. Present so middleware can read the policy it is meant to
2238
- * enforce (`ctx.meta.rateLimit`, …) instead of having it hard-wired at each
2239
- * `.use()` site; absent when the procedure never called `.meta()`.
2297
+ * across calls and deep-frozen. Present so middleware can read the policy it
2298
+ * is meant to enforce (`ctx.meta.rateLimit`, …) instead of having it
2299
+ * hard-wired at each `.use()` site; absent when the procedure never called
2300
+ * `.meta()`.
2240
2301
  */
2241
2302
  readonly meta?: Readonly<Record<string, unknown>>;
2242
2303
  readonly metrics: LunoraMetrics;
@@ -2267,4 +2328,4 @@ interface ActionCtx {
2267
2328
  */
2268
2329
  type AnyApi = Record<string, Record<string, RegisteredFunction<ArgsValidator, unknown, FunctionKind>>>;
2269
2330
  declare const anyApi: AnyApi;
2270
- export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelationDefinition, type RestCacheConfig, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectHead, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
2331
+ export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelationDefinition, type RestCacheConfig, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
package/dist/types.d.ts CHANGED
@@ -575,12 +575,6 @@ interface RegisteredFunction<A extends ArgsValidator, R, Kind extends FunctionKi
575
575
  * Absent on ordinary registrations.
576
576
  */
577
577
  readonly lifecycle?: LifecycleEventKind;
578
- /**
579
- * Static per-procedure metadata declared with `.meta(...)`. Present so
580
- * middleware (via `ctx.meta`) and tooling can read the same object; absent
581
- * when the chain never called `.meta()`.
582
- */
583
- readonly meta?: Readonly<Record<string, unknown>>;
584
578
  readonly visibility?: FunctionVisibility;
585
579
  /**
586
580
  * Set by the `.x402({ price })` builder modifier. Marks the procedure as paid
@@ -747,8 +741,6 @@ interface RegisteredStream<A extends ArgsValidator, R> {
747
741
  readonly durable?: DurableStreamOptions;
748
742
  readonly handler: (context: unknown, args: InferArgs<A>, signal: AbortSignal) => AsyncIterable<R>;
749
743
  readonly kind: "stream";
750
- /** Static per-procedure metadata attached via `.meta()`. See {@link RegisteredFunction.meta}. */
751
- readonly meta?: Readonly<Record<string, unknown>>;
752
744
  readonly visibility?: FunctionVisibility;
753
745
  }
754
746
  /**
@@ -1603,8 +1595,12 @@ interface StorageMetadata {
1603
1595
  interface StorageObjectHead {
1604
1596
  /** Custom metadata set at upload time, if any. */
1605
1597
  customMetadata?: Record<string, string>;
1606
- /** R2's unquoted etag (the MD5 hex for a single-part upload). */
1607
- etag?: string;
1598
+ /**
1599
+ * R2's unquoted etag (the MD5 hex for a single-part upload). Required: R2
1600
+ * reports one on every object, and an HTTP layer built on `head()` (the
1601
+ * `serveStorageObject` helper) needs it to emit a validator.
1602
+ */
1603
+ etag: string;
1608
1604
  /** The already-quoted form of {@link StorageObjectHead.etag}, when the binding reports one. */
1609
1605
  httpEtag?: string;
1610
1606
  /** Recorded HTTP metadata, notably the `Content-Type`. */
@@ -1622,6 +1618,30 @@ interface StorageObjectHead {
1622
1618
  /** When the object was last written. */
1623
1619
  uploaded?: Date;
1624
1620
  }
1621
+ /**
1622
+ * Byte window forwarded to {@link ReadOnlyStorage.download} so R2 resolves the
1623
+ * slice server-side and streams only those bytes back. Mirrors R2's own `range`
1624
+ * option (`@lunora/platform`'s `R2RangeLike`), restated structurally so
1625
+ * `@lunora/server` takes no dependency on the bindings package.
1626
+ */
1627
+ type StorageRange = {
1628
+ length?: number;
1629
+ offset: number;
1630
+ } | {
1631
+ length: number;
1632
+ offset?: number;
1633
+ } | {
1634
+ suffix: number;
1635
+ };
1636
+ /**
1637
+ * A downloaded object: the same metadata {@link StorageObjectHead} carries, plus
1638
+ * the body stream. This is what `download()` resolves to — R2's object, NOT a
1639
+ * bare stream.
1640
+ */
1641
+ interface StorageObjectBody extends StorageObjectHead {
1642
+ /** The object body stream. `null` for a zero-byte object. */
1643
+ body: ReadableStream | null;
1644
+ }
1625
1645
  /**
1626
1646
  * Read-only projection of `Storage` exposed on `QueryCtx` / `MutationCtx`.
1627
1647
  *
@@ -1641,8 +1661,29 @@ interface ReadOnlyStorage<Buckets extends string = string> {
1641
1661
  bucket: (name: Buckets) => ReadOnlyStorage<Buckets>;
1642
1662
  /** The bucket this accessor's operations target (the default for the bare `ctx.storage`). */
1643
1663
  readonly bucketName: string;
1644
- /** Fetch the body of an existing object. Returns `null` when absent. */
1645
- download: (key: string) => Promise<ReadableStream | null>;
1664
+ /**
1665
+ * Fetch an existing object. Returns the R2 object — metadata plus a `body`
1666
+ * stream — or `null` when absent.
1667
+ *
1668
+ * NOT a bare stream: `new Response(await ctx.storage.download(key))` would
1669
+ * stringify the object and serve the literal text `[object Object]`. Reach
1670
+ * for the body explicitly:
1671
+ *
1672
+ * ```ts
1673
+ * const object = await ctx.storage.download(key);
1674
+ *
1675
+ * return object ? new Response(object.body) : new Response("Not found", { status: 404 });
1676
+ * ```
1677
+ *
1678
+ * (`serveStorageObject` from `@lunora/server` does this, plus range/ETag
1679
+ * handling, for the common "serve a stored file over HTTP" case.)
1680
+ *
1681
+ * Pass `range` to have R2 resolve the byte window server-side, so the
1682
+ * unwanted bytes never reach the worker.
1683
+ */
1684
+ download: (key: string, options?: {
1685
+ range?: StorageRange;
1686
+ }) => Promise<StorageObjectBody | null>;
1646
1687
  /**
1647
1688
  * Read a file's metadata (size, content-type, sha256, upload time, custom
1648
1689
  * metadata) without fetching its body. Returns `null` when the object is
@@ -1697,6 +1738,23 @@ interface Storage<Buckets extends string = string> extends ReadOnlyStorage<Bucke
1697
1738
  contentType?: string;
1698
1739
  expiresInSeconds?: number;
1699
1740
  }) => Promise<string>;
1741
+ /**
1742
+ * Mint a native S3 SigV4 URL that hits R2 **directly**, so the bytes never
1743
+ * pass through the Worker — unlike {@link Storage.generateUploadUrl}, whose
1744
+ * signed URL points back at this app so its storage rules still apply.
1745
+ *
1746
+ * Requires `s3` credentials on the `.storage({ s3 })` declaration; without
1747
+ * them the call throws. That is the trade-off: no Worker in the path also
1748
+ * means no rule enforcement in the path.
1749
+ *
1750
+ * Declared structurally rather than imported — `@lunora/server` does not
1751
+ * depend on `@lunora/storage`, and this file mirrors that surface the same
1752
+ * way `head` and `download` do.
1753
+ */
1754
+ getPresignedUrl: (key: string, options?: {
1755
+ expiresInSeconds?: number;
1756
+ method?: "GET" | "PUT";
1757
+ }) => Promise<string>;
1700
1758
  /**
1701
1759
  * Upload `body` to `key` from the server, returning the stored object's key
1702
1760
  * and etag. Mirrors Convex's `storage.store`. Accepts the same guard fields
@@ -2106,9 +2164,10 @@ interface QueryCtx {
2106
2164
  /** Application counters, gauges, and histograms; see {@link LunoraMetrics}. */
2107
2165
  /**
2108
2166
  * Static metadata declared on this procedure with `.meta(...)`, merged
2109
- * across calls. Present so middleware can read the policy it is meant to
2110
- * enforce (`ctx.meta.rateLimit`, …) instead of having it hard-wired at each
2111
- * `.use()` site; absent when the procedure never called `.meta()`.
2167
+ * across calls and deep-frozen. Present so middleware can read the policy it
2168
+ * is meant to enforce (`ctx.meta.rateLimit`, …) instead of having it
2169
+ * hard-wired at each `.use()` site; absent when the procedure never called
2170
+ * `.meta()`.
2112
2171
  */
2113
2172
  readonly meta?: Readonly<Record<string, unknown>>;
2114
2173
  readonly metrics: LunoraMetrics;
@@ -2161,9 +2220,10 @@ interface MutationCtx {
2161
2220
  /** Application counters, gauges, and histograms; see {@link LunoraMetrics}. */
2162
2221
  /**
2163
2222
  * Static metadata declared on this procedure with `.meta(...)`, merged
2164
- * across calls. Present so middleware can read the policy it is meant to
2165
- * enforce (`ctx.meta.rateLimit`, …) instead of having it hard-wired at each
2166
- * `.use()` site; absent when the procedure never called `.meta()`.
2223
+ * across calls and deep-frozen. Present so middleware can read the policy it
2224
+ * is meant to enforce (`ctx.meta.rateLimit`, …) instead of having it
2225
+ * hard-wired at each `.use()` site; absent when the procedure never called
2226
+ * `.meta()`.
2167
2227
  */
2168
2228
  readonly meta?: Readonly<Record<string, unknown>>;
2169
2229
  readonly metrics: LunoraMetrics;
@@ -2234,9 +2294,10 @@ interface ActionCtx {
2234
2294
  /** Application counters, gauges, and histograms; see {@link LunoraMetrics}. */
2235
2295
  /**
2236
2296
  * Static metadata declared on this procedure with `.meta(...)`, merged
2237
- * across calls. Present so middleware can read the policy it is meant to
2238
- * enforce (`ctx.meta.rateLimit`, …) instead of having it hard-wired at each
2239
- * `.use()` site; absent when the procedure never called `.meta()`.
2297
+ * across calls and deep-frozen. Present so middleware can read the policy it
2298
+ * is meant to enforce (`ctx.meta.rateLimit`, …) instead of having it
2299
+ * hard-wired at each `.use()` site; absent when the procedure never called
2300
+ * `.meta()`.
2240
2301
  */
2241
2302
  readonly meta?: Readonly<Record<string, unknown>>;
2242
2303
  readonly metrics: LunoraMetrics;
@@ -2267,4 +2328,4 @@ interface ActionCtx {
2267
2328
  */
2268
2329
  type AnyApi = Record<string, Record<string, RegisteredFunction<ArgsValidator, unknown, FunctionKind>>>;
2269
2330
  declare const anyApi: AnyApi;
2270
- export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelationDefinition, type RestCacheConfig, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectHead, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
2331
+ export { type ActionCtx, type AggregateIndexDefinition, type AggregateOp, type AnyApi, type ArgsValidator, type AuthState, type CachePurge, type DatabaseReader, type DatabaseWriter, type DurableObjectJurisdiction, type DurableStreamOptions, type ExposeConfig, type ExternalSourceCursor, type ExternalSourceDefinition, type ExternalSourceMode, type ExternalSourceRefresh, type FunctionKind, type FunctionVisibility, type GeoBoundingBox, type GeoFilterBuilder, type GeoIndexDefinition, type GeoPointInput, type GlobalBackend, type IndexDefinition, type IndexRangeBuilder, type InferArgs, type LifecycleEvent, type LifecycleEventKind, type LogFields, type LunoraLogMethod, type LunoraLogger, type LunoraMetrics, type LunoraTracer, type LunoraWideEvent, type MutationCtx, type MutationStorage, type OnDeleteAction, type PaginationOptions, type PaginationResult, type QueryCtx, type RankIndexDefinition, type RankSortKey, type ReadOnlyStorage, type RegisteredAction, type RegisteredFunction, type RegisteredLifecycleHook, type RegisteredMutation, type RegisteredQuery, type RegisteredStream, type RelationDefinition, type RestCacheConfig, type RunQueryOptions, type ScheduledFunctionDoc, type ScheduledJob, type Scheduler, type Schema, type SearchFilterBuilder, type SearchIndexDefinition, type SearchLanguage, type SearchStrategy, type Secrets, type SecretsStoreSecretLike, type ShardInitEvent, type ShardMode, type SpanEvaluation, type SpanHandle, type SpanKind, type SpanLink, type SpanOptions, type Storage, type StorageMetadata, type StorageObjectBody, type StorageObjectHead, type StorageRange, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemTableName, type TableDefinition, type TableReader, type TableVectorIndex, type TriggerAggregateOptions, type TriggerBuilder, type TriggerCtx, type TriggerDatabase, type TriggerDefinition, type TriggerDeleteEvent, type TriggerEvent, type TriggerGroupByEntry, type TriggerGroupByOptions, type TriggerHandler, type TriggerInsertEvent, type TriggerOp, type TriggerQueryArgs, type TriggerQueryPage, type TriggerRankOptions, type TriggerRankPageOptions, type TriggerRankResult, type TriggerRow, type TriggerTiming, type TriggerUpdateEvent, type TtlDefinition, type VectorEmbedder, type VectorIndexDefinition, type VectorMatch, type VectorMatches, type VectorMetric, type VectorQueryInput, type VectorRecord, type VectorSearch, type VectorSearchReader, type VectorUpsertInput, type WorkflowCreateOptions, type WorkflowEventDefinition, type WorkflowHandle, type WorkflowInstance, type WorkflowInstanceStatus, type WorkflowStatusResult, type Workflows, type X402ProcedureConfig, anyApi };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/server",
3
- "version": "1.0.0-alpha.94",
3
+ "version": "1.0.0-alpha.95",
4
4
  "description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
5
5
  "keywords": [
6
6
  "backend",
@@ -67,7 +67,7 @@
67
67
  },
68
68
  "dependencies": {
69
69
  "@lunora/errors": "1.0.0-alpha.26",
70
- "@lunora/scheduler": "1.0.0-alpha.44",
70
+ "@lunora/scheduler": "1.0.0-alpha.45",
71
71
  "@lunora/values": "1.0.0-alpha.34",
72
72
  "drizzle-orm": "^0.45.2",
73
73
  "hono": "^4.13.1"
@@ -1 +0,0 @@
1
- import{LunoraError as a}from"@lunora/errors";class u extends a{constructor(r,o,s){super(r,o,{data:s})}}export{u as LunoraError};
@@ -1 +0,0 @@
1
- import{v as t}from"@lunora/values";import{initLunora as M}from"./initLunora-BxNkWYTz.mjs";import{LunoraError as b}from"./LunoraError-DcKdk9Ti.mjs";import{onDisconnect as T}from"./onConnect-BLRoOpv2.mjs";import{g as v,h as A,a as L}from"./plugin-DfuRhJS1.mjs";const D=3e4,g=1024,P=8,p=4096,w="presence",h="present",l=`${w}_${h}`,N=v(w,{tables:{[h]:A({data:t.optional(t.record(t.string(),t.any())),lastSeen:t.number(),roomId:t.string(),sessionId:t.string(),userId:t.optional(t.string())}).index("byRoomSession",["roomId","sessionId"]).index("byRoom",["roomId"]).index("byRoomLastSeen",["roomId","lastSeen"])}}),{mutation:E,query:B}=M.dataModel().create(),G=(u={})=>{const m=u.ttlMs??D,f=Math.max(0,Math.min(u.disconnectGraceMs??0,m)),S=u.maxSessions,y=S!==void 0&&Number.isFinite(S)?Math.max(1,Math.floor(S)):g,_=E.input({data:t.optional(t.record(t.string(),t.any())),roomId:t.string(),sessionId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now(),d=s.auth.userId??void 0;if(o.data!==void 0&&new TextEncoder().encode(JSON.stringify(o.data)).length>p)throw new b("BAD_REQUEST",`presence data exceeds the ${String(p)}-byte limit`);const e=await s.db.query(l).withIndex("byRoomSession",i=>i.eq("roomId",o.roomId).eq("sessionId",o.sessionId)).first();if(e&&(e.userId??void 0)!==d)throw new b("FORBIDDEN","presence heartbeat denied: this (roomId, sessionId) is held by another identity");const a={lastSeen:r,roomId:o.roomId,sessionId:o.sessionId,...o.data===void 0?{}:{data:o.data},...d===void 0?{}:{userId:d}};await(e?s.db.patch(e._id,a):s.db.insert(l,a));const I=r-m-Math.max(f,m),c=(await s.db.query(l).withIndex("byRoomLastSeen",i=>i.eq("roomId",o.roomId)).order("asc").take(P)).filter(i=>i.lastSeen<=I);return await Promise.all(c.map(i=>s.db.delete(i._id))),{lastSeen:r}}),x=B.input({roomId:t.string()}).query(async({args:o,ctx:s})=>{const r=Date.now()-m,e=(await s.db.query(l).withIndex("byRoomLastSeen",n=>n.eq("roomId",o.roomId)).order("desc").take(y)).filter(n=>n.lastSeen>r),a=new Set,I=[];for(const n of e){const c=n.userId;if(c!==void 0){if(a.has(c))continue;a.add(c)}const i={lastSeen:n.lastSeen,roomId:n.roomId};c!==void 0&&(i.userId=c),n.data!==void 0&&(i.data=n.data),I.push(i)}return I}),R={...E.input({roomId:t.string()}).mutation(async({args:o,ctx:s})=>{const r=Date.now()-m,d=await s.db.query(l).withIndex("byRoom",e=>e.eq("roomId",o.roomId)).filter(e=>e.lastSeen<=r).collect();return await Promise.all(d.map(e=>s.db.delete(e._id))),{deleted:d.length}}),visibility:"internal"},q=T(async(o,s)=>{const r=s.context?.roomId,d=s.context?.sessionId;if(typeof r!="string"||typeof d!="string")return;const e=await o.db.query(l).withIndex("byRoomSession",n=>n.eq("roomId",r).eq("sessionId",d)).first();if(!e)return;const a=s.userId??void 0;if((e.userId??void 0)!==a)return;if(f===0){await o.db.delete(e._id);return}const I=Math.min(e.lastSeen,Date.now()+f-m);await o.db.patch(e._id,{lastSeen:I})});return L(w,{extension:N,functions:{disconnect:q,heartbeat:_,listPresent:x,sweep:R}})};export{D as PRESENCE_DEFAULT_TTL_MS,l as PRESENCE_TABLE,G as definePresence,N as presenceExtension};
@@ -1 +0,0 @@
1
- import{ValidationError as o}from"@lunora/values";import{LunoraError as a}from"./LunoraError-DcKdk9Ti.mjs";const p=(t,e)=>{try{return t.parse(e,{rejectUnknownKeys:!0})}catch(r){throw r instanceof o?new a("INTERNAL_SERVER_ERROR",`Response did not match the declared output schema: ${r.message}`):r}};export{p as a};
@@ -1 +0,0 @@
1
- const r=Symbol.for("lunora.mask.middleware-columns"),f=(t,e)=>(Object.defineProperty(t,r,{configurable:!0,enumerable:!1,value:e}),t),l=t=>{if(!(t===null||typeof t!="function"&&typeof t!="object"))return t[r]},b=t=>{const e=new Map;for(const c of t){const o=c?.maskedTables;if(o)for(const[n,a]of o){const s=e.get(n)??new Set;for(const u of a)s.add(u);e.set(n,s)}}return e};export{b as buildMaskRegistry,l as readMaskTag,f as tagMaskMiddleware};
@@ -1 +0,0 @@
1
- import{i as d,c as f,d as h}from"./middleware-EloVU9X1.mjs";import{r as p}from"./policy-tag-D4RzgQnw.mjs";import{deny as g}from"./allowAll-DkRAgItV.mjs";const c=g(),u=s=>{const e=s?.rls?.tags;if(e)return e;const t=p(s);return t?[t]:[]},b=(s,e)=>{const t=d(e.roles),n=new Map,r=new Map;for(const o of e.policies){if(o.on!=="read")continue;const a=n.get(o.table)??new Set;if(a.has(o.when))continue;a.add(o.when),n.set(o.table,a);const i=r.get(o.table)??[];i.push(o),r.set(o.table,i)}for(const[o,a]of r){const i=s.get(o)??[];i.push({policies:a,rolePermissions:t}),s.set(o,i)}},l=s=>{const e=s.OR;return Array.isArray(e)&&e.length===0&&Object.keys(s).length===1},y=(s,e)=>!s||Object.keys(s).length===0?e:l(s)||Object.keys(e).length===0?s:{AND:[s,e]},R=(s,e)=>f(s.policies,{auth:{can:h(e.roles,s.rolePermissions),identity:e.identity,roles:e.roles,userId:e.userId},ctx:e.ctx}),m=(s,e)=>{const t=s.byTable.get(e.table);if(!t||t.length===0)return e.rlsRequired&&!e.tablePublic?c:void 0;const n=[];for(const r of t){const o=R(r,e);if(o===void 0)return;l(o)||n.push(o)}return n.length===0?c:n.length===1?n[0]:{OR:n}},P=s=>{const e=new Map,t=new Set;for(const n of s)for(const r of u(n))t.has(r)||(t.add(r),b(e,r));return{byTable:e}},W=(s,e)=>y(m(s,e),e.shapeWhere);export{P as buildRlsReadRegistry,W as composeShapeReadWhere};
@@ -1 +0,0 @@
1
- import"./run-middleware-B-JeGGp9.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-DfuRhJS1.mjs";export{i as composePluginMiddleware,s as defineComponent,o as definePlugin,m as defineSchemaExtension,l as installPlugins,t as mergeSchemaExtension};
@@ -1 +0,0 @@
1
- import{LunoraError as s}from"@lunora/errors";const a=e=>({on:e.on,table:e.table,when:e.when}),c=()=>e=>({on:e.on,table:e.table,when:e.when}),l=(e,n={})=>({name:e,...n}),d=e=>{const n=new Map;for(const o of e){const r=JSON.stringify([o.table,o.on]),t=n.get(r)??new Set;if(t.has(o.when))throw new s("INTERNAL",`definePolicies: duplicate policy for (table "${o.table}", on "${o.on}") — the same decision function is registered more than once. Multiple distinct policies per (table, on) are allowed (reads OR, writes AND); remove the duplicate.`);t.add(o.when),n.set(r,t)}return e},h=(e,n={})=>({name:e,...n});export{c as createPolicyDsl,l as definePermission,d as definePolicies,a as definePolicy,h as defineRole};
@@ -1 +0,0 @@
1
- import{LunoraError as o}from"@lunora/errors";const t=r=>{if(r.id.trim()==="")throw new o("INTERNAL","defineMigration: `id` must be a non-empty string");return{__lunoraMigration:!0,...r}};export{t as defineMigration};
@@ -1 +0,0 @@
1
- import{LunoraError as i}from"@lunora/errors";const c=r=>({bucket:r.bucket,on:r.on,prefix:r.prefix,when:r.when}),f=r=>{const o=new Map;for(const e of r){const t=JSON.stringify([e.bucket,e.on,e.prefix]),n=o.get(t)??new Set;if(n.has(e.when))throw new i("INTERNAL",`defineStorageRules: duplicate rule for (bucket "${e.bucket}", on "${e.on}"${e.prefix===void 0?"":`, prefix "${e.prefix}"`}) — the same decision function is registered more than once. Multiple distinct rules per (bucket, on) are allowed (they OR); remove the duplicate.`);n.add(e.when),o.set(t,n)}return r};export{c as defineStorageRule,f as defineStorageRules};
@@ -1,5 +0,0 @@
1
- import{toErrorBody as S}from"@lunora/errors";import{parseValidatorMap as R,ValidationError as A}from"@lunora/values";import{Hono as x}from"hono";import{a as q}from"./apply-output-D7vpBeeu.mjs";import{LunoraError as g}from"./LunoraError-DcKdk9Ti.mjs";const G=e=>async t=>e(t.get("lunora"),t.req.raw),J=()=>{const e=new x;return e.use("*",async(t,r)=>{const n=t.env.__lunoraCtx;if(!n)throw new g("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");t.set("lunora",n),await r()}),e},k=e=>e.kind==="optional"?e._meta?.inner??e:e,y=(e,t)=>{switch(e){case"bigint":try{return BigInt(t)}catch{return t}case"boolean":return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:t;case"number":return t===""?Number.NaN:Number(t);default:return t}},C=(e,t,r)=>{const n=k(e);if(n.kind==="array"){const o=t.req.queries(r);if(o===void 0)return;const s=n._meta?.inner;return o.map(c=>y(s?.kind??"string",c))}const a=t.req.query(r);return a===void 0?void 0:y(n.kind,a)},v=(e,t)=>{const r={};for(const n of Object.keys(e)){const a=e[n];a&&(r[n]=C(a,t,n))}return R(e,r,"searchParams")},N=(e,t)=>{const r=t.req.param(),n={};for(const a of Object.keys(e)){const o=e[a];if(!o)continue;const s=r[a];n[a]=s===void 0?void 0:y(k(o).kind,s)}return R(e,n,"params")},H=async(e,t)=>{let r;try{r=await t.req.json()}catch{throw new g("BAD_REQUEST","Invalid JSON body")}if(typeof r!="object"||r===null||Array.isArray(r))throw new g("BAD_REQUEST","Expected a JSON object body");return R(e,r,"body")},O=e=>{if(e instanceof A)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(e instanceof g){const{body:t,redacted:r,status:n}=S(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return r&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:t.code,error:t.message},{status:n})}throw e},B=(e,t)=>async r=>{try{const n=r.get("lunora"),a=Object.keys(e.searchParams).length>0?v(e.searchParams,r):{},o=Object.keys(e.params).length>0?N(e.params,r):{},s=Object.keys(e.body).length>0?await H(e.body,r):{},c=await t({body:s,ctx:n,params:o,searchParams:a}),u=e.output?q(e.output,c):c,i={};e.cacheControl&&(i["cache-control"]=e.cacheControl),e.cacheTag&&(i["cache-tag"]=e.cacheTag),e.vary&&(i.vary=e.vary);const h=Object.keys(i).length>0;return u===void 0?new Response(null,{headers:h?i:void 0,status:204}):Response.json(u,{headers:h?i:void 0})}catch(n){return O(n)}},E={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},b=(e,t)=>{const r=JSON.stringify(e);return`${t?`event: ${t}
2
- `:""}data: ${r}
3
-
4
- `},$=(e,t)=>(async r=>{let n,a;try{n=Object.keys(e.searchParams).length>0?v(e.searchParams,r):{},a=Object.keys(e.params).length>0?N(e.params,r):{}}catch(p){return O(p)}const o=r.get("lunora"),s=r.req.raw,c=new TextEncoder,u=new AbortController;if(s.signal.aborted)return u.abort(),new Response("",{headers:E});const i=()=>{u.abort()};s.signal.addEventListener("abort",i,{once:!0});const h=new ReadableStream({cancel(){s.signal.removeEventListener("abort",i),u.abort()},async start(p){try{const f=t({ctx:o,params:a,request:s,searchParams:n,signal:u.signal});for await(const m of f){if(u.signal.aborted)break;p.enqueue(c.encode(b(m)))}p.enqueue(c.encode(b({},"complete")))}catch(f){const{body:m,redacted:_}=S(f,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});_&&console.error("[lunora] unhandled stream handler error:",f),p.enqueue(c.encode(b({code:m.code,message:m.message},"error")))}finally{s.signal.removeEventListener("abort",i),p.close()}}});return new Response(h,{headers:E})}),d=e=>({body:t=>d({...e,body:{...e.body,...t}}),cacheControl:t=>d({...e,cacheControl:t}),cacheTag:t=>d({...e,cacheTag:t}),handler:t=>B(e,t),output:t=>d({...e,output:t}),params:t=>d({...e,params:{...e.params,...t}}),searchParams:t=>d({...e,searchParams:{...e.searchParams,...t}}),stream:t=>$(e,t),vary:t=>d({...e,vary:t})}),l=e=>t=>d({body:{},method:e,params:{},path:t,searchParams:{}}),Q={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")},I=/^bytes=(\d*)-(\d*)$/,T=e=>e.startsWith('"')||e.startsWith('W/"')?e:`"${e}"`,L=e=>!(e.includes("\r")||e.includes(`
5
- `)||e.includes("\0")),j=(e,t)=>{if(e===null)return{kind:"full"};const r=I.exec(e.trim());if(!r)return{kind:"full"};const n=r[1]??"",a=r[2]??"";if(n===""&&a==="")return{kind:"full"};let o,s;if(n===""){const c=Number(a);if(c===0)return{kind:"unsatisfiable"};o=Math.max(0,t-c),s=t-1}else o=Number(n),s=a===""?t-1:Math.min(Number(a),t-1);return o>s||o>=t?{kind:"unsatisfiable"}:{end:s,kind:"partial",start:o}},P=e=>{const t=e.httpMetadata?.contentType,r={"accept-ranges":"bytes","content-type":t!==void 0&&L(t)?t:"application/octet-stream",etag:T(e.etag)};return e.sha256Base64!==void 0&&(r["repr-digest"]=`sha-256=:${e.sha256Base64}:`),r},D=e=>j(e,0).kind==="full",w=async(e,t)=>{const r=await e.storage.download(t);return r?new Response(r.body,{headers:{...P(r),"content-length":String(r.size)},status:200}):new Response("Not Found",{status:404})},Y=async(e,t,r)=>{const n=r.headers.get("range");if(D(n))return w(e,t);const a=await e.storage.head(t);if(!a)return new Response("Not Found",{status:404});const o=j(n,a.size);if(o.kind==="unsatisfiable")return new Response("Range Not Satisfiable",{headers:{"accept-ranges":"bytes","content-range":`bytes */${String(a.size)}`,"content-type":"text/plain; charset=utf-8",etag:T(a.etag)},status:416});if(o.kind==="full")return w(e,t);const s=o.end-o.start+1,c=await e.storage.download(t,{range:{length:s,offset:o.start}});return c?new Response(c.body,{headers:{...P(a),"content-length":String(s),"content-range":`bytes ${String(o.start)}-${String(o.end)}/${String(a.size)}`},status:206}):new Response("Not Found",{status:404})};export{G as httpAction,Q as httpRoute,J as httpRouter,L as isSafeHeaderValue,Y as serveStorageObject};
@@ -1 +0,0 @@
1
- import{a as M}from"./apply-output-D7vpBeeu.mjs";import{v as f}from"./functions-B2-H4PQT.mjs";import{readMaskTag as h}from"./buildMaskRegistry-72SL8fJn.mjs";import{r as j}from"./policy-tag-D4RzgQnw.mjs";import{r as O}from"./run-middleware-B-JeGGp9.mjs";const x=(e,r)=>r===void 0||typeof e!="object"||e===null?e:Object.assign(Object.create(Object.getPrototypeOf(e)),e,{meta:r}),i=(e,r)=>O(e,r,o=>o),_=(e,r,o,a,n)=>async(s,u)=>{const t=f(e,u),l=await i(r,x(s,n)),c=await o({args:t,ctx:l});return a?M(a,c):c},q=(e,r,o,a)=>(n,s,u)=>{const t=f(e,s);return(async function*(){const c=await i(r,x(n,a)),m=o({args:t,ctx:c,signal:u})[Symbol.asyncIterator]();try{for(;;){if(u.aborted)return;const p=await m.next();if(p.done||u.aborted)return;yield p.value}}finally{await m.return?.()}})()},w=e=>{const r=e.map(o=>j(o)).filter(o=>o!==void 0);return r.length>0?{tags:r}:void 0},g=e=>{const r=new Map;for(const o of e){const a=h(o);if(a)for(const[n,s]of a.columns){const u=r.get(n)??new Set;for(const t of s)u.add(t);r.set(n,u)}}return r.size>0?r:void 0},d=(e,r,o)=>({__lunoraProcedure:e,...o?{__lunoraVisibility:o}:{},input:a=>d(e,{...r,args:{...r.args,...a}},o),[e]:a=>{const n=w(r.middlewares),s=g(r.middlewares);return{args:r.args,...r.expose?{expose:r.expose}:{},handler:_(r.args,r.middlewares,a,r.output,r.meta),kind:e,...s?{maskedTables:s}:{},...r.meta?{meta:r.meta}:{},...n?{rls:n}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}},meta:a=>d(e,{...r,meta:Object.freeze({...r.meta,...a})},o),output:a=>d(e,{...r,output:a},o),...e==="query"?{stream:(a,n)=>{const s=w(r.middlewares),u=g(r.middlewares),t=n?.durable===!0?{}:n?.durable;return{args:r.args,...t?{durable:t}:{},...r.expose?{expose:r.expose}:{},handler:q(r.args,r.middlewares,a,r.meta),kind:"stream",...u?{maskedTables:u}:{},...r.meta?{meta:r.meta}:{},...s?{rls:s}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}}}:{},use:a=>d(e,{...r,middlewares:[...r.middlewares,a]},o),...o?{}:{expose:a=>d(e,{...r,expose:a},o)},...o?{}:{x402:a=>d(e,{...r,x402:a},o)}}),A={dataModel:()=>({create:e=>({action:d("action",{args:{},middlewares:[]}),internalAction:d("action",{args:{},middlewares:[]},"internal"),internalMutation:d("mutation",{args:{},middlewares:[]},"internal"),internalQuery:d("query",{args:{},middlewares:[]},"internal"),mutation:d("mutation",{args:{},middlewares:[]}),query:d("query",{args:{},middlewares:[]})})})};export{A as initLunora};