@lunora/server 1.0.0-alpha.28 → 1.0.0-alpha.281

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 (104) hide show
  1. package/LICENSE.md +414 -104
  2. package/README.md +21 -15
  3. package/dist/data-model.d.mts +323 -78
  4. package/dist/data-model.d.ts +323 -78
  5. package/dist/data-model.mjs +0 -1
  6. package/dist/drizzle.mjs +1 -1
  7. package/dist/in-process.d.mts +115 -0
  8. package/dist/in-process.d.ts +115 -0
  9. package/dist/in-process.mjs +1 -0
  10. package/dist/index.d.mts +3593 -1124
  11. package/dist/index.d.ts +3593 -1124
  12. package/dist/index.mjs +1 -29
  13. package/dist/otel.d.mts +597 -0
  14. package/dist/otel.d.ts +597 -0
  15. package/dist/otel.mjs +1 -0
  16. package/dist/packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-Dv4DKrj0.mjs +1 -0
  17. package/dist/packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs +1 -0
  18. package/dist/packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-BCa6sLSJ.mjs +1 -0
  19. package/dist/packem_shared/LunoraEnvError-06_Zc4yc.mjs +3 -0
  20. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-aj9Ec70J.mjs +1 -0
  21. package/dist/packem_shared/PROCEDURE_META-DVzrXpfa.mjs +1 -0
  22. package/dist/packem_shared/allowAll-DkRAgItV.mjs +1 -0
  23. package/dist/packem_shared/apply-output-C5wZ5EAL.mjs +1 -0
  24. package/dist/packem_shared/asBucketStorage-DoGYOjq3.mjs +1 -0
  25. package/dist/packem_shared/assertShapesDeclareReadPolicies-C09SMvM4.mjs +1 -0
  26. package/dist/packem_shared/authorize-CVLZJxf_.mjs +1 -0
  27. package/dist/packem_shared/beginDeferredDeletes-DhwFBbvs.mjs +1 -0
  28. package/dist/packem_shared/beginDeferredSchedules-BTwq-NUO.mjs +1 -0
  29. package/dist/packem_shared/bindOrm-D5mVDvbi.mjs +1 -0
  30. package/dist/packem_shared/buildMaskRegistry-DpWMtalG.mjs +1 -0
  31. package/dist/packem_shared/compose-middleware-BK9FlblN.mjs +1 -0
  32. package/dist/packem_shared/composePluginMiddleware-3e7F9JIa.mjs +1 -0
  33. package/dist/packem_shared/context-identity-B2XYGA0B.mjs +1 -0
  34. package/dist/packem_shared/createPolicyDsl-BZa6SqLJ.mjs +1 -0
  35. package/dist/packem_shared/createSecrets-D6rLB42U.mjs +1 -0
  36. package/dist/packem_shared/createServices-IJvoqi0e.mjs +1 -0
  37. package/dist/packem_shared/defineAggregateIndex-C3xWV-Dr.mjs +1 -0
  38. package/dist/packem_shared/defineIdentity-DwkNKwYa.mjs +1 -0
  39. package/dist/packem_shared/defineIdentityGuard-Bt8N65Zs.mjs +1 -0
  40. package/dist/packem_shared/defineLiveStream-q9yO3wl6.mjs +1 -0
  41. package/dist/packem_shared/defineMigration-CXOS0Bvq.mjs +1 -0
  42. package/dist/packem_shared/defineModule-OecXWM3U.mjs +1 -0
  43. package/dist/packem_shared/defineMutator-DlLFSWbO.mjs +1 -0
  44. package/dist/packem_shared/defineRoom-CoGi-xwm.mjs +1 -0
  45. package/dist/packem_shared/defineShape-H-0IbZlb.mjs +1 -0
  46. package/dist/packem_shared/defineStorageRule-Dv4nJE0H.mjs +1 -0
  47. package/dist/packem_shared/defineWebSocket-BHoy6_ox.mjs +1 -0
  48. package/dist/packem_shared/fnv1a-D3ueNTWB.mjs +1 -0
  49. package/dist/packem_shared/functions-QFoBUe9t.mjs +1 -0
  50. package/dist/packem_shared/httpAction-Bfw3qwLG.mjs +1 -0
  51. package/dist/packem_shared/initLunora-DcvCGLL_.mjs +1 -0
  52. package/dist/packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs +1 -0
  53. package/dist/packem_shared/isSafeHeaderValue-DswDADFy.mjs +6 -0
  54. package/dist/packem_shared/mask-DHJtsP7t.mjs +1 -0
  55. package/dist/packem_shared/middleware-CHYtnvZP.mjs +1 -0
  56. package/dist/packem_shared/onConnect-BLRoOpv2.mjs +1 -0
  57. package/dist/packem_shared/onQueryChange-iuLzmyPs.mjs +1 -0
  58. package/dist/packem_shared/onWhisper-CfDbFLQh.mjs +1 -0
  59. package/dist/packem_shared/platformAdmin-kczXQme8.mjs +1 -0
  60. package/dist/packem_shared/plugin-CyLqvCB9.mjs +1 -0
  61. package/dist/packem_shared/policy-tag-V0lqFzgS.mjs +1 -0
  62. package/dist/packem_shared/protectPublic-Bi5_95aP.mjs +1 -0
  63. package/dist/packem_shared/redact-secrets-BpatNz48.mjs +2 -0
  64. package/dist/packem_shared/redactSecrets-Dmh9pHZu.mjs +1 -0
  65. package/dist/packem_shared/rls-CvWnjgtq.mjs +1 -0
  66. package/dist/packem_shared/run-middleware-BefYq7Xd.mjs +1 -0
  67. package/dist/packem_shared/serveStorageObject-CLz3qhNI.mjs +1 -0
  68. package/dist/packem_shared/storageRules-BVIXkoRg.mjs +1 -0
  69. package/dist/packem_shared/{types.d-C4CMJK8x.d.mts → types.d-B7FLdYUD.d.mts} +15 -8
  70. package/dist/packem_shared/{types.d-DdYF8E18.d.ts → types.d-BCtjbIzl.d.ts} +15 -8
  71. package/dist/packem_shared/types.d-CJnJltzy.d.mts +3025 -0
  72. package/dist/packem_shared/types.d-CJnJltzy.d.ts +3025 -0
  73. package/dist/rls/testing.d.mts +13 -5
  74. package/dist/rls/testing.d.ts +13 -5
  75. package/dist/rls/testing.mjs +1 -49
  76. package/dist/types.d.mts +2 -1373
  77. package/dist/types.d.ts +2 -1373
  78. package/dist/types.mjs +0 -31
  79. package/package.json +28 -8
  80. package/dist/packem_shared/LunoraEnvError-BGmd1Qs0.mjs +0 -187
  81. package/dist/packem_shared/LunoraError-WbxmrpxR.mjs +0 -9
  82. package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-Cv1UPaJj.mjs +0 -114
  83. package/dist/packem_shared/asBucketStorage-Cnxd9y2q.mjs +0 -11
  84. package/dist/packem_shared/bindOrm-Bfgl7f-Q.mjs +0 -146
  85. package/dist/packem_shared/buildRlsReadRegistry-D54vUQe4.mjs +0 -107
  86. package/dist/packem_shared/composePluginMiddleware-z62dttBo.mjs +0 -103
  87. package/dist/packem_shared/createPolicyDsl-By3QB4he.mjs +0 -32
  88. package/dist/packem_shared/createSecrets-DwaR2rNG.mjs +0 -58
  89. package/dist/packem_shared/defineAggregateIndex-DTULzh09.mjs +0 -333
  90. package/dist/packem_shared/defineIdentity-DiX4zM9x.mjs +0 -35
  91. package/dist/packem_shared/defineMigration-Hx01yIht.mjs +0 -10
  92. package/dist/packem_shared/defineMutator-EIXAWhs9.mjs +0 -11
  93. package/dist/packem_shared/defineShape-C5scNOrf.mjs +0 -18
  94. package/dist/packem_shared/defineStorageRule-B5nL4Z1P.mjs +0 -23
  95. package/dist/packem_shared/functions-Di9FUNkf.mjs +0 -5
  96. package/dist/packem_shared/httpAction-DCXoYPIk.mjs +0 -355
  97. package/dist/packem_shared/initLunora-CmMVk4i7.mjs +0 -107
  98. package/dist/packem_shared/mask-CZuu9WAF.mjs +0 -331
  99. package/dist/packem_shared/onConnect-CIPXKPyw.mjs +0 -13
  100. package/dist/packem_shared/policy-tag-DvpVH2tv.mjs +0 -13
  101. package/dist/packem_shared/protectPublic-BlcGpiRc.mjs +0 -15
  102. package/dist/packem_shared/rls-B_ZWgslr.mjs +0 -595
  103. package/dist/packem_shared/run-middleware-I6EiQfxL.mjs +0 -20
  104. package/dist/packem_shared/storageRules-6QxzDOcx.mjs +0 -88
