@blitznocode/blitz-orm 0.11.12 → 0.11.13
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 +1 -2
- package/dist/index.mjs +3 -3
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -711,7 +711,6 @@ type NextPipeline<Res extends BaseResponse> = {
|
|
|
711
711
|
type PipelineOperation<Res extends BaseResponse> = (req: Request, res: Res) => Promise<void | NextPipeline<Res>[]>;
|
|
712
712
|
type Pipeline<Res extends BaseResponse> = PipelineOperation<Res>[];
|
|
713
713
|
|
|
714
|
-
declare const VERSION: string | undefined;
|
|
715
714
|
type BormProps = {
|
|
716
715
|
schema: BormSchema;
|
|
717
716
|
config: BormConfig;
|
|
@@ -736,4 +735,4 @@ declare class BormClient {
|
|
|
736
735
|
close: () => Promise<void>;
|
|
737
736
|
}
|
|
738
737
|
|
|
739
|
-
export { type Action, type AllDbHandles, type BQLField, type BQLFieldObj, type BQLMutation, type BQLMutationBlock, type BQLResponse, type BQLResponseMulti, type BQLResponseSingle, type BaseResponse, type BormConfig, type BormEntity, type BormField, type BormMetadata, type BormOperation, type BormRelation, type BormSchema, type BormTrigger, type Cardinality, type CommonProvider, type ContentType, type ContentTypeMapping, type DBConnector, type DBHandleKey, type DBHandles, type DataField, type DiscreteCardinality, type EnrichedAttributeQuery, type EnrichedBQLMutationBlock, type EnrichedBQLQuery, type EnrichedBormEntity, type EnrichedBormRelation, type EnrichedBormSchema, type EnrichedDataField, type EnrichedEntityQuery, type EnrichedFieldQuery, type EnrichedLinkField, type EnrichedLinkQuery, type EnrichedRelationQuery, type EnrichedRoleField, type EnrichedRoleQuery, type FilledBQLMutationBlock, type Filter, type FilterValue, type Hooks, type LinkField, type LinkedFieldWithThing, type MutationConfig, type NegativeFilter, type NodeFunctionParams, type ParsedBQLMutation, type Pipeline, type PipelineOperation, type PlayedBy, type PositiveFilter, type PreHook, type Provider, type QueryConfig, type RawBQLMutation, type RawBQLQuery, type Request, type RightType, type RoleField, type RootBQLMutationBlock, type Sorter, type TQLEntityMutation, type TQLRequest, type ThingType, type TransFormAction, type TypeDBClusterProvider, type TypeDBHandles, type TypeDBProvider, type TypeGen,
|
|
738
|
+
export { type Action, type AllDbHandles, type BQLField, type BQLFieldObj, type BQLMutation, type BQLMutationBlock, type BQLResponse, type BQLResponseMulti, type BQLResponseSingle, type BaseResponse, type BormConfig, type BormEntity, type BormField, type BormMetadata, type BormOperation, type BormRelation, type BormSchema, type BormTrigger, type Cardinality, type CommonProvider, type ContentType, type ContentTypeMapping, type DBConnector, type DBHandleKey, type DBHandles, type DataField, type DiscreteCardinality, type EnrichedAttributeQuery, type EnrichedBQLMutationBlock, type EnrichedBQLQuery, type EnrichedBormEntity, type EnrichedBormRelation, type EnrichedBormSchema, type EnrichedDataField, type EnrichedEntityQuery, type EnrichedFieldQuery, type EnrichedLinkField, type EnrichedLinkQuery, type EnrichedRelationQuery, type EnrichedRoleField, type EnrichedRoleQuery, type FilledBQLMutationBlock, type Filter, type FilterValue, type Hooks, type LinkField, type LinkedFieldWithThing, type MutationConfig, type NegativeFilter, type NodeFunctionParams, type ParsedBQLMutation, type Pipeline, type PipelineOperation, type PlayedBy, type PositiveFilter, type PreHook, type Provider, type QueryConfig, type RawBQLMutation, type RawBQLQuery, type Request, type RightType, type RoleField, type RootBQLMutationBlock, type Sorter, type TQLEntityMutation, type TQLRequest, type ThingType, type TransFormAction, type TypeDBClusterProvider, type TypeDBHandles, type TypeDBProvider, type TypeGen, type ValidateAction, type Validations, type WithBormMetadata, BormClient as default };
|
package/dist/index.mjs
CHANGED
|
@@ -94,7 +94,7 @@ ${o}`}).join(`
|
|
|
94
94
|
`)},_t=e=>{let{queries:t,schema:r,level:n,parentQuery:s}=e,i=[],a=s[ie];return i.push(M(`"${a}" as \`$$queryPath\``,n)),i.push(M("record::id(id) as `$id`",n)),i.push(M("record::tb(id) as `$thing`",n)),t.forEach(o=>{let c=Mo({query:o,level:n,schema:r});c&&i.push(c);}),i.length===0?null:i.join(`,
|
|
95
95
|
`)},Mo=e=>{let{query:t,schema:r,level:n}=e;return t.$fieldType==="data"?So({query:t,level:n}):t.$fieldType==="link"?Lo({query:t,level:n,schema:r}):t.$fieldType==="role"?Qo({query:t,level:n,schema:r}):null},So=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?M(`record::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?M(`\`${t.$path}\``,r):M(`\`${t.$path}\` AS \`${t.$as}\``,r)},Lo=e=>{let{query:t,schema:r,level:n}=e,{$fields:s,$filter:i,$offset:a,$limit:o,$sort:c}=t;if(s.length===0)return null;let p=[];p.push(M("(",n));let u=n+1;p.push(M("SELECT",u));let d=_t({parentQuery:t,queries:s,level:u+1,schema:r});d&&p.push(d);let l=t[oe][Se].queryPath;if(p.push(M(`FROM ${l}`,u)),i){let f=ye(i,t.$thing,r),h=pe(f);p.push(`WHERE ${h}`);}return c&&p.push(M(Ve(c),u)),typeof o=="number"&&p.push(M(`LIMIT ${o}`,u)),typeof a=="number"&&p.push(M(`START ${a}`,u)),p.push(M(`) AS \`${t.$as}\``,n)),p.join(`
|
|
96
96
|
`)},Qo=e=>{let{query:t,schema:r,level:n}=e;if(t.$fields.length===0)return null;let s=[];s.push(M("(",n));let i=n+1;s.push(M("SELECT",i));let a=i+1,o=_t({parentQuery:t,queries:t.$fields,level:a,schema:r});o&&s.push(o);let c=t[oe][Se].queryPath;if(s.push(M(`FROM ${c}`,i)),t.$filter){let p=ye(t.$filter,t.$playedBy.thing,r),u=pe(p);s.push(`WHERE ${u}`);}return s.push(M(`) AS \`${t.$as}\``,n)),s.join(`
|
|
97
|
-
`)};var mn=async e=>{let{client:t,queries:r,config:n}=e,s=`
|
|
97
|
+
`)};var De="0.11.13";var mn=async e=>{let{client:t,queries:r,config:n}=e,s=`
|
|
98
98
|
BEGIN TRANSACTION;
|
|
99
99
|
${r.join(";")};
|
|
100
100
|
COMMIT TRANSACTION;
|
|
@@ -119,10 +119,10 @@ limit ${p};`),d.join(`
|
|
|
119
119
|
LET $LOGS = SELECT * FROM LOG;
|
|
120
120
|
RETURN $LOGS;
|
|
121
121
|
COMMIT TRANSACTION;
|
|
122
|
-
`;r.mutation?.debugger&&console.log(`batchedMutation[${De}]`,n);try{return (await e.query(n)).filter(Boolean)}catch(s){let a=(await e.query_raw(n)).filter(o=>o.result!=="The query was not executed due to a failed transaction"&&o.result!=="There was an error when starting a new datastore transaction"&&o.status==="ERR");throw a.length>0?new Error(`Error running SURQL mutation: ${JSON.stringify(a)}`):s}};var Zn=e=>{let{res:t,config:r}=e;return t.flat().filter(Boolean).flatMap(s=>{if(isArray(s))return s.map(i=>{if(!isObject(i)||!("meta"in i))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(i)}`);return Gn(i,r)});if(!isObject(s)||!("meta"in s))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(s)}`);return Gn(s,r)})},Gn=(e,t)=>{let r=mapEntries(e.after||{},(i,a)=>[i,i==="id"?a.id:isArray(a)&&a.length===0?void 0:a]),n=ce(e.input||{},(i,a)=>a===null),s={...r,...e.meta,...n};return t.mutation?.noMetadata?ce(s,i=>!i.startsWith("$")):s};var bs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Ts=(e,t)=>{if(!t.data||!isArray(t.data)||t.data.some(r=>typeof r!="string"))throw new Error("Invalid event data");return {...e,surql:{...e.surql,mutations:t.data}}},ws=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},lr=j("error","error",x((e,t)=>({...e,error:t.error}))),Ms=me("buildMutation",{buildMutation:z(async e=>vn(e.bql.flat,e.schema),j("done","runMutation",x(Ts)),lr),runMutation:z(async e=>Jn(e.handles.surrealDB?.get(e.handles.surrealDB?.keys().next().value)?.client,e.surql.mutations,e.config),j("done","parseMutation",x(ws)),lr),parseMutation:z(async e=>Zn({res:e.surql.res,config:e.config,schema:e.schema}),j("done","success",x(bs)),lr),success:se(),error:se()},e=>e),Ss=async e=>new Promise((t,r)=>{fe(Ms,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),ti=async(e,t,r,n,s,i)=>Ss({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:n,config:s,handles:i,error:null});var ni=(e,t)=>{let r={things:[],edges:[],arcs:[]},n=(i,a)=>{if(!i?.$thing){console.log("block without $thing",i);return}let{$op:o,$bzId:c,$tempId:p}=i,u=t.relations[i.$thing]||t.entities[i.$thing];if(!u)throw new Error(`[Internal] No schema found for ${i.$thing}`);let d=a?.bzId?a:{bzId:"",edgeField:"root"},{usedDataFields:l,usedLinkFields:f,usedRoleFields:h}=de(u,i);if(["create","update","delete","link","unlink","match","replace"].includes(o)){let g={...ce(i,m=>![...h,...f].includes(m)),...o==="link"||o==="unlink"||o==="replace"||o==="update"&&l.length===0?{$op:"match"}:{},...o==="link"||o==="replace"?{}:{[rt]:d}};r.things.push(g);}let $={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if(h){let g=ce(i,m=>isSymbol(m)||m.startsWith("$"));h.forEach(m=>{isArray(i[m])?i[m].forEach(b=>n(b,{bzId:c,edgeField:m,tempId:p})):n(i[m],{bzId:c,edgeField:m,tempId:p});let F=(isArray(i[m])?i[m]:[i[m]]).filter(Boolean);Object.entries($).forEach(([b,y])=>{let R=F.filter(L=>y.includes(L.$op)).map(L=>L.$bzId);R.length>0&&r.edges.push({...g,[m]:R,$op:b});});});}f&&f.forEach(g=>{isArray(i[g])?i[g].forEach(b=>n(b,{bzId:c,edgeField:g,tempId:p})):n(i[g],{bzId:c,edgeField:g,tempId:p});let m=u.linkFields?.find(b=>b.path===g),F=isArray(i[g])?i[g]:[i[g]];m.target==="relation"&&Object.entries($).forEach(([b,y])=>{F.filter(L=>y.includes(L.$op)).forEach(L=>{let D=ce(L,C=>isSymbol(C)||C.startsWith("$"));r.edges.push({...D,[m.plays]:c,$op:b});});}),m.target==="role"&&Object.entries({create:["link","create"],delete:["unlink","delete"],replace:["replace"]}).forEach(([y,R])=>{F.filter(D=>R.includes(D.$op)).forEach(D=>{let C={$thing:m.relation,$thingType:"relation",$bzId:`arc_${D.$bzId}`,[m.plays]:c,[m.oppositeLinkFieldsPlayedBy[0].plays]:D.$bzId,$op:y};r.arcs.push(C);});});});};return (Array.isArray(e)?e:[e]).forEach(i=>n(i)),r};var ii=se,He=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,Ls=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Qs=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),Rs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Ds=async e=>Object.keys(e.bql.enriched).length?kt(e.bql.enriched,e.schema,e.config):kt(e.bql.raw,e.schema,e.config),Cs=async e=>An(e.bql.enriched,e.schema,e.config,e.handles),Is=async e=>Nn(e.bql.enriched,e.schema,e.config,e.handles),As=async e=>Jr(e.bql.enriched,e.schema),Os=async e=>ni(e.bql.enriched,e.schema),Ps=e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return !0;if(r==="surrealDB")return !1;throw new Error(`Unsupported provider ${r}.`)},ks=e=>_e(e.bql.enriched),ke=j("error","error",x((e,t)=>({...e,error:t.error}))),qs=me("stringify",{stringify:z(async e=>(e.config.mutation?.debugger&&console.log(`originalBQLMutation[${De}]`,e.bql.raw),On(e.bql.raw,e.schema)),j("done","enrich",x(He)),ke),enrich:z(Ds,j("done","preQuery",qt(Ps),x(He)),j("done","parseBQL",x(He)),ke),preQuery:z(Cs,j("done","preHookDependencies",qt(ks),x(He)),j("done","parseBQL",x(He)),ke),preHookDependencies:z(Is,j("done","enrich",x(He)),ke),parseBQL:z(As,j("done","flattenBQL",x(Ls)),ke),flattenBQL:z(Os,j("done","adapter",x(Qs)),ke),adapter:z(async e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return Kn(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return ti(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},j("done","success",x(Rs)),ke),success:ii(),error:ii()},e=>e),Ns=async e=>new Promise((t,r)=>{fe(qs,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),oi=async(e,t,r,n)=>Ns({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[]},res:[]},schema:t,config:r,handles:n,depthLevel:0,error:null});var xs=5e3,js=18e4,_s=2e3,Us=1e3,Ws=6e4,cr=class{db;url;username;password;namespace;database;isConnecting;reconnectInterval;constructor(t){this.db=new si,this.url=t.url,this.username=t.username,this.password=t.password,this.namespace=t.namespace,this.database=t.database,this.isConnecting=!1,this.reconnectInterval=null;}async _connect(){if(this.isConnecting||this.db.status===ConnectionStatus.Connecting||this.db.status===ConnectionStatus.Connected)return;this.isConnecting=!0,this.db=new si;let t=Math.max(Us,1);for(;;){let r=!1;try{await this.db.connect(this.url,{namespace:this.namespace,database:this.database,auth:{username:this.username,password:this.password},versionCheck:!1});break}catch{if(r=!0,await this.close(),this.isClosed)break}r&&(await Vs((1+Math.random()*.1)*t),t=Math.min(2*t,Ws),await this._connect());}this.isConnecting=!1;}async connect(){return this.isClosed&&(this.reconnectInterval=setInterval(()=>this._connect(),_s)),this._connect()}async close(){if(this.reconnectInterval!==null){clearInterval(this.reconnectInterval),this.reconnectInterval=null;try{await this.db.close();}catch(t){console.error("Trying to close an already closed connection:",t);}}}get isClosed(){return this.reconnectInterval===null}async run(t){return new Promise((r,n)=>{let s=setTimeout(()=>{this.close(),this.connect(),n(new Error("Timeout"));},js);this.connect().then(()=>{t(this.db).then(r).catch(n).finally(()=>{clearTimeout(s);});}).catch(n);})}async query(...t){return this.run(r=>r.query(...t))}async query_raw(...t){return this.run(r=>r.query_raw(...t))}},Vs=async e=>new Promise(t=>{setTimeout(t,e);}),Ft=class{queue;connections;constructor(t){let{totalConnections:r,...n}=t;this.queue=[],this.connections=new Array(r).fill(0).map(()=>{let s=new cr(n);return s.connect(),s});}async dequeue(){if(this.queue.length===0||this.connections.length===0)return;let t=this.queue[0];if(this.queue=this.queue.slice(1),t.timeout()){t.cb(new Error("Timeout"),void 0),this.dequeue();return}let r=this.connections.pop();try{t.cb(void 0,r);}catch(n){t.cb(n,void 0);}finally{this.connections.push(r),this.dequeue();}}async run(t){return new Promise((r,n)=>{let s=!1,i=setTimeout(()=>{s=!0,n(new Error("Timeout"));},xs);this.queue.push({cb:(a,o)=>{clearTimeout(i),t(a,o).then(c=>r(c)).catch(c=>n(c));},timeout:()=>s}),this.dequeue();})}async query(...t){return this.run((r,n)=>{if(n)return n.query(...t);throw r})}async query_raw(...t){return this.run((r,n)=>{if(n)return n.query_raw(...t);throw r})}};var De=process.env.npm_package_version;enableMapSet();var dr=class{schema;config;dbHandles;constructor({schema:t,config:r}){this.schema=t,this.config=r;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async n=>{if(n.provider==="surrealDB"){let s=new Ft({url:n.url,username:n.username,password:n.password,namespace:n.namespace,database:n.dbName,totalConnections:8});t.surrealDB.set(n.id,{client:s,providerConfig:n.providerConfig});}if(n.provider==="typeDB"&&n.dbName){let[s,i]=await tryit(TypeDB.coreDriver)(n.url);if(s){let a=`[BORM:${n.provider}:${n.dbName}:core] ${s.message??"Can't create TypeDB Client"}`;throw new Error(a)}try{let a=await i.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:i,session:a});}catch(a){let o=`[BORM:${n.provider}:${n.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(o)}}if(n.provider==="typeDBCluster"&&n.dbName){let s=new TypeDBCredential(n.username,n.password,n.tlsRootCAPath),[i,a]=await tryit(TypeDB.cloudDriver)(n.addresses,s);if(i){let o=`[BORM:${n.provider}:${n.dbName}:core] ${i.message??"Can't create TypeDB Cluster Client"}`;throw new Error(o)}try{let o=await a.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:a,session:o});}catch(o){let c=`[BORM:${n.provider}:${n.dbName}:session] ${(o.messageTemplate?._messageBody()||o.message)??"Can't create TypeDB Session"}`;throw new Error(c)}}}));let r=Sr(this.schema,t);this.schema=r,this.dbHandles=t;};#e=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#e(),this.schema);define=async()=>{if(await this.#e(),!this.dbHandles)throw new Error("dbHandles undefined");return await gr(this.config,this.schema,this.dbHandles)};query=async(t,r)=>{await this.#e();let n={...this.config,query:{...Tt.query,...this.config.query,...r}},s=Array.isArray(t),i=s?t:[t],[a,o]=await tryit(ze)(i,this.schema,n,this.dbHandles);if(a){let p=new Error(a.error);throw p.stack=a.error.stack,p}let c=o.bql.res;return s?c:c[0]};mutate=async(t,r)=>{await this.#e();let n={...this.config,mutation:{...Tt.mutation,...this.config.mutation,...r}},[s,i]=await tryit(oi)(t,this.schema,n,this.dbHandles);if(s){let o=new Error(s.error.message);throw o.stack=s.error.stack,o}return i.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();});}},Xu=dr;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
122
|
+
`;r.mutation?.debugger&&console.log(`batchedMutation[${De}]`,n);try{return (await e.query(n)).filter(Boolean)}catch(s){let a=(await e.query_raw(n)).filter(o=>o.result!=="The query was not executed due to a failed transaction"&&o.result!=="There was an error when starting a new datastore transaction"&&o.status==="ERR");throw a.length>0?new Error(`Error running SURQL mutation: ${JSON.stringify(a)}`):s}};var Zn=e=>{let{res:t,config:r}=e;return t.flat().filter(Boolean).flatMap(s=>{if(isArray(s))return s.map(i=>{if(!isObject(i)||!("meta"in i))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(i)}`);return Gn(i,r)});if(!isObject(s)||!("meta"in s))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(s)}`);return Gn(s,r)})},Gn=(e,t)=>{let r=mapEntries(e.after||{},(i,a)=>[i,i==="id"?a.id:isArray(a)&&a.length===0?void 0:a]),n=ce(e.input||{},(i,a)=>a===null),s={...r,...e.meta,...n};return t.mutation?.noMetadata?ce(s,i=>!i.startsWith("$")):s};var bs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Ts=(e,t)=>{if(!t.data||!isArray(t.data)||t.data.some(r=>typeof r!="string"))throw new Error("Invalid event data");return {...e,surql:{...e.surql,mutations:t.data}}},ws=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},lr=j("error","error",x((e,t)=>({...e,error:t.error}))),Ms=me("buildMutation",{buildMutation:z(async e=>vn(e.bql.flat,e.schema),j("done","runMutation",x(Ts)),lr),runMutation:z(async e=>Jn(e.handles.surrealDB?.get(e.handles.surrealDB?.keys().next().value)?.client,e.surql.mutations,e.config),j("done","parseMutation",x(ws)),lr),parseMutation:z(async e=>Zn({res:e.surql.res,config:e.config,schema:e.schema}),j("done","success",x(bs)),lr),success:se(),error:se()},e=>e),Ss=async e=>new Promise((t,r)=>{fe(Ms,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),ti=async(e,t,r,n,s,i)=>Ss({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:n,config:s,handles:i,error:null});var ni=(e,t)=>{let r={things:[],edges:[],arcs:[]},n=(i,a)=>{if(!i?.$thing){console.log("block without $thing",i);return}let{$op:o,$bzId:c,$tempId:p}=i,u=t.relations[i.$thing]||t.entities[i.$thing];if(!u)throw new Error(`[Internal] No schema found for ${i.$thing}`);let d=a?.bzId?a:{bzId:"",edgeField:"root"},{usedDataFields:l,usedLinkFields:f,usedRoleFields:h}=de(u,i);if(["create","update","delete","link","unlink","match","replace"].includes(o)){let g={...ce(i,m=>![...h,...f].includes(m)),...o==="link"||o==="unlink"||o==="replace"||o==="update"&&l.length===0?{$op:"match"}:{},...o==="link"||o==="replace"?{}:{[rt]:d}};r.things.push(g);}let $={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if(h){let g=ce(i,m=>isSymbol(m)||m.startsWith("$"));h.forEach(m=>{isArray(i[m])?i[m].forEach(b=>n(b,{bzId:c,edgeField:m,tempId:p})):n(i[m],{bzId:c,edgeField:m,tempId:p});let F=(isArray(i[m])?i[m]:[i[m]]).filter(Boolean);Object.entries($).forEach(([b,y])=>{let R=F.filter(L=>y.includes(L.$op)).map(L=>L.$bzId);R.length>0&&r.edges.push({...g,[m]:R,$op:b});});});}f&&f.forEach(g=>{isArray(i[g])?i[g].forEach(b=>n(b,{bzId:c,edgeField:g,tempId:p})):n(i[g],{bzId:c,edgeField:g,tempId:p});let m=u.linkFields?.find(b=>b.path===g),F=isArray(i[g])?i[g]:[i[g]];m.target==="relation"&&Object.entries($).forEach(([b,y])=>{F.filter(L=>y.includes(L.$op)).forEach(L=>{let D=ce(L,C=>isSymbol(C)||C.startsWith("$"));r.edges.push({...D,[m.plays]:c,$op:b});});}),m.target==="role"&&Object.entries({create:["link","create"],delete:["unlink","delete"],replace:["replace"]}).forEach(([y,R])=>{F.filter(D=>R.includes(D.$op)).forEach(D=>{let C={$thing:m.relation,$thingType:"relation",$bzId:`arc_${D.$bzId}`,[m.plays]:c,[m.oppositeLinkFieldsPlayedBy[0].plays]:D.$bzId,$op:y};r.arcs.push(C);});});});};return (Array.isArray(e)?e:[e]).forEach(i=>n(i)),r};var ii=se,He=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,Ls=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Qs=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),Rs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Ds=async e=>Object.keys(e.bql.enriched).length?kt(e.bql.enriched,e.schema,e.config):kt(e.bql.raw,e.schema,e.config),Cs=async e=>An(e.bql.enriched,e.schema,e.config,e.handles),Is=async e=>Nn(e.bql.enriched,e.schema,e.config,e.handles),As=async e=>Jr(e.bql.enriched,e.schema),Os=async e=>ni(e.bql.enriched,e.schema),Ps=e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return !0;if(r==="surrealDB")return !1;throw new Error(`Unsupported provider ${r}.`)},ks=e=>_e(e.bql.enriched),ke=j("error","error",x((e,t)=>({...e,error:t.error}))),qs=me("stringify",{stringify:z(async e=>(e.config.mutation?.debugger&&console.log(`originalBQLMutation[${De}]`,e.bql.raw),On(e.bql.raw,e.schema)),j("done","enrich",x(He)),ke),enrich:z(Ds,j("done","preQuery",qt(Ps),x(He)),j("done","parseBQL",x(He)),ke),preQuery:z(Cs,j("done","preHookDependencies",qt(ks),x(He)),j("done","parseBQL",x(He)),ke),preHookDependencies:z(Is,j("done","enrich",x(He)),ke),parseBQL:z(As,j("done","flattenBQL",x(Ls)),ke),flattenBQL:z(Os,j("done","adapter",x(Qs)),ke),adapter:z(async e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return Kn(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return ti(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},j("done","success",x(Rs)),ke),success:ii(),error:ii()},e=>e),Ns=async e=>new Promise((t,r)=>{fe(qs,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),oi=async(e,t,r,n)=>Ns({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[]},res:[]},schema:t,config:r,handles:n,depthLevel:0,error:null});var xs=5e3,js=18e4,_s=2e3,Us=1e3,Ws=6e4,cr=class{db;url;username;password;namespace;database;isConnecting;reconnectInterval;constructor(t){this.db=new si,this.url=t.url,this.username=t.username,this.password=t.password,this.namespace=t.namespace,this.database=t.database,this.isConnecting=!1,this.reconnectInterval=null;}async _connect(){if(this.isConnecting||this.db.status===ConnectionStatus.Connecting||this.db.status===ConnectionStatus.Connected)return;this.isConnecting=!0,this.db=new si;let t=Math.max(Us,1);for(;;){let r=!1;try{await this.db.connect(this.url,{namespace:this.namespace,database:this.database,auth:{username:this.username,password:this.password},versionCheck:!1});break}catch{if(r=!0,await this.close(),this.isClosed)break}r&&(await Vs((1+Math.random()*.1)*t),t=Math.min(2*t,Ws),await this._connect());}this.isConnecting=!1;}async connect(){return this.isClosed&&(this.reconnectInterval=setInterval(()=>this._connect(),_s)),this._connect()}async close(){if(this.reconnectInterval!==null){clearInterval(this.reconnectInterval),this.reconnectInterval=null;try{await this.db.close();}catch(t){console.error("Trying to close an already closed connection:",t);}}}get isClosed(){return this.reconnectInterval===null}async run(t){return new Promise((r,n)=>{let s=setTimeout(()=>{this.close(),this.connect(),n(new Error("Timeout"));},js);this.connect().then(()=>{t(this.db).then(r).catch(n).finally(()=>{clearTimeout(s);});}).catch(n);})}async query(...t){return this.run(r=>r.query(...t))}async query_raw(...t){return this.run(r=>r.query_raw(...t))}},Vs=async e=>new Promise(t=>{setTimeout(t,e);}),Ft=class{queue;connections;constructor(t){let{totalConnections:r,...n}=t;this.queue=[],this.connections=new Array(r).fill(0).map(()=>{let s=new cr(n);return s.connect(),s});}async dequeue(){if(this.queue.length===0||this.connections.length===0)return;let t=this.queue[0];if(this.queue=this.queue.slice(1),t.timeout()){t.cb(new Error("Timeout"),void 0),this.dequeue();return}let r=this.connections.pop();try{t.cb(void 0,r);}catch(n){t.cb(n,void 0);}finally{this.connections.push(r),this.dequeue();}}async run(t){return new Promise((r,n)=>{let s=!1,i=setTimeout(()=>{s=!0,n(new Error("Timeout"));},xs);this.queue.push({cb:(a,o)=>{clearTimeout(i),t(a,o).then(c=>r(c)).catch(c=>n(c));},timeout:()=>s}),this.dequeue();})}async query(...t){return this.run((r,n)=>{if(n)return n.query(...t);throw r})}async query_raw(...t){return this.run((r,n)=>{if(n)return n.query_raw(...t);throw r})}};enableMapSet();var dr=class{schema;config;dbHandles;constructor({schema:t,config:r}){this.schema=t,this.config=r;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async n=>{if(n.provider==="surrealDB"){let s=new Ft({url:n.url,username:n.username,password:n.password,namespace:n.namespace,database:n.dbName,totalConnections:8});t.surrealDB.set(n.id,{client:s,providerConfig:n.providerConfig});}if(n.provider==="typeDB"&&n.dbName){let[s,i]=await tryit(TypeDB.coreDriver)(n.url);if(s){let a=`[BORM:${n.provider}:${n.dbName}:core] ${s.message??"Can't create TypeDB Client"}`;throw new Error(a)}try{let a=await i.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:i,session:a});}catch(a){let o=`[BORM:${n.provider}:${n.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(o)}}if(n.provider==="typeDBCluster"&&n.dbName){let s=new TypeDBCredential(n.username,n.password,n.tlsRootCAPath),[i,a]=await tryit(TypeDB.cloudDriver)(n.addresses,s);if(i){let o=`[BORM:${n.provider}:${n.dbName}:core] ${i.message??"Can't create TypeDB Cluster Client"}`;throw new Error(o)}try{let o=await a.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:a,session:o});}catch(o){let c=`[BORM:${n.provider}:${n.dbName}:session] ${(o.messageTemplate?._messageBody()||o.message)??"Can't create TypeDB Session"}`;throw new Error(c)}}}));let r=Sr(this.schema,t);this.schema=r,this.dbHandles=t;};#e=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#e(),this.schema);define=async()=>{if(await this.#e(),!this.dbHandles)throw new Error("dbHandles undefined");return await gr(this.config,this.schema,this.dbHandles)};query=async(t,r)=>{await this.#e();let n={...this.config,query:{...Tt.query,...this.config.query,...r}},s=Array.isArray(t),i=s?t:[t],[a,o]=await tryit(ze)(i,this.schema,n,this.dbHandles);if(a){let p=new Error(a.error);throw p.stack=a.error.stack,p}let c=o.bql.res;return s?c:c[0]};mutate=async(t,r)=>{await this.#e();let n={...this.config,mutation:{...Tt.mutation,...this.config.mutation,...r}},[s,i]=await tryit(oi)(t,this.schema,n,this.dbHandles);if(s){let o=new Error(s.error.message);throw o.stack=s.error.stack,o}return i.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();});}},Zu=dr;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
123
123
|
//! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
|
|
124
124
|
//! Todo: Sandbox the function in computeFunction()
|
|
125
125
|
//! reads all the insertions and gets the first match. This means each id must be unique
|
|
126
126
|
//!old
|
|
127
|
-
export{
|
|
127
|
+
export{Zu as default};//# sourceMappingURL=index.mjs.map
|
|
128
128
|
//# sourceMappingURL=index.mjs.map
|