@lunora/server 1.0.0-alpha.111 → 1.0.0-alpha.113
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/data-model.d.mts +13 -0
- package/dist/data-model.d.ts +13 -0
- package/dist/index.d.mts +7 -1
- package/dist/index.d.ts +7 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{assertShapesDeclareReadPolicies-CL7JKaIK.mjs → assertShapesDeclareReadPolicies-BCyJRmhj.mjs} +1 -1
- package/dist/packem_shared/bindOrm-D_hFUjmr.mjs +1 -0
- package/dist/packem_shared/{defineShape-DH52g6sI.mjs → defineShape-P9JuGPRq.mjs} +1 -1
- package/dist/packem_shared/{mask-DHt_WzTL.mjs → mask-MQFwprP0.mjs} +1 -1
- package/dist/packem_shared/{middleware-CoVBvN2z.mjs → middleware-BZcRFqUp.mjs} +1 -1
- package/dist/packem_shared/{rls-DrwDXR5u.mjs → rls-DJSGDVQX.mjs} +1 -1
- package/dist/packem_shared/{storageRules-BleDJNal.mjs → storageRules-CZOzWcxr.mjs} +1 -1
- package/dist/rls/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/packem_shared/bindOrm-ChQydkdL.mjs +0 -1
package/dist/data-model.d.mts
CHANGED
|
@@ -360,6 +360,19 @@ interface TableReaderFacade<DM, REL extends Record<keyof DM, object>, RANK exten
|
|
|
360
360
|
select?: S;
|
|
361
361
|
with?: W;
|
|
362
362
|
}) => Promise<QueryPage<LoadWith<DM, REL, T, W, S>>>;
|
|
363
|
+
/**
|
|
364
|
+
* The one row matching `where`, or `null` when none does — and a `NOT_UNIQUE`
|
|
365
|
+
* error when a SECOND one matches, so a broken uniqueness invariant surfaces at
|
|
366
|
+
* the read rather than as a wrong answer downstream. `findFirst` drops that
|
|
367
|
+
* assertion; this is the ORM spelling of the fluent reader's `.unique()`.
|
|
368
|
+
*
|
|
369
|
+
* `limit`/`cursor` are not accepted rather than silently ignored: paging a read
|
|
370
|
+
* that must match at most one row is the assertion being dropped again.
|
|
371
|
+
*/
|
|
372
|
+
findUnique: <W extends WithArg<DM, REL, T> = {}, S extends ReadonlyArray<keyof DM[T] & string> | undefined = undefined>(args?: Omit<QueryArgsOf<DM, REL, T>, "cursor" | "limit"> & {
|
|
373
|
+
select?: S;
|
|
374
|
+
with?: W;
|
|
375
|
+
}) => Promise<LoadWith<DM, REL, T, W, S> | null>;
|
|
363
376
|
get: (id: Id<string & T>) => Promise<DM[T] | null>;
|
|
364
377
|
/**
|
|
365
378
|
* Group rows by the named keys and apply `agg` per group (defaults to
|
package/dist/data-model.d.ts
CHANGED
|
@@ -360,6 +360,19 @@ interface TableReaderFacade<DM, REL extends Record<keyof DM, object>, RANK exten
|
|
|
360
360
|
select?: S;
|
|
361
361
|
with?: W;
|
|
362
362
|
}) => Promise<QueryPage<LoadWith<DM, REL, T, W, S>>>;
|
|
363
|
+
/**
|
|
364
|
+
* The one row matching `where`, or `null` when none does — and a `NOT_UNIQUE`
|
|
365
|
+
* error when a SECOND one matches, so a broken uniqueness invariant surfaces at
|
|
366
|
+
* the read rather than as a wrong answer downstream. `findFirst` drops that
|
|
367
|
+
* assertion; this is the ORM spelling of the fluent reader's `.unique()`.
|
|
368
|
+
*
|
|
369
|
+
* `limit`/`cursor` are not accepted rather than silently ignored: paging a read
|
|
370
|
+
* that must match at most one row is the assertion being dropped again.
|
|
371
|
+
*/
|
|
372
|
+
findUnique: <W extends WithArg<DM, REL, T> = {}, S extends ReadonlyArray<keyof DM[T] & string> | undefined = undefined>(args?: Omit<QueryArgsOf<DM, REL, T>, "cursor" | "limit"> & {
|
|
373
|
+
select?: S;
|
|
374
|
+
with?: W;
|
|
375
|
+
}) => Promise<LoadWith<DM, REL, T, W, S> | null>;
|
|
363
376
|
get: (id: Id<string & T>) => Promise<DM[T] | null>;
|
|
364
377
|
/**
|
|
365
378
|
* Group rows by the named keys and apply `agg` per group (defaults to
|
package/dist/index.d.mts
CHANGED
|
@@ -680,7 +680,11 @@ interface TableBuilder<Shape extends Record<string, Validator> = Record<string,
|
|
|
680
680
|
global: (options?: {
|
|
681
681
|
backend?: GlobalBackend;
|
|
682
682
|
}) => TableBuilder<Shape>;
|
|
683
|
-
/**
|
|
683
|
+
/**
|
|
684
|
+
* Add a secondary index. `fields` are top-level columns (plus the system
|
|
685
|
+
* fields) — a dotted path into a `v.object()` column is not accepted;
|
|
686
|
+
* denormalise the field you query. See `concepts/indexes` for why.
|
|
687
|
+
*/
|
|
684
688
|
index: (name: string, fields: ReadonlyArray<(keyof Shape & string) | (typeof SYSTEM_INDEX_FIELDS)[number]>, options?: {
|
|
685
689
|
unique?: boolean;
|
|
686
690
|
}) => TableBuilder<Shape>;
|
|
@@ -1503,6 +1507,8 @@ interface FacadeEntry {
|
|
|
1503
1507
|
findFirst: (args?: unknown) => Promise<unknown>;
|
|
1504
1508
|
findFirstOrThrow: (args?: unknown) => Promise<unknown>;
|
|
1505
1509
|
findMany: (args?: unknown) => Promise<unknown>;
|
|
1510
|
+
/** The one row matching `where`, or `null`. Throws `NOT_UNIQUE` when a second one matches. */
|
|
1511
|
+
findUnique: (args?: unknown) => Promise<unknown>;
|
|
1506
1512
|
get: (id: string) => Promise<unknown>;
|
|
1507
1513
|
groupBy: (options: unknown) => Promise<unknown>;
|
|
1508
1514
|
/** Physically remove a row (and physically cascade), bypassing `.softDelete()`. */
|
package/dist/index.d.ts
CHANGED
|
@@ -680,7 +680,11 @@ interface TableBuilder<Shape extends Record<string, Validator> = Record<string,
|
|
|
680
680
|
global: (options?: {
|
|
681
681
|
backend?: GlobalBackend;
|
|
682
682
|
}) => TableBuilder<Shape>;
|
|
683
|
-
/**
|
|
683
|
+
/**
|
|
684
|
+
* Add a secondary index. `fields` are top-level columns (plus the system
|
|
685
|
+
* fields) — a dotted path into a `v.object()` column is not accepted;
|
|
686
|
+
* denormalise the field you query. See `concepts/indexes` for why.
|
|
687
|
+
*/
|
|
684
688
|
index: (name: string, fields: ReadonlyArray<(keyof Shape & string) | (typeof SYSTEM_INDEX_FIELDS)[number]>, options?: {
|
|
685
689
|
unique?: boolean;
|
|
686
690
|
}) => TableBuilder<Shape>;
|
|
@@ -1503,6 +1507,8 @@ interface FacadeEntry {
|
|
|
1503
1507
|
findFirst: (args?: unknown) => Promise<unknown>;
|
|
1504
1508
|
findFirstOrThrow: (args?: unknown) => Promise<unknown>;
|
|
1505
1509
|
findMany: (args?: unknown) => Promise<unknown>;
|
|
1510
|
+
/** The one row matching `where`, or `null`. Throws `NOT_UNIQUE` when a second one matches. */
|
|
1511
|
+
findUnique: (args?: unknown) => Promise<unknown>;
|
|
1506
1512
|
get: (id: string) => Promise<unknown>;
|
|
1507
1513
|
groupBy: (options: unknown) => Promise<unknown>;
|
|
1508
1514
|
/** Physically remove a row (and physically cascade), bypassing `.softDelete()`. */
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-BUng3KOy.mjs";import{initLunora as d}from"./packem_shared/initLunora-BzC2zEfH.mjs";import{createSecrets as p}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{flushDeferredDeletes as c,withDeferredDeletes as l}from"./packem_shared/flushDeferredDeletes-DEJXlhop.mjs";import{beginDeferredSchedules as S,withDeferredSchedules as u}from"./packem_shared/beginDeferredSchedules-gJlbW6h9.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as T,DOCUMENT_HISTORY_TABLE as D,defineDocumentHistory as g,documentHistoryExtension as A}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-g-fdcytr.mjs";import{LunoraEnvError as _,defineEnv as L,redactSecrets as C}from"./packem_shared/LunoraEnvError-A5I-PzMh.mjs";import{bindOrm as y,bindTableFacade as P}from"./packem_shared/bindOrm-
|
|
1
|
+
import{ACTION_CACHE_DEFAULT_TTL_MS as t,ACTION_CACHE_TABLE as n,actionCacheExtension as i,cacheKeyFor as a,defineActionCache as f}from"./packem_shared/ACTION_CACHE_DEFAULT_TTL_MS-BUng3KOy.mjs";import{initLunora as d}from"./packem_shared/initLunora-BzC2zEfH.mjs";import{createSecrets as p}from"./packem_shared/createSecrets-D6rLB42U.mjs";import{flushDeferredDeletes as c,withDeferredDeletes as l}from"./packem_shared/flushDeferredDeletes-DEJXlhop.mjs";import{beginDeferredSchedules as S,withDeferredSchedules as u}from"./packem_shared/beginDeferredSchedules-gJlbW6h9.mjs";import{DOCUMENT_HISTORY_REDACTED_FIELDS as T,DOCUMENT_HISTORY_TABLE as D,defineDocumentHistory as g,documentHistoryExtension as A}from"./packem_shared/DOCUMENT_HISTORY_REDACTED_FIELDS-g-fdcytr.mjs";import{LunoraEnvError as _,defineEnv as L,redactSecrets as C}from"./packem_shared/LunoraEnvError-A5I-PzMh.mjs";import{bindOrm as y,bindTableFacade as P}from"./packem_shared/bindOrm-D_hFUjmr.mjs";import{httpAction as M,httpRoute as F,httpRouter as O,isSafeHeaderValue as H}from"./packem_shared/httpAction-DfKw8ZZt.mjs";import{serveStorageObject as U}from"./packem_shared/serveStorageObject-BzZEP-B5.mjs";import{defineIdentity as v}from"./packem_shared/defineIdentity-DwkNKwYa.mjs";import{onConnect as B,onDisconnect as V,onShardInit as j}from"./packem_shared/onConnect-BLRoOpv2.mjs";import{DEFAULT_LIMIT as Y,DEFAULT_MAX_LIMIT as J,clampLimit as K,defineListArgs as Q}from"./packem_shared/DEFAULT_LIMIT-vNtdsa5y.mjs";import{defineMigration as q}from"./packem_shared/defineMigration-CXOS0Bvq.mjs";import{defineMutator as G}from"./packem_shared/defineMutator-DKy8UtbB.mjs";import{c as $,d as ee,a as re,b as oe,e as te,f as ne,g as ie,h as ae,i as fe,j as se,k as de,m as me}from"./packem_shared/plugin-DY0N7ZWx.mjs";import{PRESENCE_DEFAULT_TTL_MS as xe,PRESENCE_TABLE as ce,definePresence as le,presenceExtension as Ee}from"./packem_shared/PRESENCE_DEFAULT_TTL_MS-DheiApL3.mjs";import{protectPublic as ue}from"./packem_shared/protectPublic-C-STrTgA.mjs";import{onQueryChange as Te}from"./packem_shared/onQueryChange-CatdYnH5.mjs";import{defineShape as ge}from"./packem_shared/defineShape-P9JuGPRq.mjs";import{anyApi as Re}from"./types.mjs";import{LunoraError as Le}from"@lunora/errors";import{cronJobs as Ie}from"@lunora/scheduler";import{ValidationError as Pe,v as be}from"@lunora/values";import{allowAll as Fe,deny as Oe,isDeny as He,toWhereInput as Ne}from"./packem_shared/allowAll-DkRAgItV.mjs";import{asBucketStorage as ke}from"./packem_shared/asBucketStorage-DoGYOjq3.mjs";import{assertShapesDeclareReadPolicies as we,buildRlsReadRegistry as Be,composeShapeReadWhere as Ve}from"./packem_shared/assertShapesDeclareReadPolicies-BCyJRmhj.mjs";import{buildMaskRegistry as We}from"./packem_shared/buildMaskRegistry-DpWMtalG.mjs";import{createPolicyDsl as Je,definePermission as Ke,definePolicies as Qe,definePolicy as Xe,defineRole as qe}from"./packem_shared/createPolicyDsl-BZa6SqLJ.mjs";import{defineStorageRule as Ge,defineStorageRules as Ze}from"./packem_shared/defineStorageRule-Dv4nJE0H.mjs";import{mask as er}from"./packem_shared/mask-MQFwprP0.mjs";import{r as or}from"./packem_shared/middleware-BZcRFqUp.mjs";import{storageRules as nr}from"./packem_shared/storageRules-CZOzWcxr.mjs";const e="0.0.0";export{t as ACTION_CACHE_DEFAULT_TTL_MS,n as ACTION_CACHE_TABLE,Y as DEFAULT_LIMIT,J as DEFAULT_MAX_LIMIT,T as DOCUMENT_HISTORY_REDACTED_FIELDS,D as DOCUMENT_HISTORY_TABLE,_ as LunoraEnvError,Le as LunoraError,xe as PRESENCE_DEFAULT_TTL_MS,ce as PRESENCE_TABLE,e as VERSION,Pe as ValidationError,i as actionCacheExtension,Fe as allowAll,Re as anyApi,ke as asBucketStorage,we as assertShapesDeclareReadPolicies,S as beginDeferredSchedules,y as bindOrm,P as bindTableFacade,We as buildMaskRegistry,Be as buildRlsReadRegistry,a as cacheKeyFor,K as clampLimit,$ as composePluginMiddleware,Ve as composeShapeReadWhere,Je as createPolicyDsl,p as createSecrets,Ie as cronJobs,f as defineActionCache,ee as defineAggregateIndex,re as defineComponent,g as defineDocumentHistory,L as defineEnv,v as defineIdentity,Q as defineListArgs,q as defineMigration,G as defineMutator,Ke as definePermission,oe as definePlugin,Qe as definePolicies,Xe as definePolicy,le as definePresence,te as defineRankIndex,qe as defineRole,ne as defineSchema,ie as defineSchemaExtension,ge as defineShape,Ge as defineStorageRule,Ze as defineStorageRules,ae as defineTable,fe as defineVectorIndex,Oe as deny,A as documentHistoryExtension,c as flushDeferredDeletes,M as httpAction,F as httpRoute,O as httpRouter,se as indexFieldsFromSchema,d as initLunora,de as installPlugins,He as isDeny,H as isSafeHeaderValue,er as mask,me as mergeSchemaExtension,B as onConnect,V as onDisconnect,Te as onQueryChange,j as onShardInit,Ee as presenceExtension,ue as protectPublic,C as redactSecrets,or as rls,U as serveStorageObject,nr as storageRules,Ne as toWhereInput,be as v,l as withDeferredDeletes,u as withDeferredSchedules};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{i as p,d as g,f as b,e as y}from"./middleware-
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{i as p,d as g,f as b,e as y}from"./middleware-BZcRFqUp.mjs";import{r as w}from"./policy-tag-V0lqFzgS.mjs";import{deny as m}from"./allowAll-DkRAgItV.mjs";const h=m(),v=t=>{const e=t?.rls?.tags;return e||w(t)},R=(t,e)=>{const r=p(e.roles),o=new Map,n=new Map;for(const s of e.policies){if(s.on!=="read")continue;const a=o.get(s.table)??new Set;if(a.has(s.when))continue;a.add(s.when),o.set(s.table,a);const l=n.get(s.table)??[];l.push(s),n.set(s.table,l)}for(const[s,a]of n){const l=t.get(s)??[];l.push({policies:a,rolePermissions:r}),t.set(s,l)}},d=t=>{const e=t.OR;return Array.isArray(e)&&e.length===0&&Object.keys(t).length===1},T=(t,e)=>!t||Object.keys(t).length===0?e:d(t)||Object.keys(e).length===0?t:{AND:[t,e]},S=(t,e)=>{const r=g(e.identity);return b(t.policies,{auth:{can:y(r,t.rolePermissions),identity:e.identity,roles:r,userId:e.userId},ctx:e.ctx})},A=(t,e)=>{const r=t.byTable.get(e.table);if(!r||r.length===0)return e.rlsRequired&&!e.tablePublic?h:void 0;const o=[];for(const n of r){const s=S(n,e);if(s===void 0)return;d(s)||o.push(s)}return o.length===0?h:o.length===1?o[0]:{OR:o}},O=t=>{const e=new Map,r=new Set;for(const o of t)for(const n of v(o))r.has(n)||(r.add(n),R(e,n));return{byTable:e}},W=(t,e,r)=>{if(r)return;const o=new Set(e),n=Object.entries(t).filter(([,i])=>o.has(i.table)),s=i=>i.map(([u,f])=>`"${u}" (table "${f.table}")`).join(", "),a=n.filter(([,i])=>i.use===void 0);if(a.length>0)throw new c("INTERNAL",`defineShape ${s(a)} replicate${a.length===1?"s":""} a table this project's rls() read policies restrict, but declare${a.length===1?"s":""} no \`use\` — a shape runs no procedure, so those policies never reach it and every subscriber would replicate every row the shape's own \`where\` admits. Name the guards the equivalent query lists: \`defineShape({ use: [<the rls() guard>], ... })\`. If the shape really is meant to be ungoverned (its own \`where\` is the whole filter), say so with \`use: []\`.`);const l=n.filter(([,i])=>i.use!==void 0&&i.use.length>0&&!i.rlsRegistry.byTable.has(i.table));if(l.length>0)throw new c("INTERNAL",`defineShape ${s(l)} name \`use\` guards that declare no \`on: "read"\` policy for that table, so nothing governs what replicates and the shape's own \`where\` is the whole filter — the same gap a missing \`use\` leaves, on a table this project's rls() read policies restrict. A guard for a different table, or a middleware carrying no rls() policies at all, does not count: name the same rls() guard the equivalent query lists. If the shape really is meant to be ungoverned, say so with \`use: []\`.`)},$=(t,e)=>T(A(t,e),e.shapeWhere);export{W as assertShapesDeclareReadPolicies,O as buildRlsReadRegistry,$ as composeShapeReadWhere};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as d}from"@lunora/errors";const a=e=>typeof e=="object"&&e!==null&&e.code==="CONFLICT"&&e.kind==="unique",p=(e,t,r)=>{const o=typeof t=="string"?[t]:t;if(o.length===0)throw new d("INTERNAL",`ctx.db.${e}.upsert: "target" must name at least one field`);const h={};for(const n of o){if(!(n in r))throw new d("INTERNAL",`ctx.db.${e}.upsert: target field "${n}" is missing from the create document`);h[n]=r[n]}return h},l=(e,t)=>{const r=async(n,s)=>{if(s?.skipDuplicates!==!0)return e.insert(t,n);try{return await e.insert(t,n)}catch(i){if(a(i))return null;throw i}},o=async n=>{const s=n??{},i=await e.findMany(t,{...s,limit:2});if(i.page.length>1)throw new d("NOT_UNIQUE",`ctx.db.${t}.findUnique matched more than one document; expected at most one`);return i.page[0]??null},h=async({create:n,target:s,update:i})=>{const c=p(t,s,n),u=await e.findFirst(t,{where:c});return u&&typeof u._id=="string"?(await e.patch(u._id,i??n,t),{created:!1,id:u._id}):{created:!0,id:await e.insert(t,n)}};return{aggregate:n=>e.aggregate(t,n),count:n=>e.count(t,n),delete:n=>e.delete(n,t),deleteMany:(n,s)=>{if(Array.isArray(n)){if(e.deleteMany===void 0)throw new d("INTERNAL",`ctx.db.${t}.deleteMany is unavailable: this writer has no batch delete`);return e.deleteMany(n,s,t)}if(e.deleteWhere===void 0)throw new d("INTERNAL",`ctx.db.${t}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);const i=n;return e.deleteWhere(t,i.where,{limit:i.limit})},exists:async n=>await e.findFirst(t,n===void 0?void 0:{where:n})!==null,findFirst:n=>e.findFirst(t,n),findFirstOrThrow:n=>e.findFirstOrThrow(t,n),findMany:n=>e.findMany(t,n),findUnique:o,get:n=>e.get(n,t),groupBy:n=>e.groupBy(t,n),hardDelete:n=>e.delete(n,t,{hard:!0}),insert:r,insertMany:(n,s)=>{if(e.insertMany===void 0)throw new d("INTERNAL",`ctx.db.${t}.insertMany is unavailable: this writer has no batch insert`);return e.insertMany(t,n,s)},patch:(n,s)=>e.patch(n,s,t),patchMany:(n,s)=>{if(Array.isArray(n)){if(e.patchMany===void 0)throw new d("INTERNAL",`ctx.db.${t}.patchMany is unavailable: this writer has no batch patch`);return e.patchMany(n.map(c=>({id:c.id,patch:c.values})),s,t)}if(e.patchWhere===void 0)throw new d("INTERNAL",`ctx.db.${t}.patchMany({ where, values }) is unavailable: this writer has no where-based patch`);const i=n;return e.patchWhere(t,{patch:i.values,where:i.where},{limit:i.limit})},rank:(n,s)=>e.rank(t,n,s),rankPage:(n,s)=>e.rankPage(t,n,s),replace:(n,s)=>e.replace(n,s,t),restore:async n=>{if(!e.restore)throw new d("INTERNAL",`ctx.db.${t}.restore is unavailable: this writer has no restore (is the table .softDelete()?)`);await e.restore(n,t)},upsert:h,upsertMany:async({rows:n,target:s})=>{const i=[];for(const c of n)i.push(await h({create:c.create,target:s,update:c.update}));return i},withGeoIndex:(n,s)=>e.query(t).withGeoIndex(n,s),withSearchIndex:(n,s)=>e.query(t).withSearchIndex(n,s)}},g=e=>{const t=r=>{const o=e[r];if(!o)throw new d("INTERNAL",`unknown table: ${r}`);return o};return{delete:(r,o)=>t(r).delete(o),insert:r=>({values:o=>t(r).insert(o)}),query:e,replace:(r,o)=>({with:h=>t(r).replace(o,h)}),update:(r,o)=>({set:h=>t(r).patch(o,h)})}};export{g as bindOrm,l as bindTableFacade};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as r}from"@lunora/errors";import{c as p}from"./context-identity-B2XYGA0B.mjs";import{v as u}from"./functions-B2-H4PQT.mjs";import{toWhereInput as m,deny as d}from"./allowAll-DkRAgItV.mjs";import{buildRlsReadRegistry as c}from"./assertShapesDeclareReadPolicies-
|
|
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-BCyJRmhj.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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as S}from"@lunora/errors";import{f as U}from"./fnv1a-D3ueNTWB.mjs";import{i as L,a as z,o as _,b as G,c as C}from"./middleware-
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{f as U}from"./fnv1a-D3ueNTWB.mjs";import{i as L,a as z,o as _,b as G,c as C}from"./middleware-BZcRFqUp.mjs";import{bindTableFacade as H,bindOrm as J}from"./bindOrm-D_hFUjmr.mjs";import{tagMaskMiddleware as Q}from"./buildMaskRegistry-DpWMtalG.mjs";const V=(e,i,f)=>{try{return e==="redact"?null:e==="hash"?i==null?i:typeof i=="bigint"?U(i.toString()):U(typeof i=="string"?i:JSON.stringify(i)):e(i,f)}catch{return null}},u=(e,i,f)=>{const d={...e};for(const[y,g]of Object.entries(i))y in d&&(d[y]=V(g,e[y],{...f,column:y,row:e}));return d},j=(e,i,f)=>({...e,page:e.page.map(d=>u(d,i,f))}),D=(e,i,f,d)=>{if(typeof e!="function")return;const y=new Set,g=()=>new Proxy({},{get:()=>w=>(typeof w=="string"&&y.add(w),g())});e(g());for(const w of y)if(w in i)throw new S("MASK_UNSUPPORTED",`${d}() filtering "${f}" by masked column "${w}" is not supported`)},X=(e,i,f,d)=>{const y=e.rankBefore,g=e.rankPageRows,w=(r,n)=>{const t=i.get(r);return t?n.map(o=>u(o,t,f)):n},l=r=>{const n=r?.relationMask;return{...r,relationMask:n===void 0?w:(t,o)=>n(t,w(t,o))}},k=(r,n,t,o)=>{const s=i.get(r);if(!s)return;const c=d?.[r]?.[o]?.[n];if(!c)return;const a=c.find(E=>E in s);if(a!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() reading "${r}" via index "${n}" would order rows by masked column "${a}" — use an index whose declared fields are all unmasked, or unmask the column`)},p=(r,n,t)=>({async*[Symbol.asyncIterator](){for await(const o of{[Symbol.asyncIterator]:()=>r[Symbol.asyncIterator]()})yield u(o,n,f)},collect:async()=>(await r.collect()).map(s=>u(s,n,f)),collectWithScores:async()=>(await r.collectWithScores()).map(s=>{const c=u(s.document,n,f);return"distanceMeters"in s?{distanceMeters:null,document:c}:{document:c,score:s.score}}),filter:o=>p(r.filter(s=>o(u(s,n,f))),n,t),first:async()=>{const o=await r.first();return o?u(o,n,f):null},order:o=>p(r.order(o),n,t),paginate:async o=>j(await r.paginate(o),n,f),take:async o=>(await r.take(o)).map(c=>u(c,n,f)),unique:async()=>{const o=await r.unique();return o?u(o,n,f):null},withIndex:(o,s)=>(k(t,o,"withIndex","index"),D(s,n,t,"withIndex"),p(r.withIndex(o,s),n,t)),withSearchIndex:(o,s)=>(D(s,n,t,"withSearchIndex"),p(r.withSearchIndex(o,s),n,t)),withGeoIndex:(o,s)=>(k(t,o,"withGeoIndex","geo"),p(r.withGeoIndex(o,s),n,t))}),O=async(r,n)=>{if(e.lookupById){const a=await e.lookupById(r,n);if(a)return{row:a.row,tableName:i.has(a.tableName)?a.tableName:void 0}}const t=await e.get(r,n);if(!t)return{row:null,tableName:void 0};const o=n!==void 0&&i.has(n)?[n]:[],s=n===void 0?[...i.keys()]:o,c=await Promise.all(s.map(async a=>(await e.findFirst(a,{limit:1,where:{_id:r}}))?._id===r?a:void 0));return{row:t,tableName:c.find(a=>a!==void 0)}},P=(r,n,t)=>{const o=i.get(r);if(!o)return;const s=n.find(c=>typeof c=="string"&&c in o);if(s!==void 0)throw new S("MASK_UNSUPPORTED",`${t}() over masked column "${s}" on "${r}" is not supported`)},A=new Set;for(const r of i.values())for(const n of Object.keys(r))A.add(n);const R=(r,n,t,o)=>{if(!(!r||typeof r!="object"||Array.isArray(r)))for(const[s,c]of Object.entries(r))K(s,c,n,t,o)},K=(r,n,t,o,s)=>{if(r==="AND"||r==="OR"){for(const c of Array.isArray(n)?n:[])R(c,t,o,s);return}if(r==="NOT"){R(n,t,o,s);return}if(!r.startsWith("__")){if(t.has(r))throw new S("MASK_UNSUPPORTED",`${s}() filtering "${o}" by masked column "${r}" is not supported`);if(C(n))for(const c of Object.values(n))R(c,A,`${o}.${r}`,s)}},B=r=>{const n=i.get(r);return n?new Set(Object.keys(n)):new Set},h=(r,n,t)=>{A.size===0||n===void 0||R(n,B(r),r,t)},F=(r,n,t,o)=>{if(Array.isArray(n)){for(const s of n)if(!(!s||typeof s!="object"||Array.isArray(s))){for(const c of Object.keys(s))if(t.has(c))throw new S("MASK_UNSUPPORTED",`${o}() ordering "${r}" by masked column "${c}" is not supported`)}}},$=(r,n,t)=>{if(!(A.size===0||!n||typeof n!="object"||Array.isArray(n)))for(const[o,s]of Object.entries(n)){if(o==="_count"||!s||typeof s!="object"||Array.isArray(s))continue;const c=s,a=`${r}.${o}`;R(c.where,A,a,t),F(a,c.orderBy,A,t),$(a,c.with,t)}},W=(r,n,t)=>{h(r,n?.where,t),h(r,n?.baseWhere,t),F(r,n?.orderBy,B(r),t),$(r,n?.with,t)},v=r=>r&&typeof r=="object"&&!Array.isArray(r)?r:void 0,M=(r,n,t)=>{const o=v(n);h(r,o?.where,t),h(r,o?.baseWhere,t),$(r,o?.with,t)},I={...e,async deleteWhere(r,n,t){if(h(r,n,"deleteMany({ where })"),e.deleteWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);return e.deleteWhere(r,n,t)},async patchWhere(r,n,t){if(h(r,n.where,"patchMany({ where })"),e.patchWhere===void 0)throw new S("INTERNAL",`ctx.db.${r}.patchMany({ where }) is unavailable: this writer has no where-based patch`);return e.patchWhere(r,n,t)},aggregate(r,n){return P(r,[n.field],"aggregate"),h(r,n.where,"aggregate"),e.aggregate(r,n)},count(r,n){const t=v(n),o=t&&("where"in t||"baseWhere"in t||"restrictsCounts"in t)?t.where:n;return h(r,o,"count"),t&&h(r,t.baseWhere,"count"),e.count(r,n)},async findFirst(r,n){W(r,n,"findFirst");const t=await e.findFirst(r,l(n)),o=i.get(r);return t&&o?u(t,o,f):t},async findFirstOrThrow(r,n){W(r,n,"findFirstOrThrow");const t=await e.findFirstOrThrow(r,l(n)),o=i.get(r);return o?u(t,o,f):t},async findMany(r,n){W(r,n,"findMany");const t=await e.findMany(r,l(n)),o=i.get(r);return o?j(t,o,f):t},async get(r,n){const{row:t,tableName:o}=await O(r,n),s=o===void 0?void 0:i.get(o);return!t||!s?t:u(t,s,f)},async lookupById(r,n){const t=await e.lookupById?.(r,n);if(!t)return null;const o=i.get(t.tableName);return{row:o?u(t.row,o,f):t.row,tableName:t.tableName}},groupBy(r,n){return P(r,[...n.by,n.agg?.field],"groupBy"),h(r,n.where,"groupBy"),e.groupBy(r,n)},query(r){const n=e.query(r),t=i.get(r);return t?p(n,t,r):n},async rank(r,n,t){return M(r,t,"rank"),k(r,n,"rank","rank"),e.rank(r,n,t)},async rankPage(r,n,t){M(r,t,"rankPage"),k(r,n,"rankPage","rank");const o=await e.rankPage(r,n,t),s=i.get(r);return s?j(o,s,f):o},..._("rankBefore",y,r=>(n,t,o)=>(M(n,o,"rankBefore"),k(n,t,"rankBefore","rank"),r(n,t,o))),..._("rankPageRows",g,r=>async(n,t,o)=>{M(n,o,"rankPageRows"),k(n,t,"rankPageRows","rank");const s=await r(n,t,o),c=i.get(n);return c?{...s,rows:s.rows.map(a=>({...a,doc:u(a.doc,c,f)}))}:s})},q=I;if(A.size>0)for(const[r,n]of Object.entries(e))G(n)&&(q[r]=H(I,r));return I},b=(e,i={})=>{const f=new Map(Object.entries(e)),d=L(i.roles),y=async({ctx:w,next:l})=>{const k={auth:await z(w.auth??{},d),ctx:w};if(i.bypass?.(k)===!0)return l();const p=X(w.db,f,k,i.indexFields),O={db:p},{orm:P}=w;return P!==null&&typeof P=="object"&&(O.orm=J(p)),l({ctx:O})},g=new Map;for(const[w,l]of f)g.set(w,new Set(Object.keys(l)));return Q(y,{columns:g})};export{b as mask};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as W}from"@lunora/errors";import{i as j}from"./wire-codec-CH4vwdFT.mjs";import{bindTableFacade as x,bindOrm as V}from"./bindOrm-ChQydkdL.mjs";import{t as ee}from"./policy-tag-V0lqFzgS.mjs";import{deny as te}from"./allowAll-DkRAgItV.mjs";const re=["every","is","isNot","none","some"],ne=new Set(re),se=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const r=Object.keys(e);return r.length>0&&r.every(n=>ne.has(n))},N=(e,r,n)=>r?{[e]:n(r)}:{},oe=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,v=0,R=1,k=e=>e?R:B,p=(e,r)=>e<r?e:r,ie=(e,r)=>e>r?e:r,Q=e=>e===v?v:k(e===B),q=e=>{const r=typeof e;return r==="number"||r==="string"||r==="bigint"},S=e=>e==null,D=(e,r,n)=>{if(n===void 0)throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined; a comparison needs a value`)},ae={gt:(e,r)=>e>r,gte:(e,r)=>e>=r,lt:(e,r)=>e<r,lte:(e,r)=>e<=r},ce=(e,r,n)=>{let i=R;for(const c of["gt","gte","lt","lte"]){if(!(c in n))continue;const h=n[c];if(D(e,c,h),!q(h))i=p(i,B);else if(S(r))i=p(i,v);else{const f=ae[c];i=p(i,k(q(r)&&f(r,h)))}}return i},Y=(e,r,n)=>{if(!Array.isArray(n))throw new W("BAD_REQUEST",`\`${r}\` on "${e}" expects an array of values, received ${n===null?"null":typeof n}`);if(n.includes(void 0))throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined inside its list; a comparison needs a value`);return n},K=(e,r)=>r.length===0?B:S(e)?v:r.includes(e)?R:r.some(n=>S(n))?v:B,le=(e,r,n)=>{let i=R;if("in"in n&&(i=p(i,K(r,Y(e,"in",n.in)))),"notIn"in n&&(i=p(i,Q(K(r,Y(e,"notIn",n.notIn))))),"contains"in n){const c=n.contains;D(e,"contains",c),i=S(r)?p(i,v):p(i,k(typeof r=="string"&&typeof c=="string"&&r.includes(c)))}return"isNull"in n&&(i=p(i,k(n.isNull===!0===S(r)))),i},F=(e,r,n)=>r===null?k(n===S(e)):S(e)?v:k(n===(e===r)),fe=(e,r,n)=>{let i=R;return"eq"in n&&(D(e,"eq",n.eq),i=p(i,F(r,n.eq,!0))),"ne"in n&&(D(e,"ne",n.ne),i=p(i,F(r,n.ne,!1))),i},ue=(e,r,n)=>p(fe(e,r,n),p(le(e,r,n),ce(e,r,n))),de=(e,r,n,i)=>{if(r==="NOT")return Q(i(e,n??{}));if(!Array.isArray(n))return B;let c=r==="AND"?R:B;for(const h of n){const f=i(e,h);c=r==="AND"?p(c,f):ie(c,f)}return c},z=e=>e==="AND"||e==="OR"||e==="NOT",he=e=>j(e)&&Object.keys(e).every(r=>oe.includes(r)),C=e=>Object.keys(e).some(r=>{const n=e[r];return z(r)?r==="NOT"?C(n??{}):Array.isArray(n)&&n.some(i=>C(i??{})):se(n)}),H=(e,r)=>{let n=R;for(const i of Object.keys(r)){const c=r[i];if(z(i)){n=p(n,de(e,i,c,H));continue}const h=e[i];if(he(c)){n=p(n,ue(i,h,c));continue}D(i,"eq",c),n=p(n,F(h,c,!0))}return n},L=(e,r)=>H(e,r)===R,G=500,T=(e,r,n)=>{const i=r??G;if(e>i)throw new W("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(e)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`,{status:400})},ye=te(),we=Symbol.for("lunora.ctxdb.rls-unwrap"),X=Symbol.for("lunora.rls.wrapped-chain"),pe=e=>e[X],ge=e=>{const r=new Map;for(const n of e){const i=r.get(n.table)??[];i.push(n),r.set(n.table,i)}return r},We=(e,r)=>{const n=[];let i=!1;for(const c of e){if(c.on!=="read")continue;const h=c.when(r);if(h!==void 0){if(h===!0){i=!0;break}h!==!1&&n.push(h)}}if(!i)return n.length===0?ye:n.length===1?n[0]:{OR:n}},Oe=(e,r,n)=>{const i=e.when({...r,row:n});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(C(i))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return L(n,i)},be=(e,r,n)=>{const i=e.when(r);if(i===void 0||i===!0)return n===void 0||Oe(e,r,n);if(i===!1)return!1;if(C(i))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!r.row||!L(r.row,i)?!1:n===void 0||L(n,i)},Re=(e,r,n,i)=>{let c=!1;for(const h of e)if(h.on===r&&(c=!0,!be(h,n,i)))return!1;return c},Ae=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Ee=(e,r)=>r===void 0?!0:e==="restrictsCounts"?typeof r=="boolean":e==="relationBaseWhere"?typeof r=="function":j(r),Be=e=>{const r=Object.keys(e);return r.length===0?!1:r.every(n=>Ae.has(n)&&Ee(n,e[n]))},ve=e=>e===void 0?{}:j(e)&&Be(e)?e:{where:e},$=e=>e!==void 0&&Object.keys(e).length>0,Se=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},b=(e,r)=>$(r)?!e||Object.keys(e).length===0?r:{AND:[r,e]}:e,_e=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;return typeof r.findMany=="function"&&typeof r.withSearchIndex=="function"},Te=(e,r,n)=>{const[i]=n,c=n.length===1&&i!==void 0?i.perTable:new Set(n.flatMap(t=>[...t.perTable.keys()])),h=new Map,f=t=>{const s=h.get(t);if(s)return s;const o=[];let a=!1;for(const y of n){const d=y.perTable.get(t);if(!d||d.length===0||!d.some(m=>m.on==="read"))continue;a=!0;const u=We(d,y.context);u!==void 0&&o.push(u)}const l={baseWhere:Se(o),restricts:a};return h.set(t,l),l},_=(t,s,o,a)=>{for(const l of n){const y=l.perTable.get(t);if(y&&!Re(y,s,{...l.context,row:o},a))return!1}return!0},w=t=>f(t).restricts?r:e,g=t=>f(t).baseWhere,A=async(t,s,o)=>{if(r.lookupById){const u=await r.lookupById(t,s);if(u)return{row:u.row,tableName:c.has(u.tableName)?u.tableName:void 0}}const a=await r.get(t,s);if(!a)return{row:null,tableName:void 0};const l=s??o,y=l===void 0?[...c.keys()]:[l].filter(u=>c.has(u)),d=await Promise.all(y.map(async u=>(await r.findFirst(u,{limit:1,where:{_id:t}}))?._id===t?u:void 0));return{row:a,tableName:d.find(u=>u!==void 0)}},U=async(t,s,o)=>{const a=await A(t,s,o);return a.row&&a.tableName!==void 0?{row:a.row,tableName:a.tableName}:void 0},O=async(t,s,o,a,l,y)=>{const d=await U(t,l,y);if(!d)return o(e);const u=a?a(d.row):void 0;if(!_(d.tableName,s,d.row,u))throw new W("FORBIDDEN",`${s} denied by policy`);return o(r)},E=(t,s)=>{const{baseWhere:o}=f(t);if($(o))throw new W("COUNT_RLS_UNSUPPORTED",`${s}() is not supported on "${t}" inside an RLS-restricted context`)},M=e.rankBefore,P=e.rankPageRows,I={...e,async count(t,s){const{baseWhere:o}=f(t),a=ve(s);return w(t).count(t,{...a,baseWhere:b(a.baseWhere,o),relationBaseWhere:g,restrictsCounts:(a.restrictsCounts??!1)||$(o)})},delete:(t,s,o)=>O(t,"delete",a=>a.delete(t,s,o),void 0,s),async deleteAll(t,s){const o=Math.max(1,s?.chunkSize??G),{baseWhere:a}=f(t);let l=0;for(;;){const d=(await w(t).findMany(t,{baseWhere:a,limit:o,relationBaseWhere:g})).page.map(u=>String(u._id));if(d.length===0)break;for(const u of d)await O(u,"delete",m=>m.delete(u,void 0,s?.hard===void 0?void 0:{hard:s.hard}),void 0,void 0,t),l+=1;if(d.length<o)break}return{deleted:l}},async deleteMany(t,s,o){T(t.length,s?.limit,"deleteMany");for(const a of t)await O(a,"delete",l=>l.delete(a,o),void 0,o);return{deleted:t.length}},async deleteWhere(t,s,o){const{baseWhere:a}=f(t),y=(await w(t).findMany(t,{baseWhere:b(s,a),relationBaseWhere:g})).page.map(d=>String(d._id));T(y.length,o?.limit,"deleteWhere");for(const d of y)await O(d,"delete",u=>u.delete(d),void 0,void 0,t);return{deleted:y.length}},async findFirst(t,s){const{baseWhere:o}=f(t);return w(t).findFirst(t,{...s,baseWhere:b(s?.baseWhere,o),relationBaseWhere:g})},async findFirstOrThrow(t,s){const{baseWhere:o}=f(t);return w(t).findFirstOrThrow(t,{...s,baseWhere:b(s?.baseWhere,o),relationBaseWhere:g})},async findMany(t,s){const{baseWhere:o}=f(t);return w(t).findMany(t,{...s,baseWhere:b(s?.baseWhere,o),relationBaseWhere:g})},async get(t,s){const o=await A(t,s);if(!o.row)return null;if(o.tableName===void 0)return e.get(t,s);const{baseWhere:a,restricts:l}=f(o.tableName);if(!l)return e.get(t,s);if(!a)return o.row;const y=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return y?._id===t?y:null},async lookupById(t,s){const o=await A(t,s);if(!o.row)return null;if(o.tableName===void 0||!f(o.tableName).restricts)return await e.lookupById?.(t,s)??null;const{baseWhere:a}=f(o.tableName);if(!a)return{row:o.row,tableName:o.tableName};const l=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return l?._id===t?{row:l,tableName:o.tableName}:null},async insert(t,s){if(c.has(t)){if(!_(t,"insert",s))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insert(t,s)}return e.insert(t,s)},async insertMany(t,s,o){if(T(s.length,o?.limit,"insertMany"),c.has(t)){for(const a of s)if(!_(t,"insert",a))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertMany(t,s,o)}return e.insertMany(t,s,o)},async insertManyUnsafe(t,s,o){if(T(s.length,o?.limit,"insertManyUnsafe"),c.has(t)){for(const a of s)if(!_(t,"insert",a))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertManyUnsafe(t,s,o)}return e.insertManyUnsafe(t,s,o)},patch:(t,s,o)=>O(t,"update",a=>a.patch(t,s,o),a=>({...a,...s}),o),async patchMany(t,s,o){T(t.length,s?.limit,"patchMany");for(const a of t)await O(a.id,"update",l=>l.patch(a.id,a.patch,o),l=>({...l,...a.patch}),o);return{patched:t.length}},async patchWhere(t,s,o){const{baseWhere:a}=f(t),y=(await w(t).findMany(t,{baseWhere:b(s.where,a),relationBaseWhere:g})).page.map(d=>({id:String(d._id),patch:s.patch}));return T(y.length,o?.limit,"patchWhere"),I.patchMany(y,o)},query(t){const{baseWhere:s}=f(t),o=w(t).query(t);return s?o.filter(a=>L(a,s)):o},restore:(t,s)=>O(t,"update",async o=>{const a=o.restore??r.restore;if(!a)throw new W("BAD_REQUEST","restore is not supported by this writer");await a(t,s)},void 0,s),replace:(t,s,o)=>O(t,"update",a=>a.replace(t,s,o),a=>({...s,_creationTime:s._creationTime??a._creationTime,_id:a._id}),o),aggregate(t,s){const{baseWhere:o}=f(t);return w(t).aggregate(t,{...s,baseWhere:b(s.baseWhere,o),relationBaseWhere:g})},groupBy(t,s){const{baseWhere:o}=f(t);return w(t).groupBy(t,{...s,baseWhere:b(s.baseWhere,o),relationBaseWhere:g})},rank(t,s,o){return E(t,"rank"),w(t).rank(t,s,o)},rankPage(t,s,o){return E(t,"rankPage"),w(t).rankPage(t,s,o)},wipeShard(){throw new W("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...N("rankBefore",M,t=>(s,o,a)=>(E(s,"rankBefore"),(w(s).rankBefore??t)(s,o,a))),...N("rankPageRows",P,t=>(s,o,a)=>(E(s,"rankPageRows"),(w(s).rankPageRows??t)(s,o,a)))},Z=I;if(c.size>0)for(const[t,s]of Object.entries(e))_e(s)&&(Z[t]=x(I,t));return Object.defineProperty(I,X,{configurable:!0,enumerable:!1,value:{base:e,raw:r,steps:n},writable:!1}),I},J=e=>typeof e=="string"?e:e.name,ke=e=>{const r=new Map;for(const n of e??[])r.set(n.name,new Set((n.permissions??[]).map(i=>J(i))));return r},Ie=(e,r)=>{const n=new Set;for(const i of e)for(const c of r.get(i)??[])n.add(c);return i=>n.has(J(i))},De=["roles","role"],Me=e=>{for(const r of De){const n=e?.[r];if(typeof n=="string"){const i=n.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(i.length>0)return i}if(Array.isArray(n)){const i=n.filter(c=>typeof c=="string"&&c.length>0);if(i.length>0)return i}}return[]},Pe=async(e,r)=>{const n=await e.getIdentity?.()??null,i=[...new Set([...Me(n),...e.roles??[]])];return{can:Ie(i,r),identity:n,roles:i,userId:e.userId??null}},$e=(e,r={})=>{const n=e,i=ge(n),c=ke(r.roles);return ee(async({ctx:f,next:_})=>{const w={auth:await Pe(f.auth??{},c),ctx:f},g=f.db,A=pe(g),U=A?.base??g,O=A?.raw??g[we]??g,E=Te(U,O,[...A?.steps??[],{context:w,perTable:i}]),M={db:E},{orm:P}=f;return P!==null&&typeof P=="object"&&(M.orm=V(E)),_({ctx:M})},[{policies:n,roles:r.roles??[]}])};export{Pe as a,_e as b,se as c,Me as d,Ie as e,We as f,Re as g,ke as i,L as m,N as o,J as p,$e as r};
|
|
1
|
+
import{LunoraError as W}from"@lunora/errors";import{i as j}from"./wire-codec-CH4vwdFT.mjs";import{bindTableFacade as x,bindOrm as V}from"./bindOrm-D_hFUjmr.mjs";import{t as ee}from"./policy-tag-V0lqFzgS.mjs";import{deny as te}from"./allowAll-DkRAgItV.mjs";const re=["every","is","isNot","none","some"],ne=new Set(re),se=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const r=Object.keys(e);return r.length>0&&r.every(n=>ne.has(n))},N=(e,r,n)=>r?{[e]:n(r)}:{},oe=["contains","eq","gt","gte","in","isNull","lt","lte","ne","notIn"],B=-1,v=0,R=1,k=e=>e?R:B,p=(e,r)=>e<r?e:r,ie=(e,r)=>e>r?e:r,Q=e=>e===v?v:k(e===B),q=e=>{const r=typeof e;return r==="number"||r==="string"||r==="bigint"},S=e=>e==null,D=(e,r,n)=>{if(n===void 0)throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined; a comparison needs a value`)},ae={gt:(e,r)=>e>r,gte:(e,r)=>e>=r,lt:(e,r)=>e<r,lte:(e,r)=>e<=r},ce=(e,r,n)=>{let i=R;for(const c of["gt","gte","lt","lte"]){if(!(c in n))continue;const h=n[c];if(D(e,c,h),!q(h))i=p(i,B);else if(S(r))i=p(i,v);else{const f=ae[c];i=p(i,k(q(r)&&f(r,h)))}}return i},Y=(e,r,n)=>{if(!Array.isArray(n))throw new W("BAD_REQUEST",`\`${r}\` on "${e}" expects an array of values, received ${n===null?"null":typeof n}`);if(n.includes(void 0))throw new W("BAD_REQUEST",`\`${r}\` on "${e}" received undefined inside its list; a comparison needs a value`);return n},K=(e,r)=>r.length===0?B:S(e)?v:r.includes(e)?R:r.some(n=>S(n))?v:B,le=(e,r,n)=>{let i=R;if("in"in n&&(i=p(i,K(r,Y(e,"in",n.in)))),"notIn"in n&&(i=p(i,Q(K(r,Y(e,"notIn",n.notIn))))),"contains"in n){const c=n.contains;D(e,"contains",c),i=S(r)?p(i,v):p(i,k(typeof r=="string"&&typeof c=="string"&&r.includes(c)))}return"isNull"in n&&(i=p(i,k(n.isNull===!0===S(r)))),i},F=(e,r,n)=>r===null?k(n===S(e)):S(e)?v:k(n===(e===r)),fe=(e,r,n)=>{let i=R;return"eq"in n&&(D(e,"eq",n.eq),i=p(i,F(r,n.eq,!0))),"ne"in n&&(D(e,"ne",n.ne),i=p(i,F(r,n.ne,!1))),i},ue=(e,r,n)=>p(fe(e,r,n),p(le(e,r,n),ce(e,r,n))),de=(e,r,n,i)=>{if(r==="NOT")return Q(i(e,n??{}));if(!Array.isArray(n))return B;let c=r==="AND"?R:B;for(const h of n){const f=i(e,h);c=r==="AND"?p(c,f):ie(c,f)}return c},z=e=>e==="AND"||e==="OR"||e==="NOT",he=e=>j(e)&&Object.keys(e).every(r=>oe.includes(r)),C=e=>Object.keys(e).some(r=>{const n=e[r];return z(r)?r==="NOT"?C(n??{}):Array.isArray(n)&&n.some(i=>C(i??{})):se(n)}),H=(e,r)=>{let n=R;for(const i of Object.keys(r)){const c=r[i];if(z(i)){n=p(n,de(e,i,c,H));continue}const h=e[i];if(he(c)){n=p(n,ue(i,h,c));continue}D(i,"eq",c),n=p(n,F(h,c,!0))}return n},L=(e,r)=>H(e,r)===R,G=500,T=(e,r,n)=>{const i=r??G;if(e>i)throw new W("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(e)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`,{status:400})},ye=te(),we=Symbol.for("lunora.ctxdb.rls-unwrap"),X=Symbol.for("lunora.rls.wrapped-chain"),pe=e=>e[X],ge=e=>{const r=new Map;for(const n of e){const i=r.get(n.table)??[];i.push(n),r.set(n.table,i)}return r},We=(e,r)=>{const n=[];let i=!1;for(const c of e){if(c.on!=="read")continue;const h=c.when(r);if(h!==void 0){if(h===!0){i=!0;break}h!==!1&&n.push(h)}}if(!i)return n.length===0?ye:n.length===1?n[0]:{OR:n}},Oe=(e,r,n)=>{const i=e.when({...r,row:n});if(i===void 0||i===!0)return!0;if(i===!1)return!1;if(C(i))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return L(n,i)},be=(e,r,n)=>{const i=e.when(r);if(i===void 0||i===!0)return n===void 0||Oe(e,r,n);if(i===!1)return!1;if(C(i))throw new W("RELATION_PREDICATE_UNSUPPORTED","relation predicates are not supported in write policies; use a read policy or a flat column check");return!r.row||!L(r.row,i)?!1:n===void 0||L(n,i)},Re=(e,r,n,i)=>{let c=!1;for(const h of e)if(h.on===r&&(c=!0,!be(h,n,i)))return!1;return c},Ae=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),Ee=(e,r)=>r===void 0?!0:e==="restrictsCounts"?typeof r=="boolean":e==="relationBaseWhere"?typeof r=="function":j(r),Be=e=>{const r=Object.keys(e);return r.length===0?!1:r.every(n=>Ae.has(n)&&Ee(n,e[n]))},ve=e=>e===void 0?{}:j(e)&&Be(e)?e:{where:e},$=e=>e!==void 0&&Object.keys(e).length>0,Se=e=>{if(e.length!==0)return e.length===1?e[0]:{AND:e}},b=(e,r)=>$(r)?!e||Object.keys(e).length===0?r:{AND:[r,e]}:e,_e=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const r=e;return typeof r.findMany=="function"&&typeof r.withSearchIndex=="function"},Te=(e,r,n)=>{const[i]=n,c=n.length===1&&i!==void 0?i.perTable:new Set(n.flatMap(t=>[...t.perTable.keys()])),h=new Map,f=t=>{const s=h.get(t);if(s)return s;const o=[];let a=!1;for(const y of n){const d=y.perTable.get(t);if(!d||d.length===0||!d.some(m=>m.on==="read"))continue;a=!0;const u=We(d,y.context);u!==void 0&&o.push(u)}const l={baseWhere:Se(o),restricts:a};return h.set(t,l),l},_=(t,s,o,a)=>{for(const l of n){const y=l.perTable.get(t);if(y&&!Re(y,s,{...l.context,row:o},a))return!1}return!0},w=t=>f(t).restricts?r:e,g=t=>f(t).baseWhere,A=async(t,s,o)=>{if(r.lookupById){const u=await r.lookupById(t,s);if(u)return{row:u.row,tableName:c.has(u.tableName)?u.tableName:void 0}}const a=await r.get(t,s);if(!a)return{row:null,tableName:void 0};const l=s??o,y=l===void 0?[...c.keys()]:[l].filter(u=>c.has(u)),d=await Promise.all(y.map(async u=>(await r.findFirst(u,{limit:1,where:{_id:t}}))?._id===t?u:void 0));return{row:a,tableName:d.find(u=>u!==void 0)}},U=async(t,s,o)=>{const a=await A(t,s,o);return a.row&&a.tableName!==void 0?{row:a.row,tableName:a.tableName}:void 0},O=async(t,s,o,a,l,y)=>{const d=await U(t,l,y);if(!d)return o(e);const u=a?a(d.row):void 0;if(!_(d.tableName,s,d.row,u))throw new W("FORBIDDEN",`${s} denied by policy`);return o(r)},E=(t,s)=>{const{baseWhere:o}=f(t);if($(o))throw new W("COUNT_RLS_UNSUPPORTED",`${s}() is not supported on "${t}" inside an RLS-restricted context`)},M=e.rankBefore,P=e.rankPageRows,I={...e,async count(t,s){const{baseWhere:o}=f(t),a=ve(s);return w(t).count(t,{...a,baseWhere:b(a.baseWhere,o),relationBaseWhere:g,restrictsCounts:(a.restrictsCounts??!1)||$(o)})},delete:(t,s,o)=>O(t,"delete",a=>a.delete(t,s,o),void 0,s),async deleteAll(t,s){const o=Math.max(1,s?.chunkSize??G),{baseWhere:a}=f(t);let l=0;for(;;){const d=(await w(t).findMany(t,{baseWhere:a,limit:o,relationBaseWhere:g})).page.map(u=>String(u._id));if(d.length===0)break;for(const u of d)await O(u,"delete",m=>m.delete(u,void 0,s?.hard===void 0?void 0:{hard:s.hard}),void 0,void 0,t),l+=1;if(d.length<o)break}return{deleted:l}},async deleteMany(t,s,o){T(t.length,s?.limit,"deleteMany");for(const a of t)await O(a,"delete",l=>l.delete(a,o),void 0,o);return{deleted:t.length}},async deleteWhere(t,s,o){const{baseWhere:a}=f(t),y=(await w(t).findMany(t,{baseWhere:b(s,a),relationBaseWhere:g})).page.map(d=>String(d._id));T(y.length,o?.limit,"deleteWhere");for(const d of y)await O(d,"delete",u=>u.delete(d),void 0,void 0,t);return{deleted:y.length}},async findFirst(t,s){const{baseWhere:o}=f(t);return w(t).findFirst(t,{...s,baseWhere:b(s?.baseWhere,o),relationBaseWhere:g})},async findFirstOrThrow(t,s){const{baseWhere:o}=f(t);return w(t).findFirstOrThrow(t,{...s,baseWhere:b(s?.baseWhere,o),relationBaseWhere:g})},async findMany(t,s){const{baseWhere:o}=f(t);return w(t).findMany(t,{...s,baseWhere:b(s?.baseWhere,o),relationBaseWhere:g})},async get(t,s){const o=await A(t,s);if(!o.row)return null;if(o.tableName===void 0)return e.get(t,s);const{baseWhere:a,restricts:l}=f(o.tableName);if(!l)return e.get(t,s);if(!a)return o.row;const y=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return y?._id===t?y:null},async lookupById(t,s){const o=await A(t,s);if(!o.row)return null;if(o.tableName===void 0||!f(o.tableName).restricts)return await e.lookupById?.(t,s)??null;const{baseWhere:a}=f(o.tableName);if(!a)return{row:o.row,tableName:o.tableName};const l=await r.findFirst(o.tableName,{baseWhere:a,limit:1,where:{_id:t}});return l?._id===t?{row:l,tableName:o.tableName}:null},async insert(t,s){if(c.has(t)){if(!_(t,"insert",s))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insert(t,s)}return e.insert(t,s)},async insertMany(t,s,o){if(T(s.length,o?.limit,"insertMany"),c.has(t)){for(const a of s)if(!_(t,"insert",a))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertMany(t,s,o)}return e.insertMany(t,s,o)},async insertManyUnsafe(t,s,o){if(T(s.length,o?.limit,"insertManyUnsafe"),c.has(t)){for(const a of s)if(!_(t,"insert",a))throw new W("FORBIDDEN",`insert on "${t}" denied by policy`);return r.insertManyUnsafe(t,s,o)}return e.insertManyUnsafe(t,s,o)},patch:(t,s,o)=>O(t,"update",a=>a.patch(t,s,o),a=>({...a,...s}),o),async patchMany(t,s,o){T(t.length,s?.limit,"patchMany");for(const a of t)await O(a.id,"update",l=>l.patch(a.id,a.patch,o),l=>({...l,...a.patch}),o);return{patched:t.length}},async patchWhere(t,s,o){const{baseWhere:a}=f(t),y=(await w(t).findMany(t,{baseWhere:b(s.where,a),relationBaseWhere:g})).page.map(d=>({id:String(d._id),patch:s.patch}));return T(y.length,o?.limit,"patchWhere"),I.patchMany(y,o)},query(t){const{baseWhere:s}=f(t),o=w(t).query(t);return s?o.filter(a=>L(a,s)):o},restore:(t,s)=>O(t,"update",async o=>{const a=o.restore??r.restore;if(!a)throw new W("BAD_REQUEST","restore is not supported by this writer");await a(t,s)},void 0,s),replace:(t,s,o)=>O(t,"update",a=>a.replace(t,s,o),a=>({...s,_creationTime:s._creationTime??a._creationTime,_id:a._id}),o),aggregate(t,s){const{baseWhere:o}=f(t);return w(t).aggregate(t,{...s,baseWhere:b(s.baseWhere,o),relationBaseWhere:g})},groupBy(t,s){const{baseWhere:o}=f(t);return w(t).groupBy(t,{...s,baseWhere:b(s.baseWhere,o),relationBaseWhere:g})},rank(t,s,o){return E(t,"rank"),w(t).rank(t,s,o)},rankPage(t,s,o){return E(t,"rankPage"),w(t).rankPage(t,s,o)},wipeShard(){throw new W("FORBIDDEN","ctx.db.wipeShard() is unavailable under rls(): a whole-shard erase can't be policy-gated per row, and erasing only policy-visible rows would silently leave data behind. Run it from an internalMutation, or use ctx.db.deleteAll(table) per table.",{status:403})},...N("rankBefore",M,t=>(s,o,a)=>(E(s,"rankBefore"),(w(s).rankBefore??t)(s,o,a))),...N("rankPageRows",P,t=>(s,o,a)=>(E(s,"rankPageRows"),(w(s).rankPageRows??t)(s,o,a)))},Z=I;if(c.size>0)for(const[t,s]of Object.entries(e))_e(s)&&(Z[t]=x(I,t));return Object.defineProperty(I,X,{configurable:!0,enumerable:!1,value:{base:e,raw:r,steps:n},writable:!1}),I},J=e=>typeof e=="string"?e:e.name,ke=e=>{const r=new Map;for(const n of e??[])r.set(n.name,new Set((n.permissions??[]).map(i=>J(i))));return r},Ie=(e,r)=>{const n=new Set;for(const i of e)for(const c of r.get(i)??[])n.add(c);return i=>n.has(J(i))},De=["roles","role"],Me=e=>{for(const r of De){const n=e?.[r];if(typeof n=="string"){const i=n.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(i.length>0)return i}if(Array.isArray(n)){const i=n.filter(c=>typeof c=="string"&&c.length>0);if(i.length>0)return i}}return[]},Pe=async(e,r)=>{const n=await e.getIdentity?.()??null,i=[...new Set([...Me(n),...e.roles??[]])];return{can:Ie(i,r),identity:n,roles:i,userId:e.userId??null}},$e=(e,r={})=>{const n=e,i=ge(n),c=ke(r.roles);return ee(async({ctx:f,next:_})=>{const w={auth:await Pe(f.auth??{},c),ctx:f},g=f.db,A=pe(g),U=A?.base??g,O=A?.raw??g[we]??g,E=Te(U,O,[...A?.steps??[],{context:w,perTable:i}]),M={db:E},{orm:P}=f;return P!==null&&typeof P=="object"&&(M.orm=V(E)),_({ctx:M})},[{policies:n,roles:r.roles??[]}])};export{Pe as a,_e as b,se as c,Me as d,Ie as e,We as f,Re as g,ke as i,L as m,N as o,J as p,$e as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./wire-codec-CH4vwdFT.mjs";import"./bindOrm-
|
|
1
|
+
import"./wire-codec-CH4vwdFT.mjs";import"./bindOrm-D_hFUjmr.mjs";import{f as t,g as m,i as p,b as l,m as d,p as n,d as c,e as h,a as u,r as v}from"./middleware-BZcRFqUp.mjs";import"./policy-tag-V0lqFzgS.mjs";import"./allowAll-DkRAgItV.mjs";export{t as computeReadBaseWhere,m as evaluateWrite,p as indexRolePermissions,l as isFacadeEntry,d as matchesWhere,n as permissionName,c as readIdentityRoles,h as resolveCan,u as resolvePolicyAuth,v as rls};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as A}from"@lunora/errors";import{i as U,a as $}from"./middleware-
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{i as U,a as $}from"./middleware-BZcRFqUp.mjs";const N=(e,t,o)=>{const a=s=>o.isAllowed("list",s,t)&&o.isAllowed("read",s,t),{get:r,query:b}=e,l={...e},w=s=>s.filter(n=>typeof n.key=="string"&&a(n.key));return typeof r=="function"&&(l.get=async(s,n)=>(s==="_storage"&&o.assertAllowed("read",n,t),r(s,n))),typeof b=="function"&&(l.query=s=>{const n=b(s),{collect:p}=n;return s!=="_storage"||typeof p!="function"?n:{...n,collect:async()=>w(await p())}}),l},S=(e,t)=>{if(e===void 0)return!0;const o=e.endsWith("/")?e.slice(0,-1):e;return o===""||t===o||t.startsWith(`${o}/`)},D=e=>{const t=e[1],o=typeof t=="object"&&t!==null?t.method:void 0;return typeof o=="string"&&o.toUpperCase()==="PUT"?"write":"read"},E=[["delete","delete"],["deleteAfterCommit","delete"],["download","read"],["generateUploadUrl","write"],["getMetadata","read"],["getSignedUrl",D],["getUrl","read"],["head","read"],["store","write"]],M=(e,t)=>{try{return e(t).bucketName===t}catch{return!1}},P=(e,t)=>{const o=e.bucketName??"default",{bucket:a}=e;for(const r of new Set(t))if(!(r===o||typeof a=="function"&&M(a,r)))throw new A("INTERNAL",`storageRules: rule for bucket "${r}" governs nothing — this request's storage cannot address that bucket (the accessor is "${o}", and selecting "${r}" 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 })\`.`)},C=(e,t={})=>{const o=U(t.roles);return async({ctx:a,next:r})=>{const b=await $(a.auth??{},o),l=(c,u,d)=>{const h=e.filter(i=>i.on===c&&i.bucket===d);if(h.length===0)return!0;const f={auth:b,ctx:a,key:u};return h.some(i=>S(i.prefix,u)&&i.when(f)===!0)},w=(c,u,d)=>{if(!l(c,u,d))throw new A("FORBIDDEN",`storage ${c} on "${u}" in bucket "${d}" denied by access rule`)},s=c=>{const u=c.bucketName??"default",d={bucketName:u};for(const[f,i]of E){const k=c[f];typeof k=="function"&&(d[f]=(...y)=>{const R=typeof y[0]=="string"?y[0]:"",v=typeof i=="function"?i(y):i;return w(v,R,u),k(...y)})}const{bucket:h}=c;return typeof h=="function"&&(d.bucket=f=>s(h(f))),d},n=a.storage;if(n===void 0)return r();P(n,e.map(c=>c.bucket));const p={storage:s(n)},g=a.db,m=g?.system;return g!==void 0&&m!==void 0&&typeof m=="object"&&(p.db={...g,system:N(m,n.bucketName??"default",{assertAllowed:w,isAllowed:l})}),r({ctx:p})}};export{C as storageRules};
|
package/dist/rls/testing.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as y,d as P,e as W,f as v,m as I,g as R}from"../packem_shared/middleware-
|
|
1
|
+
import{i as y,d as P,e as W,f as v,m as I,g as R}from"../packem_shared/middleware-BZcRFqUp.mjs";const p=(m,o={})=>{const h=y(o.roles),x=o.ctx??{};return{as:f=>{const c=f??{},i=c.identity??null,l=P(i),u={auth:{can:W(l,h),identity:i,roles:l,userId:c.userId??null},ctx:x},d=(e,r,t,a)=>{const s=m.filter(n=>n.table===r);if(s.length===0)return!0;if(e==="read"){if(!s.some(b=>b.on==="read"))return!0;const n=v(s,u);return n===void 0||I(t??{},n)}return R(s,e,{...u,row:t},a)};return{can:d,cannot:(e,r,t,a)=>!d(e,r,t,a)}}}};export{p as expectPolicy};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/server",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.113",
|
|
4
4
|
"description": "Server primitives for Lunora: defineSchema, defineTable, query, mutation, and action",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"backend",
|
|
@@ -67,7 +67,7 @@
|
|
|
67
67
|
},
|
|
68
68
|
"dependencies": {
|
|
69
69
|
"@lunora/errors": "1.0.0-alpha.35",
|
|
70
|
-
"@lunora/scheduler": "1.0.0-alpha.
|
|
70
|
+
"@lunora/scheduler": "1.0.0-alpha.63",
|
|
71
71
|
"@lunora/values": "1.0.0-alpha.43",
|
|
72
72
|
"drizzle-orm": "^0.45.2",
|
|
73
73
|
"hono": "^4.13.7"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";const u=e=>typeof e=="object"&&e!==null&&e.code==="CONFLICT"&&e.kind==="unique",a=(e,t,r)=>{const i=typeof t=="string"?[t]:t;if(i.length===0)throw new h("INTERNAL",`ctx.db.${e}.upsert: "target" must name at least one field`);const n={};for(const s of i){if(!(s in r))throw new h("INTERNAL",`ctx.db.${e}.upsert: target field "${s}" is missing from the create document`);n[s]=r[s]}return n},f=(e,t)=>{const r=async(n,s)=>{if(s?.skipDuplicates!==!0)return e.insert(t,n);try{return await e.insert(t,n)}catch(o){if(u(o))return null;throw o}},i=async({create:n,target:s,update:o})=>{const d=a(t,s,n),c=await e.findFirst(t,{where:d});return c&&typeof c._id=="string"?(await e.patch(c._id,o??n,t),{created:!1,id:c._id}):{created:!0,id:await e.insert(t,n)}};return{aggregate:n=>e.aggregate(t,n),count:n=>e.count(t,n),delete:n=>e.delete(n,t),deleteMany:(n,s)=>{if(Array.isArray(n)){if(e.deleteMany===void 0)throw new h("INTERNAL",`ctx.db.${t}.deleteMany is unavailable: this writer has no batch delete`);return e.deleteMany(n,s,t)}if(e.deleteWhere===void 0)throw new h("INTERNAL",`ctx.db.${t}.deleteMany({ where }) is unavailable: this writer has no where-based delete`);const o=n;return e.deleteWhere(t,o.where,{limit:o.limit})},exists:async n=>await e.findFirst(t,n===void 0?void 0:{where:n})!==null,findFirst:n=>e.findFirst(t,n),findFirstOrThrow:n=>e.findFirstOrThrow(t,n),findMany:n=>e.findMany(t,n),get:n=>e.get(n,t),groupBy:n=>e.groupBy(t,n),hardDelete:n=>e.delete(n,t,{hard:!0}),insert:r,insertMany:(n,s)=>{if(e.insertMany===void 0)throw new h("INTERNAL",`ctx.db.${t}.insertMany is unavailable: this writer has no batch insert`);return e.insertMany(t,n,s)},patch:(n,s)=>e.patch(n,s,t),patchMany:(n,s)=>{if(Array.isArray(n)){if(e.patchMany===void 0)throw new h("INTERNAL",`ctx.db.${t}.patchMany is unavailable: this writer has no batch patch`);return e.patchMany(n.map(d=>({id:d.id,patch:d.values})),s,t)}if(e.patchWhere===void 0)throw new h("INTERNAL",`ctx.db.${t}.patchMany({ where, values }) is unavailable: this writer has no where-based patch`);const o=n;return e.patchWhere(t,{patch:o.values,where:o.where},{limit:o.limit})},rank:(n,s)=>e.rank(t,n,s),rankPage:(n,s)=>e.rankPage(t,n,s),replace:(n,s)=>e.replace(n,s,t),restore:async n=>{if(!e.restore)throw new h("INTERNAL",`ctx.db.${t}.restore is unavailable: this writer has no restore (is the table .softDelete()?)`);await e.restore(n,t)},upsert:i,upsertMany:async({rows:n,target:s})=>{const o=[];for(const d of n)o.push(await i({create:d.create,target:s,update:d.update}));return o},withGeoIndex:(n,s)=>e.query(t).withGeoIndex(n,s),withSearchIndex:(n,s)=>e.query(t).withSearchIndex(n,s)}},l=e=>{const t=r=>{const i=e[r];if(!i)throw new h("INTERNAL",`unknown table: ${r}`);return i};return{delete:(r,i)=>t(r).delete(i),insert:r=>({values:i=>t(r).insert(i)}),query:e,replace:(r,i)=>({with:n=>t(r).replace(i,n)}),update:(r,i)=>({set:n=>t(r).patch(i,n)})}};export{l as bindOrm,f as bindTableFacade};
|