@@ -0,0 +1 @@
1
+ import{LunoraError as i}from"@lunora/errors";const n=r=>async({ctx:o,next:e})=>{if(!await r(o))throw new i("FORBIDDEN","Permission required");return e()};export{n as authorize};
@@ -0,0 +1 @@
1
+ const c=new WeakMap,u=s=>{let e=s;for(;e!==void 0&&!e.open;)e=e.parent;return e},f=s=>{const e={flushable:[],innermost:void 0},t=n=>{const o=n??{},r={...o,deleteAfterCommit:i=>{(e.innermost?.pending??e.flushable).push({key:i,storage:o})}};return Object.setPrototypeOf(r,Object.getPrototypeOf(o)),typeof o.bucket=="function"&&(r.bucket=i=>t(o.bucket?.(i))),c.set(r,e),r};return t(s)},d=s=>{const{storage:e}=s??{},t=typeof e=="object"&&e!==null?c.get(e):void 0;if(!t)return()=>{};const n={open:!0,parent:t.innermost,pending:[]};return t.innermost=n,o=>{n.open=!1,t.innermost===n&&(t.innermost=u(n.parent));const r=n.pending.splice(0);!o||r.length===0||(u(n.parent)?.pending??t.flushable).push(...r)}},p=async s=>{const{log:e,storage:t}=s??{},n=typeof t=="object"&&t!==null?c.get(t):void 0;if(!n||n.flushable.length===0)return{attempted:0,failures:[]};const o=n.flushable.splice(0),i=(await Promise.allSettled(o.map(async({key:a,storage:l})=>{if(typeof l.delete!="function")throw new TypeError("ctx.storage: no storage configured, so the object was not deleted");await l.delete(a)}))).flatMap((a,l)=>a.status==="rejected"?[{error:a.reason,key:o[l]?.key??""}]:[]);for(const a of i)e?.warn("ctx.storage.deleteAfterCommit: delete failed, object leaked",{error:String(a.error),key:a.key});return{attempted:o.length,failures:i}};export{d as beginDeferredDeletes,p as flushDeferredDeletes,f as withDeferredDeletes};
@@ -0,0 +1 @@
1
+ import{assertScheduleInstant as x,assertScheduleDelay as D,resolveScheduleId as O,assertDedupKey as S}from"@lunora/scheduler";import{encodeArgsOrThrow as $}from"@lunora/wire";const A=new WeakMap,m=o=>{if(typeof o=="string")return o;const n=o??{},e=n.__lunoraRef??n.binding;return typeof e=="string"?e:"<unknown>"},b=o=>{let n=o;for(;n!==void 0&&!n.open;)n=n.parent;return n},j=(o,n,e)=>o==="runAfter"?Math.max(n,e-Date.now()):Math.max(n,e),k=async(o,{id:n,run:e,token:r})=>{if(o?.handOff!==void 0){await o.handOff(n,e,r);return}await e(),o?.forget(n)},K=(o,n)=>{const e=o,r={decisions:new Map,innermost:void 0,outbox:n},l=(t,i,s,c,u)=>e[t].call(e,i,s,c,u),d=(t,i,s,c,u)=>{const h=m(s);r.decisions.has(h)||r.decisions.set(h,r.outbox?.admit(h));const g=r.decisions.get(h),p=g===void 0?i:j(t,i,g),w=r.innermost;if(w===void 0)return l(t,p,s,c,u);const a=O(u?.id),y={...u,dedupKey:S(u?.dedupKey)??`${a}-${crypto.randomUUID().replaceAll("-","")}`},v=r.outbox?.record(a,{args:$(`ctx.scheduler.${t}`,m(s),c),options:y,target:s,when:Math.ceil(t==="runAfter"?Date.now()+p:p)});return w.pending.push({id:a,run:async()=>l(t,p,s,c,{...y,id:a}),token:v}),Promise.resolve(a)},f={...e,runAfter:(t,i,s,c)=>(D(t,"ctx.scheduler.runAfter"),d("runAfter",t,i,s,c)),runAt:(t,i,s,c)=>(x(t,Date.now(),"ctx.scheduler.runAt"),d("runAt",t,i,s,c))};return Object.setPrototypeOf(f,Object.getPrototypeOf(e)),A.set(f,r),f},M=o=>{const{scheduler:n}=o,e=typeof n=="object"&&n!==null?A.get(n):void 0;if(!e)return async()=>{};const r={open:!0,parent:e.innermost,pending:[]};return e.innermost=r,async l=>{if(!r.open)return;r.open=!1,e.innermost===r&&(e.innermost=b(r.parent));const d=r.pending.splice(0);if(d.length===0)return;if(!l){for(const{id:c}of d)e.outbox?.forget(c);return}const f=b(r.parent);if(f!==void 0){f.pending.push(...d);return}const t=[];for(const c of d)try{await k(e.outbox,c)}catch(u){t.push(u)}const[i,...s]=t;if(i!==void 0)throw e.outbox?.wake(),s.length===0?i:new AggregateError(t,`ctx.scheduler: ${String(t.length)} of ${String(d.length)} deferred jobs failed to reach the scheduler after the commit`)}};export{M as beginDeferredSchedules,K as withDeferredSchedules};
@@ -0,0 +1 @@
1
+ import{LunoraError as p}from"@lunora/errors";import{isPlainObject as x}from"@lunora/wire";const M=new Set(["connect","disconnect","set"]),y=500,I=(t,n,s)=>t!==void 0&&Object.hasOwn(t,n)&&x(s),v=t=>typeof t=="object"&&t!==null&&t.code==="CONFLICT"&&t.kind==="unique",u=(t,n)=>{throw new p(t,n)},R=(t,n)=>{if(!Array.isArray(t)||t.some(e=>typeof e!="string"))return u("VALIDATION_ERROR",`${n} must be an array of ids`);const s=[...new Set(t)];return s.length>y&&u("VALIDATION_ERROR",`${n} names ${String(s.length)} rows; at most ${String(y)} per list`),s},E=(t,n,s)=>{n.nullable||u("VALIDATION_ERROR",`${t}.${s}: "${n.field}" cannot be empty; make it optional or nullable to allow it`)},D=(t,n,s)=>{const{connect:e,disconnect:i,set:c}=s;return c!==void 0&&u("VALIDATION_ERROR",`${t} is a to-one relation: use connect or disconnect, not set`),e!==void 0&&i!==void 0&&u("VALIDATION_ERROR",`${t}: connect and disconnect together are ambiguous`),e!==void 0?(typeof e!="string"&&u("VALIDATION_ERROR",`${t}.connect must be an id`),{connect:e,info:n,name:t}):(i!==!0&&u("VALIDATION_ERROR",`${t}.disconnect must be true`),E(t,n,"disconnect"),{info:n,name:t})},A=(t,n,s)=>{n.through===void 0&&E(t,n,s)},j=(t,n,s)=>{const{connect:e,disconnect:i,set:c}=s;if(c!==void 0)return(e!==void 0||i!==void 0)&&u("VALIDATION_ERROR",`${t}: set replaces the whole list and cannot be combined with connect or disconnect`),A(t,n,"set"),{attach:[],info:n,name:t,release:[],replace:R(c,`${t}.set`)};i!==void 0&&A(t,n,"disconnect");const a=e===void 0?[]:R(e,`${t}.connect`),r=i===void 0?[]:R(i,`${t}.disconnect`),o=a.find(d=>r.includes(d));return o!==void 0&&u("VALIDATION_ERROR",`${t}: "${o}" is in both connect and disconnect, which is ambiguous`),{attach:a,info:n,name:t,release:r}},k=(t,n,s,e)=>{const i=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0)),c=Object.keys(i).find(r=>!M.has(r));if(c!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}: "${n}.${c}" is not a relation operator; use connect, disconnect or set`),Object.keys(i).length===0)return;const a=s.refusal??s.refusalNow?.();return a!==void 0&&u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" cannot be written: ${a}`),s.colocated||u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" crosses to "${s.table}" on another shard or backend, so a nested write cannot be applied atomically; write each side yourself`),s.kind==="one"?D(n,s,i):j(n,s,i)},P=t=>t.info.kind==="one",T=(t,n,s)=>{if(n===void 0)return{columns:s,manys:[],ones:[]};const e={},i=[],c=[];for(const[a,r]of Object.entries(s)){if(!I(n,a,r)){e[a]=r;continue}const o=k(t,a,n[a],r);o!==void 0&&(P(o)?c.push(o):i.push(o))}for(const{info:a,name:r}of c)Object.hasOwn(e,a.field)&&u("VALIDATION_ERROR",`ctx.db.${t}: ${r} and its key "${a.field}" are both set; set one or the other`);return{columns:e,manys:i,ones:c}},w=(t,n,s,e)=>{const i=Object.entries(s).find(([c,a])=>I(n,c,a))?.[0];i!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}.${e}: "${i}" is a relation write, which ${e} does not support; use insert or patch`)},O=async(t,n,s,e,i)=>{const c=await t.get(e,i);return c===null&&u("NOT_FOUND",`${n}.${s}: no "${e}" row with id "${i}"`),c},b=async(t,n)=>{const s={...n.columns};for(const{connect:e,info:i,name:c}of n.ones){let a=null;e!==void 0&&(a=(await O(t,c,"connect",i.table,e))[i.references]),s[i.field]=a}return s},W=async(t,{info:n,name:s},e,i)=>{(await O(t,s,"connect",n.table,e))[n.field]!==i&&await t.patch(n.table,e,{[n.field]:i})},F=async(t,{info:n},s,e)=>{s[n.field]===e&&await t.patch(n.table,String(s._id),{[n.field]:null})},U=async(t,{info:n,name:s},e)=>{const{page:i}=await t.findMany(n.table,{limit:y+1,where:{[n.field]:e}});return i.length>y&&u("VALIDATION_ERROR",`${s}.set: the relation already holds more than ${String(y)} rows; disconnect in batches first`),i},L=(t,n)=>{const s=new Set(t),e=new Set(n);return{attach:n.filter(i=>!s.has(i)),release:new Set(t.filter(i=>!e.has(i)))}},$=async(t,{name:n},{from:s,table:e,to:i},c,a)=>{const r=a===void 0?{[s]:c}:{[s]:c,[i]:{in:a}},{page:o}=await t.findMany(e,{limit:y+1,where:r});return o.length>y&&u("VALIDATION_ERROR",`${n}: the relation already holds more than ${String(y)} rows; disconnect in batches first`),o},V=async(t,n,s)=>{if(s.length===0)return new Set;const{page:e}=await t.findMany(n,{limit:s.length,where:{_id:{in:s}}});return new Set(e.map(i=>String(i._id)))},C=async(t,n,s)=>{const{info:e,name:i}=n,{from:c,table:a,to:r}=e.through;let o,d;if(n.replace===void 0){await Promise.all(n.release.map(l=>O(t,i,"disconnect",e.table,l))),d=n.release.length===0?[]:await $(t,n,e.through,s,n.release);const h=n.attach.length===0?[]:await $(t,n,e.through,s,n.attach),f=new Set(h.map(l=>String(l[r])));o=n.attach.filter(l=>!f.has(l))}else{const h=await $(t,n,e.through,s,void 0),f=L(h.map(g=>String(g[r])),n.replace),l=await V(t,e.table,[...f.release]);({attach:o}=f),d=h.filter(g=>f.release.has(String(g[r]))&&l.has(String(g[r])))}await Promise.all(o.map(h=>O(t,i,"connect",e.table,h)));for(const h of d)await t.delete(a,String(h._id));for(const h of o)try{await t.insert(a,{[c]:s,[r]:h})}catch(f){if(!v(f)||!e.pairIsOnlyUnique)throw f}},q=async(t,n,s)=>{let{attach:e}=n,i;if(n.replace===void 0)i=await Promise.all(n.release.map(c=>O(t,n.name,"disconnect",n.info.table,c)));else{const c=await U(t,n,s),a=L(c.map(r=>String(r._id)),n.replace);({attach:e}=a),i=c.filter(r=>a.release.has(String(r._id)))}for(const c of i)await F(t,n,c,s);for(const c of e)await W(t,n,c,s)},_=async(t,n,s,e)=>{for(const i of s.manys){const{info:c}=i,a=c.through===void 0?c.references:"_id",r=await e(a);if(r==null&&u("VALIDATION_ERROR",`ctx.db.${n}: ${i.name} is keyed on "${a}", which this row has no value for`),c.through!==void 0){await C(t,{...i,info:c},r);continue}await q(t,{...i,info:c},r)}},S=(t,n,s,e)=>async i=>i==="_id"?s:Object.hasOwn(e,i)?e[i]:(await t.get(n,s))?.[i],B=async(t,n,s,e,i)=>{const c=T(n,s,e);if(c.ones.length===0&&c.manys.length===0)return i(c.columns);const a=await b(t,c),r=await i(a);return r!==null&&await _(t,n,c,S(t,n,r,a)),r},G=async(t,n,s,e,i)=>{const c=T(n,s,i);if(c.ones.length===0&&c.manys.length===0){await t.patch(n,e,c.columns);return}const a=await b(t,c);if(Object.keys(a).length>0)await t.patch(n,e,a);else{if(await t.get(n,e)===null)throw new p("NOT_FOUND",`document not found: ${e}`);await t.assertPatchAllowed?.(n,e)}await _(t,n,c,S(t,n,e,a))},m=(t,n,s,e)=>{const i=typeof n=="string"?[n]:n;if(i.length===0)throw new p("INTERNAL",`ctx.db.${t}.upsert: "target" must name at least one field`);const c={};for(const a of i){if(!(a in s)){const r=Object.entries(e??{}).find(([o,d])=>d.kind==="one"&&d.field===a&&o in s)?.[0];throw r!==void 0?new p("VALIDATION_ERROR",`ctx.db.${t}.upsert: target field "${a}" is supplied by the "${r}" relation write; pass "${a}" itself so the existing row can be found`):new p("INTERNAL",`ctx.db.${t}.upsert: target field "${a}" is missing from the create document`)}c[a]=s[a]}return c},z=(t,n)=>{const s=async(o,d)=>{if(d?.skipDuplicates!==!0)return t.insert(n,o);try{return await t.insert(n,o)}catch(h){if(v(h))return null;throw h}},e=t.relationWrites?.[n],i=(o,d)=>B(t,n,e,o,h=>s(h,d)),c=(o,d)=>G(t,n,e,o,d),a=async o=>{const d=o??{},h=await t.findMany(n,{...d,limit:2});if(h.page.length>1)throw new p("NOT_UNIQUE",`ctx.db.${n}.findUnique matched more than one document; expected at most one`);return h.page[0]??null},r=async({create:o,target:d,update:h})=>{const f=m(n,d,o,e),l=await t.findFirst(n,{where:f});return l&&typeof l._id=="string"?(await c(l._id,h??o),{created:!1,id:l._id}):{created:!0,id:await i(o)}};return{aggregate:o=>t.aggregate(n,o),count:o=>t.count(n,o),delete:o=>t.delete(n,o),deleteMany:(o,d)=>{if(Array.isArray(o)){if(t.deleteMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.deleteMany is unavailable: this writer has no batch delete`);return t.deleteMany(n,o,d)}if(t.deleteWhere===void 0)throw new p("INTERNAL",`ctx.db.${n}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);const h=o;return t.deleteWhere(n,h.where,{limit:h.limit})},exists:async o=>await t.findFirst(n,o===void 0?void 0:{where:o})!==null,explain:o=>t.explain(n,o),findFirst:o=>t.findFirst(n,o),findFirstOrThrow:o=>t.findFirstOrThrow(n,o),findMany:o=>t.findMany(n,o),findUnique:a,get:o=>t.get(n,o),groupBy:o=>t.groupBy(n,o),hardDelete:o=>t.delete(n,o,{hard:!0}),insert:i,insertMany:(o,d)=>{for(const h of o)w(n,e,h,"insertMany");if(t.insertMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.insertMany is unavailable: this writer has no batch insert`);return t.insertMany(n,o,d)},patch:c,patchMany:(o,d)=>{const h=Array.isArray(o)?o.map(l=>l.values):[o.values];for(const l of h)w(n,e,l,"patchMany");if(Array.isArray(o)){if(t.patchMany===void 0)throw new p("INTERNAL",`ctx.db.${n}.patchMany is unavailable: this writer has no batch patch`);return t.patchMany(n,o.map(l=>({id:l.id,patch:l.values})),d)}if(t.patchWhere===void 0)throw new p("INTERNAL",`ctx.db.${n}.patchMany({ where, values }) is unavailable: this writer has no where-based patch`);const f=o;return t.patchWhere(n,{patch:f.values,where:f.where},{limit:f.limit})},rank:(o,d)=>t.rank(n,o,d),rankPage:(o,d)=>t.rankPage(n,o,d),replace:(o,d)=>(w(n,e,d,"replace"),t.replace(n,o,d)),restore:async o=>{if(!t.restore)throw new p("INTERNAL",`ctx.db.${n}.restore is unavailable: this writer has no restore (is the table .softDelete()?)`);await t.restore(n,o)},upsert:r,upsertMany:async({rows:o,target:d})=>{const h=[];for(const f of o)h.push(await r({create:f.create,target:d,update:f.update}));return h},withGeoIndex:(o,d)=>t.query(n).withGeoIndex(o,d),withSearchIndex:(o,d)=>t.query(n).withSearchIndex(o,d)}},X=(t,n)=>{const s=e=>({configurable:!0,enumerable:!0,value:e,writable:!0});Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){const e=z(t,n);return Object.defineProperty(t,n,s(e)),e},set(e){Object.defineProperty(this,n,s(e))}})},H=t=>{const n=s=>{const e=t[s];if(!e)throw new p("INTERNAL",`unknown table: ${s}`);return e};return{delete:(s,e)=>n(s).delete(e),insert:s=>({values:e=>n(s).insert(e)}),query:t,replace:(s,e)=>({with:i=>n(s).replace(e,i)}),update:(s,e)=>({set:i=>n(s).patch(e,i)})}};export{H as bindOrm,z as bindTableFacade,X as defineLazyFacade};
@@ -0,0 +1 @@
1
+ const u=Symbol.for("lunora.mask.middleware-columns"),l=(o,n)=>(Object.defineProperty(o,u,{configurable:!0,enumerable:!1,value:n}),o),f=o=>{if(!(o===null||typeof o!="function"&&typeof o!="object"))return o[u]},i=o=>{const n=new Map;for(const c of o){const t=f(c);if(t)for(const[e,r]of t.columns){const s=n.get(e)??new Set;for(const a of r)s.add(a);n.set(e,s)}}return n.size>0?n:void 0},b=o=>{const n=new Map;for(const c of o){const t=c?.maskedTables;if(t)for(const[e,r]of t){const s=n.get(e)??new Set;for(const a of r)s.add(a);n.set(e,s)}}return n};export{b as buildMaskRegistry,f as readMaskTag,l as tagMaskMiddleware,i as unionMaskColumns};
@@ -0,0 +1 @@
1
+ import{unionMaskColumns as d,tagMaskMiddleware as l}from"./buildMaskRegistry-DpWMtalG.mjs";import{r as m,t as n}from"./policy-tag-V0lqFzgS.mjs";import{isPerDispatchMiddleware as p,tagPerDispatchMiddleware as c}from"./isPerDispatchMiddleware-DDQPatSm.mjs";import{r as M}from"./run-middleware-BefYq7Xd.mjs";const k=s=>{const a=(async({ctx:r,next:t})=>M(s,r,i=>t({ctx:i}))),e=s.flatMap(r=>m(r));e.length>0&&n(a,e);const o=d(s);return o&&l(a,{columns:o}),s.some(r=>p(r))&&c(a),a};export{k as c};
@@ -0,0 +1 @@
1
+ import"./compose-middleware-BK9FlblN.mjs";import{c as i,a as s,b as o,g as m,k as l,m as t}from"./plugin-CyLqvCB9.mjs";export{i as composePluginMiddleware,s as defineComponent,o as definePlugin,m as defineSchemaExtension,l as installPlugins,t as mergeSchemaExtension};
@@ -0,0 +1 @@
1
+ const s=e=>e?.auth?.userId??void 0;export{s as c};
@@ -0,0 +1 @@
1
+ import{LunoraError as i}from"@lunora/errors";const c=e=>({on:e.on,table:e.table,when:e.when}),l=()=>e=>({on:e.on,table:e.table,when:e.when}),a=(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 i("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{l as createPolicyDsl,a as definePermission,d as definePolicies,c as definePolicy,h as defineRole};
@@ -0,0 +1 @@
1
+ import{LunoraError as n}from"@lunora/errors";const o=["put","list","delete","getWithMetadata","head","createMultipartUpload","idFromName","newUniqueId","getByName","send","sendBatch","writeDataPoint","create","createBatch"],s=t=>{if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.get!="function"?!1:!o.some(r=>typeof e[r]=="function")},i=t=>({get:async e=>{const r=t[e];if(!s(r))throw new n("INTERNAL",`ctx.secrets: no Secrets Store binding named "${e}". Add a \`secrets_store_secrets[]\` entry (binding "${e}", pointing at your store + secret) to wrangler.jsonc — \`ctx.secrets\` reads a Secrets Store binding, not a plain \`.dev.vars\` value.`);return r.get()}});export{i as createSecrets};
@@ -0,0 +1 @@
1
+ const i=t=>new Proxy({},{get(c,e){if(!(e==="then"||typeof e=="symbol"))throw new Error(`ctx.services.${t.name}: the "${t.binding}" service binding is not bound — run \`lunora dev\` (it reconciles wrangler services[]) or add it to wrangler.jsonc`)}}),s=t=>{let c;return new Proxy(t,{get(e,n){return n==="fetch"?(c??=e.fetch.bind(e),c):Reflect.get(e,n,e)}})},f=(t,c)=>{const e=Object.create(null);for(const n of c){const r=t[n.binding];if(typeof r!="object"&&typeof r!="function"||r===null)e[n.name]=i(n);else if(n.rpc===!0)e[n.name]=s(r);else{const o=r;e[n.name]={fetch:o.fetch.bind(o)}}}return e};export{f as createServices};
@@ -0,0 +1 @@
1
+ import{d,e as s,f as i,h as n,i as l,j as f,v as o,l as t,n as r}from"./plugin-CyLqvCB9.mjs";export{d as defineAggregateIndex,s as defineRankIndex,i as defineSchema,n as defineTable,l as defineVectorIndex,f as indexFieldsFromSchema,o as validateGlobalVectors,t as validateIndexFields,r as validateTableModes};
@@ -0,0 +1 @@
1
+ import{LunoraError as d}from"@lunora/errors";import{parseValidatorMap as s,ValidationError as l}from"@lunora/values";const u=new Set(["array","bigint","boolean","bytes","date","geoPoint","null","number","object","optional","record","timestamp"]),p=(o,n={})=>{const r=o,e=r.userId;if(e===void 0||u.has(e.kind))throw new d("INTERNAL","defineIdentity: the claim map must declare a required string `userId` validator (e.g. `v.string()` or `v.id(...)`)");const a=n.onInvalid??"anonymous";return{__lunoraIdentity:!0,claims:r,onInvalid:a,validate:i=>{try{return s(r,i,"identity"),{ok:!0}}catch(t){return{error:t instanceof l?t.message:String(t),ok:!1}}}}};export{p as defineIdentity};
@@ -0,0 +1 @@
1
+ const t=e=>e;export{t as default};
@@ -0,0 +1 @@
1
+ import{LunoraError as O,isLunoraError as I}from"@lunora/errors";import{isStringValidator as P,parseValidatorMap as b}from"@lunora/values";import{Hono as g}from"hono";import{isHttpRouter as j,httpRouter as C,httpAction as E}from"./httpAction-Bfw3qwLG.mjs";const A="/_lunora/live/connect",N="/_lunora/live/control",D="room:",B="__lunora_socket__:",K=256,m=e=>`/live/${e}/connect`,v=e=>`/live/${e}/control`,U=/^[A-Za-z]\w*$/u,T=e=>U.test(e),H=e=>`${e}:`.startsWith(D)||`${e}:`.startsWith(B),V=(e,t,o)=>[e,...t.map(d=>{const i=o[d];if(typeof i!="string")throw new TypeError(`live topic "${e}" needs a string key.${d}`);return encodeURIComponent(i)})].join(":"),k=(e,t)=>{if(e.length>K)return;const[o,...d]=e.split(":");if(o===void 0||!Object.hasOwn(t,o))return;const i=t[o];if(d.length!==i.length)return;const r={};try{for(const[c,u]of i.entries())r[u]=decodeURIComponent(d[c]);return V(o,i,r)===e?{key:r,name:o}:void 0}catch{return}},F=async e=>{try{const t=await e.json();return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:void 0}catch{return}},S=e=>Response.json({code:"FORBIDDEN_TOPIC",error:`subscribe to "${e}" was denied`},{status:403}),h=e=>Response.json({code:"BAD_REQUEST",error:e},{status:400}),M=(e,t)=>{for(const[o,d]of Object.entries(t)){if(!T(o))throw new TypeError(`defineLiveStream("${e}"): topic name "${o}" must be a plain identifier (letters, digits and "_", starting with a letter)`);if(H(o))throw new TypeError(`defineLiveStream("${e}"): topic name "${o}" would encode into a reserved topic prefix`);for(const[i,r]of Object.entries(d.key??{})){if(!T(i))throw new TypeError(`defineLiveStream("${e}"): key field "${o}.${i}" must be a plain identifier`);if(!P(r))throw new TypeError(`defineLiveStream("${e}"): key field "${o}.${i}" must be a string validator (v.string(), v.id(), v.literal(…))`)}}},z=(e,t)=>new O("BAD_REQUEST",`publish to "${e}" was refused: ${t instanceof Error?t.message:String(t)}`,{status:400}),q=e=>{M(e.id,e.topics);const t=m(e.id),o=v(e.id),d=Object.fromEntries(Object.entries(e.topics).map(([s,a])=>[s,Object.keys(a.key??{})])),i=s=>{const a=k(s,d),n=a===void 0?void 0:e.topics[a.name];if(!(a===void 0||n===void 0))try{return{declaration:n,key:b(n.key??{},a.key,"key"),name:a.name}}catch{return}},r=(s,a)=>{const n=i(s);if(n===void 0)throw new O("BAD_REQUEST",`"${s}" is not a topic declared by live stream "${e.id}"`,{status:400});const{declaration:p}=n;try{return b({payload:p.payload},{payload:a},"topic").payload}catch(f){throw z(s,f)}},c=async(s,a)=>{const n=i(a);if(n===void 0)return!1;if(!e.onSubscribe)return e.allowAnonymousControl===!0&&s.auth.userId===null;try{return await e.onSubscribe({ctx:s,key:n.key,raw:a,topic:n.name})===!0}catch(p){return console.error("[lunora] live subscribe authorization threw; denying:",p),!1}},u=E(async(s,a)=>{const n=new URL(a.url).searchParams.get("shard")??void 0;return s.fetchShard(n,A,{method:"GET"})}),R=E(async(s,a)=>{const n=await F(a);if(!n)return h("Expected a JSON object body");const{action:p}=n,f=typeof n.topic=="string"?n.topic:void 0;if(f===void 0||f.length===0)return h("topic is required");if(p!=="subscribe"&&p!=="unsubscribe")return h("action must be subscribe or unsubscribe");const y=typeof n.shardKey=="string"?n.shardKey:void 0,L=y===void 0?s:{...s,...s.forShard(y)};if(p==="subscribe"&&!await c(L,f))return S(f);const w=s.fetchShard(y,N,{body:JSON.stringify({...n,stream:e.id}),method:"POST"});if(p!=="subscribe")return w;try{return await w}catch(l){if(I(l)&&l.code==="FORBIDDEN_SHARD")return S(f);throw l}});return{connect:u,connectPath:t,control:R,controlPath:o,id:e.id,topics:e.topics,validatePublish:r}},G=e=>typeof e!="object"?{}:{...typeof e.email=="function"?{email:e.email}:{},...typeof e.queue=="function"?{queue:e.queue}:{},...typeof e.scheduled=="function"?{scheduled:e.scheduled}:{}},_=new WeakMap,$=(e,t)=>{for(const o of t){let d;const i=()=>(d??=o.load().catch(r=>{throw d=void 0,r}),d);e.get(m(o.id),async r=>{const{connect:c}=await i();return c(r)}),e.post(v(o.id),async r=>{const{control:c}=await i();return c(r)})}},Y=(e,t)=>{if(t instanceof g&&j(t)){const r=_.get(t)??new Set,c=e.filter(u=>!r.has(u.id));$(t,c),_.set(t,r);for(const u of c)r.add(u.id);return t}const o=C();if($(o,e),t===void 0)return o;const d=new Set(e.flatMap(r=>[`GET ${m(r.id)}`,`POST ${v(r.id)}`])),i=(r,c,u)=>typeof t=="function"?t(r,c,u):t.fetch(r,c,u);return{...G(t),fetch:(r,c,u)=>d.has(`${r.method} ${new URL(r.url).pathname}`)?o.fetch(r,c,u):i(r,c,u)}};export{q as defineLiveStream,Y as liveStreamRouter};
@@ -0,0 +1 @@
1
+ import{LunoraError as t}from"@lunora/errors";const n=r=>{if(r.id.trim()==="")throw new t("INTERNAL","defineMigration: `id` must be a non-empty string");return{__lunoraMigration:!0,...r}};export{n as defineMigration};
@@ -0,0 +1 @@
1
+ const t=(e={})=>{if(e.description!==void 0&&typeof e.description!="string")throw new TypeError("defineModule: `description` must be a string when provided");if(e.tables!==void 0&&(!Array.isArray(e.tables)||e.tables.some(r=>typeof r!="string"||r.length===0)))throw new TypeError("defineModule: `tables` must be an array of non-empty table names when provided");return{...e,isLunoraModule:!0}};export{t as defineModule};
@@ -0,0 +1 @@
1
+ import{LunoraError as n}from"@lunora/errors";import{c}from"./context-identity-B2XYGA0B.mjs";import{v as m,a as w}from"./functions-QFoBUe9t.mjs";const i=(r,a,s)=>{if(r.trim()==="")throw new n("INTERNAL",'defineMutator: `owner` must name the column carrying the row owner (e.g. `owner: "userId"`)');const t=c(a);if(t===void 0)throw new n("UNAUTHORIZED","defineMutator: an owner-scoped mutator requires a verified identity; none was resolved for this request");const e=s,o=e[r];if(o!==void 0&&o!==t)throw new n("FORBIDDEN",`defineMutator: \`${r}\` does not match the verified identity — a mutator may only write rows its caller owns`);return e[r]=t,s},h=r=>{const a={},s=async(t,e)=>{const o=m(r.args??{},e);w(t,r.args??{},o);const u=r.owner===void 0?o:i(r.owner,t,o);return Reflect.apply(r.server,a.mutator,[t,u])};return a.mutator={__lunoraMutator:!0,...r,handler:s,kind:"mutation",server:async(t,e)=>s(t,e)},a.mutator};export{h as defineMutator};
@@ -0,0 +1 @@
1
+ import{parseValidatorMap as f}from"@lunora/values";const w=i=>{const{message:o,name:e,onJoin:r,onLeave:t,onMessage:m}=i;if(typeof e!="string"||e.length===0)throw new TypeError("defineRoom: `name` must be a non-empty string");return{args:{},handler:async(n,g)=>{const{kind:s,message:d,socket:a}=g;if(s==="join"){await r?.(n,a);return}if(s==="leave"){await t?.(n,a);return}const{message:p}=f({message:o},{message:d},"message");await m(n,p,a)},channel:{kind:"room",name:e},kind:"mutation",visibility:"internal"}};export{w as defineRoom};
@@ -0,0 +1 @@
1
+ import{LunoraError as r}from"@lunora/errors";import{c as m}from"./context-identity-B2XYGA0B.mjs";import{v as p,a as u}from"./functions-QFoBUe9t.mjs";import{toWhereInput as d,deny as c}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as b}from"./assertShapesDeclareReadPolicies-C09SMvM4.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:(t,w,n)=>{const s=p(e.args??{},w);u(t,e.args??{},s);const o=e.where?d(e.where(t,s)):void 0;if(e.owner===void 0)return o;const a=e.owner===!0?n?.ownerField:e.owner;if(a===void 0||a==="")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=m(t);if(h===void 0)return c();const l={[a]:h};return o===void 0?l:{AND:[l,o]}},rlsRegistry:b(e.use??[])}};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 @@
1
+ import{parseValidatorMap as u}from"@lunora/values";const m=s=>{const{auth:n=!1,message:o,onClose:i,onMessage:p,onOpen:h,path:e}=s;if(typeof e!="string"||!e.startsWith("/")||new URL(e,"https://lunora.invalid").pathname!==e)throw new TypeError("defineWebSocket: `path` must be a plain URL path starting with `/` (no `?`, `#`, `..` or unencoded characters)");if(e==="/_lunora"||e.startsWith("/_lunora/"))throw new TypeError("defineWebSocket: `path` must not be under the reserved `/_lunora` prefix");return{args:{},auth:n,handler:async(t,c)=>{const{kind:r,message:l,socket:a}=c;if(r==="open"){await h?.(t,a);return}if(r==="close"){await i?.(t,a);return}const{message:d}=u({message:o},{message:l},"message");await p(t,d,a)},kind:"mutation",lifecycle:"socket",socketPath:e,visibility:"internal"}};export{m as defineWebSocket};
@@ -0,0 +1 @@
1
+ const S=2166136261,n=16777619,o=(F,e=2166136261)=>{let t=e;for(let a=0;a<F.length;a+=1)t^=F.charCodeAt(a),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")};export{S as F,n as a,o as f};
@@ -0,0 +1 @@
1
+ import{parseValidatorMap as o,sensitiveArgumentNames as r}from"@lunora/values";const f=(s,t)=>o(s,t,"args"),n=Symbol.for("lunora.admitSensitiveArgs"),l=(s,t,e)=>{const a=r(t);if(a.size===0||typeof s!="object"||s===null)return;const i=s[n];typeof i=="function"&&i(e,a)};export{l as a,f as v};
@@ -0,0 +1 @@
1
+ import{LunoraError as f,isLunoraError as I,toErrorBody as C}from"@lunora/errors";import{ValidationError as M,parseValidatorMap as v}from"@lunora/values";import{encodeWire as S}from"@lunora/wire";import{Hono as H}from"hono";import{SSE_HEADERS as A,sseFrame as w,isSafeHeaderValue as U}from"./isSafeHeaderValue-DswDADFy.mjs";import{a as R}from"./apply-output-C5wZ5EAL.mjs";import{isDevEnvironment as $}from"@lunora/shard-engine";const O=["authorization","cf-access-jwt-assertion","cookie","payment-signature","x-payment"],B=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/u,T=e=>B.test(e),V=(e,r,t=[])=>r?.access!==void 0||O.some(n=>e.has(n))||t.some(n=>!T(n)||e.has(n)),W=e=>{const r=[];let t="",n=!1,o=!1;for(const a of e){if(o)o=!1;else if(n&&a==="\\")o=!0;else if(a==='"')n=!n;else if(a===","&&!n){r.push(t.trim()),t="";continue}t+=a}return r.push(t.trim()),r.filter(a=>a!=="")},J=new Set(["proxy-revalidate","public","s-maxage"]),Q=e=>{const r=W(e),t=r.map(o=>o.toLowerCase());return t.includes("private")||t.includes("no-store")?e:["private",...r.filter((o,a)=>{const s=(t[a]?.split("=",1)[0]??"").trim();return!J.has(s)&&s!=="private"})].join(", ")},N=new WeakSet,z=e=>{try{return e.executionCtx}catch{return}},G=(e,r)=>[...O,...r].find(t=>e.has(t))??"cloudflare access",K=(e,r,t)=>{const{headers:n}=t.req.raw,o=e.credentialHeaders??[];if(!V(n,z(t),o))return r;const a=Q(r);return a!==r&&!N.has(e)&&$(t.env)&&(N.add(e),console.warn(`[lunora] httpRoute ${e.method} ${e.path}: sent Cache-Control "${a}" instead of the declared "${r}" because the request carries a credential (${G(n,o)}). A shared cache must not store a per-caller response. Further downgrades on this route are not reported.`)),a},g=e=>{if(e instanceof M)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(I(e)){const{body:r,redacted:t,status:n}=C(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return t&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:r.code,error:r.message,...r.why===void 0?{}:{why:r.why}},{status:n})}throw e},fe=e=>async r=>{try{return await e(r.get("lunora"),r.req.raw)}catch(t){return g(t)}},_=new WeakSet,k=new WeakSet,ye=e=>k.has(e),L=new WeakSet,Z=new Set(["*","/*"]),X="__COMPOSED_HANDLER",Y=e=>e[X]??e,ee=e=>{let r,t=-1;return async n=>{if(r===void 0||t!==e.routes.length){const a=new H;for(const s of e.routes)L.has(Y(s.handler))||a.on(s.method,s.path,()=>new Response(null,{status:204}));r=a,t=e.routes.length}return(await r.fetch(new Request(n.url,{method:n.method}))).status===204}},Ee=()=>{const e=new H,r=ee(e),t=e.use.bind(e);k.add(e),e.use=((...o)=>{const[a]=o;if(typeof a!="string"||Z.has(a))for(const s of o)typeof s=="function"&&L.add(s);return t(...o)}),e.use("*",async(o,a)=>{const s=o.env.__lunoraCtx;if(!s)throw new f("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");o.set("lunora",s);const{__lunoraShellFirst:i,__lunoraUnrouted:u}=o.env;if(i===!0&&!await r(o.req.raw))return u?.(),o.text("404 Not Found",404);const c=o.notFound;o.notFound=()=>(_.add(o),c()),await a()});const n=e.notFound;return e.notFound=o=>n(a=>{const{__lunoraUnrouted:s}=a.env;return _.has(a)||s?.(),o(a)}),e.notFound(o=>o.text("404 Not Found",404)),e},P=e=>e.kind==="optional"?e._meta?.inner??e:e,b=(e,r)=>{switch(e){case"bigint":try{return BigInt(r)}catch{return r}case"boolean":return r==="true"||r==="1"?!0:r==="false"||r==="0"?!1:r;case"number":return r===""?Number.NaN:Number(r);default:return r}},re=(e,r,t)=>{const n=P(e);if(n.kind==="array"){const a=r.req.queries(t);if(a===void 0)return;const s=n._meta?.inner;return a.map(i=>b(s?.kind??"string",i))}const o=r.req.query(t);return o===void 0?void 0:b(n.kind,o)},j=(e,r)=>{const t={};for(const n of Object.keys(e)){const o=e[n];o&&(t[n]=re(o,r,n))}return v(e,t,"searchParams")},D=(e,r)=>{const t=r.req.param(),n={};for(const o of Object.keys(e)){const a=e[o];if(!a)continue;const s=t[o];n[o]=s===void 0?void 0:b(P(a).kind,s)}return v(e,n,"params")},te=async(e,r)=>{let t;try{t=await r.req.json()}catch{throw new f("BAD_REQUEST","Invalid JSON body")}if(typeof t!="object"||t===null||Array.isArray(t))throw new f("BAD_REQUEST","Expected a JSON object body");return v(e,t,"body")},x=(e,r)=>{const{method:t}=r.req;if(!(t===e.method||e.method==="GET"&&t==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${t} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},oe=(e,r)=>async t=>{const n=x(e,t);if(n)return n;try{const o=t.get("lunora"),a=Object.keys(e.searchParams).length>0?j(e.searchParams,t):{},s=Object.keys(e.params).length>0?D(e.params,t):{},i=Object.keys(e.body).length>0?await te(e.body,t):{},u=await r({body:i,ctx:o,params:s,searchParams:a}),c=e.output?R(e.output,u):u,d={};e.cacheControl&&(d["cache-control"]=K(e,e.cacheControl,t)),e.cacheTag&&(d["cache-tag"]=e.cacheTag),e.vary&&(d.vary=e.vary);const y=Object.keys(d).length>0;return c===void 0?new Response(null,{headers:y?d:void 0,status:204}):Response.json(c,{headers:y?d:void 0})}catch(o){return g(o)}},we=e=>{const r=e.headers.get("last-event-id");if(r!==null)return r===""?void 0:r;const t=new URL(e.url).searchParams.get("lastEventId");return t===null||t===""?void 0:t},q=Symbol.for("@lunora/server/sse-event"),Re=e=>({[q]:!0,data:e.data,id:e.id}),ne=e=>typeof e=="object"&&e!==null&&e[q]===!0,ae=(e,r)=>{if(ne(r)){if(!U(r.id))throw new f("INTERNAL","sseEvent id must not contain CR, LF or NUL");const t=e?R(e,r.data):r.data;return w(S(t),void 0,r.id)}return w(S(e?R(e,r):r))},se=(e,r)=>(async t=>{const n=x(e,t);if(n)return n;let o,a;try{o=Object.keys(e.searchParams).length>0?j(e.searchParams,t):{},a=Object.keys(e.params).length>0?D(e.params,t):{}}catch(p){return g(p)}const s=t.get("lunora"),i=t.req.raw,u=new TextEncoder,c=new AbortController;if(i.signal.aborted)return c.abort(),new Response("",{headers:A});const d=()=>{c.abort()};i.signal.addEventListener("abort",d,{once:!0});const y=new ReadableStream({cancel(){i.signal.removeEventListener("abort",d),c.abort()},async start(p){try{const E=r({ctx:s,params:a,request:i,searchParams:o,signal:c.signal});for await(const m of E){if(c.signal.aborted)break;p.enqueue(u.encode(ae(e.output,m)))}c.signal.aborted||p.enqueue(u.encode(w({},"complete")))}catch(E){const{body:m,redacted:F}=C(E,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});F&&console.error("[lunora] unhandled stream handler error:",E),c.signal.aborted||p.enqueue(u.encode(w({code:m.code,hint:m.hint,message:m.message,why:m.why},"error")))}finally{i.signal.removeEventListener("abort",d);try{p.close()}catch{}}}});return new Response(y,{headers:A})}),ce=e=>{const r=e?.find(t=>!T(t));if(r!==void 0)throw new f("INTERNAL",`httpRoute .cacheControl(): credentialHeaders entry ${JSON.stringify(r)} is not a header name`);return e},l=e=>({body:r=>l({...e,body:{...e.body,...r}}),cacheControl:(r,t)=>l({...e,cacheControl:r,credentialHeaders:ce(t?.credentialHeaders)}),cacheTag:r=>l({...e,cacheTag:r}),handler:r=>oe(e,r),output:r=>l({...e,output:r}),params:r=>l({...e,params:{...e.params,...r}}),searchParams:r=>l({...e,searchParams:{...e.searchParams,...r}}),stream:r=>se(e,r),vary:r=>l({...e,vary:r})}),h=e=>r=>l({body:{},method:e,params:{},path:r,searchParams:{}}),be={delete:h("DELETE"),get:h("GET"),head:h("HEAD"),options:h("OPTIONS"),patch:h("PATCH"),post:h("POST"),put:h("PUT")};export{fe as httpAction,be as httpRoute,Ee as httpRouter,ye as isHttpRouter,U as isSafeHeaderValue,we as lastEventId,Re as sseEvent};
@@ -0,0 +1 @@
1
+ import{a as _}from"./apply-output-C5wZ5EAL.mjs";import{v as C,a as M}from"./functions-QFoBUe9t.mjs";import{unionMaskColumns as w}from"./buildMaskRegistry-DpWMtalG.mjs";import{PROCEDURE_META as i}from"./PROCEDURE_META-DVzrXpfa.mjs";import{r as b}from"./policy-tag-V0lqFzgS.mjs";import{r as z,e as D}from"./run-middleware-BefYq7Xd.mjs";import{isPerDispatchMiddleware as O}from"./isPerDispatchMiddleware-DDQPatSm.mjs";const y=(e,r,o,n)=>n===0&&r===void 0||typeof e!="object"||e===null?e:D(e,{args:Object.freeze({...o}),...r===void 0?{}:{meta:r}}),j=(e,r)=>z(e,r,o=>o),P=(e,r,o,n,d)=>async(s,t)=>{const c=C(e,t);M(s,e,c);const m=await j(r,y(s,d,c,r.length)),l=await o({args:c,ctx:m});return n?_(n,l):l},S=(e,r,o,n)=>(d,s,t)=>{const c=C(e,s);return M(d,e,c),(async function*(){const l=await j(r,y(d,n,c,r.length)),f=o({args:c,ctx:l,signal:t})[Symbol.asyncIterator]();try{for(;;){if(t.aborted)return;const p=await f.next();if(p.done||t.aborted)return;yield p.value}}finally{await f.return?.()}})()},g=e=>{const r=e.flatMap(o=>b(o));return r.length>0?{tags:r}:void 0},x=e=>e.some(r=>O(r)),h=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);h(e)}else if(e instanceof Set){for(const o of e)u(o,r);h(e)}for(const o of Object.values(e))u(o,r);return Object.freeze(e),e},T=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 d=g(r.middlewares),s=w(r.middlewares),t=x(r.middlewares);return{args:r.args,...r.expose?{expose:r.expose}:{},handler:P(r.args,r.middlewares,n,r.output,r.meta),kind:e,...s?{maskedTables:s}:{},...t?{perDispatch:t}:{},...d?{rls:d}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{},...r.meta?{[i]:r.meta}:{}}},meta:n=>a(e,{...r,meta:T({...r.meta,...n})},o),output:n=>a(e,{...r,output:n},o),...e==="query"?{stream:(n,d)=>{const s=g(r.middlewares),t=w(r.middlewares),c=x(r.middlewares),m=d?.durable===!0?{}:d?.durable;return{args:r.args,...m?{durable:m}:{},...r.expose?{expose:r.expose}:{},handler:S(r.args,r.middlewares,n,r.meta),kind:"stream",...t?{maskedTables:t}:{},...c?{perDispatch:c}:{},...s?{rls:s}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{},...r.meta?{[i]:r.meta}:{}}}}:{},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)}}),F={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{F as initLunora};
@@ -0,0 +1 @@
1
+ const t=Symbol.for("lunora.middleware.per-dispatch"),r=e=>(Object.defineProperty(e,t,{configurable:!0,enumerable:!1,value:!0}),e),n=e=>e===null||typeof e!="function"&&typeof e!="object"?!1:e[t]===!0;export{n as isPerDispatchMiddleware,r as tagPerDispatchMiddleware};
@@ -0,0 +1,6 @@
1
+ const i={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},s=n=>!(n.includes("\r")||n.includes(`
2
+ `)||n.includes("\0")),a=(n,e,t)=>{if(t!==void 0&&!s(t))throw new Error("SSE event id must not contain CR, LF or NUL");const o=JSON.stringify(n),c=t===void 0?"":`id: ${t}
3
+ `,r=e===void 0?"":`event: ${e}
4
+ `;return`${c}${r}data: ${o}
5
+
6
+ `};export{i as SSE_HEADERS,s as isSafeHeaderValue,a as sseFrame};
@@ -0,0 +1 @@
1
+ import{LunoraError as S}from"@lunora/errors";import{f as L}from"./fnv1a-D3ueNTWB.mjs";import{i as q,a as z,o as x,b as T,c as C,d as H}from"./middleware-CHYtnvZP.mjs";import{defineLazyFacade as J,bindOrm as Y}from"./bindOrm-D5mVDvbi.mjs";import{tagMaskMiddleware as Q}from"./buildMaskRegistry-DpWMtalG.mjs";const D=Symbol.for("lunora.ctxdb.rls-relation-gate"),V=(s,i,c)=>{try{return s==="redact"?null:s==="hash"?i==null?i:typeof i=="bigint"?L(i.toString()):L(typeof i=="string"?i:JSON.stringify(i)):s(i,c)}catch{return null}},d=(s,i,c)=>{const u={...s};for(const[w,p]of Object.entries(i))w in u&&(u[w]=V(p,s[w],{...c,column:w,row:s}));return u},E=(s,i,c)=>({...s,page:s.page.map(u=>d(u,i,c))}),P=(s,i)=>{const c=C(i);return s instanceof Set?s.has(c):Object.hasOwn(s,c)},G=(s,i,c,u)=>{if(typeof s!="function")return;const w=new Set,p=()=>new Proxy({},{get:()=>f=>(typeof f=="string"&&w.add(f),p())});s(p());for(const f of w)if(P(i,f))throw new S("MASK_UNSUPPORTED",`${u}() filtering "${c}" by masked column "${f}" is not supported`)},X=(s,i,c,u)=>{const w=s.rankBefore,p=s.rankPageRows,f=(r,t)=>{const n=i.get(r);return n?t.map(o=>d(o,n,c)):t},k=r=>{const t=r?.relationMask;return{...r,relationMask:t===void 0?f:(n,o)=>t(n,f(n,o))}},y=(r,t,n,o)=>{const e=i.get(r);if(!e)return;const a=u?.[r]?.[o]?.[t];if(!a)return;const g=a.find(I=>P(e,I));if(g!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() reading "${r}" via index "${t}" would order rows by masked column "${g}" — use an index whose declared fields are all unmasked, or unmask the column`)},O=(r,t,n)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield d(o,t,c)},collect:async()=>(await r.collect()).map(e=>d(e,t,c)),collectWithScores:async()=>(await r.collectWithScores()).map(e=>{const a=d(e.document,t,c);return"distanceMeters"in e?{distanceMeters:null,document:a}:{document:a,score:e.score}}),filter:o=>O(r.filter(e=>o(d(e,t,c))),t,n),first:async()=>{const o=await r.first();return o?d(o,t,c):null},order:o=>O(r.order(o),t,n),paginate:async o=>E(await r.paginate(o),t,c),take:async o=>(await r.take(o)).map(a=>d(a,t,c)),unique:async()=>{const o=await r.unique();return o?d(o,t,c):null},withIndex:(o,e)=>(y(n,o,"withIndex","index"),G(e,t,n,"withIndex"),O(r.withIndex(o,e),t,n)),withSearchIndex:(o,e)=>(G(e,t,n,"withSearchIndex"),O(r.withSearchIndex(o,e),t,n)),withGeoIndex:(o,e)=>(y(n,o,"withGeoIndex","geo"),O(r.withGeoIndex(o,e),t,n))}),R=(r,t,n)=>{const o=i.get(r);if(!o)return;const e=t.find(a=>typeof a=="string"&&P(o,a));if(e!==void 0)throw new S("MASK_UNSUPPORTED",`${n}() over masked column "${e}" on "${r}" is not supported`)},l=new Set;for(const r of i.values())for(const t of Object.keys(r))l.add(t);const A=(r,t,n,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[e,a]of Object.entries(r))K(e,a,t,n,o)},K=(r,t,n,o,e)=>{if(r==="AND"||r==="OR"){for(const a of Array.isArray(t)?t:[])A(a,n,o,e);return}if(r==="NOT"){A(t,n,o,e);return}if(!r.startsWith("__")){if(P(n,r))throw new S("MASK_UNSUPPORTED",`${e}() filtering "${o}" by masked column "${r}" is not supported`);if(H(t))for(const a of Object.values(t))A(a,l,`${o}.${r}`,e)}},F=r=>{const t=i.get(r);return t?new Set(Object.keys(t)):new Set},h=(r,t,n)=>{l.size===0||t===void 0||A(t,F(r),r,n)},v=(r,t,n,o)=>{if(Array.isArray(t)){for(const e of t)if(!(!e||typeof e!="object"||Array.isArray(e))){for(const a of Object.keys(e))if(P(n,a))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${a}" is not supported`)}}},j=(r,t,n)=>{if(!(l.size===0||!t||typeof t!="object"||Array.isArray(t)))for(const[o,e]of Object.entries(t)){if(o==="_count"||!e||typeof e!="object"||Array.isArray(e))continue;const a=e,g=`${r}.${o}`;A(a.where,l,g,n),v(g,a.orderBy,l,n),j(g,a.with,n)}},M=(r,t,n)=>{h(r,t?.where,n),h(r,t?.baseWhere,n),v(r,t?.orderBy,F(r),n),j(r,t?.with,n)},_=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,W=(r,t,n)=>{const o=_(t);h(r,o?.where,n),h(r,o?.baseWhere,n),j(r,o?.with,n)},$=(r,t)=>Object.hasOwn(i.get(r)??{},t)?t:void 0,B={...s,relationWrites:(()=>{if(s.relationWrites===void 0)return;const r={};for(const[t,n]of Object.entries(s.relationWrites))r[t]=Object.fromEntries(Object.entries(n).map(([o,e])=>{const[a,g]=e.kind==="one"?[t,e.table]:[e.table,t],I=e.through?$(e.through.table,e.through.from)??$(e.through.table,e.through.to):$(a,e.field)??$(g,e.references);return[o,I===void 0?e:{...e,refusal:`"${I}" is masked for this caller, so its stored value cannot be copied`}]}));return r})(),async deleteWhere(r,t,n){if(h(r,t,"deleteMany({ where })"),s.deleteWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return s.deleteWhere(r,t,n)},async patchIf(r,t,n){if(h(r,n.where,"patchIf"),s.patchIf===void 0)throw new S("INTERNAL",`ctx.db.patchIf on "${r}" is unsupported: this writer has no conditional write`);const o=await s.patchIf(r,t,n),e=i.get(r);return o.doc&&e?{applied:o.applied,doc:d(o.doc,e,c)}:o},async patchWhere(r,t,n){if(h(r,t.where,"patchMany({ where })"),s.patchWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return s.patchWhere(r,t,n)},aggregate(r,t){return R(r,[t.field],"aggregate"),h(r,t.where,"aggregate"),s.aggregate(r,t)},count(r,t){const n=_(t),o=n&&("where"in n||"baseWhere"in n||"restrictsCounts"in n)?n.where:t;return h(r,o,"count"),n&&h(r,n.baseWhere,"count"),s.count(r,t)},async findFirst(r,t){M(r,t,"findFirst");const n=await s.findFirst(r,k(t)),o=i.get(r);return n&&o?d(n,o,c):n},async findFirstOrThrow(r,t){M(r,t,"findFirstOrThrow");const n=await s.findFirstOrThrow(r,k(t)),o=i.get(r);return o?d(n,o,c):n},async explain(r,t){return M(r,t,"explain"),s.explain(r,t)},async findMany(r,t){M(r,t,"findMany");const n=await s.findMany(r,k(t)),o=i.get(r);return o?E(n,o,c):n},async get(r,t){const n=await s.get(r,t),o=i.get(r);return!n||!o?n:d(n,o,c)},related:s.related?async(r,t)=>await s.related(r,k(t)):void 0,async lookupById(r,t){const n=await s.lookupById?.(r,t);if(!n)return null;const o=i.get(n.tableName);return{row:o?d(n.row,o,c):n.row,tableName:n.tableName}},groupBy(r,t){return R(r,[...t.by,t.agg?.field],"groupBy"),h(r,t.where,"groupBy"),s.groupBy(r,t)},query(r){const t=s.query(r),n=i.get(r);return n?O(t,n,r):t},async rank(r,t,n){return W(r,n,"rank"),y(r,t,"rank","rank"),s.rank(r,t,n)},async rankPage(r,t,n){W(r,n,"rankPage"),y(r,t,"rankPage","rank");const o=await s.rankPage(r,t,n),e=i.get(r);return e?E(o,e,c):o},...x("rankBefore",w,r=>(t,n,o)=>(W(t,o,"rankBefore"),y(t,n,"rankBefore","rank"),r(t,n,o))),...x("rankPageRows",p,r=>async(t,n,o)=>{W(t,o,"rankPageRows"),y(t,n,"rankPageRows","rank");const e=await r(t,n,o),a=i.get(t);return a?{...e,rows:e.rows.map(g=>({...g,doc:d(g.doc,a,c)}))}:e})};if(l.size>0)for(const[r,t]of Object.entries(s))T(t)&&J(B,r);const U=s[D];return U!==void 0&&Object.defineProperty(B,D,{configurable:!0,enumerable:!1,value:U,writable:!1}),B},nr=(s,i={})=>{const c=new Map(Object.entries(s)),u=q(i.roles),w=async({ctx:f,next:k})=>{const y=f,O={auth:await z(y.auth??{},u),ctx:y};if(i.bypass?.(O)===!0)return k();const R=X(y.db,c,O,i.indexFields),l={db:R},{orm:A}=y;return A!==null&&typeof A=="object"&&(l.orm=Y(R)),k({ctx:l})},p=new Map;for(const[f,k]of c)p.set(f,new Set(Object.keys(k)));return Q(w,{columns:p})};export{nr as mask};
@@ -0,0 +1 @@
1
+ import{LunoraError as p,isLunoraError as Be}from"@lunora/errors";import{findRelated as Ee,whereFilter as Se}from"@lunora/shard-engine";import{isPlainObject as X}from"@lunora/wire";import{defineLazyFacade as Ae,bindOrm as Te}from"./bindOrm-D5mVDvbi.mjs";import{t as ke}from"./policy-tag-V0lqFzgS.mjs";import{deny as Ie}from"./allowAll-DkRAgItV.mjs";const J=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},re=4;class m extends Error{}const N=e=>e.includes("."),Wt=e=>{const t=e.indexOf(".");return t===-1?e:e.slice(0,t)},fe=e=>{const t=e.split(".");if(t.length>re||t.includes(""))throw new m(`field path "${e}" must have 1 to ${String(re)} non-empty segments`);return t},_e=(e,t)=>{if(!N(t))return e[t];let r=e;for(const i of fe(t)){if(!J(r)||!Object.hasOwn(r,i))return;r=r[i]}return r},de=(e,t,r,i)=>{const[a,...f]=t;if(a===void 0)throw new m(`field path "${i}" is empty`);if(e!=null&&!J(e))throw new m(`cannot set "${i}": "${a}" sits inside a value that is not an object`);const u=e??{};return{...u,[a]:f.length===0?r:de(u[a],f,r,i)}},me=(e,t)=>{const r=Object.keys(e).filter(a=>N(a));if(r.length===0)return e;for(const a of r){const f=r.find(u=>u!==a&&u.startsWith(`${a}.`));if(f!==void 0)throw new m(`patch sets both "${a}" and "${f}", which overlap; set one or the other`)}const i={};for(const[a,f]of Object.entries(e))N(a)||(i[a]=f);for(const a of r){const[f="",...u]=fe(a);if(Object.hasOwn(e,f))throw new m(`patch sets both "${f}" and "${a}"; set one or the other`);i[f]=de(Object.hasOwn(i,f)?i[f]:t[f],u,e[a],a)}return i},Pe=e=>{const t=typeof e;return t==="number"||t==="string"||t==="boolean"?t:void 0},$e=["every","is","isNot","none","some"],De=new Set($e),Fe=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>De.has(r))},oe=(e,t,r)=>t?{[e]:r(t)}:{},ue=500,K=(e,t,r)=>{if(e!==void 0&&e!==Number.POSITIVE_INFINITY&&(!Number.isInteger(e)||e<0))throw r(`${t}: batch limit must be a non-negative integer`);return e??ue},Q=(e,t,r,i)=>{if(e>t)throw i(`${r}: batch of ${String(e)} exceeds the limit of ${String(t)} (raise options.limit or chunk the call)`)},Z={decrement:{apply:(e,t)=>e-t,kind:"number"},divide:{apply:(e,t)=>e/t,kind:"number"},increment:{apply:(e,t)=>e+t,kind:"number"},multiply:{apply:(e,t)=>e*t,kind:"number"},toggle:{kind:"boolean"}};class B extends Error{}const he=e=>{if(!J(e))return;const t=Object.keys(e),[r]=t;if(!(t.length!==1||r===void 0||!Object.hasOwn(Z,r)))return{operand:e[r],operator:r}},Me=e=>he(e)!==void 0,Le=(e,t,r,i)=>{const a=Z[t];if(a.apply===void 0){if(r!==!0)throw new B(`patch: use { toggle: true } on "${e}".`);if(typeof i!="boolean")throw new B(`patch: cannot toggle "${e}" — its current value is ${String(i)}; set a boolean first.`);return!i}if(typeof r!="number"||!Number.isFinite(r))throw new B(`patch: "${t}" on "${e}" needs a finite number, got ${String(r)}.`);if(typeof i!="number"||!Number.isFinite(i))throw new B(`patch: cannot ${t} "${e}" — its current value is ${String(i)}; set a number first.`);if(t==="divide"&&r===0)throw new B(`patch: cannot divide "${e}" by zero.`);const f=a.apply(i,r);if(!Number.isFinite(f))throw new B(`patch: "${t}" on "${e}" overflows to ${String(f)}.`);return f},ye=(e,t)=>{const r=new Set;for(const[i,a]of Object.entries(e))t(i)!==void 0&&Me(a)&&r.add(i);return r},je=(e,t,r)=>{let i;for(const a of ye(e,r)){const{operand:f,operator:u}=he(e[a]),g=r(a);if(Z[u].kind!==g)throw new B(`patch: "${u}" does not apply to the ${String(g)} column "${a}".`);i??={...e},i[a]=Le(a,u,f,t[a])}return i??e},Ce=(e,t)=>{const r=a=>{const f=t[a];return typeof f=="number"||typeof f=="boolean"?typeof f:void 0},i={...e};for(const a of ye(e,r))try{Object.assign(i,je({[a]:e[a]},t,r))}catch(f){if(!(f instanceof B))throw f}try{return me(i,t)}catch(a){if(a instanceof m)return i;throw a}},Ue=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],S=-1,A=0,E=1,P=e=>e?E:S,w=(e,t)=>e<t?e:t,xe=(e,t)=>e>t?e:t,pe=e=>e===A?A:P(e===S),se=e=>{const t=typeof e;return t==="number"||t==="string"||t==="bigint"},T=e=>e==null,F=(e,t,r)=>{if(r===void 0)throw new p("BAD_REQUEST",`\`${t}\` on "${e}" received undefined; a comparison needs a value`)},Ne={gt:(e,t)=>e>t,gte:(e,t)=>e>=t,lt:(e,t)=>e<t,lte:(e,t)=>e<=t},qe=(e,t,r)=>{let i=E;for(const a of["gt","gte","lt","lte"]){if(!(a in r))continue;const f=r[a];F(e,a,f);const u=N(e);if(u?Pe(f)===void 0:!se(f))i=w(i,S);else if(T(t))i=w(i,A);else{const g=Ne[a],y=u?typeof t==typeof f:se(t);i=w(i,P(y&&g(t,f)))}}return i},ie=(e,t,r)=>{if(!Array.isArray(r))throw new p("BAD_REQUEST",`\`${t}\` on "${e}" expects an array of values, received ${r===null?"null":typeof r}`);if(r.includes(void 0))throw new p("BAD_REQUEST",`\`${t}\` on "${e}" received undefined inside its list; a comparison needs a value`);return r},ae=(e,t)=>t.length===0?S:T(e)?A:t.includes(e)?E:t.some(r=>T(r))?A:S,Ye=(e,t,r)=>{let i=E;if("in"in r&&(i=w(i,ae(t,ie(e,"in",r.in)))),"notIn"in r&&(i=w(i,pe(ae(t,ie(e,"notIn",r.notIn))))),"contains"in r){const a=r.contains;F(e,"contains",a),i=T(t)?w(i,A):w(i,P(typeof t=="string"&&typeof a=="string"&&t.includes(a)))}return"isNull"in r&&(i=w(i,P(r.isNull===!0===T(t)))),i},G=(e,t,r)=>t===null?P(r===T(e)):T(e)?A:P(r===(e===t)),ze=(e,t,r)=>{let i=E;return"eq"in r&&(F(e,"eq",r.eq),i=w(i,G(t,r.eq,!0))),"ne"in r&&(F(e,"ne",r.ne),i=w(i,G(t,r.ne,!1))),i},He=(e,t,r)=>w(ze(e,t,r),w(Ye(e,t,r),qe(e,t,r))),Ke=(e,t,r,i)=>{if(t==="NOT")return pe(i(e,r??{}));if(!Array.isArray(r))return S;let a=t==="AND"?E:S;for(const f of r){const u=i(e,f);a=t==="AND"?w(a,u):xe(a,u)}return a},we=e=>e==="AND"||e==="OR"||e==="NOT",Qe=e=>X(e)&&Object.keys(e).every(t=>Ue.includes(t)),q=e=>Object.keys(e).some(t=>{const r=e[t];return we(t)?t==="NOT"?q(r??{}):Array.isArray(r)&&r.some(i=>q(i??{})):Fe(r)}),ge=(e,t)=>{let r=E;for(const i of Object.keys(t)){const a=t[i];if(we(i)){r=w(r,Ke(e,i,a,ge));continue}const f=_e(e,i);if(Qe(a)){r=w(r,He(i,f,a));continue}F(i,"eq",a),r=w(r,G(f,a,!0))}return r},Y=(e,t)=>ge(e,t)===E,ce=(e,t)=>e===void 0||t===void 0?e??t:(r,i)=>e(r,i)&&t(r,i),_=e=>new p("BATCH_LIMIT_EXCEEDED",e,{status:400}),U=(e,t,r)=>{Q(e,K(t,r,_),r,_)},Ge=Ie(),Xe=Symbol.for("lunora.ctxdb.rls-unwrap"),Je=Symbol.for("lunora.ctxdb.rls-relation-gate"),be=Symbol.for("lunora.rls.wrapped-chain"),H=new WeakMap,Ze=e=>e[be],Ve=e=>{const t=new Map;for(const r of e){const i=t.get(r.table)??[];i.push(r),t.set(r.table,i)}return t},et=(e,t)=>{const r=[];let i=!1;for(const a of e){if(a.on!=="read")continue;const f=a.when(t);if(f!==void 0){if(f===!0){i=!0;break}f!==!1&&r.push(f)}}if(!i)return r.length===0?Ge:r.length===1?r[0]:{OR:r}},tt=(e,t,r)=>{const i=e.when({...t,row:r});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(q(i))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return Y(r,i)},nt=(e,t,r)=>{const i=e.when(t);if(i===void 0||i===!0)return r===void 0||tt(e,t,r);if(i===!1)return!1;if(q(i))throw new p("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!Y(t.row,i)?!1:r===void 0||Y(r,i)},rt=(e,t,r,i)=>{let a=!1;for(const f of e)if(f.on===t&&(a=!0,!nt(f,r,i)))return!1;return a},ot=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),st=(e,t)=>t===void 0?!0:e==="restrictsCounts"?typeof t=="boolean":e==="relationBaseWhere"?typeof t=="function":X(t),it=e=>{const t=Object.keys(e);return t.length===0?!1:t.every(r=>ot.has(r)&&st(r,e[r]))},at=e=>e===void 0?{}:X(e)&&it(e)?e:{where:e},x=e=>e!==void 0&&Object.keys(e).length>0,le=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},W=(e,t)=>x(t)?!e||Object.keys(e).length===0?t:{AND:[t,e]}:e,ct=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},lt=(e,t,r)=>{const[i]=r,a=r.length===1&&i!==void 0?i.perTable:new Set(r.flatMap(n=>[...n.perTable.keys()])),f=new Map,u=n=>{const o=f.get(n);if(o)return o;const s=[];let c=!1;for(const d of r){const h=d.perTable.get(n);if(!h||h.length===0||!h.some(D=>D.on==="read"))continue;c=!0;const O=et(h,d.context);O!==void 0&&s.push(O)}const l={baseWhere:le(s),restricts:c};return f.set(n,l),l},g=(n,o,s,c)=>{for(const l of r){const d=l.perTable.get(n);if(d&&!rt(d,o,{...l.context,row:s},c))return!1}return!0},y=n=>u(n).restricts?t:e,k=e[Je],b=n=>{const{baseWhere:o,restricts:s}=u(n);return s||k?.gate(n),o};k?.trust(b),H.set(b,u);const v=n=>{const o=typeof n=="function"?H.get(n):void 0;if(o===void 0)return b;const s=l=>{const d=u(l),h=o(l);return{baseWhere:le([d.baseWhere,h.baseWhere].filter(O=>x(O))),restricts:d.restricts||h.restricts}},c=l=>{const{baseWhere:d,restricts:h}=s(l);return h||k?.gate(l),d};return k?.trust(c),H.set(c,s),c},$=async(n,o)=>{const s=await t.get(n,o);return s?{row:s,tableName:a.has(n)?n:void 0}:{row:null,tableName:void 0}},z=async n=>{if(t.lookupById){const l=await t.lookupById(n);if(l)return{row:l.row,tableName:a.has(l.tableName)?l.tableName:void 0}}const o=[...a.keys()],c=(await Promise.all(o.map(async l=>{const d=await t.findFirst(l,{limit:1,where:{_id:n}});return d?._id===n?{row:d,tableName:l}:void 0}))).find(l=>l!==void 0);return c?{row:c.row,tableName:c.tableName}:{row:null,tableName:void 0}},M=async(n,o)=>{const s=await $(n,o);return s.row&&s.tableName!==void 0?{row:s.row,tableName:s.tableName}:void 0},R=async(n,o,s,c,l)=>{const d=await M(n,o);if(!d)return c(e);const h=l?l(d.row):void 0;if(!g(d.tableName,s,d.row,h))throw new p("FORBIDDEN",`${s} denied by policy`);return c(t,d.tableName)},L=(n,o,s)=>{if(s?.hard===!0)return!1;const c=e.softDeleteFields?.get(n);return c!==void 0&&o[c]!==null&&o[c]!==void 0},ve=async(n,o,s,c,l)=>{const d=s?t:e,h=await d.findFirst(o,{...s?{baseWhere:u(o).baseWhere}:{},...c?.hard===!0?{includeDeleted:!0}:{},limit:1,relationBaseWhere:b,where:l===void 0?{_id:n}:W(l,{_id:n})});if(!h||L(o,h,c))return!1;if(s&&!g(o,"delete",h))throw new p("FORBIDDEN","delete denied by policy");return await d.delete(o,n,c),!0},V=async(n,o,s,c)=>{const l=a.has(n),d=l?t:e,h=s===void 0?void 0:{hard:s},O=e.inTransaction?.()!==!0||e.deleteRereadTables?.has(n)===!0;let D=0;for(const te of o){const ne=String(te._id);if(O){await ve(ne,n,l,h,c)&&(D+=1);continue}if(l&&!g(n,"delete",te))throw new p("FORBIDDEN","delete denied by policy");await d.delete(n,ne,h),D+=1}return D},j=(n,o,s,c)=>R(n,o,"update",(l,d)=>c(l,{verify:d===void 0?void 0:(h,O)=>g(d,"update",h,O)}),l=>({...l,...Ce(s,l)})),C=(n,o)=>{const{baseWhere:s}=u(n);if(x(s))throw new p("COUNT_RLS_UNSUPPORTED",`${o}() is not supported on "${n}" inside an RLS-restricted context`)},We=e.rankBefore,Re=e.rankPageRows,{relationEdges:ee}=e,I={...e,async count(n,o){const{baseWhere:s}=u(n),c=at(o);return y(n).count(n,{...c,baseWhere:W(c.baseWhere,s),relationBaseWhere:v(c.relationBaseWhere),restrictsCounts:(c.restrictsCounts??!1)||x(s)})},delete:(n,o,s)=>R(n,o,"delete",c=>c.delete(n,o,s)),async deleteAll(n,o){const s=Math.max(1,o?.chunkSize??ue),{baseWhere:c}=u(n);let l=0;for(;;){const d=await y(n).findMany(n,{baseWhere:c,limit:s,relationBaseWhere:b}),{page:h}=d;if(h.length===0||(l+=await V(n,h,o?.hard),h.length<s))break}return{deleted:l}},async deleteMany(n,o,s){U(o.length,s?.limit,"deleteMany");for(const c of o)await R(n,c,"delete",l=>l.delete(n,c));return{deleted:o.length}},async deleteWhere(n,o,s){const{baseWhere:c}=u(n),l=K(s?.limit,"deleteWhere",_),d=await y(n).findMany(n,{baseWhere:W(o,c),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b}),h=d.page.map(O=>String(O._id));return Q(h.length,l,"deleteWhere",_),{deleted:await V(n,d.page,void 0,o)}},async findFirst(n,o){const{baseWhere:s}=u(n);return y(n).findFirst(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async findFirstOrThrow(n,o){const{baseWhere:s}=u(n);return y(n).findFirstOrThrow(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async explain(n,o){const{baseWhere:s}=u(n);return y(n).explain(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async findMany(n,o){const{baseWhere:s}=u(n);return y(n).findMany(n,{...o,baseWhere:W(o?.baseWhere,s),relationBaseWhere:v(o?.relationBaseWhere)})},async get(n,o){const s=await $(n,o);if(!s.row)return null;if(s.tableName===void 0)return e.get(n,o);const{baseWhere:c,restricts:l}=u(s.tableName);if(!l)return e.get(n,o);if(!c)return s.row;const d=await t.findFirst(s.tableName,{baseWhere:c,limit:1,where:{_id:o}});return d?._id===o?d:null},async lookupById(n,o){const s=o===void 0?await z(n):await $(o,n);if(!s.row)return null;if(s.tableName===void 0||!u(s.tableName).restricts)return await e.lookupById?.(n,o)??null;const{baseWhere:c}=u(s.tableName);if(!c)return{row:s.row,tableName:s.tableName};const l=await t.findFirst(s.tableName,{baseWhere:c,limit:1,where:{_id:n}});return l?._id===n?{row:l,tableName:s.tableName}:null},async insert(n,o,s){if(a.has(n)){if(!g(n,"insert",o))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insert(n,o,s)}return e.insert(n,o,s)},async insertMany(n,o,s){if(U(o.length,s?.limit,"insertMany"),a.has(n)){for(const c of o)if(!g(n,"insert",c))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertMany(n,o,s)}return e.insertMany(n,o,s)},async insertManyUnsafe(n,o,s){if(U(o.length,s?.limit,"insertManyUnsafe"),a.has(n)){for(const c of o)if(!g(n,"insert",c))throw new p("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertManyUnsafe(n,o,s)}return e.insertManyUnsafe(n,o,s)},patch:(n,o,s,c)=>j(n,o,s,(l,d)=>l.patch(n,o,s,{...c,verify:ce(c?.verify,d.verify)})),assertPatchAllowed:(n,o)=>j(n,o,{},()=>Promise.resolve()),async patchIf(n,o,s){const c=await j(n,o,s.patch,async(d,h)=>{if(d.patchIf===void 0)throw new p("INTERNAL",`ctx.db.patchIf on "${n}" is unsupported: this writer has no conditional write`);return d.patchIf(n,o,{...s,verify:ce(s.verify,h.verify)})});return c.doc===null||await I.get(n,o).then(d=>d!==null,d=>{if(Be(d)&&d.code==="RLS_REQUIRED")return!1;throw d})?c:{applied:c.applied,doc:null}},async patchMany(n,o,s){U(o.length,s?.limit,"patchMany");for(const c of o)await j(n,c.id,c.patch,(l,d)=>l.patch(n,c.id,c.patch,d));return{patched:o.length}},async patchWhere(n,o,s){const{baseWhere:c}=u(n),l=K(s?.limit,"patchWhere",_),h=(await y(n).findMany(n,{baseWhere:W(o.where,c),...Number.isFinite(l)?{limit:l+1}:{},relationBaseWhere:b})).page.map(O=>({id:String(O._id),patch:o.patch}));return Q(h.length,l,"patchWhere",_),I.patchMany(n,h,s)},query(n){const{baseWhere:o}=u(n),s=y(n).query(n);return o?s.filter(Se(o,c=>Y(c,o))):s},related:ee===void 0?void 0:async(n,o)=>Ee({findMany:async(s,c)=>I.findMany(s,c),lookupById:async s=>t.lookupById?.(s)},ee,n,{cursor:o?.cursor,depth:o?.depth,direction:o?.direction,edges:o?.edges,limit:o?.limit,relationMask:o?.relationMask}),restore:(n,o)=>R(n,o,"update",async s=>{const c=s.restore??t.restore;if(!c)throw new p("BAD_REQUEST","restore is not supported by this writer");await c(n,o)}),replace:(n,o,s)=>R(n,o,"update",c=>c.replace(n,o,s),c=>({...s,_creationTime:s._creationTime??c._creationTime,_id:c._id})),aggregate(n,o){const{baseWhere:s}=u(n);return y(n).aggregate(n,{...o,baseWhere:W(o.baseWhere,s),relationBaseWhere:v(o.relationBaseWhere)})},groupBy(n,o){const{baseWhere:s}=u(n);return y(n).groupBy(n,{...o,baseWhere:W(o.baseWhere,s),relationBaseWhere:v(o.relationBaseWhere)})},rank(n,o,s){return C(n,"rank"),y(n).rank(n,o,s)},rankPage(n,o,s){return C(n,"rankPage"),y(n).rankPage(n,o,s)},wipeShard(){throw new p("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})},...oe("rankBefore",We,n=>(o,s,c)=>(C(o,"rankBefore"),(y(o).rankBefore??n)(o,s,c))),...oe("rankPageRows",Re,n=>(o,s,c)=>(C(o,"rankPageRows"),(y(o).rankPageRows??n)(o,s,c)))};if(a.size>0)for(const[n,o]of Object.entries(e))ct(o)&&Ae(I,n);return Object.defineProperty(I,be,{configurable:!0,enumerable:!1,value:{base:e,raw:t,steps:r},writable:!1}),I},Oe=e=>typeof e=="string"?e:e.name,ft=e=>{const t=new Map;for(const r of e??[])t.set(r.name,new Set((r.permissions??[]).map(i=>Oe(i))));return t},dt=(e,t)=>{const r=new Set;for(const i of e)for(const a of t.get(i)??[])r.add(a);return i=>r.has(Oe(i))},ut=["roles","role"],ht=e=>{for(const t of ut){const r=e?.[t];if(typeof r=="string"){const i=r.split(",").map(a=>a.trim()).filter(a=>a.length>0);if(i.length>0)return i}if(Array.isArray(r)){const i=r.filter(a=>typeof a=="string"&&a.length>0);if(i.length>0)return i}}return[]},yt=async(e,t)=>{const r=await e.getIdentity?.()??null,i=[...new Set([...ht(r),...e.roles??[]])];return{can:dt(i,t),identity:r,roles:i,userId:e.userId??null}},Rt=(e,t={})=>{const r=e,i=Ve(r),a=ft(t.roles);return ke(async({ctx:u,next:g})=>{const y=u,k={auth:await yt(y.auth??{},a),ctx:y},b=y.db,v=Ze(b),$=v?.base??b,z=v?.raw??b[Xe]??b,M=lt($,z,[...v?.steps??[],{context:k,perTable:i}]),R={db:M},{orm:L}=y;return L!==null&&typeof L=="object"&&(R.orm=Te(M)),g({ctx:R})},[{policies:r,roles:t.roles??[]}])};export{yt as a,ct as b,Wt as c,Fe as d,ht as e,et as f,dt as g,rt as h,ft as i,Y as m,oe as o,Rt as r};
@@ -0,0 +1 @@
1
+ const t=(n,c)=>({args:{},handler:(i,o)=>c(i,o),kind:"mutation",lifecycle:n,visibility:"internal"}),e=n=>t("connect",n),r=n=>t("disconnect",n),s=n=>t("init",n);export{e as onConnect,r as onDisconnect,s as onShardInit};
@@ -0,0 +1 @@
1
+ import{stableStringify as o}from"@lunora/wire";import{f as e,F as c,a as f}from"./fnv1a-D3ueNTWB.mjs";const l=r=>`${e(r,c)}${e(r,f)}`,m=(r,i)=>({args:{},handler:async(a,s)=>{const n=await r(a),t=l(o(n));return t===s?.previousDigest?{digest:t,ran:!1}:(await i(a,n),{digest:t,ran:!0})},kind:"mutation",lifecycle:"reactor",visibility:"internal"});export{m as onQueryChange};
@@ -0,0 +1 @@
1
+ const n=r=>({args:{},handler:async(e,i)=>await r(e,i)===!0,kind:"query",lifecycle:"whisper",visibility:"internal"});export{n as onWhisper};
@@ -0,0 +1 @@
1
+ import{LunoraError as t}from"@lunora/errors";const e=r=>async({ctx:o,next:a})=>{if(!await r(o))throw new t("FORBIDDEN","Platform admin access required");return a()};export{e as platformAdmin};
@@ -0,0 +1 @@
1
+ import{LunoraError as s}from"@lunora/errors";import{c as W}from"./compose-middleware-BK9FlblN.mjs";import{v as S}from"@lunora/values";const C=["de","en","es","fr","it","nl","none","pt"],H=["native","portable"],Y=e=>H.includes(e),Z=e=>C.includes(e),ee=e=>{const{value:t}=e._meta??{};if(t===null)return"null";switch(typeof t){case"bigint":case"boolean":case"number":case"string":return typeof t;default:return e.kind}},K=e=>{if(e.kind==="literal")return ee(e);if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?K(t):e.kind},te=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,ne=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,re=(e,t,n)=>e.some(r=>r.unique===!0&&r.fields.length===2&&r.fields.includes(t)&&r.fields.includes(n)),ae=e=>{const t=e?.kind==="id"?e._meta?.tableName:void 0;return typeof t=="string"?t:void 0},oe=(e,t,n,r)=>{const{from:a,table:c,to:d}=r.through,l=`defineSchema: relation "${n}" on table "${t}" (through "${c}")`,f=e[c];if(f===void 0)throw new s("INTERNAL",`${l} names a join table that is not declared`);if(e[r.table]===void 0)throw new s("INTERNAL",`${l} targets "${r.table}", which is not declared`);if(a===d)throw new s("INTERNAL",`${l}: "from" and "to" both name "${a}"; a link needs two different columns`);for(const[p,h]of[[a,t],[d,r.table]])if(ae(f.shape[p])!==h)throw new s("INTERNAL",`${l}: "${c}.${p}" must be a required v.id("${h}") column`);if(!re(f.indexes,a,d))throw new s("INTERNAL",`${l} needs a unique index over ("${a}", "${d}") on "${c}": ${JSON.stringify(`.index("by_${a}_${d}", ["${a}", "${d}"], { unique: true })`)}. Without it a repeated connect stores the same link twice.`);if(f.softDeleteMode!==void 0)throw new s("INTERNAL",`${l}: the join table is .softDelete(), so a disconnected pair could never be linked again (the unique index still holds the soft-deleted row). Hard-delete the soft-deleted rows of "${c}" first, or those links come back, then remove .softDelete() from it.`)},U=e=>{for(const[t,n]of Object.entries(e))for(const[r,a]of Object.entries(n.relationMap))a.through!==void 0&&oe(e,t,r,a)},F=16;function ie(e,t){return"through"in t?{kind:"many",table:e,through:{...t.through}}:{field:t.field,kind:"many",references:t.references??"_id",table:e}}const se={many:ie,one:(e,t)=>({field:t.field,kind:"one",onDelete:t.onDelete,references:t.references??"_id",table:e})},x=(e,t,n)=>({handler:n,op:t,timing:e}),de=()=>({afterDelete:e=>x("after","delete",e),afterInsert:e=>x("after","insert",e),afterUpdate:e=>x("after","update",e),beforeDelete:e=>x("before","delete",e),beforeInsert:e=>x("before","insert",e),beforeUpdate:e=>x("before","update",e)}),Q=(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}))},Te=e=>{const t={...e},n=[],r=[],a=[],c=[],d={},l=[],f={},p=de(),h=[];let m={kind:"root"},g=!1,R=!1,k=!1,M=!1,O=!1,D,T,I;const j=(i,o)=>{i in t||(t[i]=o)};let _,B;const q=i=>{if(m.kind!=="root"&&m.kind!==i.kind)throw new s("INTERNAL","shardBy/global: a table cannot be both .shardBy(key) and .global() — pick one. .shardBy(key) puts the rows in one Durable Object per key (isolation, poke-live reactivity); .global() puts them in a single replicated backend read from the edge.");m=i},u={aggregateIndex(i,o){const b=o?.op??"count";if(b!=="count"&&!o?.field)throw new s("INTERNAL",`aggregateIndex "${i}": op "${b}" requires a "field"`);return n.push({by:o?.by,field:o?.field,name:i,on:"",op:b,where:o?.where}),u},get aggregateIndexes(){return n},get externalSource(){return B},commitOrdered(){return g=!0,u},get commitOrderedMode(){return g},dropStalePatches(){return R=!0,u},get dropStalePatchesMode(){return R},externallyManaged(){return k=!0,u},geoIndex(i,o){return r.push({field:o.field,name:i,precision:o.precision}),u},get geoIndexes(){return r},global(i){return q({backend:i?.backend??"d1",kind:"global"}),u},get isExternallyManaged(){return k},get isPublic(){return O},index(i,o,b){return a.push({fields:o,name:i,unique:b?.unique??!1}),u},get indexes(){return a},memory(){return M=!0,u},get memoryMode(){return M},ownedBy(i){return D=i,u},get ownerField(){return D},public(){return O=!0,u},rankIndex(i,o){return c.push({name:i,on:"",partitionBy:o.partitionBy,sortBy:Q(i,o.sortBy),where:o.where}),u},get rankIndexes(){return c},get relationMap(){return d},relations(i){return Object.assign(d,i(se)),u},searchIndex(i,o){if(o.filterFields&&o.filterFields.length>F)throw new s("INTERNAL",`searchIndex "${i}": at most ${String(F)} filterFields are supported (got ${String(o.filterFields.length)})`);const{language:b}=o;if(b!==void 0&&!Z(b))throw new s("INTERNAL",`searchIndex "${i}": unknown language "${b}" (supported: ${C.join(", ")})`);const{strategy:w}=o;if(w!==void 0&&!Y(w))throw new s("INTERNAL",`searchIndex "${i}": unknown strategy "${w}" (supported: ${H.join(", ")})`);return l.push({field:o.field,filterFields:o.filterFields,language:o.language,name:i,staged:o.staged,strategy:o.strategy}),u},get searchIndexes(){return l},shape:t,shardBy(i){return q({field:i,kind:"shardBy"}),u},get shardMode(){return m},get softDeleteMode(){return T},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 B=i,k=!0,u},softDelete(i){const o=i?.field??"deletedAt";if(T={field:o},o===I)throw new s("INTERNAL",`defineTable: .softDelete() and .timestamps() both use "${o}"; give one of them another field`);return j(o,S.optional(S.number().nullable())),u},timestamps(i){const o=i?.field??"updatedAt";if(I!==void 0)throw new s("INTERNAL",`defineTable: .timestamps() was called twice ("${I}" and "${o}"); one table tracks one last-change column`);if(o===T?.field)throw new s("INTERNAL",`defineTable: .softDelete() and .timestamps() both use "${o}"; give one of them another field`);const b=t[o],w=b?._meta?.column;if(b!==void 0&&(b.kind!=="timestamp"||w?.onUpdateFn===void 0||w.defaultFn===void 0&&w.defaultValue===void 0))throw new s("INTERNAL",`defineTable: .timestamps() would add "${o}", but the table already declares it as something other than v.timestamp().defaultNow().$onUpdateFn(() => Date.now()); remove the column or declare it that way`);return I=o,j(o,S.timestamp().defaultNow().$onUpdateFn(()=>Date.now())),u},get triggerMap(){return f},triggers(i){return Object.assign(f,i(p)),u},ttl(i,o){return _={after:o?.after,field:i},u},get ttlPolicy(){return _},get vectorIndexes(){return h},vectorize(i,o){return h.push({dimensions:o.dimensions,embed:o.embed,field:i,metadata:o.metadata,metric:o.metric,model:o.model,name:o.index}),u}};return u},Se=e=>({dimensions:e.dimensions,embed:e.embed,kind:"vectorIndex",metadata:e.metadata,metric:e.metric,model:e.model,select:e.source.select,table:e.source.table}),Le=(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}},Ae=(e,t)=>({name:e,on:t.table,partitionBy:t.partitionBy,sortBy:Q(e,t.sortBy),where:t.where}),v=e=>({...e,extend(t){return v(J(e,t))},jurisdiction(t,n){return v(e)},rls(t){return v({...e,rlsMode:t})}}),le=e=>{for(const[t,n]of Object.entries(e))for(const r of[...n.aggregateIndexes,...n.rankIndexes])r.on===""&&(r.on=t)},ce=(e,t,n)=>{for(const r of Object.values(t)){const a=e[r.on];if(!a)throw new s("INTERNAL",`defineAggregateIndex "${r.name}": unknown table "${r.on}"`);a.aggregateIndexes.push(r)}for(const r of Object.values(n)){const a=e[r.on];if(!a)throw new s("INTERNAL",`defineRankIndex "${r.name}": unknown table "${r.on}"`);a.rankIndexes.push(r)}},ue=e=>{if(e.cursor)return"cursor";if(e.reconcileEveryMs!==void 0)return"reconcileEveryMs";if(e.softDeleteColumn!==void 0)return"softDeleteColumn"},he=(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=ue(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).`)},fe=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.`);he(t,r)}}},me=["_commitSeq","_creationTime","_id"],P="_commitSeq",be=new Set(me),N=(e,t,n,r)=>{if(!(be.has(n)||n in r.shape))throw n.includes(".")?new s("INDEX_FIELD_NESTED_PATH",`defineSchema: table "${e}" index "${t}" indexes the nested path ${JSON.stringify(n)}, but indexes cover top-level columns only. Denormalise the value into its own column and index that instead.`):new s("INTERNAL",`defineSchema: table "${e}" index "${t}" names column "${n}" which is not in the table's shape`)},L=(e,t,n,r)=>{const a=new Set;for(const c of n){if(a.has(c.name))throw new s("INTERNAL",`defineSchema: table "${e}" declares ${t} "${c.name}" more than once`);a.add(c.name),r(c)}},z=e=>{for(const[t,n]of Object.entries(e))L(t,"index",n.indexes,r=>{for(const a of r.fields)N(t,r.name,a,n)}),L(t,"rank index",n.rankIndexes,r=>{for(const a of r.sortBy)N(t,r.name,a.field,n);for(const a of r.partitionBy??[])N(t,r.name,a,n)}),L(t,"geo index",n.geoIndexes,r=>{N(t,r.name,r.field,n)})},A=(e,t,n)=>{if(e.length===0)return;const r={};for(const a of e)r[t(a)]=n(a);return r},ge=e=>{const t=new Set(e.sortBy.map(n=>n.field));for(const n of e.partitionBy??[])t.add(n);return[...t]},Re=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const a=A(r.geoIndexes,l=>l.name,l=>[l.field]),c=A(r.indexes,l=>l.name,l=>l.fields),d=A(r.rankIndexes,l=>l.name,ge);(a||c||d)&&(t[n]={...a?{geo:a}:{},...c?{index:c}:{},...d?{rank:d}:{}})}return t},we=e=>{for(const[t,n]of Object.entries(e)){if(!n.memoryMode)continue;const a=[[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(([c])=>c)?.[1];if(a!==void 0)throw new s("INTERNAL",`defineSchema: table "${t}" is both .memory() and ${a}. Plain .index() is supported; SQLite maintains it through the DELETE.`)}},pe=e=>{for(const[t,n]of Object.entries(e))if(n.shardMode.kind==="global"){for(const[r,a]of Object.entries(n.shape))if(K(a)==="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.`)}},xe=e=>{for(const[t,n]of Object.entries(e))if(n.dropStalePatchesMode===!0&&n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: table "${t}" is both .global() and .dropStalePatches(). The stale check reads the caller's baseline out of the shard's \`__cdc_log\`, which a global (D1/Hyperdrive) table has no entries in — so every patch would read as "no baseline" and apply unchanged. Drop one of the two.`)},ye=e=>{for(const[t,n]of Object.entries(e))if(n.ttlPolicy!==void 0&&n.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: ${te(t)}`)},X=(e,t)=>{const n=[...Object.entries(e).flatMap(([r,a])=>a.vectorIndexes.map(c=>[r,c.name])),...Object.entries(t).map(([r,a])=>[a.table,r])];for(const[r,a]of n)if(e[r]?.shardMode.kind==="global")throw new s("INTERNAL",`defineSchema: ${ne(r,a)}`)},Ie=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(P))throw new s("INTERNAL",`defineSchema: table "${t}" index "${r.name}" names "${P}", 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.`)}},G=e=>{Ie(e),xe(e),pe(e),ye(e),we(e)},Me=(e,t={},n={},r={})=>(le(e),ce(e,n,r),fe(e),G(e),X(e,t),z(e),U(e),v({tables:e,vectorIndexes:t})),E=(e,t)=>`${e}_${t}`,y=(e,t,n)=>n.has(e)?E(t,e):e,V=(e,t)=>({...e,_meta:t}),$=(e,t)=>{const n=e._meta;if(n===void 0)return e;if(e.kind==="id"&&n.tableName!==void 0){const d=t(n.tableName);return d===n.tableName?e:V(e,{...n,tableName:d})}const r=d=>d===void 0?void 0:$(d,t),a={...n,...n.inner&&{inner:r(n.inner)},...n.keyValidator&&{keyValidator:r(n.keyValidator)},...n.valueValidator&&{valueValidator:r(n.valueValidator)},...n.members&&{members:n.members.map(d=>$(d,t))},...n.shape&&{shape:Object.fromEntries(Object.entries(n.shape).map(([d,l])=>[d,$(l,t)]))}};return a.inner===n.inner&&a.keyValidator===n.keyValidator&&a.valueValidator===n.valueValidator&&(a.members??[]).every((d,l)=>d===n.members?.[l])&&Object.entries(a.shape??{}).every(([d,l])=>l===n.shape?.[d])?e:V(e,a)},Ne=(e,t,n,r)=>{const a=E(t,r),c=h=>h===""?a:y(h,t,n),d={};for(const[h,m]of Object.entries(e.relationMap)){const g=y(m.table,t,n);d[h]=m.through===void 0?{...m,table:g}:{...m,table:g,through:{...m.through,table:y(m.through.table,t,n)}}}const l=e.aggregateIndexes.map(h=>({...h,on:c(h.on)})),f=e.rankIndexes.map(h=>({...h,on:c(h.on)})),p=Object.fromEntries(Object.entries(e.shape).map(([h,m])=>[h,$(m,g=>y(g,t,n))]));return{...e,aggregateIndexes:l,rankIndexes:f,relationMap:d,shape:p}},Oe=(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}:{}}},ve=((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}:{}}}),De=(e,t)=>({...ve(e,{...t.extension?{extension:t.extension}:{},...t.middleware?{middleware:t.middleware}:{}}),functions:t.functions??{}}),J=(e,t)=>{const{key:n}=t,r=new Set(Object.keys(t.tables)),a={...e.tables};for(const[d,l]of Object.entries(t.tables)){const f=E(n,d);if(Object.hasOwn(a,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`);a[f]=Ne(l,n,r,d)}const c={...e.vectorIndexes};if(t.vectorIndexes)for(const[d,l]of Object.entries(t.vectorIndexes)){const f=E(n,d);if(Object.hasOwn(c,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`);c[f]={...l,table:y(l.table,n,r)}}return z(a),G(a),X(a,c),U(a),{rlsMode:e.rlsMode,tables:a,vectorIndexes:c}},je=(e,t)=>{let n=e;for(const r of t)r.extension&&(n=J(n,r.extension));return n},_e=e=>{const t=e.map(n=>n.middleware).filter(n=>n!==void 0);return W(t)};export{De as a,ve as b,_e as c,Le as d,Ae as e,Me as f,Oe as g,Te as h,Se as i,Re as j,je as k,z as l,J as m,G as n,X 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-BK9FlblN.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,2 @@
1
+ const l=t=>t.endsWith("S")?t.slice(0,-1):t,_=t=>t.replaceAll(/([a-z\d])([A-Z])/gu,"$1_$2").toUpperCase().split(/[_-]+/u).filter(e=>e.length>0),a=new Set(["CREDENTIAL","DSN","PASSPHRASE","PASSWD","PASSWORD","SECRET","TOKEN"]),A=["ACCESS_KEY","API_KEY","ENCRYPTION_KEY","PRIVATE_KEY","SIGNING_KEY"],i=new RegExp(`(?:${[...a,...A.map(t=>t.replaceAll("_",""))].join("|")})S?$`,"iu"),S=t=>_(t).some(e=>e==="PUBLIC"||e==="PUBLISHABLE"),h=t=>{if(S(t))return!1;const e=_(t);if(e.some(n=>a.has(l(n))))return!0;const r=l(e.join("_"));return A.some(n=>r===n||r.endsWith(`_${n}`))||i.test(t)},p=[/^sk_/u,/^pk_/u,/^rk_/u,/^ghp_/u,/^gho_/u,/^ghs_/u,/^ghr_/u,/^github_pat_/u,/^xox[baprs]-/u,/^AKIA/u,/^AIza/u,/^Bearer\s/u],R=/[\w./+-]{24,}/gu,I=/^[\w./+-]+$/u,T=/\b(?:(?:sk|pk|rk|ghp|gho|ghs|ghr)_[\w./+-]*|github_pat_[\w./+-]*|xox[baprs]-[\w./+-]*)/gu,N=/\b(?:AKIA|AIza)[\w./+-]+|Bearer\s+[\w./+-]+/gu,D=/:\/\/([\w.%+-]*):[\w.%+\-!$&'()*,;=~]+@/gu,E="[redacted]",K=t=>{if(p.some(r=>r.test(t)))return!0;const e=t.trim();return e.length>=24&&I.test(e)},u=new Set([`
2
+ `,"\r","\u2028","\u2029"]),g=(t,e)=>{const r=t.charAt(e);let n=-1,c=e+1;for(;c<t.length;){const s=t.charAt(c);if(s===r)return c;if(u.has(s))break;const o=t.charAt(c+1);s==="\\"&&c+1<t.length&&!u.has(o)?(o===r&&(n=c+1),c+=2):c+=1}return n},d=(t,e)=>{let r="",n=0;for(;n<t.length;){const c=t.charAt(n),s=c==='"'||c==="'"?g(t,n):-1;s===-1?(r+=c,n+=1):(r+=e(t.slice(n,s+1),t.slice(n+1,s)),n=s+1)}return r},O=/\b(?<key>[A-Za-z_]\w*)\s*[=:]\s*(?:"(?:[^"\\\n]|\\[^\n])*"|'(?:[^'\\\n]|\\[^\n])*'|\S+)/gu,P=t=>{let e=t;return e=d(e,(r,n)=>K(n)?E:r),e=e.replaceAll(D,(r,n)=>`://${n}:${E}@`),e=e.replaceAll(T,E),e=e.replaceAll(N,E),e=e.replaceAll(O,(r,...n)=>{const c=n.at(-1);return c?.key!==void 0&&h(c.key)?`${c.key}=${E}`:r}),e=e.replaceAll(R,E),e};export{E as R,h as i,P as r};
@@ -0,0 +1 @@
1
+ import{R as a,r as s}from"./redact-secrets-BpatNz48.mjs";export{a as REDACTED,s as redactSecrets};
@@ -0,0 +1 @@
1
+ import{f as t,h as i,i as m,b as l,m as d,e as h,g as n,a as p,r as c}from"./middleware-CHYtnvZP.mjs";import"./bindOrm-D5mVDvbi.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{t as computeReadBaseWhere,i as evaluateWrite,m as indexRolePermissions,l as isFacadeEntry,d as matchesWhere,h as readIdentityRoles,n as resolveCan,p as resolvePolicyAuth,c as rls};
@@ -0,0 +1 @@
1
+ import{LunoraError as u}from"@lunora/errors";const w=(e,t,r)=>{const o=t.get!==void 0||t.set!==void 0;if(!o&&!Object.hasOwn(e,r)){Reflect.set(e,r,t.value);return}Object.defineProperty(e,r,o?{...t,configurable:!0}:{configurable:!0,enumerable:!0,value:t.value,writable:!0})},f=(e,t)=>{const r=typeof e=="object"&&e!==null?e:{},o=Object.create(Object.getPrototypeOf(r));for(const a of[r,t])for(const n of Reflect.ownKeys(a)){const s=Object.getOwnPropertyDescriptor(a,n);s?.enumerable&&w(o,s,n)}return o},b=async(e,t,r)=>{let o=-1;const a=async(n,s)=>{if(n<=o)throw new u("INTERNAL","middleware next() called multiple times");o=n;const l=e[n];if(!l)return r(s);const c={promise:void 0},d=await l({ctx:s,next:(i=>(c.promise=a(n+1,i?.ctx?f(s,i.ctx):s),c.promise))});if(c.promise===void 0)throw new u("INTERNAL",`middleware at position ${String(n)} resolved without calling next(): every later .use() step (rls/mask/storageRules) and the handler's context were skipped. Return next() — or next({ ctx }) to extend the context — and throw to deny.`);return await c.promise,d};return a(0,t)};export{f as e,b as r};
@@ -0,0 +1 @@
1
+ import{isSafeHeaderValue as b}from"./isSafeHeaderValue-DswDADFy.mjs";const N=/^bytes=(\d*)-(\d*)$/,g=t=>t.startsWith('"')||t.startsWith('W/"')?t:`"${t}"`,R=/(?:W\/)?"[^"]*"/g,p=t=>t.startsWith("W/")?t.slice(2):t,S=(t,e)=>{if(t.trim()==="*")return!0;const n=p(g(e));return(t.match(R)??[]).some(s=>p(s)===n)},m=(t,e)=>{if(t===null)return{kind:"full"};const n=N.exec(t.trim());if(!n)return{kind:"full"};const s=n[1]??"",a=n[2]??"";if(s===""&&a==="")return{kind:"full"};let r,o;if(s===""){const u=Number(a);if(u===0)return{kind:"unsatisfiable"};r=Math.max(0,e-u),o=e-1}else r=Number(s),o=a===""?e-1:Math.min(Number(a),e-1);return r>o||r>=e?{kind:"unsatisfiable"}:{end:o,kind:"partial",start:r}},v=new Set(["audio/mpeg","audio/ogg","audio/wav","image/apng","image/avif","image/gif","image/jpeg","image/png","image/webp","video/mp4","video/webm"]),w=(t,e)=>{const n=t.httpMetadata?.contentType,s=n!==void 0&&b(n)?n:"application/octet-stream",a={"accept-ranges":"bytes","cache-control":e,"content-type":s,etag:g(t.etag),"x-content-type-options":"nosniff"};return v.has(s.split(";")[0]?.trim().toLowerCase()??"")||(a["content-disposition"]="attachment"),t.sha256Base64!==void 0&&(a["repr-digest"]=`sha-256=:${t.sha256Base64}:`),a},y=t=>m(t,0).kind==="full",h=async(t,e,n)=>{const s=await t.storage.download(e);return s?new Response(s.body,{headers:{...w(s,n),"content-length":String(s.size)},status:200}):new Response("Not Found",{status:404})},T=async(t,e,n)=>{try{return await t({key:e,request:n})===!0}catch{return!1}},W=async(t,e,n,s,a="no-store")=>{if(!await T(s,e,n))return new Response("Forbidden",{status:403});const r=n.headers.get("if-none-match");let o;if(r!==null){const d=await t.storage.head(e);if(!d)return new Response("Not Found",{status:404});if(S(r,d.etag))return new Response(void 0,{headers:{"cache-control":a,etag:g(d.etag)},status:304});o=d}const u=n.headers.get("range");if(y(u))return h(t,e,a);const c=o??await t.storage.head(e);if(!c)return new Response("Not Found",{status:404});const i=m(u,c.size);if(i.kind==="unsatisfiable")return new Response("Range Not Satisfiable",{headers:{"accept-ranges":"bytes","content-range":`bytes */${String(c.size)}`,"content-type":"text/plain; charset=utf-8",etag:g(c.etag)},status:416});if(i.kind==="full")return h(t,e,a);const f=i.end-i.start+1,l=await t.storage.download(e,{range:{length:f,offset:i.start}});return l?new Response(l.body,{headers:{...w(c,a),"content-length":String(f),"content-range":`bytes ${String(i.start)}-${String(i.end)}/${String(c.size)}`},status:206}):new Response("Not Found",{status:404})};export{W as serveStorageObject};
@@ -0,0 +1 @@
1
+ import{LunoraError as k}from"@lunora/errors";import{i as A,a as D}from"./middleware-CHYtnvZP.mjs";const E=(e,t,o)=>{const i=n=>o.isAllowed("list",n,t)&&o.isAllowed("read",n,t),{get:c,query:g}=e,f={...e},b=n=>n.filter(r=>typeof r.key=="string"&&i(r.key));return typeof c=="function"&&(f.get=async(n,r)=>(n==="_storage"&&o.assertAllowed("read",r,t),c(n,r))),typeof g=="function"&&(f.query=n=>{const r=g(n),{collect:p}=r;return n!=="_storage"||typeof p!="function"?r:{...r,collect:async()=>b(await p())}}),f},N=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},S=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},M=[["createMultipartUpload","write"],["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",S],["getUrl","read"],["head","read"],["resumeMultipartUpload","write"],["store","write"],["upload","write"]],$=[["getPresignedUrl","ctx.storage.getPresignedUrl is not available under storageRules(...): a presigned URL reaches R2 directly, past every rule. Use getSignedUrl or generateUploadUrl, which route back through the Worker."],["list",'ctx.storage.list is not available under storageRules(...); enumerate via ctx.db.system.query("_storage"), which the rules filter.']],P=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},B=(e,t)=>{const o=e.bucketName??"default",{bucket:i}=e;for(const c of new Set(t))if(!(c===o||typeof i=="function"&&P(i,c)))throw new k("INTERNAL",`storageRules: rule for bucket "${c}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${c}" does not reach a bucket of that name). A rule on an unaddressable bucket leaves the operation it was written to gate wide open. Match the rule's \`bucket\` to the name the binding is registered under in \`.storage({ bucket, buckets })\`.`)},_=(e,t={})=>{const o=A(t.roles);return async({ctx:i,next:c})=>{const g=await D(i.auth??{},o),f=(s,d,u)=>{const h=e.filter(a=>a.on===s&&a.bucket===u);if(h.length===0)return!0;const l={auth:g,ctx:i,key:d};return h.some(a=>N(a.prefix,d)&&a.when(l)===!0)},b=(s,d,u)=>{if(!f(s,d,u))throw new k("FORBIDDEN",`storage ${s} on "${d}" in bucket "${u}" denied by access rule`)},n=s=>{const d=s.bucketName??"default",u={bucketName:d};for(const[l,a]of M){const U=s[l];typeof U=="function"&&(u[l]=(...w)=>{const R=typeof w[0]=="string"?w[0]:"",v=typeof a=="function"?a(w):a;return b(v,R,d),U(...w)})}for(const[l,a]of $)typeof s[l]=="function"&&(u[l]=async()=>{throw new k("FORBIDDEN",a)});const{bucket:h}=s;return typeof h=="function"&&(u.bucket=l=>n(h(l))),u},r=i.storage;if(r===void 0)return c();B(r,e.map(s=>s.bucket));const p={storage:n(r)},y=i.db,m=y?.system;return y!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...y,system:E(m,r.bucketName??"default",{assertAllowed:b,isAllowed:f})}),c({ctx:p})}};export{_ as storageRules};
@@ -32,7 +32,7 @@ type PolicyDecision = WhereInput | boolean | undefined;
32
32
  * generated `DataModel` (`DM`) + `Relations` (`REL`) maps and a table `T`. A
