@lunora/server 1.0.0-alpha.21 → 1.0.0-alpha.211
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +213 -0
- package/README.md +18 -12
- package/dist/data-model.d.mts +392 -170
- package/dist/data-model.d.ts +392 -170
- package/dist/data-model.mjs +0 -1
- package/dist/drizzle.mjs +1 -1
- package/dist/in-process.d.mts +101 -0
- package/dist/in-process.d.ts +101 -0
- package/dist/in-process.mjs +1 -0
- package/dist/index.d.mts +3618 -1548
- package/dist/index.d.ts +3618 -1548
- package/dist/index.mjs +1 -29
- package/dist/otel.d.mts +554 -0
- package/dist/otel.d.ts +554 -0
- package/dist/otel.mjs +1 -0
- package/dist/packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-mmP-6BcT.mjs +1 -0
- package/dist/packem_shared/DEFAULT_LIMIT-pT_tV8R0.mjs +1 -0
- package/dist/packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-B5Zp-7SI.mjs +1 -0
- package/dist/packem_shared/LunoraEnvError-bkdMu_-N.mjs +4 -0
- package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-DFpy5J8G.mjs +1 -0
- package/dist/packem_shared/allowAll-DkRAgItV.mjs +1 -0
- package/dist/packem_shared/apply-output-C5wZ5EAL.mjs +1 -0
- package/dist/packem_shared/asBucketStorage-DoGYOjq3.mjs +1 -0
- package/dist/packem_shared/assertShapesDeclareReadPolicies-Bg4Ter7Q.mjs +1 -0
- package/dist/packem_shared/beginDeferredDeletes-DhwFBbvs.mjs +1 -0
- package/dist/packem_shared/beginDeferredSchedules-C7QLYr6C.mjs +1 -0
- package/dist/packem_shared/bindOrm-9fbLRbOb.mjs +1 -0
- package/dist/packem_shared/buildMaskRegistry-DpWMtalG.mjs +1 -0
- package/dist/packem_shared/compose-middleware-BK9FlblN.mjs +1 -0
- package/dist/packem_shared/composePluginMiddleware-ZtDIkbvJ.mjs +1 -0
- package/dist/packem_shared/context-identity-B2XYGA0B.mjs +1 -0
- package/dist/packem_shared/createPolicyDsl-BZa6SqLJ.mjs +1 -0
- package/dist/packem_shared/createSecrets-D6rLB42U.mjs +1 -0
- package/dist/packem_shared/createServices-IJvoqi0e.mjs +1 -0
- package/dist/packem_shared/defineAggregateIndex-DF8NiKHr.mjs +1 -0
- package/dist/packem_shared/defineIdentity-DwkNKwYa.mjs +1 -0
- package/dist/packem_shared/defineIdentityGuard-Bt8N65Zs.mjs +1 -0
- package/dist/packem_shared/defineMigration-CXOS0Bvq.mjs +1 -0
- package/dist/packem_shared/defineModule-OecXWM3U.mjs +1 -0
- package/dist/packem_shared/defineMutator-B4ipDtDR.mjs +1 -0
- package/dist/packem_shared/defineRoom-CoGi-xwm.mjs +1 -0
- package/dist/packem_shared/defineShape-CwKm5KLp.mjs +1 -0
- package/dist/packem_shared/defineStorageRule-Dv4nJE0H.mjs +1 -0
- package/dist/packem_shared/fnv1a-D3ueNTWB.mjs +1 -0
- package/dist/packem_shared/functions-B2-H4PQT.mjs +1 -0
- package/dist/packem_shared/httpAction-D2S7bQzl.mjs +6 -0
- package/dist/packem_shared/initLunora-B-7Xs3Qq.mjs +1 -0
- package/dist/packem_shared/isPerDispatchMiddleware-DDQPatSm.mjs +1 -0
- package/dist/packem_shared/mask-D-jRCAhy.mjs +1 -0
- package/dist/packem_shared/middleware-3ySZVrpt.mjs +1 -0
- package/dist/packem_shared/onConnect-BLRoOpv2.mjs +1 -0
- package/dist/packem_shared/onQueryChange-iuLzmyPs.mjs +1 -0
- package/dist/packem_shared/onWhisper-CfDbFLQh.mjs +1 -0
- package/dist/packem_shared/platformAdmin-kczXQme8.mjs +1 -0
- package/dist/packem_shared/plugin-Bm9wIpiI.mjs +1 -0
- package/dist/packem_shared/policy-tag-V0lqFzgS.mjs +1 -0
- package/dist/packem_shared/protectPublic-Bi5_95aP.mjs +1 -0
- package/dist/packem_shared/rls-Dwj6TlY_.mjs +1 -0
- package/dist/packem_shared/run-middleware-BefYq7Xd.mjs +1 -0
- package/dist/packem_shared/serveStorageObject-aqBFrLyo.mjs +1 -0
- package/dist/packem_shared/storageRules-CBLioxF7.mjs +1 -0
- package/dist/packem_shared/types.d-B7FLdYUD.d.mts +148 -0
- package/dist/packem_shared/types.d-BCtjbIzl.d.ts +148 -0
- package/dist/rls/testing.d.mts +42 -34
- package/dist/rls/testing.d.ts +42 -34
- package/dist/rls/testing.mjs +1 -49
- package/dist/types.d.mts +2234 -623
- package/dist/types.d.ts +2234 -623
- package/dist/types.mjs +0 -31
- package/package.json +24 -6
- package/dist/packem_shared/LunoraEnvError-BGmd1Qs0.mjs +0 -187
- package/dist/packem_shared/LunoraError-WbxmrpxR.mjs +0 -9
- package/dist/packem_shared/PRESENCE_DEFAULT_TTL_MS-BtPCiNLW.mjs +0 -114
- package/dist/packem_shared/asBucketStorage-Cnxd9y2q.mjs +0 -11
- package/dist/packem_shared/bindOrm-Bfgl7f-Q.mjs +0 -146
- package/dist/packem_shared/buildRlsReadRegistry-D54vUQe4.mjs +0 -107
- package/dist/packem_shared/composePluginMiddleware-CcTj1_v2.mjs +0 -103
- package/dist/packem_shared/createPolicyDsl-By3QB4he.mjs +0 -32
- package/dist/packem_shared/createSecrets-DwaR2rNG.mjs +0 -58
- package/dist/packem_shared/defineAggregateIndex-znq4ygKQ.mjs +0 -295
- package/dist/packem_shared/defineIdentity-DiX4zM9x.mjs +0 -35
- package/dist/packem_shared/defineMigration-Hx01yIht.mjs +0 -10
- package/dist/packem_shared/defineMutator-EIXAWhs9.mjs +0 -11
- package/dist/packem_shared/defineShape-C5scNOrf.mjs +0 -18
- package/dist/packem_shared/defineStorageRule-B5nL4Z1P.mjs +0 -23
- package/dist/packem_shared/functions-Di9FUNkf.mjs +0 -5
- package/dist/packem_shared/httpAction-DCXoYPIk.mjs +0 -355
- package/dist/packem_shared/initLunora-sQUqaejx.mjs +0 -100
- package/dist/packem_shared/mask-BT1YgRbF.mjs +0 -291
- package/dist/packem_shared/onConnect-CIPXKPyw.mjs +0 -13
- package/dist/packem_shared/policy-tag-DvpVH2tv.mjs +0 -13
- package/dist/packem_shared/protectPublic-BlcGpiRc.mjs +0 -15
- package/dist/packem_shared/rls-B_ZWgslr.mjs +0 -595
- package/dist/packem_shared/run-middleware-I6EiQfxL.mjs +0 -20
- package/dist/packem_shared/storageRules-6QxzDOcx.mjs +0 -88
- package/dist/packem_shared/types.d-BB3pjV0m.d.mts +0 -141
- package/dist/packem_shared/types.d-Cxl6ndhm.d.ts +0 -141
|
@@ -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,e)=>t!==void 0&&Object.hasOwn(t,n)&&x(e),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(s=>typeof s!="string"))return u("VALIDATION_ERROR",`${n} must be an array of ids`);const e=[...new Set(t)];return e.length>y&&u("VALIDATION_ERROR",`${n} names ${String(e.length)} rows; at most ${String(y)} per list`),e},E=(t,n,e)=>{n.nullable||u("VALIDATION_ERROR",`${t}.${e}: "${n.field}" cannot be empty; make it optional or nullable to allow it`)},D=(t,n,e)=>{const{connect:s,disconnect:i,set:c}=e;return c!==void 0&&u("VALIDATION_ERROR",`${t} is a to-one relation: use connect or disconnect, not set`),s!==void 0&&i!==void 0&&u("VALIDATION_ERROR",`${t}: connect and disconnect together are ambiguous`),s!==void 0?(typeof s!="string"&&u("VALIDATION_ERROR",`${t}.connect must be an id`),{connect:s,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,e)=>{n.through===void 0&&E(t,n,e)},k=(t,n,e)=>{const{connect:s,disconnect:i,set:c}=e;if(c!==void 0)return(s!==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=s===void 0?[]:R(s,`${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}},j=(t,n,e,s)=>{const i=Object.fromEntries(Object.entries(s).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=e.refusal??e.refusalNow?.();return a!==void 0&&u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" cannot be written: ${a}`),e.colocated||u("UNPROCESSABLE",`ctx.db.${t}: relation "${n}" crosses to "${e.table}" on another shard or backend, so a nested write cannot be applied atomically; write each side yourself`),e.kind==="one"?D(n,e,i):k(n,e,i)},W=t=>t.info.kind==="one",T=(t,n,e)=>{if(n===void 0)return{columns:e,manys:[],ones:[]};const s={},i=[],c=[];for(const[a,r]of Object.entries(e)){if(!I(n,a,r)){s[a]=r;continue}const o=j(t,a,n[a],r);o!==void 0&&(W(o)?c.push(o):i.push(o))}for(const{info:a,name:r}of c)Object.hasOwn(s,a.field)&&u("VALIDATION_ERROR",`ctx.db.${t}: ${r} and its key "${a.field}" are both set; set one or the other`);return{columns:s,manys:i,ones:c}},w=(t,n,e,s)=>{const i=Object.entries(e).find(([c,a])=>I(n,c,a))?.[0];i!==void 0&&u("VALIDATION_ERROR",`ctx.db.${t}.${s}: "${i}" is a relation write, which ${s} does not support; use insert or patch`)},O=async(t,n,e,s,i)=>{const c=await t.get(i,s);return c===null&&u("NOT_FOUND",`${n}.${e}: no "${s}" row with id "${i}"`),c},b=async(t,n)=>{const e={...n.columns};for(const{connect:s,info:i,name:c}of n.ones){let a=null;s!==void 0&&(a=(await O(t,c,"connect",i.table,s))[i.references]),e[i.field]=a}return e},F=async(t,{info:n,name:e},s,i)=>{(await O(t,e,"connect",n.table,s))[n.field]!==i&&await t.patch(s,{[n.field]:i},n.table)},P=async(t,{info:n},e,s)=>{e[n.field]===s&&await t.patch(String(e._id),{[n.field]:null},n.table)},U=async(t,{info:n,name:e},s)=>{const{page:i}=await t.findMany(n.table,{limit:y+1,where:{[n.field]:s}});return i.length>y&&u("VALIDATION_ERROR",`${e}.set: the relation already holds more than ${String(y)} rows; disconnect in batches first`),i},L=(t,n)=>{const e=new Set(t),s=new Set(n);return{attach:n.filter(i=>!e.has(i)),release:new Set(t.filter(i=>!s.has(i)))}},$=async(t,{name:n},{from:e,table:s,to:i},c,a)=>{const r=a===void 0?{[e]:c}:{[e]:c,[i]:{in:a}},{page:o}=await t.findMany(s,{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,e)=>{if(e.length===0)return new Set;const{page:s}=await t.findMany(n,{limit:e.length,where:{_id:{in:e}}});return new Set(s.map(i=>String(i._id)))},C=async(t,n,e)=>{const{info:s,name:i}=n,{from:c,table:a,to:r}=s.through;let o,d;if(n.replace===void 0){await Promise.all(n.release.map(h=>O(t,i,"disconnect",s.table,h))),d=n.release.length===0?[]:await $(t,n,s.through,e,n.release);const l=n.attach.length===0?[]:await $(t,n,s.through,e,n.attach),f=new Set(l.map(h=>String(h[r])));o=n.attach.filter(h=>!f.has(h))}else{const l=await $(t,n,s.through,e,void 0),f=L(l.map(g=>String(g[r])),n.replace),h=await V(t,s.table,[...f.release]);({attach:o}=f),d=l.filter(g=>f.release.has(String(g[r]))&&h.has(String(g[r])))}await Promise.all(o.map(l=>O(t,i,"connect",s.table,l)));for(const l of d)await t.delete(String(l._id),a);for(const l of o)try{await t.insert(a,{[c]:e,[r]:l})}catch(f){if(!v(f)||!s.pairIsOnlyUnique)throw f}},q=async(t,n,e)=>{let{attach:s}=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,e),a=L(c.map(r=>String(r._id)),n.replace);({attach:s}=a),i=c.filter(r=>a.release.has(String(r._id)))}for(const c of i)await P(t,n,c,e);for(const c of s)await F(t,n,c,e)},_=async(t,n,e,s)=>{for(const i of e.manys){const{info:c}=i,a=c.through===void 0?c.references:"_id",r=await s(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,e,s)=>async i=>i==="_id"?e:Object.hasOwn(s,i)?s[i]:(await t.get(e,n))?.[i],B=async(t,n,e,s,i)=>{const c=T(n,e,s);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},m=async(t,n,e,s,i)=>{const c=T(n,e,i);if(c.ones.length===0&&c.manys.length===0){await t.patch(s,c.columns,n);return}const a=await b(t,c);if(Object.keys(a).length>0)await t.patch(s,a,n);else{if(await t.get(s,n)===null)throw new p("NOT_FOUND",`document not found: ${s}`);await t.assertPatchAllowed?.(s,n)}await _(t,n,c,S(t,n,s,a))},G=(t,n,e,s)=>{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 e)){const r=Object.entries(s??{}).find(([o,d])=>d.kind==="one"&&d.field===a&&o in e)?.[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]=e[a]}return c},z=(t,n)=>{const e=async(o,d)=>{if(d?.skipDuplicates!==!0)return t.insert(n,o);try{return await t.insert(n,o)}catch(l){if(v(l))return null;throw l}},s=t.relationWrites?.[n],i=(o,d)=>B(t,n,s,o,l=>e(l,d)),c=(o,d)=>m(t,n,s,o,d),a=async o=>{const d=o??{},l=await t.findMany(n,{...d,limit:2});if(l.page.length>1)throw new p("NOT_UNIQUE",`ctx.db.${n}.findUnique matched more than one document; expected at most one`);return l.page[0]??null},r=async({create:o,target:d,update:l})=>{const f=G(n,d,o,s),h=await t.findFirst(n,{where:f});return h&&typeof h._id=="string"?(await c(h._id,l??o),{created:!1,id:h._id}):{created:!0,id:await i(o)}};return{aggregate:o=>t.aggregate(n,o),count:o=>t.count(n,o),delete:o=>t.delete(o,n),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(o,d,n)}if(t.deleteWhere===void 0)throw new p("INTERNAL",`ctx.db.${n}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);const l=o;return t.deleteWhere(n,l.where,{limit:l.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(o,n),groupBy:o=>t.groupBy(n,o),hardDelete:o=>t.delete(o,n,{hard:!0}),insert:i,insertMany:(o,d)=>{for(const l of o)w(n,s,l,"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 l=Array.isArray(o)?o.map(h=>h.values):[o.values];for(const h of l)w(n,s,h,"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(o.map(h=>({id:h.id,patch:h.values})),d,n)}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,s,d,"replace"),t.replace(o,d,n)),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(o,n)},upsert:r,upsertMany:async({rows:o,target:d})=>{const l=[];for(const f of o)l.push(await r({create:f.create,target:d,update:f.update}));return l},withGeoIndex:(o,d)=>t.query(n).withGeoIndex(o,d),withSearchIndex:(o,d)=>t.query(n).withSearchIndex(o,d)}},X=(t,n)=>{Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){const e=z(t,n);return Object.defineProperty(t,n,{configurable:!0,enumerable:!0,value:e,writable:!1}),e}})},H=t=>{const n=e=>{const s=t[e];if(!s)throw new p("INTERNAL",`unknown table: ${e}`);return s};return{delete:(e,s)=>n(e).delete(s),insert:e=>({values:s=>n(e).insert(s)}),query:t,replace:(e,s)=>({with:i=>n(e).replace(s,i)}),update:(e,s)=>({set:i=>n(e).patch(s,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-Bm9wIpiI.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-Bm9wIpiI.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 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 s}from"@lunora/errors";import{c}from"./context-identity-B2XYGA0B.mjs";import{v as m}from"./functions-B2-H4PQT.mjs";const w=(r,o,a)=>{if(r.trim()==="")throw new s("INTERNAL",'defineMutator: `owner` must name the column carrying the row owner (e.g. `owner: "userId"`)');const t=c(o);if(t===void 0)throw new s("UNAUTHORIZED","defineMutator: an owner-scoped mutator requires a verified identity; none was resolved for this request");const e=a,n=e[r];if(n!==void 0&&n!==t)throw new s("FORBIDDEN",`defineMutator: \`${r}\` does not match the verified identity — a mutator may only write rows its caller owns`);return e[r]=t,a},h=r=>{const o={},a=async(t,e)=>{const n=m(r.args??{},e),u=r.owner===void 0?n:w(r.owner,t,n);return Reflect.apply(r.server,o.mutator,[t,u])};return o.mutator={__lunoraMutator:!0,...r,handler:a,kind:"mutation",server:async(t,e)=>a(t,e)},o.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 p}from"./context-identity-B2XYGA0B.mjs";import{v as u}from"./functions-B2-H4PQT.mjs";import{toWhereInput as m,deny as d}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as c}from"./assertShapesDeclareReadPolicies-Bg4Ter7Q.mjs";const I=e=>{if(e.table.trim()==="")throw new r("INTERNAL","defineShape: `table` must be a non-empty string");if(e.columns?.length===0)throw new r("INTERNAL","defineShape: `columns` must list at least one column when provided");if(!e.where&&e.owner===void 0)throw new r("INTERNAL",`defineShape: shape on table "${e.table}" needs a \`where\` predicate or an \`owner\` (\`owner: true\` uses the table's .ownedBy(field), \`owner: "field"\` names the column) — a shape with neither would replicate the whole table`);return{__lunoraShape:!0,...e,compileWhere:(a,l,n)=>{const w=u(e.args??{},l),o=e.where?m(e.where(a,w)):void 0;if(e.owner===void 0)return o;const t=e.owner===!0?n?.ownerField:e.owner;if(t===void 0||t==="")throw new r("INTERNAL",`defineShape: shape on table "${e.table}" declares \`owner: true\` but the table has no \`.ownedBy(field)\` — add it to the table, or name the column directly with \`owner: "field"\``);const s=p(a);if(s===void 0)return d();const h={[t]:s};return o===void 0?h:{AND:[h,o]}},rlsRegistry:c(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
|
+
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}from"@lunora/values";const t=(a,r)=>o(a,r,"args");export{t as v};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{LunoraError as b,toErrorBody as S,isLunoraError as k}from"@lunora/errors";import{parseValidatorMap as v,ValidationError as L}from"@lunora/values";import{encodeWire as q}from"@lunora/wire";import{Hono as C}from"hono";import{a as R}from"./apply-output-C5wZ5EAL.mjs";const W=e=>async r=>e(r.get("lunora"),r.req.raw),G=()=>{const e=new C;return e.use("*",async(r,o)=>{const n=r.env.__lunoraCtx;if(!n)throw new b("INTERNAL_SERVER_ERROR","HttpActionCtx was not injected — mount httpRouter() on createWorker(), which supplies it per request.");r.set("lunora",n),await o()}),e},O=e=>e.kind==="optional"?e._meta?.inner??e:e,g=(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}},x=(e,r,o)=>{const n=O(e);if(n.kind==="array"){const a=r.req.queries(o);if(a===void 0)return;const i=n._meta?.inner;return a.map(d=>g(i?.kind??"string",d))}const t=r.req.query(o);return t===void 0?void 0:g(n.kind,t)},T=(e,r)=>{const o={};for(const n of Object.keys(e)){const t=e[n];t&&(o[n]=x(t,r,n))}return v(e,o,"searchParams")},N=(e,r)=>{const o=r.req.param(),n={};for(const t of Object.keys(e)){const a=e[t];if(!a)continue;const i=o[t];n[t]=i===void 0?void 0:g(O(a).kind,i)}return v(e,n,"params")},H=async(e,r)=>{let o;try{o=await r.req.json()}catch{throw new b("BAD_REQUEST","Invalid JSON body")}if(typeof o!="object"||o===null||Array.isArray(o))throw new b("BAD_REQUEST","Expected a JSON object body");return v(e,o,"body")},A=e=>{if(e instanceof L)return Response.json({code:"BAD_REQUEST",error:e.message},{status:400});if(k(e)){const{body:r,redacted:o,status:n}=S(e,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});return o&&console.error("[lunora] http action error (redacted on the wire):",e),Response.json({code:r.code,error:r.message},{status:n})}throw e},j=(e,r)=>{const{method:o}=r.req;if(!(o===e.method||e.method==="GET"&&o==="HEAD"))return Response.json({code:"METHOD_NOT_ALLOWED",error:`${o} is not allowed on this route (declared as ${e.method})`},{headers:{allow:e.method},status:405})},I=(e,r)=>async o=>{const n=j(e,o);if(n)return n;try{const t=o.get("lunora"),a=Object.keys(e.searchParams).length>0?T(e.searchParams,o):{},i=Object.keys(e.params).length>0?N(e.params,o):{},d=Object.keys(e.body).length>0?await H(e.body,o):{},h=await r({body:d,ctx:t,params:i,searchParams:a}),s=e.output?R(e.output,h):h,c={};e.cacheControl&&(c["cache-control"]=e.cacheControl),e.cacheTag&&(c["cache-tag"]=e.cacheTag),e.vary&&(c.vary=e.vary);const p=Object.keys(c).length>0;return s===void 0?new Response(null,{headers:p?c:void 0,status:204}):Response.json(s,{headers:p?c:void 0})}catch(t){return A(t)}},w={"cache-control":"no-cache, no-transform","content-type":"text/event-stream; charset=utf-8","x-accel-buffering":"no"},z=e=>{const r=e.headers.get("last-event-id");if(r!==null)return r===""?void 0:r;const o=new URL(e.url).searchParams.get("lastEventId");return o===null||o===""?void 0:o},P=Symbol.for("@lunora/server/sse-event"),K=e=>({[P]:!0,data:e.data,id:e.id}),D=e=>typeof e=="object"&&e!==null&&e[P]===!0,B=e=>!(e.includes("\r")||e.includes(`
|
|
2
|
+
`)||e.includes("\0")),E=(e,r,o)=>{const n=JSON.stringify(r===void 0?q(e):e);if(o!==void 0&&!B(o))throw new b("INTERNAL","sseEvent id must not contain CR, LF or NUL");const t=o===void 0?"":`id: ${o}
|
|
3
|
+
`,a=r?`event: ${r}
|
|
4
|
+
`:"";return`${t}${a}data: ${n}
|
|
5
|
+
|
|
6
|
+
`},V=(e,r)=>{if(D(r)){const o=e?R(e,r.data):r.data;return E(o,void 0,r.id)}return E(e?R(e,r):r)},$=(e,r)=>(async o=>{const n=j(e,o);if(n)return n;let t,a;try{t=Object.keys(e.searchParams).length>0?T(e.searchParams,o):{},a=Object.keys(e.params).length>0?N(e.params,o):{}}catch(m){return A(m)}const i=o.get("lunora"),d=o.req.raw,h=new TextEncoder,s=new AbortController;if(d.signal.aborted)return s.abort(),new Response("",{headers:w});const c=()=>{s.abort()};d.signal.addEventListener("abort",c,{once:!0});const p=new ReadableStream({cancel(){d.signal.removeEventListener("abort",c),s.abort()},async start(m){try{const f=r({ctx:i,params:a,request:d,searchParams:t,signal:s.signal});for await(const y of f){if(s.signal.aborted)break;m.enqueue(h.encode(V(e.output,y)))}s.signal.aborted||m.enqueue(h.encode(E({},"complete")))}catch(f){const{body:y,redacted:_}=S(f,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"Internal error"});_&&console.error("[lunora] unhandled stream handler error:",f),s.signal.aborted||m.enqueue(h.encode(E({code:y.code,message:y.message},"error")))}finally{d.signal.removeEventListener("abort",c);try{m.close()}catch{}}}});return new Response(p,{headers:w})}),u=e=>({body:r=>u({...e,body:{...e.body,...r}}),cacheControl:r=>u({...e,cacheControl:r}),cacheTag:r=>u({...e,cacheTag:r}),handler:r=>I(e,r),output:r=>u({...e,output:r}),params:r=>u({...e,params:{...e.params,...r}}),searchParams:r=>u({...e,searchParams:{...e.searchParams,...r}}),stream:r=>$(e,r),vary:r=>u({...e,vary:r})}),l=e=>r=>u({body:{},method:e,params:{},path:r,searchParams:{}}),X={delete:l("DELETE"),get:l("GET"),head:l("HEAD"),options:l("OPTIONS"),patch:l("PATCH"),post:l("POST"),put:l("PUT")};export{W as httpAction,X as httpRoute,G as httpRouter,B as isSafeHeaderValue,z as lastEventId,K as sseEvent};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as M}from"./apply-output-C5wZ5EAL.mjs";import{v as h}from"./functions-B2-H4PQT.mjs";import{unionMaskColumns as w}from"./buildMaskRegistry-DpWMtalG.mjs";import{r as j}from"./policy-tag-V0lqFzgS.mjs";import{r as b,e as z}from"./run-middleware-BefYq7Xd.mjs";import{isPerDispatchMiddleware as _}from"./isPerDispatchMiddleware-DDQPatSm.mjs";const C=(e,r,o,n)=>n===0&&r===void 0||typeof e!="object"||e===null?e:z(e,{args:Object.freeze({...o}),...r===void 0?{}:{meta:r}}),y=(e,r)=>b(e,r,o=>o),q=(e,r,o,n,s)=>async(d,t)=>{const c=h(e,t),u=await y(r,C(d,s,c,r.length)),m=await o({args:c,ctx:u});return n?M(n,m):m},D=(e,r,o,n)=>(s,d,t)=>{const c=h(e,d);return(async function*(){const m=await y(r,C(s,n,c,r.length)),f=o({args:c,ctx:m,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=>j(o));return r.length>0?{tags:r}:void 0},i=e=>e.some(r=>_(r)),x=e=>{for(const r of["add","clear","delete","set"])typeof e[r]=="function"&&Object.defineProperty(e,r,{configurable:!1,enumerable:!1,value:()=>{throw new TypeError(`Cannot mutate a frozen .meta() declaration (${e.constructor.name}.${r})`)},writable:!1})},l=(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)l(o,r),l(n,r);x(e)}else if(e instanceof Set){for(const o of e)l(o,r);x(e)}for(const o of Object.values(e))l(o,r);return Object.freeze(e),e},O=e=>l(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 s=g(r.middlewares),d=w(r.middlewares),t=i(r.middlewares);return{args:r.args,...r.expose?{expose:r.expose}:{},handler:q(r.args,r.middlewares,n,r.output,r.meta),kind:e,...d?{maskedTables:d}:{},...t?{perDispatch:t}:{},...s?{rls:s}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}},meta:n=>a(e,{...r,meta:O({...r.meta,...n})},o),output:n=>a(e,{...r,output:n},o),...e==="query"?{stream:(n,s)=>{const d=g(r.middlewares),t=w(r.middlewares),c=i(r.middlewares),u=s?.durable===!0?{}:s?.durable;return{args:r.args,...u?{durable:u}:{},...r.expose?{expose:r.expose}:{},handler:D(r.args,r.middlewares,n,r.meta),kind:"stream",...t?{maskedTables:t}:{},...c?{perDispatch:c}:{},...d?{rls:d}:{},...o?{visibility:o}:{},...r.x402?{x402:r.x402}:{}}}}:{},use:n=>a(e,{...r,middlewares:[...r.middlewares,n]},o),...o?{}:{expose:n=>a(e,{...r,expose:n},o)},...o?{}:{x402:n=>a(e,{...r,x402:n},o)}}),k={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{k 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 @@
|
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{f as D}from"./fnv1a-D3ueNTWB.mjs";import{i as z,a as G,o as L,b as C,c as H,d as J}from"./middleware-3ySZVrpt.mjs";import{defineLazyFacade as m,bindOrm as Q}from"./bindOrm-9fbLRbOb.mjs";import{tagMaskMiddleware as V}from"./buildMaskRegistry-DpWMtalG.mjs";const X=(s,i,c)=>{try{return s==="redact"?null:s==="hash"?i==null?i:typeof i=="bigint"?D(i.toString()):D(typeof i=="string"?i:JSON.stringify(i)):s(i,c)}catch{return null}},u=(s,i,c)=>{const w={...s};for(const[y,g]of Object.entries(i))y in w&&(w[y]=X(g,s[y],{...c,column:y,row:s}));return w},B=(s,i,c)=>({...s,page:s.page.map(w=>u(w,i,c))}),I=(s,i)=>{const c=H(i);return s instanceof Set?s.has(c):Object.hasOwn(s,c)},K=(s,i,c,w)=>{if(typeof s!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>f=>(typeof f=="string"&&y.add(f),g())});s(g());for(const f of y)if(I(i,f))throw new A("MASK_UNSUPPORTED",`${w}() filtering "${c}" by masked column "${f}" is not supported`)},Y=(s,i,c,w)=>{const y=s.rankBefore,g=s.rankPageRows,f=(r,t)=>{const n=i.get(r);return n?t.map(o=>u(o,n,c)):t},l=r=>{const t=r?.relationMask;return{...r,relationMask:t===void 0?f:(n,o)=>t(n,f(n,o))}},p=(r,t,n,o)=>{const e=i.get(r);if(!e)return;const a=w?.[r]?.[o]?.[t];if(!a)return;const d=a.find(R=>I(e,R));if(d!==void 0)throw new A("MASK_UNSUPPORTED",`${n}() reading "${r}" via index "${t}" would order rows by masked column "${d}" — use an index whose declared fields are all unmasked, or unmask the column`)},k=(r,t,n)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield u(o,t,c)},collect:async()=>(await r.collect()).map(e=>u(e,t,c)),collectWithScores:async()=>(await r.collectWithScores()).map(e=>{const a=u(e.document,t,c);return"distanceMeters"in e?{distanceMeters:null,document:a}:{document:a,score:e.score}}),filter:o=>k(r.filter(e=>o(u(e,t,c))),t,n),first:async()=>{const o=await r.first();return o?u(o,t,c):null},order:o=>k(r.order(o),t,n),paginate:async o=>B(await r.paginate(o),t,c),take:async o=>(await r.take(o)).map(a=>u(a,t,c)),unique:async()=>{const o=await r.unique();return o?u(o,t,c):null},withIndex:(o,e)=>(p(n,o,"withIndex","index"),K(e,t,n,"withIndex"),k(r.withIndex(o,e),t,n)),withSearchIndex:(o,e)=>(K(e,t,n,"withSearchIndex"),k(r.withSearchIndex(o,e),t,n)),withGeoIndex:(o,e)=>(p(n,o,"withGeoIndex","geo"),k(r.withGeoIndex(o,e),t,n))}),W=async(r,t)=>{if(s.lookupById){const d=await s.lookupById(r,t);if(d)return{row:d.row,tableName:i.has(d.tableName)?d.tableName:void 0}}const n=await s.get(r,t);if(!n)return{row:null,tableName:void 0};const o=t!==void 0&&i.has(t)?[t]:[],e=t===void 0?[...i.keys()]:o,a=await Promise.all(e.map(async d=>(await s.findFirst(d,{limit:1,where:{_id:r}}))?._id===r?d:void 0));return{row:n,tableName:a.find(d=>d!==void 0)}},S=(r,t,n)=>{const o=i.get(r);if(!o)return;const e=t.find(a=>typeof a=="string"&&I(o,a));if(e!==void 0)throw new A("MASK_UNSUPPORTED",`${n}() over masked column "${e}" on "${r}" is not supported`)},O=new Set;for(const r of i.values())for(const t of Object.keys(r))O.add(t);const P=(r,t,n,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[e,a]of Object.entries(r))q(e,a,t,n,o)},q=(r,t,n,o,e)=>{if(r==="AND"||r==="OR"){for(const a of Array.isArray(t)?t:[])P(a,n,o,e);return}if(r==="NOT"){P(t,n,o,e);return}if(!r.startsWith("__")){if(I(n,r))throw new A("MASK_UNSUPPORTED",`${e}() filtering "${o}" by masked column "${r}" is not supported`);if(J(t))for(const a of Object.values(t))P(a,O,`${o}.${r}`,e)}},F=r=>{const t=i.get(r);return t?new Set(Object.keys(t)):new Set},h=(r,t,n)=>{O.size===0||t===void 0||P(t,F(r),r,n)},E=(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(I(n,a))throw new A("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${a}" is not supported`)}}},v=(r,t,n)=>{if(!(O.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,d=`${r}.${o}`;P(a.where,O,d,n),E(d,a.orderBy,O,n),v(d,a.with,n)}},$=(r,t,n)=>{h(r,t?.where,n),h(r,t?.baseWhere,n),E(r,t?.orderBy,F(r),n),v(r,t?.with,n)},U=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,t,n)=>{const o=U(t);h(r,o?.where,n),h(r,o?.baseWhere,n),v(r,o?.with,n)},j=(r,t)=>Object.hasOwn(i.get(r)??{},t)?t:void 0,_={...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,d]=e.kind==="one"?[t,e.table]:[e.table,t],R=e.through?j(e.through.table,e.through.from)??j(e.through.table,e.through.to):j(a,e.field)??j(d,e.references);return[o,R===void 0?e:{...e,refusal:`"${R}" 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 A("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 A("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:u(o.doc,e,c)}:o},async patchWhere(r,t,n){if(h(r,t.where,"patchMany({ where })"),s.patchWhere===void 0)throw new A("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 S(r,[t.field],"aggregate"),h(r,t.where,"aggregate"),s.aggregate(r,t)},count(r,t){const n=U(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){$(r,t,"findFirst");const n=await s.findFirst(r,l(t)),o=i.get(r);return n&&o?u(n,o,c):n},async findFirstOrThrow(r,t){$(r,t,"findFirstOrThrow");const n=await s.findFirstOrThrow(r,l(t)),o=i.get(r);return o?u(n,o,c):n},async explain(r,t){return $(r,t,"explain"),s.explain(r,t)},async findMany(r,t){$(r,t,"findMany");const n=await s.findMany(r,l(t)),o=i.get(r);return o?B(n,o,c):n},async get(r,t){const{row:n,tableName:o}=await W(r,t),e=o===void 0?void 0:i.get(o);return!n||!e?n:u(n,e,c)},related:s.related?async(r,t)=>await s.related(r,l(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?u(n.row,o,c):n.row,tableName:n.tableName}},groupBy(r,t){return S(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?k(t,n,r):t},async rank(r,t,n){return M(r,n,"rank"),p(r,t,"rank","rank"),s.rank(r,t,n)},async rankPage(r,t,n){M(r,n,"rankPage"),p(r,t,"rankPage","rank");const o=await s.rankPage(r,t,n),e=i.get(r);return e?B(o,e,c):o},...L("rankBefore",y,r=>(t,n,o)=>(M(t,o,"rankBefore"),p(t,n,"rankBefore","rank"),r(t,n,o))),...L("rankPageRows",g,r=>async(t,n,o)=>{M(t,o,"rankPageRows"),p(t,n,"rankPageRows","rank");const e=await r(t,n,o),a=i.get(t);return a?{...e,rows:e.rows.map(d=>({...d,doc:u(d.doc,a,c)}))}:e})};if(O.size>0)for(const[r,t]of Object.entries(s))C(t)&&m(_,r);return _},tr=(s,i={})=>{const c=new Map(Object.entries(s)),w=z(i.roles),y=async({ctx:f,next:l})=>{const p={auth:await G(f.auth??{},w),ctx:f};if(i.bypass?.(p)===!0)return l();const k=Y(f.db,c,p,i.indexFields),W={db:k},{orm:S}=f;return S!==null&&typeof S=="object"&&(W.orm=Q(k)),l({ctx:W})},g=new Map;for(const[f,l]of c)g.set(f,new Set(Object.keys(l)));return V(y,{columns:g})};export{tr as mask};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g,isLunoraError as ye}from"@lunora/errors";import{findRelated as pe,whereFilter as we}from"@lunora/shard-engine";import{isPlainObject as z}from"@lunora/wire";import{defineLazyFacade as ge,bindOrm as Oe}from"./bindOrm-9fbLRbOb.mjs";import{t as be}from"./policy-tag-V0lqFzgS.mjs";import{deny as ve}from"./allowAll-DkRAgItV.mjs";const H=e=>{if(e===null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===null||t===Object.prototype},J=4;class T extends Error{}const C=e=>e.includes("."),ut=e=>{const t=e.indexOf(".");return t===-1?e:e.slice(0,t)},ne=e=>{const t=e.split(".");if(t.length>J||t.includes(""))throw new T(`field path "${e}" must have 1 to ${String(J)} non-empty segments`);return t},Re=(e,t)=>{if(!C(t))return e[t];let r=e;for(const s of ne(t)){if(!H(r)||!Object.hasOwn(r,s))return;r=r[s]}return r},re=(e,t,r,s)=>{const[a,...l]=t;if(a===void 0)throw new T(`field path "${s}" is empty`);if(e!=null&&!H(e))throw new T(`cannot set "${s}": "${a}" sits inside a value that is not an object`);const d=e??{};return{...d,[a]:l.length===0?r:re(d[a],l,r,s)}},We=(e,t)=>{const r=Object.keys(e).filter(a=>C(a));if(r.length===0)return e;for(const a of r){const l=r.find(d=>d!==a&&d.startsWith(`${a}.`));if(l!==void 0)throw new T(`patch sets both "${a}" and "${l}", which overlap; set one or the other`)}const s={};for(const[a,l]of Object.entries(e))C(a)||(s[a]=l);for(const a of r){const[l="",...d]=ne(a);if(Object.hasOwn(e,l))throw new T(`patch sets both "${l}" and "${a}"; set one or the other`);s[l]=re(Object.hasOwn(s,l)?s[l]:t[l],d,e[a],a)}return s},Ee=e=>{const t=typeof e;return t==="number"||t==="string"||t==="boolean"?t:void 0},Ae=["every","is","isNot","none","some"],Se=new Set(Ae),ke=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>Se.has(r))},Z=(e,t,r)=>t?{[e]:r(t)}:{},K={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 R extends Error{}const oe=e=>{if(!H(e))return;const t=Object.keys(e),[r]=t;if(!(t.length!==1||r===void 0||!Object.hasOwn(K,r)))return{operand:e[r],operator:r}},Be=e=>oe(e)!==void 0,Pe=(e,t,r,s)=>{const a=K[t];if(a.apply===void 0){if(r!==!0)throw new R(`patch: use { toggle: true } on "${e}".`);if(typeof s!="boolean")throw new R(`patch: cannot toggle "${e}" — its current value is ${String(s)}; set a boolean first.`);return!s}if(typeof r!="number"||!Number.isFinite(r))throw new R(`patch: "${t}" on "${e}" needs a finite number, got ${String(r)}.`);if(typeof s!="number"||!Number.isFinite(s))throw new R(`patch: cannot ${t} "${e}" — its current value is ${String(s)}; set a number first.`);if(t==="divide"&&r===0)throw new R(`patch: cannot divide "${e}" by zero.`);const l=a.apply(s,r);if(!Number.isFinite(l))throw new R(`patch: "${t}" on "${e}" overflows to ${String(l)}.`);return l},se=(e,t)=>{const r=new Set;for(const[s,a]of Object.entries(e))t(s)!==void 0&&Be(a)&&r.add(s);return r},_e=(e,t,r)=>{let s;for(const a of se(e,r)){const{operand:l,operator:d}=oe(e[a]),b=r(a);if(K[d].kind!==b)throw new R(`patch: "${d}" does not apply to the ${String(b)} column "${a}".`);s??={...e},s[a]=Pe(a,d,l,t[a])}return s??e},Ie=(e,t)=>{const r=a=>{const l=t[a];return typeof l=="number"||typeof l=="boolean"?typeof l:void 0},s={...e};for(const a of se(e,r))try{Object.assign(s,_e({[a]:e[a]},t,r))}catch(l){if(!(l instanceof R))throw l}try{return We(s,t)}catch(a){if(a instanceof T)return s;throw a}},Te=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],S=-1,k=0,W=1,$=e=>e?W:S,O=(e,t)=>e<t?e:t,$e=(e,t)=>e>t?e:t,ie=e=>e===k?k:$(e===S),V=e=>{const t=typeof e;return t==="number"||t==="string"||t==="bigint"},B=e=>e==null,D=(e,t,r)=>{if(r===void 0)throw new g("BAD_REQUEST",`\`${t}\` on "${e}" received undefined; a comparison needs a value`)},me={gt:(e,t)=>e>t,gte:(e,t)=>e>=t,lt:(e,t)=>e<t,lte:(e,t)=>e<=t},De=(e,t,r)=>{let s=W;for(const a of["gt","gte","lt","lte"]){if(!(a in r))continue;const l=r[a];D(e,a,l);const d=C(e);if(d?Ee(l)===void 0:!V(l))s=O(s,S);else if(B(t))s=O(s,k);else{const b=me[a],p=d?typeof t==typeof l:V(t);s=O(s,$(p&&b(t,l)))}}return s},ee=(e,t,r)=>{if(!Array.isArray(r))throw new g("BAD_REQUEST",`\`${t}\` on "${e}" expects an array of values, received ${r===null?"null":typeof r}`);if(r.includes(void 0))throw new g("BAD_REQUEST",`\`${t}\` on "${e}" received undefined inside its list; a comparison needs a value`);return r},te=(e,t)=>t.length===0?S:B(e)?k:t.includes(e)?W:t.some(r=>B(r))?k:S,Me=(e,t,r)=>{let s=W;if("in"in r&&(s=O(s,te(t,ee(e,"in",r.in)))),"notIn"in r&&(s=O(s,ie(te(t,ee(e,"notIn",r.notIn))))),"contains"in r){const a=r.contains;D(e,"contains",a),s=B(t)?O(s,k):O(s,$(typeof t=="string"&&typeof a=="string"&&t.includes(a)))}return"isNull"in r&&(s=O(s,$(r.isNull===!0===B(t)))),s},Y=(e,t,r)=>t===null?$(r===B(e)):B(e)?k:$(r===(e===t)),Fe=(e,t,r)=>{let s=W;return"eq"in r&&(D(e,"eq",r.eq),s=O(s,Y(t,r.eq,!0))),"ne"in r&&(D(e,"ne",r.ne),s=O(s,Y(t,r.ne,!1))),s},Le=(e,t,r)=>O(Fe(e,t,r),O(Me(e,t,r),De(e,t,r))),je=(e,t,r,s)=>{if(t==="NOT")return ie(s(e,r??{}));if(!Array.isArray(r))return S;let a=t==="AND"?W:S;for(const l of r){const d=s(e,l);a=t==="AND"?O(a,d):$e(a,d)}return a},ae=e=>e==="AND"||e==="OR"||e==="NOT",Ce=e=>z(e)&&Object.keys(e).every(t=>Te.includes(t)),U=e=>Object.keys(e).some(t=>{const r=e[t];return ae(t)?t==="NOT"?U(r??{}):Array.isArray(r)&&r.some(s=>U(s??{})):ke(r)}),ce=(e,t)=>{let r=W;for(const s of Object.keys(t)){const a=t[s];if(ae(s)){r=O(r,je(e,s,a,ce));continue}const l=Re(e,s);if(Ce(a)){r=O(r,Le(s,l,a));continue}D(s,"eq",a),r=O(r,Y(l,a,!0))}return r},q=(e,t)=>ce(e,t)===W,le=500,I=(e,t,r)=>{const s=t??le;if(e>s)throw new g("BATCH_LIMIT_EXCEEDED",`${r}: batch of ${String(e)} exceeds the limit of ${String(s)} (raise options.limit or chunk the call)`,{status:400})},Ue=ve(),qe=Symbol.for("lunora.ctxdb.rls-unwrap"),fe=Symbol.for("lunora.rls.wrapped-chain"),Ne=e=>e[fe],Ye=e=>{const t=new Map;for(const r of e){const s=t.get(r.table)??[];s.push(r),t.set(r.table,s)}return t},xe=(e,t)=>{const r=[];let s=!1;for(const a of e){if(a.on!=="read")continue;const l=a.when(t);if(l!==void 0){if(l===!0){s=!0;break}l!==!1&&r.push(l)}}if(!s)return r.length===0?Ue:r.length===1?r[0]:{OR:r}},ze=(e,t,r)=>{const s=e.when({...t,row:r});if(s===void 0||s===!0)return!0;if(s===!1)return!1;if(U(s))throw new g("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return q(r,s)},He=(e,t,r)=>{const s=e.when(t);if(s===void 0||s===!0)return r===void 0||ze(e,t,r);if(s===!1)return!1;if(U(s))throw new g("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!t.row||!q(t.row,s)?!1:r===void 0||q(r,s)},Ke=(e,t,r,s)=>{let a=!1;for(const l of e)if(l.on===t&&(a=!0,!He(l,r,s)))return!1;return a},Qe=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Xe=(e,t)=>t===void 0?!0:e==="restrictsCounts"?typeof t=="boolean":e==="relationBaseWhere"?typeof t=="function":z(t),Ge=e=>{const t=Object.keys(e);return t.length===0?!1:t.every(r=>Qe.has(r)&&Xe(r,e[r]))},Je=e=>e===void 0?{}:z(e)&&Ge(e)?e:{where:e},x=e=>e!==void 0&&Object.keys(e).length>0,Ze=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},v=(e,t)=>x(t)?!e||Object.keys(e).length===0?t:{AND:[t,e]}:e,Ve=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=e;return typeof t.findMany=="function"&&typeof t.withSearchIndex=="function"},et=(e,t,r)=>{const[s]=r,a=r.length===1&&s!==void 0?s.perTable:new Set(r.flatMap(n=>[...n.perTable.keys()])),l=new Map,d=n=>{const o=l.get(n);if(o)return o;const i=[];let c=!1;for(const u of r){const h=u.perTable.get(n);if(!h||h.length===0||!h.some(_=>_.on==="read"))continue;c=!0;const y=xe(h,u.context);y!==void 0&&i.push(y)}const f={baseWhere:Ze(i),restricts:c};return l.set(n,f),f},b=(n,o,i,c)=>{for(const f of r){const u=f.perTable.get(n);if(u&&!Ke(u,o,{...f.context,row:i},c))return!1}return!0},p=n=>d(n).restricts?t:e,w=n=>d(n).baseWhere,E=async(n,o,i)=>{if(t.lookupById){const y=await t.lookupById(n,o);if(y)return{row:y.row,tableName:a.has(y.tableName)?y.tableName:void 0}}const c=await t.get(n,o);if(!c)return{row:null,tableName:void 0};const f=o??i,u=f===void 0?[...a.keys()]:[f].filter(y=>a.has(y)),h=await Promise.all(u.map(async y=>(await t.findFirst(y,{limit:1,where:{_id:n}}))?._id===n?y:void 0));return{row:c,tableName:h.find(y=>y!==void 0)}},N=async(n,o,i)=>{const c=await E(n,o,i);return c.row&&c.tableName!==void 0?{row:c.row,tableName:c.tableName}:void 0},A=async(n,o,i,c,f,u)=>{const h=await N(n,f,u);if(!h)return i(e);const y=c?c(h.row):void 0;if(!b(h.tableName,o,h.row,y))throw new g("FORBIDDEN",`${o} denied by policy`);return i(t,h.tableName)},M=(n,o,i)=>{if(i?.hard===!0)return!1;const c=e.softDeleteFields?.get(n);return c!==void 0&&o[c]!==null&&o[c]!==void 0},F=async(n,o,i,c,f)=>{const u=i?t:e,h=await u.findFirst(o,{...i?{baseWhere:d(o).baseWhere}:{},...c?.hard===!0?{includeDeleted:!0}:{},limit:1,relationBaseWhere:w,where:f===void 0?{_id:n}:v(f,{_id:n})});if(!h||M(o,h,c))return!1;if(i&&!b(o,"delete",h))throw new g("FORBIDDEN","delete denied by policy");return await u.delete(n,o,c),!0},m=async(n,o,i,c)=>{const f=a.has(n),u=f?t:e,h=i===void 0?void 0:{hard:i},y=e.inTransaction?.()!==!0||e.deleteRereadTables?.has(n)===!0;let _=0;for(const X of o){const G=String(X._id);if(y){await F(G,n,f,h,c)&&(_+=1);continue}if(f&&!b(n,"delete",X))throw new g("FORBIDDEN","delete denied by policy");await u.delete(G,n,h),_+=1}return _},L=(n,o,i,c)=>A(n,"update",(f,u)=>i(f,{verify:u===void 0?void 0:(h,y)=>b(u,"update",h,y)}),f=>({...f,...Ie(o,f)}),c),j=(n,o)=>{const{baseWhere:i}=d(n);if(x(i))throw new g("COUNT_RLS_UNSUPPORTED",`${o}() is not supported on "${n}" inside an RLS-restricted context`)},ue=e.rankBefore,he=e.rankPageRows,{relationEdges:Q}=e,P={...e,async count(n,o){const{baseWhere:i}=d(n),c=Je(o);return p(n).count(n,{...c,baseWhere:v(c.baseWhere,i),relationBaseWhere:w,restrictsCounts:(c.restrictsCounts??!1)||x(i)})},delete:(n,o,i)=>A(n,"delete",c=>c.delete(n,o,i),void 0,o),async deleteAll(n,o){const i=Math.max(1,o?.chunkSize??le),{baseWhere:c}=d(n);let f=0;for(;;){const u=await p(n).findMany(n,{baseWhere:c,limit:i,relationBaseWhere:w}),{page:h}=u;if(h.length===0||(f+=await m(n,h,o?.hard),h.length<i))break}return{deleted:f}},async deleteMany(n,o,i){I(n.length,o?.limit,"deleteMany");for(const c of n)await A(c,"delete",f=>f.delete(c,i),void 0,i);return{deleted:n.length}},async deleteWhere(n,o,i){const{baseWhere:c}=d(n),f=await p(n).findMany(n,{baseWhere:v(o,c),relationBaseWhere:w}),u=f.page.map(h=>String(h._id));return I(u.length,i?.limit,"deleteWhere"),{deleted:await m(n,f.page,void 0,o)}},async findFirst(n,o){const{baseWhere:i}=d(n);return p(n).findFirst(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:w})},async findFirstOrThrow(n,o){const{baseWhere:i}=d(n);return p(n).findFirstOrThrow(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:w})},async explain(n,o){const{baseWhere:i}=d(n);return p(n).explain(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:w})},async findMany(n,o){const{baseWhere:i}=d(n);return p(n).findMany(n,{...o,baseWhere:v(o?.baseWhere,i),relationBaseWhere:w})},async get(n,o){const i=await E(n,o);if(!i.row)return null;if(i.tableName===void 0)return e.get(n,o);const{baseWhere:c,restricts:f}=d(i.tableName);if(!f)return e.get(n,o);if(!c)return i.row;const u=await t.findFirst(i.tableName,{baseWhere:c,limit:1,where:{_id:n}});return u?._id===n?u:null},async lookupById(n,o){const i=await E(n,o);if(!i.row)return null;if(i.tableName===void 0||!d(i.tableName).restricts)return await e.lookupById?.(n,o)??null;const{baseWhere:c}=d(i.tableName);if(!c)return{row:i.row,tableName:i.tableName};const f=await t.findFirst(i.tableName,{baseWhere:c,limit:1,where:{_id:n}});return f?._id===n?{row:f,tableName:i.tableName}:null},async insert(n,o,i){if(a.has(n)){if(!b(n,"insert",o))throw new g("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insert(n,o,i)}return e.insert(n,o,i)},async insertMany(n,o,i){if(I(o.length,i?.limit,"insertMany"),a.has(n)){for(const c of o)if(!b(n,"insert",c))throw new g("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertMany(n,o,i)}return e.insertMany(n,o,i)},async insertManyUnsafe(n,o,i){if(I(o.length,i?.limit,"insertManyUnsafe"),a.has(n)){for(const c of o)if(!b(n,"insert",c))throw new g("FORBIDDEN",`insert on "${n}" denied by policy`);return t.insertManyUnsafe(n,o,i)}return e.insertManyUnsafe(n,o,i)},patch:(n,o,i)=>L(n,o,(c,f)=>c.patch(n,o,i,f),i),assertPatchAllowed:(n,o)=>L(n,{},()=>Promise.resolve(),o),async patchIf(n,o,i){const c=await L(o,i.patch,async(u,h)=>{if(u.patchIf===void 0)throw new g("INTERNAL",`ctx.db.patchIf on "${n}" is unsupported: this writer has no conditional write`);return u.patchIf(n,o,{...i,verify:h.verify})},n);return c.doc===null||await P.get(o,n).then(u=>u!==null,u=>{if(ye(u)&&u.code==="RLS_REQUIRED")return!1;throw u})?c:{applied:c.applied,doc:null}},async patchMany(n,o,i){I(n.length,o?.limit,"patchMany");for(const c of n)await L(c.id,c.patch,(f,u)=>f.patch(c.id,c.patch,i,u),i);return{patched:n.length}},async patchWhere(n,o,i){const{baseWhere:c}=d(n),u=(await p(n).findMany(n,{baseWhere:v(o.where,c),relationBaseWhere:w})).page.map(h=>({id:String(h._id),patch:o.patch}));return I(u.length,i?.limit,"patchWhere"),P.patchMany(u,i)},query(n){const{baseWhere:o}=d(n),i=p(n).query(n);return o?i.filter(we(o,c=>q(c,o))):i},related:Q===void 0?void 0:async(n,o)=>pe({findMany:async(i,c)=>P.findMany(i,c),lookupById:async i=>t.lookupById?.(i)},Q,n,{cursor:o?.cursor,depth:o?.depth,direction:o?.direction,edges:o?.edges,limit:o?.limit,relationMask:o?.relationMask}),restore:(n,o)=>A(n,"update",async i=>{const c=i.restore??t.restore;if(!c)throw new g("BAD_REQUEST","restore is not supported by this writer");await c(n,o)},void 0,o),replace:(n,o,i)=>A(n,"update",c=>c.replace(n,o,i),c=>({...o,_creationTime:o._creationTime??c._creationTime,_id:c._id}),i),aggregate(n,o){const{baseWhere:i}=d(n);return p(n).aggregate(n,{...o,baseWhere:v(o.baseWhere,i),relationBaseWhere:w})},groupBy(n,o){const{baseWhere:i}=d(n);return p(n).groupBy(n,{...o,baseWhere:v(o.baseWhere,i),relationBaseWhere:w})},rank(n,o,i){return j(n,"rank"),p(n).rank(n,o,i)},rankPage(n,o,i){return j(n,"rankPage"),p(n).rankPage(n,o,i)},wipeShard(){throw new g("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})},...Z("rankBefore",ue,n=>(o,i,c)=>(j(o,"rankBefore"),(p(o).rankBefore??n)(o,i,c))),...Z("rankPageRows",he,n=>(o,i,c)=>(j(o,"rankPageRows"),(p(o).rankPageRows??n)(o,i,c)))};if(a.size>0)for(const[n,o]of Object.entries(e))Ve(o)&&ge(P,n);return Object.defineProperty(P,fe,{configurable:!0,enumerable:!1,value:{base:e,raw:t,steps:r},writable:!1}),P},de=e=>typeof e=="string"?e:e.name,tt=e=>{const t=new Map;for(const r of e??[])t.set(r.name,new Set((r.permissions??[]).map(s=>de(s))));return t},nt=(e,t)=>{const r=new Set;for(const s of e)for(const a of t.get(s)??[])r.add(a);return s=>r.has(de(s))},rt=["roles","role"],ot=e=>{for(const t of rt){const r=e?.[t];if(typeof r=="string"){const s=r.split(",").map(a=>a.trim()).filter(a=>a.length>0);if(s.length>0)return s}if(Array.isArray(r)){const s=r.filter(a=>typeof a=="string"&&a.length>0);if(s.length>0)return s}}return[]},st=async(e,t)=>{const r=await e.getIdentity?.()??null,s=[...new Set([...ot(r),...e.roles??[]])];return{can:nt(s,t),identity:r,roles:s,userId:e.userId??null}},ht=(e,t={})=>{const r=e,s=Ye(r),a=tt(t.roles);return be(async({ctx:d,next:b})=>{const p={auth:await st(d.auth??{},a),ctx:d},w=d.db,E=Ne(w),N=E?.base??w,A=E?.raw??w[qe]??w,M=et(N,A,[...E?.steps??[],{context:p,perTable:s}]),F={db:M},{orm:m}=d;return m!==null&&typeof m=="object"&&(F.orm=Oe(M)),b({ctx:F})},[{policies:r,roles:t.roles??[]}])};export{st as a,Ve as b,ut as c,ke as d,ot as e,xe as f,nt as g,Ke as h,tt as i,q as m,Z as o,ht 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"],K=["native","portable"],Y=e=>K.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}},H=e=>{if(e.kind==="literal")return ee(e);if(e.kind!=="optional")return e.kind;const t=e._meta?.inner;return t?H(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.`)},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,A=!1,E=!1,M=!1,O=!1,j,T,I;const D=(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 A=!0,u},get dropStalePatchesMode(){return A},externallyManaged(){return E=!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 E},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 j=i,u},get ownerField(){return j},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: ${K.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,E=!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 D(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,D(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}},Re=(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 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)})},R=(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]},Ae=e=>{const t={};for(const[n,r]of Object.entries(e.tables)){const a=R(r.geoIndexes,l=>l.name,l=>[l.field]),c=R(r.indexes,l=>l.name,l=>l.fields),d=R(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(H(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})),k=(e,t)=>`${e}_${t}`,y=(e,t,n)=>n.has(e)?k(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=k(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}:{}}}),je=(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=k(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=k(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}},De=(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{je as a,ve as b,_e as c,Le as d,Re as e,Me as f,Oe as g,Te as h,Se as i,Ae as j,De 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 @@
|
|
|
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-3ySZVrpt.mjs";import"./bindOrm-9fbLRbOb.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"./httpAction-D2S7bQzl.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-3ySZVrpt.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};
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { WhereOf } from "../data-model.mjs";
|
|
2
|
+
/** Structural mirror of `@lunora/do`'s `WhereInput`. */
|
|
3
|
+
interface WhereInput {
|
|
4
|
+
[field: string]: unknown;
|
|
5
|
+
AND?: WhereInput[];
|
|
6
|
+
NOT?: WhereInput;
|
|
7
|
+
OR?: WhereInput[];
|
|
8
|
+
}
|
|
9
|
+
/** Operations a policy can gate. `read` covers `get`/`findMany`/`query`/`count`. */
|
|
10
|
+
type PolicyOperation = "delete" | "insert" | "read" | "update";
|
|
11
|
+
/**
|
|
12
|
+
* A policy's `when` decision:
|
|
13
|
+
*
|
|
14
|
+
* - `WhereInput`: a row-shape predicate. On reads it is AND-merged into every
|
|
15
|
+
* query against the table — the row is invisible unless it matches. On writes
|
|
16
|
+
* it is evaluated against the candidate document (`insert`) or the pre-write
|
|
17
|
+
* row (`update`/`delete`); a mismatch denies the write with
|
|
18
|
+
* `LunoraError("FORBIDDEN")`. Same operator set as the SQL compiler
|
|
19
|
+
* (`eq`/`ne`/`in`/`notIn`/`lt`/`lte`/`gt`/`gte`/`isNull`/`contains` +
|
|
20
|
+
* `AND`/`OR`/`NOT`).
|
|
21
|
+
* - `true`: unrestricted. On reads no predicate is merged; on writes the row is
|
|
22
|
+
* allowed.
|
|
23
|
+
* - `false`: deny. On reads the table is forced to match zero rows (a sentinel
|
|
24
|
+
* predicate); on writes the operation throws `LunoraError("FORBIDDEN")`.
|
|
25
|
+
*
|
|
26
|
+
* Returning `undefined` opts this specific policy out (rare; useful when
|
|
27
|
+
* branching on `ctx.auth.roles`).
|
|
28
|
+
*/
|
|
29
|
+
type PolicyDecision = WhereInput | boolean | undefined;
|
|
30
|
+
/**
|
|
31
|
+
* Relation-aware twin of {@link PolicyDecision}, parameterized over the
|
|
32
|
+
* generated `DataModel` (`DM`) + `Relations` (`REL`) maps and a table `T`. A
|
|
33
|
+
* read policy may now return a Prisma-style relation predicate (the
|
|
34
|
+
* `@lunora/do` pre-resolver resolves it via a semijoin), so the typed
|
|
35
|
+
* authoring surface accepts `WhereOf<DM, REL, T>` — column predicates **and**
|
|
36
|
+
* `is`/`isNot`/`some`/`none`/`every` over `T`'s declared relations — in
|
|
37
|
+
* addition to the `boolean`/`undefined` decisions. Used by the project-bound
|
|
38
|
+
* `definePolicy` from `createPolicyDsl`.
|
|
39
|
+
*/
|
|
40
|
+
type PolicyDecisionOf<DM, REL extends Record<keyof DM, object>, T extends keyof DM> = WhereOf<DM, REL, T> | boolean | undefined;
|
|
41
|
+
/**
|
|
42
|
+
* Relation-aware input for a project-bound `definePolicy` (see
|
|
43
|
+
* `createPolicyDsl`). `table` is constrained to a real table name and
|
|
44
|
+
* `when`'s return type is the table-specific {@link PolicyDecisionOf} — so an
|
|
45
|
+
* unknown table, a stray column, or a relation predicate naming a relation the
|
|
46
|
+
* table does not declare is a compile error rather than a silent runtime deny.
|
|
47
|
+
*/
|
|
48
|
+
interface TypedDefinePolicyInput<DM, REL extends Record<keyof DM, object>, T extends keyof DM, Context = unknown, Identity = Record<string, unknown>> {
|
|
49
|
+
on: PolicyOperation;
|
|
50
|
+
table: T;
|
|
51
|
+
when: (context: PolicyContext<Context, Identity>) => PolicyDecisionOf<DM, REL, T>;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
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`
|
|
60
|
+
* answers whether any of those roles grants a permission (see
|
|
61
|
+
* {@link Permission} / {@link RlsOptions}). `row` is present only on write
|
|
62
|
+
* policies (`insert`/`update`/`delete`) — for `update` and `delete` it is the
|
|
63
|
+
* pre-write row; for `insert` it is the candidate document. `ctx` is the full
|
|
64
|
+
* procedure context the middleware closed over.
|
|
65
|
+
*/
|
|
66
|
+
interface PolicyContext<Context = unknown, Identity = Record<string, unknown>> {
|
|
67
|
+
readonly auth: {
|
|
68
|
+
/**
|
|
69
|
+
* `true` when any of the request's `roles` grants `permission` (passed
|
|
70
|
+
* by {@link Permission} object or its `name`). Always `false` when no
|
|
71
|
+
* roles were handed to the middleware (`rls(policies, { roles })`), or
|
|
72
|
+
* when none of the request's roles lists the permission.
|
|
73
|
+
*/
|
|
74
|
+
readonly can: (permission: Permission | string) => boolean;
|
|
75
|
+
/**
|
|
76
|
+
* The resolved identity, typed to the `Identity` type parameter bound on
|
|
77
|
+
* `createPolicyDsl` — e.g. the app's `defineIdentity(...)` claim type via
|
|
78
|
+
* the `InferIdentity` helper; otherwise the untyped claim bag.
|
|
79
|
+
* `undefined`/`null` when the request is anonymous.
|
|
80
|
+
*/
|
|
81
|
+
readonly identity?: Identity | null;
|
|
82
|
+
readonly roles: ReadonlyArray<string>;
|
|
83
|
+
readonly userId: null | string;
|
|
84
|
+
};
|
|
85
|
+
readonly ctx: Context;
|
|
86
|
+
readonly row?: Record<string, unknown>;
|
|
87
|
+
}
|
|
88
|
+
/** A registered policy as stored in the policy table. */
|
|
89
|
+
interface Policy<Context = unknown> {
|
|
90
|
+
readonly on: PolicyOperation;
|
|
91
|
+
readonly table: string;
|
|
92
|
+
readonly when: (context: PolicyContext<Context>) => PolicyDecision;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Input accepted by `definePolicy`. The branded result is the same
|
|
96
|
+
* shape; we keep the input/output split so callers can read JSDoc on the
|
|
97
|
+
* constructor without the type re-exposing `Policy` internals.
|
|
98
|
+
*/
|
|
99
|
+
interface DefinePolicyInput<Context = unknown> {
|
|
100
|
+
on: PolicyOperation;
|
|
101
|
+
/** Logical table name the policy applies to. */
|
|
102
|
+
table: string;
|
|
103
|
+
/**
|
|
104
|
+
* Decision function. Returning a `WhereInput` (read only) AND-merges the
|
|
105
|
+
* predicate; `true` allows; `false` denies; `undefined` skips this policy.
|
|
106
|
+
*
|
|
107
|
+
* NOTE: `count()` is **unsupported** on a policy-restricted table — the
|
|
108
|
+
* reader throws `LunoraError("COUNT_RLS_UNSUPPORTED")` (422). This mirrors
|
|
109
|
+
* kitcn's documented behavior.
|
|
110
|
+
*/
|
|
111
|
+
when: (context: PolicyContext<Context>) => PolicyDecision;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* A named, abstract capability a policy can check with `ctx.auth.can(...)`,
|
|
115
|
+
* instead of branching on raw role strings. Declare one with
|
|
116
|
+
* `definePermission`; grant it to a role via {@link Role.permissions};
|
|
117
|
+
* register the roles with the middleware via {@link RlsOptions.roles}.
|
|
118
|
+
*/
|
|
119
|
+
interface Permission {
|
|
120
|
+
readonly description?: string;
|
|
121
|
+
readonly name: string;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
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
|
|
131
|
+
* `ctx.auth.can(permission)` rather than enumerate roles.
|
|
132
|
+
*/
|
|
133
|
+
interface Role {
|
|
134
|
+
readonly description?: string;
|
|
135
|
+
readonly name: string;
|
|
136
|
+
/** Permissions this role grants — by {@link Permission} object or bare name. */
|
|
137
|
+
readonly permissions?: ReadonlyArray<Permission | string>;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Options for the `rls(policies, options)` middleware. `roles` registers the
|
|
141
|
+
* role→permission grants that back `ctx.auth.can(...)`; a role not listed here
|
|
142
|
+
* grants no permissions (so `can` is conservative — it fails closed for
|
|
143
|
+
* unknown roles).
|
|
144
|
+
*/
|
|
145
|
+
interface RlsOptions {
|
|
146
|
+
readonly roles?: ReadonlyArray<Role>;
|
|
147
|
+
}
|
|
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 };
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { WhereOf } from "../data-model.js";
|
|
2
|
+
/** Structural mirror of `@lunora/do`'s `WhereInput`. */
|
|
3
|
+
interface WhereInput {
|
|
4
|
+
[field: string]: unknown;
|
|
5
|
+
AND?: WhereInput[];
|
|
6
|
+
NOT?: WhereInput;
|
|
7
|
+
OR?: WhereInput[];
|
|
8
|
+
}
|
|
9
|
+
/** Operations a policy can gate. `read` covers `get`/`findMany`/`query`/`count`. */
|
|
10
|
+
type PolicyOperation = "delete" | "insert" | "read" | "update";
|
|
11
|
+
/**
|
|
12
|
+
* A policy's `when` decision:
|
|
13
|
+
*
|
|
14
|
+
* - `WhereInput`: a row-shape predicate. On reads it is AND-merged into every
|
|
15
|
+
* query against the table — the row is invisible unless it matches. On writes
|
|
16
|
+
* it is evaluated against the candidate document (`insert`) or the pre-write
|
|
17
|
+
* row (`update`/`delete`); a mismatch denies the write with
|
|
18
|
+
* `LunoraError("FORBIDDEN")`. Same operator set as the SQL compiler
|
|
19
|
+
* (`eq`/`ne`/`in`/`notIn`/`lt`/`lte`/`gt`/`gte`/`isNull`/`contains` +
|
|
20
|
+
* `AND`/`OR`/`NOT`).
|
|
21
|
+
* - `true`: unrestricted. On reads no predicate is merged; on writes the row is
|
|
22
|
+
* allowed.
|
|
23
|
+
* - `false`: deny. On reads the table is forced to match zero rows (a sentinel
|
|
24
|
+
* predicate); on writes the operation throws `LunoraError("FORBIDDEN")`.
|
|
25
|
+
*
|
|
26
|
+
* Returning `undefined` opts this specific policy out (rare; useful when
|
|
27
|
+
* branching on `ctx.auth.roles`).
|
|
28
|
+
*/
|
|
29
|
+
type PolicyDecision = WhereInput | boolean | undefined;
|
|
30
|
+
/**
|
|
31
|
+
* Relation-aware twin of {@link PolicyDecision}, parameterized over the
|
|
32
|
+
* generated `DataModel` (`DM`) + `Relations` (`REL`) maps and a table `T`. A
|
|
33
|
+
* read policy may now return a Prisma-style relation predicate (the
|
|
34
|
+
* `@lunora/do` pre-resolver resolves it via a semijoin), so the typed
|
|
35
|
+
* authoring surface accepts `WhereOf<DM, REL, T>` — column predicates **and**
|
|
36
|
+
* `is`/`isNot`/`some`/`none`/`every` over `T`'s declared relations — in
|
|
37
|
+
* addition to the `boolean`/`undefined` decisions. Used by the project-bound
|
|
38
|
+
* `definePolicy` from `createPolicyDsl`.
|
|
39
|
+
*/
|
|
40
|
+
type PolicyDecisionOf<DM, REL extends Record<keyof DM, object>, T extends keyof DM> = WhereOf<DM, REL, T> | boolean | undefined;
|
|
41
|
+
/**
|
|
42
|
+
* Relation-aware input for a project-bound `definePolicy` (see
|
|
43
|
+
* `createPolicyDsl`). `table` is constrained to a real table name and
|
|
44
|
+
* `when`'s return type is the table-specific {@link PolicyDecisionOf} — so an
|
|
45
|
+
* unknown table, a stray column, or a relation predicate naming a relation the
|
|
46
|
+
* table does not declare is a compile error rather than a silent runtime deny.
|
|
47
|
+
*/
|
|
48
|
+
interface TypedDefinePolicyInput<DM, REL extends Record<keyof DM, object>, T extends keyof DM, Context = unknown, Identity = Record<string, unknown>> {
|
|
49
|
+
on: PolicyOperation;
|
|
50
|
+
table: T;
|
|
51
|
+
when: (context: PolicyContext<Context, Identity>) => PolicyDecisionOf<DM, REL, T>;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
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`
|
|
60
|
+
* answers whether any of those roles grants a permission (see
|
|
61
|
+
* {@link Permission} / {@link RlsOptions}). `row` is present only on write
|
|
62
|
+
* policies (`insert`/`update`/`delete`) — for `update` and `delete` it is the
|
|
63
|
+
* pre-write row; for `insert` it is the candidate document. `ctx` is the full
|
|
64
|
+
* procedure context the middleware closed over.
|
|
65
|
+
*/
|
|
66
|
+
interface PolicyContext<Context = unknown, Identity = Record<string, unknown>> {
|
|
67
|
+
readonly auth: {
|
|
68
|
+
/**
|
|
69
|
+
* `true` when any of the request's `roles` grants `permission` (passed
|
|
70
|
+
* by {@link Permission} object or its `name`). Always `false` when no
|
|
71
|
+
* roles were handed to the middleware (`rls(policies, { roles })`), or
|
|
72
|
+
* when none of the request's roles lists the permission.
|
|
73
|
+
*/
|
|
74
|
+
readonly can: (permission: Permission | string) => boolean;
|
|
75
|
+
/**
|
|
76
|
+
* The resolved identity, typed to the `Identity` type parameter bound on
|
|
77
|
+
* `createPolicyDsl` — e.g. the app's `defineIdentity(...)` claim type via
|
|
78
|
+
* the `InferIdentity` helper; otherwise the untyped claim bag.
|
|
79
|
+
* `undefined`/`null` when the request is anonymous.
|
|
80
|
+
*/
|
|
81
|
+
readonly identity?: Identity | null;
|
|
82
|
+
readonly roles: ReadonlyArray<string>;
|
|
83
|
+
readonly userId: null | string;
|
|
84
|
+
};
|
|
85
|
+
readonly ctx: Context;
|
|
86
|
+
readonly row?: Record<string, unknown>;
|
|
87
|
+
}
|
|
88
|
+
/** A registered policy as stored in the policy table. */
|
|
89
|
+
interface Policy<Context = unknown> {
|
|
90
|
+
readonly on: PolicyOperation;
|
|
91
|
+
readonly table: string;
|
|
92
|
+
readonly when: (context: PolicyContext<Context>) => PolicyDecision;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Input accepted by `definePolicy`. The branded result is the same
|
|
96
|
+
* shape; we keep the input/output split so callers can read JSDoc on the
|
|
97
|
+
* constructor without the type re-exposing `Policy` internals.
|
|
98
|
+
*/
|
|
99
|
+
interface DefinePolicyInput<Context = unknown> {
|
|
100
|
+
on: PolicyOperation;
|
|
101
|
+
/** Logical table name the policy applies to. */
|
|
102
|
+
table: string;
|
|
103
|
+
/**
|
|
104
|
+
* Decision function. Returning a `WhereInput` (read only) AND-merges the
|
|
105
|
+
* predicate; `true` allows; `false` denies; `undefined` skips this policy.
|
|
106
|
+
*
|
|
107
|
+
* NOTE: `count()` is **unsupported** on a policy-restricted table — the
|
|
108
|
+
* reader throws `LunoraError("COUNT_RLS_UNSUPPORTED")` (422). This mirrors
|
|
109
|
+
* kitcn's documented behavior.
|
|
110
|
+
*/
|
|
111
|
+
when: (context: PolicyContext<Context>) => PolicyDecision;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* A named, abstract capability a policy can check with `ctx.auth.can(...)`,
|
|
115
|
+
* instead of branching on raw role strings. Declare one with
|
|
116
|
+
* `definePermission`; grant it to a role via {@link Role.permissions};
|
|
117
|
+
* register the roles with the middleware via {@link RlsOptions.roles}.
|
|
118
|
+
*/
|
|
119
|
+
interface Permission {
|
|
120
|
+
readonly description?: string;
|
|
121
|
+
readonly name: string;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
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
|
|
131
|
+
* `ctx.auth.can(permission)` rather than enumerate roles.
|
|
132
|
+
*/
|
|
133
|
+
interface Role {
|
|
134
|
+
readonly description?: string;
|
|
135
|
+
readonly name: string;
|
|
136
|
+
/** Permissions this role grants — by {@link Permission} object or bare name. */
|
|
137
|
+
readonly permissions?: ReadonlyArray<Permission | string>;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Options for the `rls(policies, options)` middleware. `roles` registers the
|
|
141
|
+
* role→permission grants that back `ctx.auth.can(...)`; a role not listed here
|
|
142
|
+
* grants no permissions (so `can` is conservative — it fails closed for
|
|
143
|
+
* unknown roles).
|
|
144
|
+
*/
|
|
145
|
+
interface RlsOptions {
|
|
146
|
+
readonly roles?: ReadonlyArray<Role>;
|
|
147
|
+
}
|
|
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 };
|