@lunora/do 1.0.0-alpha.57 → 1.0.0-alpha.59
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +454 -4940
- package/dist/index.d.ts +454 -4940
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ROOT_DO_SIZE_WARN_BYTES-D0Ee_0XI.mjs +14 -0
- package/dist/packem_shared/SESSION_DO_TTL_DEFAULT-Dan63qLN.mjs +1 -0
- package/dist/packem_shared/serveRelationFanout-Cbmlso1k.mjs +1 -0
- package/package.json +5 -3
- package/dist/packem_shared/ADMIN_FUNCTIONS-B0xlQJ4w.mjs +0 -1
- package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs +0 -1
- package/dist/packem_shared/AUTH_METRICS_BUCKETS_TABLE-D0wNaez7.mjs +0 -22
- package/dist/packem_shared/CDC_LOG_TABLE-E_J5LPoK.mjs +0 -8
- package/dist/packem_shared/ConflictError-C8GtJmjS.mjs +0 -1
- package/dist/packem_shared/CountRlsUnsupportedError-Cl8XpYDL.mjs +0 -1
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs +0 -31
- package/dist/packem_shared/DEFAULT_EXPLAIN_ISSUE_MODEL-Dicm4iLF.mjs +0 -3
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-VxD8RtL0.mjs +0 -1
- package/dist/packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-BPPeqM11.mjs +0 -56
- package/dist/packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs +0 -1
- package/dist/packem_shared/LogBuffer-bIvCelI-.mjs +0 -1
- package/dist/packem_shared/MAIL_RETENTION-KmozO2NQ.mjs +0 -18
- package/dist/packem_shared/MAX_SQL_ROWS-C3-CO4jz.mjs +0 -1
- package/dist/packem_shared/MIN_ADMIN_TOKEN_LENGTH-Ch6OW6_3.mjs +0 -1
- package/dist/packem_shared/NotFoundError-J3tjf4Uo.mjs +0 -1
- package/dist/packem_shared/NotUniqueError-CQaRCv1y.mjs +0 -1
- package/dist/packem_shared/RANK_TIEBREAK-DtX8zQyc.mjs +0 -1
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs +0 -1
- package/dist/packem_shared/ROOT_DO_SIZE_WARN_BYTES-BEH-jSP0.mjs +0 -130
- package/dist/packem_shared/ReactiveCache-1_9Rs7J_.mjs +0 -1
- package/dist/packem_shared/SCAN_DEP-D_yR9EeV.mjs +0 -1
- package/dist/packem_shared/SESSION_DO_TTL_DEFAULT-GvBy_DBz.mjs +0 -1
- package/dist/packem_shared/aggregateTableName-G-eXyjcz.mjs +0 -1
- package/dist/packem_shared/applyOnDelete-DCeU2Jh0.mjs +0 -1
- package/dist/packem_shared/applySelect-B0CF8T7y.mjs +0 -1
- package/dist/packem_shared/armRestore-BNzdvQ_o.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-BwW0684A.mjs +0 -1
- package/dist/packem_shared/compileWhereSql-BLcfs4QW.mjs +0 -1
- package/dist/packem_shared/context-telemetry-BFO0N_e4.mjs +0 -1
- package/dist/packem_shared/createMetrics-B5oH1Xgn.mjs +0 -1
- package/dist/packem_shared/createSystemReader-DcDcrtM3.mjs +0 -1
- package/dist/packem_shared/ctx-db-backfill-Hl48Dr77.mjs +0 -1
- package/dist/packem_shared/ctx-db-shapes-CHC2cS0g.mjs +0 -1
- package/dist/packem_shared/diffExternalSource-DMpkJta1.mjs +0 -1
- package/dist/packem_shared/do-exec-BLe9lLrN.mjs +0 -1
- package/dist/packem_shared/do-sql-x0AjZhaN.mjs +0 -1
- package/dist/packem_shared/exportShardRows-kt42wijd.mjs +0 -1
- package/dist/packem_shared/hasTrigger-_rexbWMO.mjs +0 -1
- package/dist/packem_shared/isSoftDeleted-juJOq515.mjs +0 -9
- package/dist/packem_shared/materializeExternalRows-BUmj_9WO.mjs +0 -1
- package/dist/packem_shared/quote-identifier-CGiYFBvY.mjs +0 -1
- package/dist/packem_shared/renderSql-B5lF5Jd9.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-DBSceD0H.mjs +0 -5
- package/dist/packem_shared/schema-history-YGeVjyvV.mjs +0 -24
- package/dist/packem_shared/security-audit-BKUOgE0x.mjs +0 -1
- package/dist/packem_shared/selectExpiredIds-BXJDiUtz.mjs +0 -1
- package/dist/packem_shared/serialize-sql-DiRzL7A4.mjs +0 -1
- package/dist/packem_shared/serveRelationFanout-BqVyM54k.mjs +0 -1
- package/dist/packem_shared/sql-console-Cln4Xfju.mjs +0 -2
- package/dist/packem_shared/stableStringify-BjLh4gvA.mjs +0 -1
- package/dist/packem_shared/stableWireKey-YEHLaX6X.mjs +0 -1
- package/dist/packem_shared/subscriptionListDeltas-Bs69JbA8.mjs +0 -1
- package/dist/packem_shared/wire-codec-Ctnni0h6.mjs +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as D}from"@lunora/errors";import{applySelect as A}from"./applySelect-B0CF8T7y.mjs";const v=(r,o)=>o.select?A(r,o.select,o.with):r,_=async(r,o,t,a,s)=>{const d=await Promise.all(a.map(async c=>{const m=s?{AND:[{[t]:c},s]}:{[t]:c};return[c,await r(o,m)]}));return new Map(d)},W=(r,o)=>{const t=new Set;for(const a of r){const s=a[o];s!=null&&t.add(s)}return[...t]},C=async r=>{const{groupedCounter:o,fetcher:t,parents:a,relationBaseWhere:s,schema:d,tableName:c,with:m}=r;if(a.length===0)return;const k=d.tables[c];if(!k)throw new D("INTERNAL",`unknown table: ${c}`);const O=k.relationMap??{},g=l=>{const e=O[l];if(!e)throw new D("INTERNAL",`unknown relation "${l}" on table "${c}"`);return e},M=async(l,e,n)=>{const u=W(a,e.field);if(u.length===0){for(const i of a)i[l]=null;return}const{page:p}=await t(e.table,{baseWhere:s?.(e.table),relationBaseWhere:s,where:{[e.references]:{in:u}},with:n.with}),b=new Map;for(const i of p)b.set(i[e.references],i);for(const i of a){const w=b.get(i[e.field]);i[l]=w?v([w],n)[0]??null:null}},R=async(l,e,n)=>{const u=W(a,e.references);if(u.length===0){for(const f of a)f[l]=[];return}const p={[e.field]:{in:u}},b=n.where?{AND:[n.where,p]}:p,{page:i}=await t(e.table,{baseWhere:s?.(e.table),orderBy:n.orderBy,relationBaseWhere:s,where:b,with:n.with}),w=new Map;for(const f of i){const h=f[e.field],$=w.get(h);$?$.push(f):w.set(h,[f])}const y=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;for(const f of a){const h=w.get(f[e.references])??[];f[l]=v(y===void 0?h:h.slice(0,y),n)}},N=async l=>{for(const e of Object.keys(l)){const n=g(e),[u,p]=n.kind==="many"?[n.field,n.references]:[n.references,n.field],b=s?.(n.table),i=W(a,p),w=i.length===0?new Map:await o(n.table,u,i,b);for(const y of a){const f=y._count??{},h=y[p];f[e]=h==null?0:w.get(h)??0,y._count=f}}};for(const[l,e]of Object.entries(m)){if(e===void 0||e===!1)continue;if(l==="_count"){await N(e);continue}const n=g(l),u=e===!0?{}:e;await(n.kind==="one"?M(l,n,u):R(l,n,u))}},B=async(r,o,t)=>{const{deletedId:a,deletedReference:s,findHolders:d,onCascade:c,onRestrict:m,onSetNull:k,tableName:O}=r,g=t.references==="_id"?a:s(t.references);if(g==null)return;const M=await d(o,t.field,g);if(M.length!==0){t.onDelete==="restrict"&&m(`cannot delete "${O}" row: "${o}.${t.field}" still references it`);for(const R of M){const N=R._id;typeof N=="string"&&await(t.onDelete==="cascade"?c(o,N):k(o,N,t.field))}}},E=async r=>{const{schema:o,tableName:t}=r;if(!o.tables[t])throw new D("INTERNAL",`unknown table: ${t}`);for(const[a,s]of Object.entries(o.tables)){const d=s.relationMap;if(d)for(const c of Object.values(d))c.kind!=="one"||c.table!==t||!c.onDelete||await B(r,a,c)}},I=(r,o,t=!1)=>{for(const[a,s]of Object.entries(r.shape))a in o&&typeof s.parse=="function"&&(t&&o[a]===null&&s.kind==="optional"||s.parse(o[a]))};export{E as applyOnDelete,W as distinctValues,_ as fanOutScalarCounts,C as resolveWith,I as runRowValidators};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as m}from"@lunora/errors";const u="id",h=new Set(["_id","id"]),b=t=>{const e=[];for(const r of t??[])for(const[o,s]of Object.entries(r))e.push({direction:s,field:o});return e.length===0?[{direction:"asc",field:"_creationTime"}]:e},S=t=>{const e=new TextEncoder().encode(t);let r="";for(const o of e)r+=String.fromCodePoint(o);return btoa(r)},g=t=>{const e=atob(t),r=Uint8Array.from(e,o=>o.codePointAt(0)??0);return new TextDecoder().decode(r)},A=(t,e)=>{const r=e.map(o=>t[o.field]);return r.push(t._id),S(JSON.stringify(r))},l=()=>new m("BAD_REQUEST","invalid cursor"),D=t=>{let e;try{e=JSON.parse(g(t))}catch{throw l()}if(!Array.isArray(e))throw l();return e},_=(t,e)=>{const r=t.some(s=>h.has(s.field))?t:[...t,{direction:"asc",field:u}],o=[];for(const[s,n]of r.entries()){const i=[];for(const[d,a]of r.slice(0,s).entries())i.push({[a.field]:{eq:e[d]}});const f=n.direction==="desc"?"lt":"gt";i.push({[n.field]:{[f]:e[s]}});const[c]=i;o.push(i.length===1&&c!==void 0?c:{AND:i})}return{OR:o}},y=(t,e)=>t==="desc"?e?"gte":"gt":e?"lte":"lt",v=(t,e)=>{const r=t.some(s=>h.has(s.field))?t:[...t,{direction:"asc",field:u}],o=[];for(const[s,n]of r.entries()){const i=[];for(const[a,p]of r.slice(0,s).entries())i.push({[p.field]:{eq:e[a]}});const f=s===r.length-1,c=y(n.direction,f);i.push({[n.field]:{[c]:e[s]}});const[d]=i;o.push(i.length===1&&d!==void 0?d:{AND:i})}return{OR:o}},w=["_id","_creationTime"],E=(t,e,r)=>{if(!e)return t;const o=new Set([...e,...w,...r?Object.keys(r):[]]);return t.map(s=>{const n={};for(const i of o)i in s&&(n[i]=s[i]);return n})},N=(t,e)=>t&&e!==!0?{[t.field]:{isNull:!0}}:void 0;export{E as applySelect,v as buildSeekBeforeWhere,_ as buildSeekWhere,D as decodeCursor,A as encodeCursor,g as fromBase64,l as invalidCursor,b as normalizeOrderKeys,N as softDeleteScope,S as toBase64};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as a}from"@lunora/errors";const t=()=>Object.assign(new Error("native PITR is unavailable here (local dev or a non-SQLite Durable Object); use `lunora backup restore` for off-platform recovery"),{code:"PITR_UNAVAILABLE",name:"LunoraError",status:409}),i=o=>{if(typeof o=="number")return o;const r=Date.parse(o);if(Number.isNaN(r))throw new a("BAD_REQUEST",`pitr: invalid time "${o}" — expected epoch-ms or an ISO timestamp`);return r},s=async(o,r)=>{if(!o.getCurrentBookmark)throw t();const e=await o.getCurrentBookmark();return r===void 0||!o.getBookmarkForTime?{current:e}:{current:e,forTime:await o.getBookmarkForTime(i(r))}},k=async(o,r)=>{if(!o.onNextSessionRestoreBookmark)throw t();let e=r.bookmark;if(e===void 0){if(r.time===void 0)throw new a("BAD_REQUEST","pitrRestore: provide a `bookmark` or a `time` to restore to");if(!o.getBookmarkForTime)throw t();e=await o.getBookmarkForTime(i(r.time))}const n=await o.onNextSessionRestoreBookmark(e);return{restoredTo:e,undoBookmark:n}};export{k as armRestore,s as readBookmark};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{H as b,P as f,X as k,Y as n}from"./ctx-db-backfill-Hl48Dr77.mjs";import"@lunora/errors";import"drizzle-orm";import"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import"./aggregateTableName-G-eXyjcz.mjs";import"./do-exec-BLe9lLrN.mjs";import"./do-sql-x0AjZhaN.mjs";import"./renderSql-B5lF5Jd9.mjs";import"./RANK_TIEBREAK-DtX8zQyc.mjs";import"./serialize-sql-DiRzL7A4.mjs";export{b as backfillAggregateIndexes,f as backfillRankIndexes,k as backfillSearchIndexes,n as backfillSearchIndexesForTable};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as $}from"@lunora/errors";import{sql as i}from"drizzle-orm";const c="__relationExists",N=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],h=new Set(N),p={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},I=r=>{if(r===null||typeof r!="object"||Array.isArray(r))return!1;const e=Object.keys(r);return e.length>0&&e.every(t=>h.has(t))},g=r=>typeof r=="string"?r.replaceAll(/[\\%_]/g,e=>`\\${e}`):r,L=(r,e,t)=>{const s=i`${t.serialize(g(e))}`;return t.likeContains?t.likeContains(r,s):i`${r} LIKE '%' || ${s} || '%' ESCAPE '\\'`},O=(r,e,t,s,o)=>s===null?e==="ne"?i`${r} IS NOT NULL`:i`${r} IS NULL`:i`${r} ${i.raw(t)} ${o.serialize(s)}`,y=(r,e,t,s)=>{const o=Array.isArray(t)?t:[];if(o.length===0)return e==="IN"?i`0 = 1`:i`1 = 1`;const n=i.join(o.map(l=>i`${s.serialize(l)}`),i`, `);return e==="IN"?i`${r} IN (${n})`:i`${r} NOT IN (${n})`},S=(r,e,t)=>{const s=e,o=[];for(const n of N){if(!(n in s))continue;const l=s[n],u=p[n];u?o.push(O(r,n,u,l,t)):n==="isNull"?o.push(l?i`${r} IS NULL`:i`${r} IS NOT NULL`):n==="contains"?o.push(L(r,l,t)):o.push(y(r,n==="in"?"IN":"NOT IN",l,t))}return o},A=(r,e,t)=>{const s=t.fieldRef(r);return I(e)?S(s,e,t):e===null?[i`${s} IS NULL`]:[i`${s} = ${t.serialize(e)}`]},f=(r,e)=>{if(r.length!==0)return r.length===1?r[0]:i.join(r.map(t=>i`(${t})`),i` ${i.raw(e)} `)},E=(r,e,t)=>{const s=Array.isArray(r)?r:[],o=[];for(const n of s){const l=a(n??{},t);l&&o.push(l)}return o.length===0?e==="OR"?i`0 = 1`:void 0:f(o,e)},m=new Set(["AND","NOT","OR",c]),T=(r,e,t)=>{if(r===c){if(!t.relationExists)throw new $("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return t.relationExists(e)}if(r==="NOT"){const s=a(e??{},t);return s?i`NOT (${s})`:void 0}return E(e,r,t)},a=(r,e)=>{const t=[];for(const[s,o]of Object.entries(r))if(m.has(s)){const n=T(s,o,e);n&&t.push(n)}else t.push(...A(s,o,e));return f(t,"AND")},j=(r,e)=>{if(!(!r||Object.keys(r).length===0))return a(r,e)};export{j as compileWhereSql};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{isLunoraError as _}from"@lunora/errors";const L=/[\w.-]/u,x=t=>{let e="";for(const r of t)e+=L.test(r)?r:"_";return e},C=t=>{if(typeof t.name!="string"||t.name.length===0)throw new Error("recordEvaluation requires a non-empty `name`");if(typeof t.score!="number"||!Number.isFinite(t.score))throw new Error("recordEvaluation `score` must be a finite number");const e=x(t.name),r={[`gen_ai.evaluation.${e}.score`]:t.score};return t.label!==void 0&&(r[`gen_ai.evaluation.${e}.label`]=t.label),r},D=t=>{if(typeof t=="string")return t;try{return JSON.stringify(t)??String(t)}catch{return String(t)}},K=t=>typeof t=="boolean"||typeof t=="number"||typeof t=="string"?t:D(t),y=(t,e)=>{if(t===void 0&&e===void 0)return;const r={};if(e!==void 0)for(const[n,a]of Object.entries(e))r[n]=K(a);if(t!==void 0)for(const[n,a]of Object.entries(t))r[n]=K(a);return Object.keys(r).length===0?void 0:r},E=t=>{const e=new Uint8Array(t);crypto.getRandomValues(e);let r="";for(const n of e)r+=n.toString(16).padStart(2,"0");return r},S=/^[0-9a-f]+$/,F=(t,e,r=!0)=>`00-${t}-${e}-${r?"01":"00"}`,R=t=>{if(t==null)return;const e=t.trim().toLowerCase().split("-"),[r,n,a,s]=e;if(!(e.length<4||r===void 0||r.length!==2||!S.test(r)||r==="ff"||r==="00"&&e.length!==4||n===void 0||a===void 0||s===void 0||s.length!==2||!S.test(s)||n.length!==32||a.length!==16||!S.test(n)||!S.test(a)||n==="00000000000000000000000000000000"||a==="0000000000000000"))return{parentSpanId:a,sampled:(Number.parseInt(s,16)&1)===1,traceId:n}},f=Object.freeze({durationMs:"lunora.duration_ms",errorMessage:"error.message",errorType:"error.type",functionPath:"lunora.function_path",ok:"lunora.ok",shardKey:"lunora.shard_key",userId:"lunora.user_id"}),W=t=>{const e=R(t);return{rootSpanId:e?.parentSpanId??E(8),sampled:e?.sampled??!0,traceId:e?.traceId??E(16)}},T=t=>_(t)?t.code:t instanceof Error?t.constructor.name:"Error",N=t=>{const e=Object.keys(t);return e.length>0&&e.every(r=>r==="attributes"||r==="kind"||r==="links")},U=128,q=128,z=t=>{try{const e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return t}},H=t=>{try{return new URL(t).host}catch{return t}},V=(t,e)=>{try{return t(new URL(e))}catch{return!1}},J=t=>t===void 0?{}:N(t)?t:{attributes:t},B=(t,e)=>{if(t.isTraced){t.setAttribute(f.functionPath,e.functionPath),t.setAttribute(f.ok,e.ok),t.setAttribute(f.durationMs,e.durationMs),e.shardKey!==void 0&&t.setAttribute(f.shardKey,e.shardKey),e.userId!==void 0&&t.setAttribute(f.userId,e.userId),e.error!==void 0&&(t.setAttribute(f.errorType,e.error.type),t.setAttribute(f.errorMessage,e.error.message));for(const[r,n]of Object.entries(e.attributes))(typeof n=="boolean"||typeof n=="number"||typeof n=="string")&&t.setAttribute(`lunora.attr.${r}`,n)}},G=t=>{const e={attributes:{},events:[],links:[]},r={spanContext:()=>t,addEvent:(n,a)=>{if(e.events.length>=U)return;const s=y(a);e.events.push({...s===void 0?{}:{attributes:s},name:n,ts:Date.now()})},addLink:n=>{if(e.links.length>=q)return;const a=y(n.attributes);e.links.push({...a===void 0?{}:{attributes:a},spanId:n.spanId,traceId:n.traceId})},recordEvaluation:n=>{Object.assign(e.attributes,y(C(n)))},recordException:n=>{r.addEvent("exception",{"exception.message":n instanceof Error?n.message:String(n),...n instanceof Error&&typeof n.stack=="string"?{"exception.stacktrace":n.stack}:{},"exception.type":T(n)})},setAttribute:(n,a)=>{Object.assign(e.attributes,y({[n]:a}))},setAttributes:n=>{Object.assign(e.attributes,y(n))}};return{collected:e,handle:r}},X=t=>{const{anchor:e,fuseCloudflareSpans:r,functionPath:n,record:a,resolveCloudflareTracing:s,shardKey:i,userId:c}=t,h=u=>async(v,I,d)=>{const l=E(8),g=Date.now(),o=J(d),M=y(o.attributes),{collected:k,handle:j}=G({spanId:l,traceId:e.traceId}),A=async b=>{let m=!0,w;try{return await I(h(l),j)}catch(p){throw m=!1,w={message:p instanceof Error?p.message:String(p),type:T(p)},p}finally{const p=Date.now()-g,O=c(),$={...M,...k.attributes},P=[...o.links??[],...k.links];try{a({...Object.keys($).length===0?{}:{attributes:$},durationMs:p,...k.events.length===0?{}:{events:k.events},...w===void 0?{}:{error:w},functionPath:n,...o.kind===void 0||o.kind==="internal"?{}:{kind:o.kind},...P.length===0?{}:{links:P},name:v,ok:m,parentSpanId:u,shardKey:i,spanId:l,startTs:g,traceId:e.traceId,userId:O})}catch{}if(b!==void 0)try{B(b,{attributes:$,durationMs:p,error:w,functionPath:n,ok:m,shardKey:i,userId:O})}catch{}}};if(r===!0&&s!==void 0){const b=await s();if(b!==void 0&&typeof b.enterSpan=="function")return await b.enterSpan(v,m=>A(m))}return await A()};return h(e.rootSpanId)},Y=(t,e)=>{const{anchor:r,functionPath:n,propagate:a=!0,record:s,shardKey:i,userId:c}=t;return async(h,u)=>{const v=E(8),I=Date.now(),d=new Request(h,u);(typeof a=="function"?V(a,d.url):a)&&d.headers.set("traceparent",F(r.traceId,v,r.sampled??!0));let l,g;try{const o=await e(d);return g=o.status,o.ok||(l={message:`HTTP ${String(o.status)}`,type:`HTTP_${String(o.status)}`}),o}catch(o){throw l={message:o instanceof Error?o.message:String(o),type:T(o)},o}finally{try{s({attributes:{"http.request.method":d.method,...g===void 0?{}:{"http.response.status_code":g},"url.full":z(d.url)},durationMs:Date.now()-I,...l===void 0?{}:{error:l},functionPath:n,kind:"client",name:`${d.method} ${H(d.url)}`,ok:l===void 0,parentSpanId:r.rootSpanId,shardKey:i,spanId:v,startTs:I,traceId:r.traceId,userId:c()})}catch{}}}},Z=t=>{const{functionPath:e,record:r,shardKey:n}=t,a=(s,i,c,h)=>{if(!Number.isFinite(c))return;const u=y(h);try{r({...u===void 0?{}:{attributes:u},functionPath:e,kind:s,name:i,shardKey:n,ts:Date.now(),value:c})}catch{}};return{count:(s,i=1,c)=>{a("counter",s,i,c)},gauge:(s,i,c)=>{a("gauge",s,i,c)},record:(s,i,c)=>{a("histogram",s,i,c)}}},tt=t=>{const{anchor:e,collected:r,durationMs:n,failure:a,functionPath:s,shardKey:i,startTs:c,userId:h}=t,u=r?.attributes??{};return{...Object.keys(u).length===0?{}:{attributes:u},dispatch:!0,durationMs:n,...r===void 0||r.events.length===0?{}:{events:r.events},...a===void 0?{}:{error:{message:a.thrown instanceof Error?a.thrown.message:String(a.thrown),type:T(a.thrown)}},functionPath:s,...r===void 0||r.links.length===0?{}:{links:r.links},name:s,ok:a===void 0,parentSpanId:"",shardKey:i,spanId:e.rootSpanId,startTs:c,traceId:e.traceId,userId:h}};export{R as A,E as O,X as a,Y as b,Z as c,tt as d,G as e,B as f,y as n,W as r,T as t,f as w};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as r,c as t,e as c,b as s,a as o,d as p}from"./context-telemetry-BFO0N_e4.mjs";export{r as applyCloudflareSpanAttributes,t as createMetrics,c as createSpanCollector,s as createTracedFetch,o as createTracer,p as dispatchRootSpan};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";const d=t=>{const e={args:t.args??{},enqueuedAt:typeof t.enqueuedAt=="number"?t.enqueuedAt:0,functionPath:typeof t.functionPath=="string"?t.functionPath:"",id:typeof t.id=="string"?t.id:"",scheduledFor:typeof t.scheduledFor=="number"?t.scheduledFor:0};return typeof t.attempts=="number"&&(e.attempts=t.attempts),typeof t.shardKey=="string"&&(e.shardKey=t.shardKey),e},i=t=>{const e={key:typeof t.key=="string"?t.key:"",size:typeof t.size=="number"?t.size:0},s=t.httpMetadata?.contentType??t.contentType;typeof s=="string"&&(e.contentType=s),t.customMetadata&&typeof t.customMetadata=="object"&&(e.customMetadata=t.customMetadata),typeof t.sha256=="string"&&(e.sha256=t.sha256);const{uploaded:r}=t;return typeof r=="number"?e.uploaded=r:r instanceof Date&&(e.uploaded=r.getTime()),e},f=(t={})=>{const e=()=>{if(!t.scheduler)throw new c("INTERNAL",'ctx.db.system.query("_scheduled_functions"): no scheduler configured. Pass `scheduler` to createShardDO().');return t.scheduler},s=()=>{if(!t.storage)throw new c("INTERNAL",'ctx.db.system.query("_storage"): no storage configured. Pass `storage` to createShardDO().');return t.storage},r=async()=>(await e().list()).map(a=>d(a)),y=async()=>{const{objects:a}=await s().list();return a.map(n=>i(n))};return{get:(async(a,n)=>{if(a==="_scheduled_functions"){const u=await e().get(n);return u?d(u):null}const o=await s().getMetadata(n);return o?i(o):null}),query:(a=>a==="_scheduled_functions"?{collect:r}:{collect:y})}};export{f as createSystemReader};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"@lunora/errors";import{sql as i}from"drizzle-orm";import{matchesStaticWhere as A}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as L,foldAggregateTally as w,aggregateTableName as I}from"./aggregateTableName-G-eXyjcz.mjs";import{r as f}from"./do-exec-BLe9lLrN.mjs";import{b,s as E,g as y,a as v,_ as M,m as j,N as C}from"./do-sql-x0AjZhaN.mjs";import{param as F}from"./renderSql-B5lF5Jd9.mjs";import{sortColumnName as x,matchesRankStaticWhere as z,encodePartitionKey as q,rankTableName as D}from"./RANK_TIEBREAK-DtX8zQyc.mjs";import{t as k}from"./serialize-sql-DiRzL7A4.mjs";const U=["de","en","es","fr","it","nl","none","pt"],B=e=>U.includes(e),W="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",X="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",H="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",Y="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",K="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",P="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",V="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",G=/[\u0300-\u036F]/gu,O=e=>e.normalize("NFD").replaceAll(G,"").normalize("NFC").toLowerCase(),$=e=>new Set(O(e).split(" ")),J={de:$(X),en:$(W),es:$(H),fr:$(Y),it:$(K),nl:$(P),none:new Set,pt:$(V)},Q=2,Z=256,_=new Map,R=e=>{const o=e!==void 0&&B(e)?e:"none",n=_.get(o);if(n)return n;const r=J[o],s=c=>{const a=(O(c).match(/[\p{L}\p{N}]+/gu)??[]).filter(t=>t.length<=Z);return r.size===0?a:a.filter(t=>!r.has(t))},d={document:s,profile:`${o}-v${String(Q)}`,query:c=>{const a=s(c),t=new Set,u=[];for(let m=a.length-1;m>=0;m-=1){const l=a[m];t.has(l)||(t.add(l),u.unshift(l))}return u}};return _.set(o,d),d},ee=(e,o)=>e.profile!==o?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},ie=(e,o)=>{if(!o.includes("."))return e[o];let n=e;for(const r of o.split(".")){if(n===null||typeof n!="object"||Array.isArray(n))return;n=n[r]}return n},oe=(e,o)=>`${e}__fts_${o}`,ne="__text__",T="__id__",re=1e3,te=(e,o)=>o.document(e),S=(e,o)=>ie(e,o),se=e=>typeof e=="string"?e:e==null?"":typeof e=="number"||typeof e=="bigint"||typeof e=="boolean"?String(e):JSON.stringify(e)??"",ye=(e,o,n)=>e!==void 0&&o!==void 0&&S(e,n.field)===S(o,n.field),ae=(e,o)=>te(se(S(e,o.field)),R(o.language)).slice(0,re).join(" "),h="__lunora_search_state",de=e=>{const o=()=>{try{f(e,i`ALTER TABLE ${i.identifier(h)} ADD COLUMN ${i.identifier("profile")} TEXT`)}catch{}};f(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(h)} (${i.identifier("companion")} TEXT PRIMARY KEY, ${i.identifier("cursor")} TEXT, ${i.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${i.identifier("profile")} TEXT)`),o()},fe=e=>e===1||e===!0||e==="1",ce=(e,o)=>{const n=f(e,i`SELECT ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")} FROM ${i.identifier(h)} WHERE ${i.identifier("companion")} = ${o}`).toArray()[0];return n?{cursor:n.cursor??void 0,done:fe(n.done),profile:n.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},le=(e,o,n,r,s)=>{const d=n??null;f(e,i`INSERT INTO ${i.identifier(h)} (${i.identifier("companion")}, ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")}) VALUES (${o}, ${d}, ${r?1:0}, ${s}) ON CONFLICT (${i.identifier("companion")}) DO UPDATE SET ${i.identifier("cursor")} = excluded.${i.identifier("cursor")}, ${i.identifier("done")} = excluded.${i.identifier("done")}, ${i.identifier("profile")} = excluded.${i.identifier("profile")}`)},ue=(e,o,n)=>{const r=I(o,n.name);if(f(e,i`SELECT COUNT(*) AS count FROM ${i.identifier(r)}`).one().count>0)return;const s=n.by??[],d=new Map,c=f(e,i`SELECT id, _creationTime, ${i.identifier(E)} FROM ${i.identifier(o)}`).toArray();for(const a of c){const t=y(a);if(!t||n.where&&!A(t,n.where))continue;const u=L(s,t);w(d,u,n,t)}for(const[a,t]of d)f(e,i`INSERT INTO ${i.identifier(r)} (${v}, ${M}, ${j}) VALUES (${a}, ${t.value}, ${t.count})`)},Oe=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.aggregateIndexes))for(const s of r.aggregateIndexes)ue(e,n,s)},me=(e,o,n)=>{const r=D(o,n.name);if(f(e,i`SELECT COUNT(*) AS count FROM ${i.identifier(r)}`).one().count>0)return;const s=n.sortBy.map((a,t)=>x(t)),d=i.join(["__id__","__partition__",...s].map(a=>i.identifier(a)),i`, `),c=f(e,i`SELECT id, _creationTime, ${i.identifier(E)} FROM ${i.identifier(o)}`).toArray();for(const a of c){const t=y(a);if(!t||n.where&&!z(t,n.where))continue;const u=q(n.partitionBy??[],t),m=n.sortBy.map(p=>k(t[p.field]??null)),l=i.join([t._id,u,...m].map(p=>F(p)),i`, `);f(e,i`INSERT INTO ${i.identifier(r)} (${d}) VALUES (${l})`)}},Re=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.rankIndexes))for(const s of r.rankIndexes)me(e,n,s)},g=500,N=(e,o,n)=>{const r=oe(o,n.name),{profile:s}=R(n.language),d=ee(ce(e,r),s);if(d.finished)return!0;d.wipe&&f(e,i`DELETE FROM ${i.identifier(r)}`);const{cursor:c}=d,a=f(e,c===void 0?i`SELECT id, _creationTime, ${i.identifier(E)} FROM ${i.identifier(o)} ORDER BY id ASC LIMIT ${i.raw(String(g))}`:i`SELECT id, _creationTime, ${i.identifier(E)} FROM ${i.identifier(o)} WHERE id > ${c} ORDER BY id ASC LIMIT ${i.raw(String(g))}`).toArray();let t=c;for(const m of a){const{id:l}=m;if(typeof l!="string")continue;t=l;const p=C(m);if(!p){f(e,i`DELETE FROM ${i.identifier(r)} WHERE ${i.identifier(T)} = ${l}`);continue}f(e,i`DELETE FROM ${i.identifier(r)} WHERE ${i.identifier(T)} = ${l}`),f(e,i`INSERT INTO ${i.identifier(r)} (${i.identifier(ne)}, ${i.identifier(T)}) VALUES (${ae(p,n)}, ${l})`)}const u=a.length<g;return le(e,r,t,u,s),u},Ne=(e,o,n)=>{if(b(e))for(const r of n.searchIndexes??[])r.staged||N(e,o,r)},Ae=(e,o)=>{if(b(e)){de(e);for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.searchIndexes))for(const s of r.searchIndexes){let d=!1;for(;!d;)d=N(e,n,s)}}};export{R as A,Oe as H,Re as P,T,Ae as X,Ne as Y,ne as a,oe as c,de as l,te as n,h as o,ye as u,ae as y};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{r as m}from"./do-exec-BLe9lLrN.mjs";import{s as c,g as l,$}from"./do-sql-x0AjZhaN.mjs";import{compileWhereSql as h}from"./compileWhereSql-BLcfs4QW.mjs";import{t as u}from"./serialize-sql-DiRzL7A4.mjs";const g={fieldRef:$,serialize:u},S=i=>{if(i.length!==0)return e`id IN (${e.join(i.map(r=>e`${r}`),e`, `)})`},a=(i,r)=>{const t=[];r&&t.push(r);const o=h(i,g);return o&&t.push(o),t.length===0?e``:e` WHERE ${e.join(t,e` AND `)}`},A=(i,r,t)=>{const o=a(t,void 0),d=m(i,e`SELECT id, _creationTime, ${e.identifier(c)} FROM ${e.identifier(r)}${o}`).toArray(),n=[];for(const s of d){const f=l(s),{id:p}=s;f!==void 0&&typeof p=="string"&&n.push({doc:f,id:p})}return n},M=(i,r,t,o)=>{if(o.length===0)return new Set;const d=a(t,S(o)),n=m(i,e`SELECT id FROM ${e.identifier(r)}${d}`).toArray();return new Set(n.map(s=>s.id))};export{M as a,A as s};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{stableStringify as u}from"./stableStringify-BjLh4gvA.mjs";const l=(t,s)=>{const o={_id:t._id};if(s){for(const e of s)Object.hasOwn(t,e)&&(o[e]=t[e]);return o}for(const[e,n]of Object.entries(t))e!=="_id"&&e!=="_creationTime"&&(o[e]=n);return o},h=(t,s,o)=>{const{columns:e,table:n}=o,i=[],d=new Map;for(const r of t){const c=l(r,e),a=String(c._id),f=u(c);d.set(a,f);const p=s.get(a);p===void 0?i.push({doc:c,id:a,op:"insert",seq:0,table:n,ts:0}):p!==f&&i.push({doc:c,id:a,op:"update",seq:0,table:n,ts:0})}for(const r of s.keys())d.has(r)||i.push({id:r,op:"delete",seq:0,table:n,ts:0});return{changes:i,nextBaseline:d}};export{h as diffExternalSource,l as projectExternalSourceRow};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{renderSql as o}from"./renderSql-B5lF5Jd9.mjs";const s=(r,e,...l)=>r.exec.call(r,e,...l),a=(r,e)=>{const{params:l,sql:n}=o("sqlite",e);return s(r,n,...l)};export{a as r};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as i}from"drizzle-orm";import{r as c}from"./do-exec-BLe9lLrN.mjs";const n="__doc__",m=(e,t)=>`${e}__geo_${t}`,s=e=>`"${e.replaceAll('"','""')}"`,f=e=>e==="_id"||e==="id"?"id":e==="_creationTime"?"_creationTime":`json_extract(${n}, '$.${e.replaceAll("'","''")}')`,I=e=>i.raw(f(e)),T=(e,t)=>{const r=s(e);return t==="_id"||t==="id"?`${r}.id`:t==="_creationTime"?`${r}._creationTime`:`json_extract(${r}.${n}, '$.${t.replaceAll("'","''")}')`},N=(e,t)=>i.raw(T(e,t)),S=(e,t,r,o)=>i`CREATE ${o?i`UNIQUE `:i``}INDEX IF NOT EXISTS ${i.identifier(e)} ON ${i.identifier(t)} (${r})`,a=i.identifier("__key__"),l=i.identifier("__value__"),d=i.identifier("__count__"),A=(e,t,r,o,_)=>i`INSERT INTO ${i.identifier(e)} (${a}, ${l}, ${d}) VALUES (${t}, ${r}, ${o}) ON CONFLICT(${a}) DO UPDATE SET ${_}`,O=e=>{const t=[];for(const[r,o]of Object.entries(e.shape)){const _=o._meta?.column;_&&t.push([r,_])}return t},u=e=>{if(!e)return;const t=e[n];let r;typeof t=="string"?r=JSON.parse(t):t&&typeof t=="object"?r=t:r={};const{id:o}=e;typeof o=="string"&&(r._id=o);const _=e._creationTime;return typeof _=="number"&&(r._creationTime=_),r},y=e=>{try{return u(e)}catch{return}},$=new WeakMap,b=e=>{const t=$.get(e);if(t!==void 0)return t;let r;try{c(e,i`CREATE VIRTUAL TABLE IF NOT EXISTS ${i.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{c(e,i`DROP TABLE IF EXISTS ${i.identifier("__lunora_fts_probe")}`)}catch{}}return $.set(e,r),r};export{I as $,A as E,O as L,y as N,N as S,m as T,l as _,a,b,u as g,s as l,d as m,S as p,n as s};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{toErrorBody as f}from"@lunora/errors";const d=200,b=(r,s)=>{const n=t=>{const e=r.tables[t];return e?e.shardMode?.kind!=="global":!1};if(s&&s.length>0){const t=[];for(const e of s)n(e)&&t.push(e);return t}const o=[];for(const t of Object.keys(r.tables))n(t)&&o.push(t);return o},u=async function*(r,s,n=d){let o=null,t=!1;for(;!t;){const e=await r.findMany(s,{cursor:o,limit:n});for(const a of e.page)yield{doc:a,table:s};o=e.continueCursor,t=e.isDone||o===null}},k=async function*(r,s,n){const o=b(s,n.tables),t=n.batchSize??d;for(const e of o)yield*u(r,e,t)},p=new Set(["_creationTime","_id"]),y=(r,s)=>{for(const[n,o]of Object.entries(r.shape)){const t=s[n];if(t===void 0&&o.kind==="optional")continue;const e=o.parse;if(typeof e=="function")try{e(t)}catch(a){const c=a instanceof Error?a.message:String(a);return`field "${n}": ${c}`}}},h=(r,s,n)=>{const o=r.tables[s];if(!o)return`unknown table: ${s}`;if(o.shardMode?.kind==="global")return`table "${s}" is a global (.global()) table and is not importable through the shard import path`;const t=Object.fromEntries(Object.entries(n).filter(([e])=>!p.has(e)));for(const e of Object.keys(t))if(!(e in o.shape))return`unexpected field "${e}": not declared in table "${s}"`;return y(o,t)},g=async(r,s)=>{try{return await r.get(s)!==null}catch{return!1}},m=async(r,s,n,o)=>{const{doc:t,table:e}=n;if(typeof e!="string"||e.length===0)return{error:{code:"BAD_ROW",line:o,message:"row is missing `table`",table:e},kind:"error"};if(!t||typeof t!="object"||Array.isArray(t))return{error:{code:"BAD_ROW",line:o,message:"row is missing or malformed `doc`",table:e},kind:"error"};const a=h(s,e,t);if(a!==void 0)return{error:{code:"VALIDATION_ERROR",line:o,message:a,table:e},kind:"error"};const c=typeof t._id=="string"?t._id:void 0;if(c!==void 0&&await g(r,c))return{kind:"conflict"};try{return await r.insert(e,t,{allowExplicitId:!0}),{kind:"inserted",table:e}}catch(i){const{body:l}=f(i,{fallbackCode:"INSERT_FAILED"});return{error:{code:l.code,line:o,message:l.message,table:e},kind:"error"}}},A=async(r,s,n)=>{const o=[],t={};let e=0,a=(n.startLine??1)-1;for(const c of n.rows){a+=1;const i=await m(r,s,c,a);i.kind==="error"?o.push(i.error):i.kind==="conflict"?e+=1:t[i.table]=(t[i.table]??0)+1}return{conflicts:e,errors:o,inserted:t}},S=r=>{const s=Array.isArray(r.tables)?r.tables.filter(n=>typeof n=="string"):void 0;return{batchSize:typeof r.batchSize=="number"?r.batchSize:void 0,tables:s}},E=r=>{const s=Array.isArray(r.rows)?r.rows:[],n=[];for(const t of s){if(!t||typeof t!="object")continue;const e=t;if(typeof e.table!="string"||!e.doc||typeof e.doc!="object"||Array.isArray(e.doc)){n.push({doc:e.doc??{},table:typeof e.table=="string"?e.table:""});continue}n.push({doc:e.doc,table:e.table})}const o=typeof r.startLine=="number"?r.startLine:void 0;return{rows:n,startLine:o}};export{k as exportShardRows,u as exportShardTable,A as importShardRows,S as parseExportShardArgs,E as parseImportShardArgs,b as selectExportTables,h as validateImportRow};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const i=async t=>{const e=t.schema.tables[t.tableName]?.triggerMap;if(e)for(const a of Object.values(e))a.timing===t.timing&&a.op===t.op&&await a.handler(t.ctx,t.event)},n=(t,e,a)=>{const r=t.tables[e]?.triggerMap;return r?Object.values(r).some(s=>s.op===a):!1};export{n as hasTrigger,i as runTriggers};
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{LunoraError as f}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{r as T}from"./do-exec-BLe9lLrN.mjs";import{runExternalSourceTick as v,materializeExternalRowsIncremental as A}from"./materializeExternalRows-BUmj_9WO.mjs";const h="__lunora_source_cursor",D=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,O=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},N=/^-?\d+$/,I=/^-?\d+(?:\.\d+)?$/,M=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&I.test(e)&&I.test(t)?N.test(e)&&N.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),q=(e,t,o)=>{let r=o===null?void 0:O(o);for(const n of e){const s=n[t];if(s==null)continue;const c=s;(r===void 0||M(c,r))&&(r=c)}return r===void 0?null:D(r)},C=e=>{T(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(h)} (
|
|
2
|
-
table_name TEXT NOT NULL,
|
|
3
|
-
shard_key TEXT NOT NULL,
|
|
4
|
-
watermark TEXT,
|
|
5
|
-
last_reconcile_ms INTEGER,
|
|
6
|
-
PRIMARY KEY (table_name, shard_key)
|
|
7
|
-
)`)},j=(e,t,o)=>{const r=T(e,m`SELECT watermark, last_reconcile_ms FROM ${m.identifier(h)} WHERE table_name = ${t} AND shard_key = ${o} LIMIT 1`).toArray()[0];return{lastReconcileMs:r?.last_reconcile_ms??null,watermark:r?.watermark??null}},B=(e,t,o,r)=>{T(e,m`INSERT INTO ${m.identifier(h)} (table_name, shard_key, watermark, last_reconcile_ms)
|
|
8
|
-
VALUES (${t}, ${o}, ${r.watermark}, ${r.lastReconcileMs})
|
|
9
|
-
ON CONFLICT(table_name, shard_key) DO UPDATE SET watermark = excluded.watermark, last_reconcile_ms = excluded.last_reconcile_ms`)},x=e=>e instanceof Date?e.toISOString():typeof e=="bigint"?String(e):Array.isArray(e)?e.map(t=>x(t)):e!==null&&typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype?g(e):e,g=e=>{const t={};for(const[o,r]of Object.entries(e))t[o]=x(r);return t},z=(e,t={})=>{const{idColumn:o="id",map:r}=t,n=e[o];if(n==null)throw new f("INTERNAL",`external-source: row is missing id column "${o}"`);if(typeof n!="string"&&typeof n!="number"&&typeof n!="bigint")throw new TypeError(`external-source: id column "${o}" must be a string or number`);const s=String(n);if(r)return g({...r(e),_id:s});const c={};for(const[l,i]of Object.entries(e))l!==o&&(c[l]=i);return g({...c,_id:s})},V=(e,t,o)=>e==="manual"?!1:e===void 0||t===void 0?!0:o-t>=e.everyMs,E=async(e,t,o,r)=>{const n=await e.query(t,o);return{documents:n.map(s=>z(s,{idColumn:r.idColumn,map:r.map})),rows:n}},Y=async(e,t,o,r,n,s)=>{const c=n.tenantBy?n.tenantBy(s):[],{documents:l}=await E(o,n.query,c,n);return v(e,t,l,{columns:n.columns,table:r})},R=(e,t)=>{const o=e[t];return o!=null&&o!==!1&&o!==0},G=async(e,t,o,r,n,s,c)=>{const{cursor:l}=n;if(!l)throw new f("INTERNAL",`external-source: table "${r}" is mode "incremental" but has no \`cursor\` — this should have been rejected at defineSchema`);C(e);const i=j(e,r,s),S=n.tenantBy?n.tenantBy(s):[],_=n.reconcileEveryMs!==void 0&&(i.lastReconcileMs===null||c-i.lastReconcileMs>=n.reconcileEveryMs),w=i.watermark===null||_;let a,y;if(i.watermark===null||_){a=await E(o,n.query,S,n);const{softDeleteColumn:u}=n,p=u?a.documents.filter((k,b)=>{const d=a.rows[b];return!(d&&R(d,u))}):a.documents;({applied:y}=await v(e,t,p,{columns:n.columns,table:r}))}else{a=await E(o,l.query,[...S,O(i.watermark)],n);const{softDeleteColumn:u}=n,p=u?new Set(a.documents.flatMap((k,b)=>{const d=a.rows[b];return d&&R(d,u)?[String(k._id)]:[]})):void 0;({applied:y}=await A(t,a.documents,{columns:n.columns,deletedIds:p,table:r}))}const $=q(a.rows,l.column,i.watermark);if(w&&$===null&&a.rows.length>0)throw new f("INTERNAL",`external-source: table "${r}" (mode "incremental") pulled ${String(a.rows.length)} rows but none carry the cursor column "${l.column}" — the seed \`query\` must project it (matching \`cursor.query\`'s alias), or the watermark can never advance.`);const L=a.rows.length>0&&a.rows.every(u=>u[l.column]===null||u[l.column]===void 0);if(!w&&L)throw new f("INTERNAL",`external-source: table "${r}" (mode "incremental") pulled ${String(a.rows.length)} rows but none carry the cursor column "${l.column}" — \`cursor.query\` must project it (matching the seed \`query\`'s alias), or the watermark can never advance and every tick re-pulls the same stranded slice.`);return B(e,r,s,{lastReconcileMs:w?c:i.lastReconcileMs,watermark:$}),{applied:y}};export{R as isSoftDeleted,V as isSourceDue,z as liftSourceId,x as normalizeSourceValue,G as pullExternalSourceIncrementalTick,Y as pullExternalSourceTick};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{applyCdcChanges as m}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{s as f}from"./ctx-db-shapes-CHC2cS0g.mjs";import{diffExternalSource as g,projectExternalSourceRow as c}from"./diffExternalSource-DMpkJta1.mjs";import{stableStringify as p}from"./stableStringify-BjLh4gvA.mjs";const x=async(t,s,r,e)=>{const{changes:n,nextBaseline:a}=g(s,r,e);return await m(t,n),{applied:n.length,nextBaseline:a}},E=async(t,s,r)=>{const{columns:e,deletedIds:n,table:a}=r,i=[];for(const u of s){const l=c(u,e),o=String(l._id);if(n?.has(o)){await t.get(o,a)&&i.push({id:o,op:"delete",seq:0,table:a,ts:0});continue}const d=await t.get(o,a);d&&p(c({...d,_id:o},e))===p(l)||i.push({doc:l,id:o,op:"insert",seq:0,table:a,ts:0})}return await m(t,i),{applied:i.length}},w=(t,s,r)=>{const e=new Map;for(const{doc:n,id:a}of f(t,s,void 0))e.set(a,p(c({...n,_id:a},r)));return e},R=async(t,s,r,e)=>{const n=w(t,e.table,e.columns);return x(s,r,n,e)};export{x as materializeExternalRows,E as materializeExternalRowsIncremental,w as readExternalSourceBaseline,R as runExternalSourceTick};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const t=e=>`"${e.replaceAll('"','""')}"`;export{t as q};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as m}from"drizzle-orm";import{MySqlDialect as s}from"drizzle-orm/mysql-core";import{PgDialect as l}from"drizzle-orm/pg-core";import{SQLiteSyncDialect as n}from"drizzle-orm/sqlite-core";const p=new l,a=new s,i=new n,q={mysql:a,postgres:p,sqlite:i},w=(r,t)=>{const{params:e,sql:o}=q[r].sqlToQuery(t);return{params:e,sql:o}},D=r=>m`${r}`;export{D as param,w as renderSql};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{l as I,a as N,T as S,Y as g,c as R}from"./ctx-db-backfill-Hl48Dr77.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{aggregateTableName as h}from"./aggregateTableName-G-eXyjcz.mjs";import{migrateCdcLog as p,migrateCdcMeta as l}from"./CDC_LOG_TABLE-E_J5LPoK.mjs";import{u as O,_ as u,E as C,a as U}from"./schema-history-YGeVjyvV.mjs";import{r as s}from"./do-exec-BLe9lLrN.mjs";import{s as X,$,p as T,L as B,b,a as x,_ as Y,m,T as M}from"./do-sql-x0AjZhaN.mjs";import{sortColumnName as D,rankTableName as F}from"./RANK_TIEBREAK-DtX8zQyc.mjs";const j=(n,t,o)=>{for(const i of o.indexes){const r=`${t}_${i.name}`,a=e.join(i.fields.map(_=>$(_)),e`, `);s(n,T(r,t,a,i.unique??!1))}for(const[i,r]of B(o)){if(!r.unique)continue;const a=`${t}_unique_${i}`;s(n,T(a,t,$(i),!0))}},k=(n,t,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!b(n))){for(const i of o.searchIndexes){const r=R(t,i.name);s(n,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(r)} USING fts5(${e.identifier(N)}, ${e.identifier(S)} UNINDEXED)`),s(n,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${r}__vocab`)} USING fts5vocab(${e.identifier(r)}, ${e.raw("instance")})`)}g(n,t,o)}},y=(n,t,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const r=M(t,i.name);s(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const a=`${t}__geo_${i.name}__btree`;s(n,T(a,r,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},G=(n,t,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const r=h(t,i.name);s(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (${x} TEXT PRIMARY KEY, ${Y} REAL, ${m} INTEGER NOT NULL DEFAULT 0)`),s(n,e`PRAGMA table_info(${e.identifier(r)})`).toArray().some(a=>a.name==="__count__")||s(n,e`ALTER TABLE ${e.identifier(r)} ADD COLUMN ${m} INTEGER NOT NULL DEFAULT 0`)}},P=(n,t,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const r=F(t,i.name),a=i.sortBy.map((f,d)=>D(d)),_=a.map(f=>e`${e.identifier(f)} BLOB`),c=_.length>0?e`, ${e.join(_,e`, `)}`:e``;s(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${c})`);const E=[e`${e.identifier("__partition__")} ASC`];for(const[f,d]of a.entries()){const A=i.sortBy[f]?.direction;E.push(e`${e.identifier(d)} ${e.raw(A==="desc"?"DESC":"ASC")}`)}E.push(e`${e.identifier("__id__")} ASC`);const L=`${t}__rank_${i.name}__btree`;s(n,T(L,r,e.join(E,e`, `),!1))}},W=(n,t,o={})=>{o.schemaSnapshot!==void 0&&O(n,o.schemaSnapshot.hash,o.schemaSnapshot.json),I(n);for(const[i,r]of Object.entries(t.tables))r.shardMode?.kind!=="global"&&(s(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
_creationTime REAL NOT NULL,
|
|
4
|
-
${e.identifier(X)} TEXT NOT NULL
|
|
5
|
-
)`),j(n,i,r),k(n,i,r),y(n,i,r),G(n,i,r),P(n,i,r));o.cdc&&(p(n),l(n),u(n)),C(n),U(n)};export{W as runShardMigrations};
|
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
import{sql as s}from"drizzle-orm";import{r as E}from"./do-exec-BLe9lLrN.mjs";import{q as O}from"./quote-identifier-CGiYFBvY.mjs";const _="__client_watermark",l=t=>{E(t,s`CREATE TABLE IF NOT EXISTS ${s.identifier(_)} (
|
|
2
|
-
identity TEXT NOT NULL,
|
|
3
|
-
client_id TEXT NOT NULL,
|
|
4
|
-
last_mutation_id INTEGER NOT NULL,
|
|
5
|
-
PRIMARY KEY (identity, client_id)
|
|
6
|
-
)`)},I=(t,e,i)=>E(t,s`SELECT last_mutation_id FROM ${s.identifier(_)} WHERE identity = ${e} AND client_id = ${i} LIMIT 1`).toArray()[0]?.last_mutation_id??0,m=(t,e,i,n)=>{E(t,s`INSERT INTO ${s.identifier(_)} (identity, client_id, last_mutation_id) VALUES (${e}, ${i}, ${n})
|
|
7
|
-
ON CONFLICT(identity, client_id) DO UPDATE SET last_mutation_id = MAX(last_mutation_id, excluded.last_mutation_id)`)},T="__global_shape_snapshot",A=t=>{E(t,s`CREATE TABLE IF NOT EXISTS ${s.identifier(T)} (
|
|
8
|
-
connection_id TEXT NOT NULL,
|
|
9
|
-
sub_id TEXT NOT NULL,
|
|
10
|
-
members TEXT NOT NULL,
|
|
11
|
-
PRIMARY KEY (connection_id, sub_id)
|
|
12
|
-
)`)},S=(t,e,i)=>{const n=E(t,s`SELECT members FROM ${s.identifier(T)} WHERE connection_id = ${e} AND sub_id = ${i} LIMIT 1`).toArray()[0]?.members;if(n===void 0)return new Map;try{const a=JSON.parse(n);return a===null||typeof a!="object"?new Map:new Map(Object.entries(a))}catch{return new Map}},f=(t,e,i,n)=>{const a=JSON.stringify(Object.fromEntries(n));E(t,s`INSERT INTO ${s.identifier(T)} (connection_id, sub_id, members) VALUES (${e}, ${i}, ${a})
|
|
13
|
-
ON CONFLICT(connection_id, sub_id) DO UPDATE SET members = excluded.members`)},y=(t,e,i)=>{E(t,s`DELETE FROM ${s.identifier(T)} WHERE connection_id = ${e} AND sub_id = ${i}`)},M=(t,e)=>{E(t,s`DELETE FROM ${s.identifier(T)} WHERE connection_id = ${e}`)},d="__idempotency",b=t=>{E(t,s`CREATE TABLE IF NOT EXISTS ${s.identifier(d)} (
|
|
14
|
-
identity TEXT NOT NULL,
|
|
15
|
-
mutation_id TEXT NOT NULL,
|
|
16
|
-
result_json TEXT NOT NULL,
|
|
17
|
-
ts REAL NOT NULL,
|
|
18
|
-
PRIMARY KEY (identity, mutation_id)
|
|
19
|
-
)`)},C=(t,e,i)=>{const n=E(t,s`SELECT result_json, ts FROM ${s.identifier(d)} WHERE identity = ${e} AND mutation_id = ${i} LIMIT 1`).toArray()[0];return n===void 0?void 0:{resultJson:n.result_json,ts:n.ts}},D=(t,e,i,n,a)=>{E(t,s`INSERT OR IGNORE INTO ${s.identifier(d)} (identity, mutation_id, result_json, ts) VALUES (${e}, ${i}, ${n}, ${a})`)},F=(t,e)=>{E(t,s`DELETE FROM ${s.identifier(d)} WHERE ts < ${e}`)},c="__lunora_schema_history",p=50,o=(t,e,...i)=>t.exec(e,...i),r=O(c),N=t=>{o(t,`CREATE TABLE IF NOT EXISTS ${r} (
|
|
20
|
-
hash TEXT PRIMARY KEY,
|
|
21
|
-
seq INTEGER NOT NULL,
|
|
22
|
-
snapshot_json TEXT NOT NULL,
|
|
23
|
-
applied_at INTEGER NOT NULL
|
|
24
|
-
)`)},u=t=>{o(t,`DELETE FROM ${r} WHERE hash NOT IN (SELECT hash FROM ${r} ORDER BY seq DESC LIMIT ?)`,p)},U=(t,e,i,n=Date.now())=>{if(e===""||i==="")return!1;try{if(N(t),o(t,`SELECT hash FROM ${r} WHERE hash = ? LIMIT 1`,e).toArray().length>0)return!1;const[a]=o(t,`SELECT COALESCE(MAX(seq), 0) + 1 AS next FROM ${r}`).toArray(),L=typeof a?.next=="number"?a.next:1;return o(t,`INSERT INTO ${r} (hash, seq, snapshot_json, applied_at) VALUES (?, ?, ?, ?) ON CONFLICT(hash) DO NOTHING`,e,L,i,n),u(t),!0}catch{return!1}},q=t=>{try{return N(t),o(t,`SELECT hash, seq, applied_at FROM ${r} ORDER BY seq DESC`).toArray().map(e=>({appliedAt:typeof e.applied_at=="number"?e.applied_at:0,hash:typeof e.hash=="string"?e.hash:"",seq:typeof e.seq=="number"?e.seq:0}))}catch{return[]}},X=(t,e)=>{try{N(t);const[i]=o(t,`SELECT hash, seq, applied_at, snapshot_json FROM ${r} WHERE hash = ? LIMIT 1`,e).toArray();return i===void 0?void 0:{appliedAt:typeof i.applied_at=="number"?i.applied_at:0,hash:typeof i.hash=="string"?i.hash:"",seq:typeof i.seq=="number"?i.seq:0,snapshotJson:typeof i.snapshot_json=="string"?i.snapshot_json:""}}catch{return}};export{b as E,f as S,D as T,l as _,A as a,I as b,F as c,S as d,_ as e,X as f,q as g,y as l,C as m,m as o,M as p,d as r,T as t,U as u};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const g=/key|secret|token|password|passwd|credential|private|auth|bearer|session|cookie|salt|signature|dsn|webhook/iu,R=new Set(["LUNORA_ADMIN_TOKEN","LUNORA_WS_BEARER"]),E=["CF_PAGES_URL","WORKER_URL","LUNORA_WORKER_URL"],c=["CF_ENV","ENVIRONMENT","WORKER_ENV","NODE_ENV"],h=t=>t.length<=4?"••••":`${t.slice(0,4)}${"•".repeat(Math.min(8,t.length-4))}`,_=t=>g.test(t),v=t=>{const e=n=>typeof t[n]=="function";return e("idFromName")||e("idFromString")?"durable-object":e("createMultipartUpload")||e("put")&&e("get")&&e("list")&&e("head")?"r2":e("getWithMetadata")?"kv":e("prepare")&&e("dump")?"d1":e("send")&&e("sendBatch")?"queue":e("fetch")&&!e("get")?"service":"object"},k=t=>{const e={};for(const r of E)if(typeof t[r]=="string"&&t[r]!==""){e.workerUrl=t[r];break}for(const r of c)if(typeof t[r]=="string"&&t[r]!==""){e.environment=t[r];break}const n=t.CF_VERSION_METADATA;if(n!==null&&typeof n=="object"){const r=n;typeof r.id=="string"&&(e.deploymentId=r.id),typeof r.tag=="string"&&(e.versionTag=r.tag)}return e},A=/^(?:dev(?:elopment)?|local(?:host)?|test)$/iu,N=t=>{const e=t??{};for(const n of c){const r=e[n];if(typeof r=="string"&&A.test(r))return!0}return!1},w=t=>{const e=t??{},n=[];for(const[r,o]of Object.entries(e))if(!R.has(r)){if(typeof o=="string"){const s=_(r);n.push({kind:s?"secret":"var",name:r,value:h(o)});continue}if(typeof o=="number"||typeof o=="boolean"){n.push({kind:"var",name:r,value:String(o)});continue}if(o!==null&&typeof o=="object"){n.push({bindingType:v(o),kind:"binding",name:r,value:null});continue}n.push({kind:"var",name:r,value:null})}return n.sort((r,o)=>r.name.localeCompare(o.name)),{deploy:k(e),settings:n}},a=24,l=32,d={error:0,info:2,warning:1},u=new Set(["0","disabled","false","no","off"]),m=new Set(["1","enabled","on","true","yes"]),i=t=>typeof t=="string"?t.trim().toLowerCase():void 0,y=t=>{const e=t.AUTH_SECRET??t.BETTER_AUTH_SECRET,n=typeof e=="string"?e.trim().length:0;return n>0&&n<l?[{detail:{length:n,min:l},kind:"auth-secret-weak",level:"warning"}]:[]},O=t=>{const e=i(t.LUNORA_ALLOWED_ORIGINS),n=m.has(i(t.LUNORA_CORS_ALLOW_CREDENTIALS)??"");return(e?.split(",").some(r=>r.trim()==="*")??!1)&&n?[{kind:"cors-wildcard-credentials",level:"error"}]:[]},U=(t,e)=>{if(e)return[];const n=[];return u.has(i(t.LUNORA_SECURITY_HEADERS)??"")&&n.push({kind:"security-headers-disabled",level:"warning"}),u.has(i(t.LUNORA_SECURITY_CSRF)??"")&&n.push({kind:"csrf-disabled",level:"warning"}),i(t.BETTER_AUTH_URL)?.startsWith("http://")===!0&&n.push({kind:"cookies-insecure",level:"warning"}),n},L=t=>{const e=t??{},n=[],r=e.LUNORA_ADMIN_TOKEN;typeof r=="string"&&r.length>0&&r.length<a&&n.push({detail:{length:r.length,min:a},kind:"admin-token-weak",level:"warning"});const o=e.LUNORA_WS_BEARER,s=N(e);return(typeof o!="string"||o==="")&&n.push({kind:"ws-gate-open",level:s?"info":"error"}),s&&n.push({kind:"dev-args-unredacted",level:"warning"}),n.push(...y(e),...O(e),...U(e,s)),{findings:n.toSorted((p,f)=>d[p.level]-d[f.level])}};export{w as E,N as R,L as _,l as c,a as o};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{r as p}from"./do-exec-BLe9lLrN.mjs";import{$ as o}from"./do-sql-x0AjZhaN.mjs";const E=(s,i,d,r)=>{const a=d-(i.after??0),t=[e`${o(i.field)} IS NOT NULL`,e`${o(i.field)} < ${a}`];i.softDeleteField!==void 0&&t.push(e`${o(i.softDeleteField)} IS NULL`);const f=e`SELECT id FROM ${e.identifier(i.table)} WHERE ${e.join(t,e` AND `)} LIMIT ${e.raw(String(Math.max(0,Math.floor(r))+1))}`,l=p(s,f).toArray(),n=l.length>r,m=l.slice(0,r).map($=>$.id);return{hasMore:n,ids:m}};export{E as selectExpiredIds};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const o=t=>typeof t=="boolean"?t?1:0:t===null||typeof t=="string"||typeof t=="number"?t:typeof t=="bigint"?t.toString():JSON.stringify(t);export{o as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{RELATION_FUNCTION_PREFIX as r}from"./ADMIN_FUNCTIONS-B0xlQJ4w.mjs";const h=async(s,n,l,t)=>{const o=typeof t.table=="string"?t.table:"",a=s.tables[o];if(!a)throw new i("UNKNOWN_TABLE",`${r} unknown table "${o}"`,{status:404});if(a.shardMode?.kind==="global")throw new i("BAD_REQUEST",`${r} table "${o}" is global, not shard-local`);const e=t.where??void 0;return l===`${r}count`?n.count(o,e):(await n.findMany(o,{orderBy:t.orderBy,where:e,with:t.with})).page};export{h as serveRelationFanout};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{LunoraError as f}from"@lunora/errors";const g=/^(?:explain\s+(?:query\s+plan\s+)?)?(?:select|with)\b/iu,d=/\b(?:alter|attach|create|delete|detach|drop|insert|pragma|reindex|replace|truncate|update|vacuum)\b/iu,h=/^\w+/u,m=/;\s*$/u,p=/\s/u,y=(r,e)=>{let t=e+2;for(;t<r.length&&r[t]!==`
|
|
2
|
-
`;)t+=1;return t},E=(r,e)=>{const t=r.indexOf("*/",e+2);return t===-1?-1:t+2},L=r=>{let e=0;for(;e<r.length;){const t=r[e];if(t!==void 0&&p.test(t))e+=1;else if(t==="-"&&r[e+1]==="-")e=y(r,e);else if(t==="/"&&r[e+1]==="*"){const s=E(r,e);if(s===-1)break;e=s}else break}return e},u=r=>{const e=L(r),t=r.slice(e).trimEnd();if(t==="")return{code:"SQL_EMPTY",message:"the query is empty"};const s=t.replace(m,""),c=s.indexOf(";");if(c!==-1)return{code:"SQL_MULTIPLE_STATEMENTS",length:1,message:"only a single statement may be run",offset:e+c};const i="the SQL editor is read-only — only SELECT / WITH / EXPLAIN queries are allowed";if(!g.test(s))return{code:"SQL_NOT_READONLY",length:h.exec(s)?.[0].length??1,message:i,offset:e};const n=d.exec(s);if(n!==null)return{code:"SQL_NOT_READONLY",length:n[0].length,message:`${i} (\`${n[0].toUpperCase()}\` is not allowed)`,offset:e+n.index}},l=1e3,x=r=>{const e=u(r);if(e!==void 0)throw new f(e.code,e.message,{status:400})},N=(r,e)=>{x(e);const t=r.exec(e).toArray(),s=t.length>l?t.slice(0,l):t;return{columns:s.length>0?Object.keys(s[0]):[],rowCount:t.length,rows:s,truncated:t.length>l}},S=/near "([^"]*)": syntax error/iu,T=/^SCAN (?:TABLE )?(?!CONSTANT\b|SUBQUERY\b)([^\s(]+)/u,w=(r,e)=>{if(e==="")return{};const t=r.indexOf(e);return t===-1?{}:{length:e.length,offset:t}},b=(r,e)=>{const t=u(e);if(t!==void 0)return{diagnostics:t.code==="SQL_EMPTY"?[]:[{length:t.length,message:t.message,offset:t.offset,severity:"error",source:"gate"}],plan:[]};let s;try{s=r.exec(`EXPLAIN QUERY PLAN ${e}`).toArray().map(n=>{const{detail:o}=n;return typeof o=="string"?o:""}).filter(n=>n!=="")}catch(n){const o=n instanceof Error?n.message:String(n),a=S.exec(o);return{diagnostics:[{...a?w(e,a[1]??""):{},message:o,severity:"error",source:"syntax"}],plan:[]}}const c=[],i=new Set;for(const n of s){const o=T.exec(n);if(o){const a=o[1]??"";i.has(a)||(i.add(a),c.push({message:`full table scan on \`${a}\` — this query reads every row`,severity:"warning",source:"plan"}))}}return{diagnostics:c,plan:s}};export{u as L,l as a,N as d,x as u,b as y};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const y=(e,t)=>e<t?-1:e>t?1:0,s=e=>{if(e===void 0)return"null";if(typeof e=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key — pass it as a string, or use stableWireKey");if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(r=>s(r)).join(",")}]`;const t=Object.getPrototypeOf(e);if(t!==null&&t!==Object.prototype){const r=e.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${r} in a stable JSON cache key — only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}const n=e,a=Object.keys(n).toSorted(y),i=[];for(const r of a){const o=n[r];o!==void 0&&i.push(`${JSON.stringify(r)}:${s(o)}`)}return`{${i.join(",")}}`};export{s as stableStringify};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{stableStringify as r}from"./stableStringify-BjLh4gvA.mjs";import{f as e}from"./wire-codec-Ctnni0h6.mjs";const s=t=>r(e(t));export{s as stableWireKey};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as l}from"./wire-codec-Ctnni0h6.mjs";const c="_id",p="__lunora__",b=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;const r=t[c];return typeof r=="string"?r:void 0},y=t=>{const r=new Map,n=[];for(const s of t){const e=b(s);if(e===void 0||r.has(e))return;r.set(e,s),n.push(e)}return{byId:r,order:n}},h=(t,r)=>{const n=t.order.filter(e=>r.byId.has(e)),s=r.order.filter(e=>t.byId.has(e));return n.length!==s.length?!1:n.every((e,o)=>s[o]===e)},g=(t,r,n,s)=>{const e=[];for(const o of t.order)r.byId.has(o)||e.push({delta:{key:o,op:"delete",table:n},frame:`{"key":${JSON.stringify(o)},"op":"delete","table":${s}}`});return e},m=(t,r,n,s)=>{const e=[];for(const o of r.order){const i=r.byId.get(o),a=t.byId.get(o),u=JSON.stringify(l(i)),f=a===void 0?void 0:JSON.stringify(a);if(f===u)continue;const d=f===void 0?"insert":"update";e.push({delta:{key:o,op:d,row:i,table:n},frame:`{"key":${JSON.stringify(o)},"op":"${d}","row":${u},"table":${s}}`})}return e},S=(t,r,n,s)=>{let e;try{e=JSON.parse(t)}catch{return}if(!Array.isArray(e)||!Array.isArray(r))return;const o=y(e),i=y(r);if(o===void 0||i===void 0||!h(o,i))return;const a=n===""?p:n,u=JSON.stringify(a),f=[...g(o,i,a,u),...m(o,i,a,u)];if(!(f.length>i.order.length)){if(s!==void 0)for(const{frame:d}of f)s.push(d);return f.map(({delta:d})=>d)}},$=(t,r)=>{try{return t.send(r),!0}catch{return!1}},w=(t,r,n,s)=>{const e=JSON.stringify(r);let o=!0;for(const i of n)$(t,`{"type":"delta","id":${e},"delta":${i}${s}}`)||(o=!1);return o},A=async t=>{let r=0;for(;r<100;){r+=1;const n=t.bufferedAmount;if(typeof n!="number"||n<1048576)return;await new Promise(s=>{setTimeout(s,20)})}};export{A as awaitWsDrain,w as sendDeltaFrames,S as subscriptionListDeltas,$ as trySendFrame};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const b=e=>{let t="";for(let i=0;i<e.length;i+=32768)t+=String.fromCharCode(...e.subarray(i,i+32768));return btoa(t)},w=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let c=0;c<t.length;c+=1)i[c]=t.codePointAt(c)??0;return i},o="$lunora.wire$";const g="__proto__",d={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},p={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},l=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===void 0)return[o,"undefined"];if(e===null)return null;const i=typeof e;if(i==="bigint")return[o,"bigint",e.toString()];if(i==="number"){const r=e;return Number.isNaN(r)?[o,"nan"]:r===1/0?[o,"inf"]:r===-1/0?[o,"-inf"]:r}if(i!=="object")return e;if(e instanceof Date)return[o,"date",l(e.getTime(),t+1)];if(e instanceof Error){const r=e,a={};for(const y of Object.keys(r))r[y]!==void 0&&(a[y]=l(r[y],t+1));const f=[o,"error",r.name,r.message,a];return r.cause!==void 0&&f.push(l(r.cause,t+1)),f}if(e instanceof URL)return[o,"url",e.href];if(e instanceof Map)return[o,"map",[...e.entries()].map(([r,a])=>[l(r,t+1),l(a,t+1)])];if(e instanceof Set)return[o,"set",[...e].map(r=>l(r,t+1))];if(e instanceof ArrayBuffer)return[o,"bytes",b(new Uint8Array(e)),"ArrayBuffer"];if(ArrayBuffer.isView(e)){const r=e,a=r.constructor.name,f=new Uint8Array(r.buffer,r.byteOffset,r.byteLength);return a==="Uint8Array"?[o,"bytes",b(f)]:[o,"bytes",b(f),a]}if(Array.isArray(e)){const r=e.map(a=>l(a,t+1));return r.length>0&&r[0]===o?[o,"arr",r]:r}const c=Object.getPrototypeOf(e);if(c!==null&&c!==Object.prototype){const r=e.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${r} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const n=e,u={};for(const r of Object.keys(n)){const a=n[r];a!==void 0&&(u[r]=l(a,t+1))}return u},s=(e,t=0)=>{if(t>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(e===null||typeof e!="object")return e;if(Array.isArray(e)){if(e[0]===o)switch(e[1]){case"-inf":return-1/0;case"arr":return e[2].map(n=>s(n,t+1));case"bigint":{const n=e[2];if(typeof n!="string"||n.length>1024||!/^-?\d+$/.test(n))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(n)}case"date":return new Date(s(e[2],t+1));case"map":return new Map(e[2].map(([n,u])=>[s(n,t+1),s(u,t+1)]));case"set":return new Set(e[2].map(n=>s(n,t+1)));case"url":return new URL(e[2]);case"error":{const n=e[2],u=e[3],r=(Object.hasOwn(p,n)?p[n]:void 0)??Error,a=new r(u);a.name!==n&&Object.defineProperty(a,"name",{configurable:!0,value:n,writable:!0});const f=s(e[4],t+1);for(const y of Object.keys(f))y===g?Object.defineProperty(a,y,{configurable:!0,enumerable:!0,value:f[y],writable:!0}):a[y]=f[y];return e.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:s(e[5],t+1),writable:!0}),a}case"bytes":{const n=w(e[2]),u=e[3]??"Uint8Array";if(u==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;const r=Object.hasOwn(d,u)?d[u]:void 0;return r?new r(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return e.map(n=>s(n,t+1))}return e.map(n=>s(n,t+1))}const i=e,c={};for(const n of Object.keys(i)){const u=s(i[n],t+1);n===g?Object.defineProperty(c,n,{configurable:!0,enumerable:!0,value:u,writable:!0}):c[n]=u}return c};export{s as c,l as f};
|