33
33
  * read policy may now return a Prisma-style relation predicate (the
34
34
  * `@lunora/do` pre-resolver resolves it via a semijoin), so the typed
35
- * authoring surface accepts `WhereOf&lt;DM, REL, T>` — column predicates **and**
35
+ * authoring surface accepts `WhereOf<DM, REL, T>` — column predicates **and**
36
36
  * `is`/`isNot`/`some`/`none`/`every` over `T`'s declared relations — in
37
37
  * addition to the `boolean`/`undefined` decisions. Used by the project-bound
38
38
  * `definePolicy` from `createPolicyDsl`.
@@ -51,8 +51,12 @@ interface TypedDefinePolicyInput<DM, REL extends Record<keyof DM, object>, T ext
51
51
  when: (context: PolicyContext<Context, Identity>) => PolicyDecisionOf<DM, REL, T>;
52
52
  }
53
53
  /**
54
- * Context handed to a policy. `auth.roles` is the per-request role list,
55
- * sourced from the identity resolver (better-auth claims today). `auth.can`
54
+ * Context handed to a policy. `auth.roles` is the per-request role list, read
55
+ * from the `roles` CLAIM on the resolved identity — a `string[]` or a
56
+ * comma-separated string returned by `WorkerOptions.resolveIdentity` (and
57
+ * validated by `defineIdentity(...)` at the worker's trust boundary). A
58
+ * resolver that forwards no `roles` claim yields no roles, so every
59
+ * role-branched policy is evaluated against `[]`. `auth.can`
56
60
  * answers whether any of those roles grants a permission (see
57
61
  * {@link Permission} / {@link RlsOptions}). `row` is present only on write
58
62
  * policies (`insert`/`update`/`delete`) — for `update` and `delete` it is the
@@ -117,10 +121,13 @@ interface Permission {
117
121
  readonly name: string;
118
122
  }
119
123
  /**
120
- * A role declaration. Roles are string labels attached to the request's
121
- * identity (via better-auth claims today). `permissions` lists the
122
- * capabilities the role grants — at request time the middleware unions the
123
- * permissions of every role in `ctx.auth.roles` so a policy can ask
124
+ * A role declaration. Roles are string labels the request carries in the
125
+ * `roles` claim of its resolved identity — `WorkerOptions.resolveIdentity`
126
+ * forwards every non-`userId` key verbatim, so a resolver returning
127
+ * `{ userId, roles: ["admin"] }` (or the comma-joined `"user,admin"` that
128
+ * better-auth's `admin()` plugin stores) is what puts them there. `permissions`
129
+ * lists the capabilities the role grants — at request time the middleware
130
+ * unions the permissions of every role in `ctx.auth.roles` so a policy can ask
124
131
  * `ctx.auth.can(permission)` rather than enumerate roles.
125
132
  */
126
133
  interface Role {
@@ -138,4 +145,4 @@ interface Role {
138
145
  interface RlsOptions {
139
146
  readonly roles?: ReadonlyArray<Role>;
140
147
  }
141
- export { DefinePolicyInput as D, PolicyOperation as P, Role as R, TypedDefinePolicyInput as T, WhereInput as W, Policy as a, Permission as b, RlsOptions as c, PolicyContext as d, PolicyDecision as e, PolicyDecisionOf as f };
148
+ export { DefinePolicyInput as D, PolicyOperation as P, Role as R, TypedDefinePolicyInput as T, WhereInput as W, Policy as a, RlsOptions as b, Permission as c, PolicyContext as d, PolicyDecision as e, PolicyDecisionOf as f };
@@ -32,7 +32,7 @@ type PolicyDecision = WhereInput | boolean | undefined;
32
32
  * generated `DataModel` (`DM`) + `Relations` (`REL`) maps and a table `T`. A
33
33
  * read policy may now return a Prisma-style relation predicate (the
34
34
  * `@lunora/do` pre-resolver resolves it via a semijoin), so the typed
35
- * authoring surface accepts `WhereOf&lt;DM, REL, T>` — column predicates **and**
35
+ * authoring surface accepts `WhereOf<DM, REL, T>` — column predicates **and**
36
36
  * `is`/`isNot`/`some`/`none`/`every` over `T`'s declared relations — in
37
37
  * addition to the `boolean`/`undefined` decisions. Used by the project-bound
38
38
  * `definePolicy` from `createPolicyDsl`.
@@ -51,8 +51,12 @@ interface TypedDefinePolicyInput<DM, REL extends Record<keyof DM, object>, T ext
51
51
  when: (context: PolicyContext<Context, Identity>) => PolicyDecisionOf<DM, REL, T>;
52
52
  }
53
53
  /**
54
- * Context handed to a policy. `auth.roles` is the per-request role list,
55
- * sourced from the identity resolver (better-auth claims today). `auth.can`
54
+ * Context handed to a policy. `auth.roles` is the per-request role list, read
55
+ * from the `roles` CLAIM on the resolved identity — a `string[]` or a
56
+ * comma-separated string returned by `WorkerOptions.resolveIdentity` (and
57
+ * validated by `defineIdentity(...)` at the worker's trust boundary). A
58
+ * resolver that forwards no `roles` claim yields no roles, so every
59
+ * role-branched policy is evaluated against `[]`. `auth.can`
56
60
  * answers whether any of those roles grants a permission (see
57
61
  * {@link Permission} / {@link RlsOptions}). `row` is present only on write
58
62
  * policies (`insert`/`update`/`delete`) — for `update` and `delete` it is the
@@ -117,10 +121,13 @@ interface Permission {
117
121
  readonly name: string;
118
122
  }
119
123
  /**
120
- * A role declaration. Roles are string labels attached to the request's
121
- * identity (via better-auth claims today). `permissions` lists the
122
- * capabilities the role grants — at request time the middleware unions the
123
- * permissions of every role in `ctx.auth.roles` so a policy can ask
124
+ * A role declaration. Roles are string labels the request carries in the
125
+ * `roles` claim of its resolved identity — `WorkerOptions.resolveIdentity`
126
+ * forwards every non-`userId` key verbatim, so a resolver returning
127
+ * `{ userId, roles: ["admin"] }` (or the comma-joined `"user,admin"` that
128
+ * better-auth's `admin()` plugin stores) is what puts them there. `permissions`
129
+ * lists the capabilities the role grants — at request time the middleware
130
+ * unions the permissions of every role in `ctx.auth.roles` so a policy can ask
124
131
  * `ctx.auth.can(permission)` rather than enumerate roles.
125
132
  */
126
133
  interface Role {
@@ -138,4 +145,4 @@ interface Role {
138
145
  interface RlsOptions {
139
146
  readonly roles?: ReadonlyArray<Role>;
140
147
  }
141
- export { DefinePolicyInput as D, PolicyOperation as P, Role as R, TypedDefinePolicyInput as T, WhereInput as W, Policy as a, Permission as b, RlsOptions as c, PolicyContext as d, PolicyDecision as e, PolicyDecisionOf as f };
148
+ export { DefinePolicyInput as D, PolicyOperation as P, Role as R, TypedDefinePolicyInput as T, WhereInput as W, Policy as a, RlsOptions as b, Permission as c, PolicyContext as d, PolicyDecision as e, PolicyDecisionOf as f };