@blitznocode/blitz-orm 0.10.22 → 0.10.23
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.mjs +25 -26
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -7,25 +7,24 @@ import { v4 } from 'uuid';
|
|
|
7
7
|
import { isSet } from 'util/types';
|
|
8
8
|
import 'acorn';
|
|
9
9
|
import { nanoid } from 'nanoid';
|
|
10
|
-
import { transition, reduce, createMachine, invoke, state, guard, interpret } from 'robot3';
|
|
11
10
|
|
|
12
|
-
var it={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var
|
|
13
|
-
`,Object.keys(t.entities).forEach(g=>{let
|
|
14
|
-
`;let R=[];if(
|
|
15
|
-
`,R.push(
|
|
16
|
-
`),m.push({dbPath:E.dbPath,contentType:E.contentType});}),
|
|
17
|
-
`,E.push(`${
|
|
11
|
+
var it={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var wn=e=>{let t=[],r=new Map;return e.forEach(i=>{let{dbPath:o,contentType:n}=i,l=`${o}-${n}`;r.has(l)||(r.set(l,!0),t.push(i));}),t},Vt=async(e,t,r)=>{let o=(()=>{let y="",m=[];y+=`
|
|
12
|
+
`,Object.keys(t.entities).forEach(g=>{let S=t.entities[g],{idFields:C,dataFields:D,linkFields:I,name:j}=S,N=[],se=[],H=[];if("extends"in S){let E=t.entities[S.extends];E.dataFields&&E.dataFields.forEach(T=>{N.push(T.dbPath);}),E.linkFields&&E.linkFields.forEach(T=>{se.push(T.path);}),E.idFields&&E.idFields.forEach(T=>{H.push(T);});}y+=`${j} sub ${"extends"in S?S.extends:"entity"},
|
|
13
|
+
`;let R=[];if(C&&C.length>0){let E=new Set(C),b=Array.from(E).map(F=>`${F}`).join(", ");H.includes(b)||(y+=` owns ${b} @key,
|
|
14
|
+
`,R.push(b));}if(D&&D.length>0&&D.forEach(E=>{!N.includes(E.dbPath)&&!R.includes(E.dbPath)&&(y+=` owns ${E.dbPath},
|
|
15
|
+
`),m.push({dbPath:E.dbPath,contentType:E.contentType});}),I&&I.length>0){let E=[];I.forEach(T=>{let{relation:b,plays:F}=T;!se.includes(T.path)&&!E.includes(`${b}:${F}`)&&(y+=` plays ${b}:${F},
|
|
16
|
+
`,E.push(`${b}:${F}`));});}y=y.replace(/,\s*$/,`;
|
|
18
17
|
`),y+=`
|
|
19
|
-
`;}),Object.keys(t.relations).forEach(g=>{let
|
|
20
|
-
`;let
|
|
21
|
-
`,
|
|
22
|
-
`),m.push({dbPath:
|
|
23
|
-
`);}),N&&N.length>0){let
|
|
24
|
-
`,
|
|
18
|
+
`;}),Object.keys(t.relations).forEach(g=>{let S=t.relations[g],{idFields:C,dataFields:D,roles:I,name:j,linkFields:N}=S,se=[],H=[],R=[],E=[];if("extends"in S){let b=t.relations[S.extends];b.dataFields&&b.dataFields.forEach(F=>{se.push(F.dbPath);}),b.linkFields&&b.linkFields.forEach(F=>{H.push(F.dbPath);}),b.roles&&Object.values(b.roles).forEach(Q=>{R.push(Q.name);}),b.idFields&&b.idFields.forEach(F=>{E.push(F);});}y+=`${j} sub ${"extends"in S?S.extends:"relation"},
|
|
19
|
+
`;let T=[];if(C&&C.length>0){let b=new Set(C),Q=Array.from(b).map(L=>`${L}`).join(", ");E.includes(Q)||(y+=` owns ${Q} @key,
|
|
20
|
+
`,T.push(Q));}if(D&&D.length>0&&D.forEach(b=>{!se.includes(b.dbPath)&&!T.includes(b.dbPath)&&(y+=` owns ${b.dbPath},
|
|
21
|
+
`),m.push({dbPath:b.dbPath,contentType:b.contentType});}),I&&Object.keys(I).forEach(b=>{R.includes(b)||(y+=` relates ${b},
|
|
22
|
+
`);}),N&&N.length>0){let b=[];N.forEach(F=>{let{plays:Q}=F;!H.includes(F.path)&&!b.includes(`${S}:${Q}`)&&(y+=` plays ${F.relation}:${Q},
|
|
23
|
+
`,b.push(`${S}:${Q}`));});}y=y.replace(/,\s*$/,`;
|
|
25
24
|
`),y+=`
|
|
26
25
|
`;});let B=`define
|
|
27
26
|
|
|
28
|
-
`;return
|
|
27
|
+
`;return wn(m).forEach(g=>{if(B+=`${g.dbPath} sub attribute,
|
|
29
28
|
`,g.contentType==="TEXT"||g.contentType==="ID"||g.contentType==="JSON")B+=` value string;
|
|
30
29
|
`;else if(g.contentType==="EMAIL")B+=` value string,
|
|
31
30
|
`,B+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$';
|
|
@@ -34,27 +33,27 @@ var it={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},muta
|
|
|
34
33
|
`;else if(g.contentType==="NUMBER")B+=` value long;
|
|
35
34
|
`;else throw new Error(`Conversion of borm schema to TypeDB schema for data type "${g.contentType}" is not implemented`)}),`${B}
|
|
36
35
|
|
|
37
|
-
${y}`})(),n=e.dbConnectors[0].id,l=r.typeDB.get(n)?.session,s=r.typeDB.get(n)?.client;if(!l){console.log("Session Status: ","NO SESSION");return}await l.close();let[{dbName:u}]=e.dbConnectors;await(await s.databases.get(u)).delete(),await s.databases.create(u);let c=await s.session(e.dbConnectors[0].dbName,SessionType.SCHEMA),d=await c.transaction(TransactionType.WRITE);await d.query.define(o),await d.commit(),await d.close();let a=await c.transaction(TransactionType.READ);(await(await a.query.match("match $a sub thing;")).collect()).forEach(async y=>{y.get("a");}),await a.close();};var ne=Symbol.for("queryPath"),Pe=Symbol.for("stepPrint"),Ee=Symbol.for("edgeType"),$e=Symbol.for("edgeSchema"),Me=Symbol.for("dbNode"),ot=Symbol.for("isTransformed"),ie=Symbol.for("fieldSchema"),ue=Symbol.for("sharedMetadata"),Fe=Symbol.for("suqlMetadata");var Vt={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Ht=({linkField:e,originalRelation:t,withExtensionsSchema:r})=>{if(e.isVirtual)return `$this.${e.path}.id`;let i=r.relations[e.relation].subTypes||[],o=[e.relation,...i],n=`<-\`${t}_${e.plays}\`<-(\`${o.join("`,`")}\`)`;if(e.target==="relation")return n;if(e.target==="role"){let[l]=e.oppositeLinkFieldsPlayedBy,s=r.entities[l.thing]?.subTypes||r.relations[l.thing]?.subTypes||[],u=[l.thing,...s],f=`->\`${t}_${l.plays}\`->(\`${u.join("`,`")}\`)`;return `${n}${f}`}else throw new Error("Unsupported linkField target")};var Jt=(e,t,r)=>r?t:`${e}\xB7${t}`;var Zt=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))))[0],Ae=(e,t)=>Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))),Yt=(e,t)=>{let r=[],i=produce(e,n=>traverse(n,({key:l,value:s,meta:u})=>{if(u.depth===2&&(l&&(s.dataFields=s.dataFields?.map(f=>({...f,cardinality:f.cardinality||"ONE",dbPath:Jt(l,f.path,f.shared)}))),s.extends)){if(!s.defaultDBConnector.as)throw new Error(`[Schema] ${l} is extending a thing but missing the "as" property in its defaultDBConnector. Path:${u.nodePath}`);let f=n.entities[s.extends]||n.relations[s.extends],c=[s.extends,...f.allExtends||[]];if(s.allExtends=c,c.forEach(d=>{if(n.entities[d])n.entities[d].subTypes=[l,...n.entities[d].subTypes||[]];else if(n.relations[d])n.relations[d].subTypes=[l,...n.relations[d].subTypes||[]];else throw new Error(`[Schema] ${l} is extending a thing that does not exist in the schema: ${d}`)}),s.idFields=f.idFields?Array.from(new Set((s.idFields||[]).concat(f.idFields))):s.idFields,s.dataFields=f.dataFields?(s.dataFields||[]).concat(f.dataFields.map(d=>{let a=s.extends,p=e.entities[a]||e.relations[a];for(;!p.dataFields?.find(h=>h.path===d.path);)a="extends"in p?p.extends:void 0,p=e.entities[a]||e.relations[a];return {...d,dbPath:Jt(a,d.path,d.shared),[ue]:{inheritanceOrigin:d[ue]?.inheritanceOrigin||s.extends}}})):s.dataFields,"roles"in f){let d=s,a=f;if(a.roles){let p=mapEntries(a.roles,(h,$)=>[h,{...$,[ue]:{inheritanceOrigin:$[ue]?.inheritanceOrigin||s.extends}}]);d.roles={...d.roles||{},...p};}}s.linkFields=f.linkFields?(s.linkFields||[]).concat(f.linkFields.map(d=>({...d,[ue]:{inheritanceOrigin:d[ue]?.inheritanceOrigin||s.extends}}))):s.linkFields,f?.hooks?.pre&&(s.hooks=s.hooks||{},s.hooks.pre=s.hooks.pre||[],s.hooks.pre=[...f?.hooks?.pre||[],...s?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:n,value:l,meta:s})=>{if(n==="linkFields"){let f=(()=>{if(!s.nodePath)throw new Error("No path");let[d,a]=s.nodePath.split(".");return {thing:a,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),c=Array.isArray(l)?l.map(d=>({...d,...f})):[{...l,...f}];r.push(...c);}}),produce(i,n=>traverse(n,({value:l,key:s,meta:u})=>{if(u.depth===2&&l.idFields&&!l.id){l.name=s;let f=()=>{if(u.nodePath?.split(".")[0]==="entities")return "entity";if(u.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};l.thingType=f();let c=Object.keys(t).find(d=>t[d]?.get(l.defaultDBConnector.id));if(l.db=c,l.dbContext=Vt[c],l.computedFields=[],l.virtualFields=[],l.requiredFields=[],l.enumFields=[],l.fnValidatedFields=[],"roles"in l&&Object.entries(l.roles).forEach(([a,p])=>{p.fieldType="roleField";let h=r.filter(Q=>Q.relation===s&&Q.plays===a)||[];p.playedBy=h,p.name=a;let $=[...new Set(h.map(Q=>Q.thing))];p.$things=$;let y=p[ue]?.inheritanceOrigin||l.name;if($.length>1)throw new Error(`Not supported yet: Role ${a} in ${l.name} is played by multiple things: ${$.join(", ")}`);let m=$.flatMap(Q=>{let L=v(e,Q)?.subTypes||[];return [Q,...L]}),B=`->\`${y}_${a}\`->(\`${m.join("`,`")}\`)`;p[Fe]={queryPath:B};}),"linkFields"in l&&l.linkFields){let d=l;d.linkFields?.forEach(a=>{a.fieldType="linkField";let p=i.relations[a.relation];if(!a.isVirtual){if(!p)throw new Error(`The relation ${a.relation} does not exist in the schema`);if(p.roles?.[a.plays]===void 0)throw new Error(`The role ${a.plays} is not defined in the relation ${a.relation} (linkField: ${a.path})`)}if(a.target==="relation"){if(a.isVirtual)throw new Error(`[Schema] Virtual linkFields can't target a relation. Thing: "${d.name}" LinkField: "${a.path}. Path:${u.nodePath}."`);a.$things=[a.relation],a.oppositeLinkFieldsPlayedBy=[{plays:a.path,thing:a.relation,thingType:"relation"}];}if(a.target==="role"){let y=r.filter(m=>m.relation===a.relation&&m.plays!==a.plays)||[];if(a.oppositeLinkFieldsPlayedBy=y,a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter(m=>m.target==="role"),a.oppositeLinkFieldsPlayedBy.length===0)throw new Error(`[Schema] LinkFields require to have at least one opposite linkField playing an opposite role. Thing: "${d.name}" LinkField: "${a.path}. Path:${u.nodePath}."`);if(a.$things=a.oppositeLinkFieldsPlayedBy.map(m=>m.thing),a.oppositeLinkFieldsPlayedBy.length>1)throw new Error(`Not supported: LinkField ${a.path} in ${d.name} has multiple candidates ${a.oppositeLinkFieldsPlayedBy.map(m=>m.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`)}let h=p?.roles?.[a.plays][ue]?.inheritanceOrigin??a.relation,$=Ht({linkField:a,originalRelation:h,withExtensionsSchema:i});a[Fe]={queryPath:$};});}}if(typeof l=="object"&&"playedBy"in l){let f=[...new Set(l.playedBy.map(c=>c.thing))];if(f.length>1)throw new Error(`[Schema] roleFields can be only played by one thing. Role: ${s}, path:${u.nodePath}, played by: ${f.join(", ")}`);if(l.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${s}, path:${u.nodePath}`)}if(u.depth===4){let[f,c]=u.nodePath?.split(".")||[],d=n[f][c];!isArray(l)&&typeof l=="object"&&(l.validations&&(l.validations.required&&d.requiredFields.push(l.path),l.validations.enum&&d.enumFields.push(l.path),l.validations.fn&&d.fnValidatedFields.push(l.path)),l.default?l.isVirtual?d.virtualFields.push(l.path):d.computedFields.push(l.path):l.isVirtual&&d.virtualFields.push(l.path));}}))},v=(e,t)=>{if(t in e.entities)return e.entities[t];if(t in e.relations)return e.relations[t];throw new Error(`${t} is not defined in the schema`)},j=(e,t)=>{if(!t)throw new Error("[Internal] No node for getCurrentSchema");if(t.$thing){if(t.$thingType==="entity"){if(!(t.$thing in e.entities))throw new Error(`Missing entity '${t.$thing}' in the schema`);return e.entities[t.$thing]}if(t.$thingType==="relation"){if(!(t.$thing in e.relations))throw new Error(`Missing relation '${t.$thing}' in the schema`);return e.relations[t.$thing]}if(t.$thing in e.entities&&t.$thing in e.relations)throw new Error(`Ambiguous $thing ${t.$thing}`);if(t.$thing in e.entities)return e.entities[t.$thing];if(t.$thing in e.relations)return e.relations[t.$thing];throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)}if(t.$entity){if(!(t.$entity in e.entities))throw new Error(`Missing entity '${t.$entity}' in the schema`);return e.entities[t.$entity]}if(t.$relation){if(!(t.$relation in e.relations))throw new Error(`Missing relation '${t.$relation}' in the schema`);return e.relations[t.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)},xe=(e,t)=>{let r=e.dataFields?.find(n=>n.path===t);if(r)return ["dataField",r];let i=e.linkFields?.find(n=>n.path===t);if(i)return ["linkField",i];let o="roles"in e?e.roles[t]:void 0;if(o)return ["roleField",o];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},Ne=(e,t)=>{let r=j(e,t);if(r?.idFields?.length&&r?.idFields?.length>1)throw new Error(`Multiple ids not yet enabled / composite ids: ${r?.idFields}`);let[i]=r.idFields;return i},Xt=(e,t)=>{let r=e.$thing||e.$entity||e.$relation;if(!r)throw new Error("[Internal] No thing found");if(e.$entity)return "entity";if(e.$relation)return "relation";if(t.entities[r])return "entity";if(t.relations[r])return "relation";throw new Error("No thing found")},lt=(e,t,r)=>{let i=j(e,t),o=i.linkFields?.find(s=>s.path===r);if(o)return o;let n=i.dataFields?.find(s=>s.path===r);if(n)return n;let l="roles"in i?i.roles?.[r]:void 0;if(l)return l;throw new Error(`Field ${r} not found in schema`)},ct=(e,t,r)=>lt(e,t,r)?.cardinality,ce=(e,t)=>{let r=e.dataFields?.map(h=>h.path)||[],i=e.linkFields?.map(h=>h.path)||[],o="roles"in e?listify(e.roles,h=>h):[],n=[...r||[],...i||[],...o||[]],s=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...n];if(!t)return {fields:n,dataFields:r,roleFields:o,linkFields:i};let u=t.$fields?t.$fields.map(h=>{if(typeof h=="string"){if(h.startsWith("$")||h.startsWith("%"))return;if(!n.includes(h))throw new Error(`Field ${h} not found in the schema`);return h}if("$path"in h&&typeof h.$path=="string")return h.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,h=>{if(!(h.startsWith("$")||h.startsWith("%"))){if(!n.includes(h))throw new Error(`[Schema] Field ${h} not found in the schema`);return h}}).filter(h=>h!==void 0),f=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&r?.includes(h)):[],c=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&[...o||[],...i||[]].includes(h)):[],d=[...u,...f].filter(h=>!h?.startsWith("%")).filter(h=>!s.includes(h)).filter(h=>h),a=t.$filter?Ae(t.$filter,(h,$)=>f.includes(h)):{},p=t.$filter?Ae(t.$filter,(h,$)=>c.includes(h)):{};return {fields:n,dataFields:r,roleFields:o,linkFields:i,usedFields:u,usedLinkFields:i.filter(h=>u.includes(h)),usedRoleFields:o.filter(h=>u.includes(h)),usedDataFields:r.filter(h=>u.includes(h)),unidentifiedFields:d,...f.length?{localFilters:a}:{},...c.length?{nestedFilters:p}:{}}};var Gt=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},er=(e,t,r)=>{let o=(r.nodePath||"").split("."),n=isArray(t)?o.slice(0,-2).join("."):o.slice(0,-1).join(".");return t?getNodeByPath(e,n):{}},me=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var We=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),de=e=>{if(Array.isArray(e))return e.map(t=>current(t));if(e&&typeof e=="object"){let t=isDraft(e)?current(e):e,r={};return Object.entries(t).forEach(([i,o])=>{r[i]=isDraft(o)?current(o):o;}),r}else return e},te=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},b=(e,t)=>{let r="";for(let i=0;i<t;i++)r+=" ";return `${r}${e}`};var Te=(e,t)=>{if(t.fieldType==="linkField"){let r=t.oppositeLinkFieldsPlayedBy;if(r?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(r=>r.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!t.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return t.playedBy}else throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var tr=(e,t,r)=>{let i=isArray(e[t])?e[t]:[e[t]];if(!i.every(o=>typeof o=="object"))if(i.every(o=>typeof o=="string")){let o=Te(t,r),[n]=o,l=e.$op==="create"?"link":"replace",s=n.thing,u=n.thingType;if(i.some(f=>f.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:l,$thing:s,$thingType:u,$bzId:`S_${v4()}`};}else throw new Error(`[Mutation Error] Replace can only be used with a single id or an array of ids. (Field: ${t} Nodes: ${JSON.stringify(i)} Parent: ${JSON.stringify(e,null,2)})`)};var we=(e,t,r)=>{let i=j(r,t),{usedDataFields:o}=ce(i,t);if(t.$op){if(t.$op==="create"&&t.$id)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(["unlink","delete","update"].includes(t.$op)&&e.$op==="create")throw new Error(`[Wrong format] Cannot ${t.$op} under a create`);if(t.$op==="delete"&&o.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&o.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var ze=(e,t,r)=>{let i=j(r,t),{usedFields:o}=ce(i,t);return t.$op?(we(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(we(e,{...t,$op:"update"},r),"update"):(we(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(we(e,{...t,$op:"create"},r),"create"):(we(e,{...t,$op:"create"},r),"link"):(we(e,{...t,$op:"create"},r),"create")};var nr=(e,t)=>{let i=(isArray(e.$root)?e.$root:[e.$root]).map(o=>{let n=ze(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:Xt(o,t)},...o.$op?{}:{$op:n},...o.$bzId?{}:{$bzId:`R_${v4()}`}},...o}});e.$root=isArray(e.$root)?i:i[0];};var _e=(e,t)=>{let r=t[Pe];return isSet(r)?r.has("clean")?(Reflect.set(t,Pe,r.add("clean")),!0):!1:(Reflect.set(t,Pe,new Set(["clean"])),!0)};var ir=(e,t,r)=>{if(_e("split_ids",e)){let i=(isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(isObject(o)&&"$id"in o&&isArray(o.$id)){let n=o;if(j(r,n),!n.$bzId)throw new Error("[Internal Error] No bzId found");return n.$id.map((l,s)=>({...de(n),$id:l,$bzId:`${n.$bzId}_${s}`,...me(n)}))}return o});(i.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=i);}};var sr=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{let l=Te(t,r),[s]=l,u=ze(e,{...n,$thing:s.thing,$thingType:s.thingType},i),f=n.$bzId?n.$bzId:n.$tempId?n.$tempId:`N_${v4()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...n,[$e]:r,$thing:s.thing,$thingType:s.thingType,$op:u,$bzId:f}});e[t]=isArray(e[t])?o:o[0];};var Mn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Tn=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,ar=e=>{let r=e.toString().replace(Mn,"").trim().split("=>")[0].split("{")[0].replace(Tn,"").trim(),i=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return i?(i.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(n=>n.includes("{")&&n.includes("}")?(n.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(s=>s.split(":")[0].trim().replace(/['"[\]]/g,"")):n.trim()).filter(Boolean):[]};var Le=({currentThing:e,fieldSchema:t,mandatoryDependencies:r=!1})=>{if(!t||!t.default||!("fn"in t.default||"value"in t.default))throw new Error(`[Internal] Virtual field: No field schema found, or wrongly configured. Field: ${JSON.stringify(t,null,3)}`);if(t.default.type==="value")return t.default.value;if(r){let{fn:o}=t.default,l=ar(o).filter(s=>!(s in e));if(l.length)throw new Error(`Virtual field: Missing arguments ${l.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");return "default"in t?t.default?.fn(e):void 0};var lr=(e,t,r)=>{let i=e[t];i&&(isArray(i)?i:[i]).forEach(o=>{let n=j(r,o),{unidentifiedFields:l}=ce(n,o),{computedFields:s,virtualFields:u}=n,f=listify(o,(a,p)=>p!==void 0?a:void 0),c=f.filter(a=>u?.includes(a));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(s.filter(a=>!f.includes(a)).forEach(a=>{let p=n.dataFields?.find(B=>B.path===a),$=n.linkFields?.find(B=>B.path===a)?.oppositeLinkFieldsPlayedBy[0],y="roles"in n?Zt(n.roles,(B,Q)=>B===a):void 0,m=p||$||y;if(!m)throw new Error(`no field Def for ${a}`);if(o.$op==="create"&&!o[a]){let B=Le({currentThing:o,fieldSchema:m,mandatoryDependencies:!0});o[a]=B;}}),l.length>0)throw new Error(`Unknown fields: [${l.join(",")}] in ${JSON.stringify(o)}`)});};var Ve=(e,t)=>{let r=j(t,e).hooks;if(r?.pre){let i=`on${Gt(e.$op)}`;return r.pre.filter(l=>!l.triggers||l.triggers[i]?.()).flatMap(l=>l.actions)}return []};var dr=(e,t,r,i)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(n=>{if("$thing"in n){if(n.$fields)return n;let{requiredFields:l,enumFields:s,fnValidatedFields:u,dataFields:f}=j(r,n);if("$op"in n&&n.$op==="create"&&l.forEach(c=>{if(!(c in n))throw new Error(`[Validations] Required field "${c}" is missing.`)}),("$op"in n&&n.$op==="update"||n.$op==="create")&&s.forEach(c=>{if(c in n){let d=f?.find(a=>a.path===c)?.validations?.enum;if(!d)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(isArray(n[c]))n[c].some(a=>{if(!d.includes(a))throw new Error(`[Validations] Option "${a}" is not a valid option for field "${c}".`)});else if(d&&!d.includes(n[c]))throw new Error(`[Validations] Option "${n[c]}" is not a valid option for field "${c}".`)}}),("$op"in n&&n.$op==="update"||n.$op==="create")&&u.forEach(c=>{if(c in n)try{let d=f?.find(a=>a.path===c)?.validations?.fn;if(!d)throw new Error("Missing validation function.");if(!d(n[c]))throw new Error("Failed validation function.")}catch(d){throw new Error(`[Validations:attribute:${c}] ${d.message}`)}}),isObject(n)&&"$thing"in n){let c=n.$thing,d=n,a=clone(de(e)),p=clone(de(d)),h=i.mutation?.context||{},$=clone(de(n[Me]||{}));Ve(d,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let B=m.fn(p,a,h,$);if(B===!1)throw new Error(`${m.message}.`);if(B!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(B){throw new Error(`[Validations:thing:${c}] ${B.message}`)}}});}}});};var ur=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{if(We(n)){if(n.$fields||n[ot])return n;let l=Ve(n,r).filter(d=>d.type==="transform"),s=clone(de(e)),u=clone(de(n)),f=i.mutation?.context||{},c=clone(de(n[Me]||n.$dbNode));return l.forEach(d=>{let a=d.fn(u,s,f,c||{});Object.keys(a).length!==0&&(n={...u,...a,...me(n),[ot]:!0});}),n}});e[t]=isArray(e[t])?o:o[0];};var pr=(e,t,r)=>{let i=Te(t,r),[o]=i;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[$e]:r};};var Se=e=>{if(Array.isArray(e)){for(let t of e)if(Se(t))return !0;return !1}if(e.$fields)return !0;for(let t in e){if(t.startsWith("$"))continue;let r=e[t];if(r&&typeof r=="object"&&Se(e[t]))return !0}return !1};var On=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(_e("set_tempId",e))if(e.$tempId?.startsWith("_:")){let r=e.$tempId.substring(2);e.$tempId=r,e.$bzId=r;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},Pn=(e,t)=>{},ft=(e,t,r)=>{let i={$rootWrap:{$root:e}},o=Se(Array.isArray(e)?e:[e]),n=produce(i,l=>traverse(l,({value:s,parent:u,key:f,meta:c})=>{if(!(!u||!f)&&isObject(s)){let d=c.nodePath?.split(".")||[];if(!("$root"in s)){if(!("$thing"in s||"$entity"in s||"$relation"in s)){let h=["$fields","$dbNode","$filter"],$=d[d.length-1],y=d[d.length-2];if(f==="$root")throw new Error("Root things must specify $entity or $relation");if(!h.includes($)&&!h.includes(y))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(s)?current(s):s)}`)}}let a=s,p=d.includes("$filter");Object.keys(a).forEach(h=>{if(On(a,h),h!=="$root"&&p||h!=="$root"&&(h.startsWith("$")||h.startsWith("%")))return;let $=h!=="$root"?lt(t,a,h):{fieldType:"rootField"};if(!$)throw new Error(`[Internal] Field ${h} not found in schema`);if("contentType"in $)return Pn();if(["rootField","linkField","roleField"].includes($.fieldType)){if(["linkField","roleField"].includes($.fieldType)&&(a[h]===null?pr(a,h,$):tr(a,h,$)),$.fieldType==="rootField"){if(!("$root"in a))throw new Error(`[Internal] Field ${h} is a rootField but the object is not a root`);nr(a,t);}let y=isArray(a[h])?a[h]:[a[h]],m=d.slice(1).join(".");y.forEach(Q=>{if(Q){if($?.cardinality==="ONE"&&!Q.$op&&!Q.$id&&!Q.$filter&&!Q.$tempId&&a.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${m}.${h}`);if(Q.$tempId&&!(Q.$op===void 0||Q.$op==="link"||Q.$op==="create"||Q.$op==="update"))throw new Error(`Invalid op ${Q.$op} for tempId. TempIds can be created, or when created in another part of the same mutation. In the future maybe we can use them to catch stuff in the DB as well and group them under the same tempId.`)}}),["linkField","roleField"].includes($.fieldType)&&sr(a,h,$,t),ir(a,h,t),["rootField","linkField","roleField"].includes($.fieldType)&&lr(a,h,t),(isArray(a[h])?a[h]:[a[h]]).forEach(Q=>{let g=j(t,Q),{unidentifiedFields:L,usedLinkFields:D,usedFields:A,fields:C}=ce(g,Q);if(A.forEach(x=>{if(!C.includes(x))throw new Error(`[Schema] Field ${x} not found in the schema`)}),L.length>0)throw new Error(`Unknown fields: [${L.join(",")}] in ${JSON.stringify(s)}`);if(D.length>1){let x=g.linkFields?.filter(N=>D.includes(N.path));x?.some((N,re)=>x.some((V,R)=>{if(re!==R&&N.target!==V.target&&N.relation===V.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),o||(ur(a,h,t,r),dr(a,h,t,r));}});}}));return isArray(n.$rootWrap.$root),n.$rootWrap.$root};var He=async(e,t)=>{let r=t.dbConnectors[0].id,i=e.typeDB?.get(r)?.session,o=e.typeDB?.get(r)?.client;if(!i||!i.isOpen()){if(!o)throw new Error("Client not found");i=await o.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:o,session:i});}return {client:o,session:i}};var fr=async(e,t,r)=>{if(!e)throw new Error("TQL request not built");if(!(e.deletions&&e.deletionMatches||e.insertions))throw new Error("TQL request error, no things");let{session:i}=await He(t,r),o=await i.transaction(TransactionType.WRITE),n=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,l=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{n&&await o.query.delete(n);let s=l&&o.query.insert(l),u=s?await s.collect():void 0;return await o.commit(),{insertions:u}}catch(s){throw new Error(`Transaction failed: ${s.message}`)}finally{await o.close();}};var $r=async(e,t,r,i,o)=>{let n=[...t,...r],l=n.map(s=>{let u=e.insertions?.find(d=>d.get(`${s.$bzId}`))?.get(`${s.$bzId}`),f=s.$thing||s.$relation||s.$entity,c=f?v(i,f):void 0;if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!u&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let d=u?.asThing().iid,a=Object.entries(s).filter(([h,$])=>!h.startsWith("$")).reduce((h,[$,y])=>{if(c?.dataFields?.find(B=>B.path===$)?.contentType==="JSON")return h[$]=JSON.parse(y),h;if(s.$thingType==="relation"){let B=n.filter(Q=>Q.$id&&Q.$bzId===y);return B.length===1?(h[$]=B[0].$id,h):(h[$]=y,h)}return h[$]=y,h},{});if(o.mutation?.noMetadata)return a;let p=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:d,...s,...a,[s.path]:s.$id,...p}}if(s.$op==="delete"||s.$op==="unlink")return s;if(s.$op!=="match")throw new Error(`Unsupported op ${s.$op}`)}).filter(s=>s);return clone(l)};var mr=e=>{let t=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(n=>n.startsWith("$")).forEach(n=>delete r[n]),Object.keys(r).filter(n=>typeof n=="symbol").forEach(n=>delete r[n])),r);return produce(e,r=>traverse(r,t))};var Er=async(e,t)=>{let r=c=>{let d=[],a=[],p=m=>{if(m.$id)return m.$id;let B=j(t,m),{idFields:Q}=B;if(!Q)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[g]=Q;if(!g)throw new Error(`no idField: ${JSON.stringify(m)}`);let L=B.dataFields?.find(C=>C.path===g),D=Le({currentThing:m,fieldSchema:L,mandatoryDependencies:!0}),A=m[g]||m.$id||D;if(!A)throw new Error(`no idValue: ${JSON.stringify(m)}`);return A},h=m=>{if(m.$op==="create"){let B=p(m);if(d.find(Q=>Q.$id===B&&Q.$op==="create"))throw new Error(`Duplicate id ${B} for node ${JSON.stringify(m)}`);if(a.find(Q=>Q.$bzId===m.$bzId))throw new Error(`Duplicate $bzId ${m.$bzId} for node ${JSON.stringify(m)}`);d.push({...m,$id:B});return}m.$tempId&&m.$op==="match"||d.push(m);},$=m=>{if(m.$op==="create"){let B=p(m);if(d.find(Q=>Q.$id===B),a.find(Q=>Q.$bzId===m.$bzId))throw new Error(`Duplicate %bzId ${m.$bzIdd} for edge ${JSON.stringify(m)}`);a.push({...m,$id:B});return}a.push(m);};return traverse(c,({value:m,parent:B,meta:Q})=>{if(!isObject(m))return;let g=m;if(g.$thing){if(!g.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(g)}`);if(!g.$bzId)throw new Error("[internal error] BzId not found");let L=j(t,g),{dataFields:D,roleFields:A,linkFields:C,usedFields:x}=ce(L,g),N=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let R=x.filter(w=>D?.includes(w)),E=x.filter(w=>A?.includes(w)),M=x.filter(w=>C?.includes(w));if(R.length>0)return "update";if(E.length>0||M.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},re={...g.$id&&{$id:g.$id},...g.$tempId&&{$tempId:g.$tempId},...g.$filter&&{$filter:g.$filter},$thing:g.$thing,...g.$thingType&&{$thingType:g.$thingType},...shake(pick(g,D||[""])),$op:N(),$bzId:g.$bzId};h(re);let V=g[$e];if(V?.fieldType==="linkField"){if((g.$op==="link"||g.$op==="unlink")&&(g.$id||g.$filter)){if(g.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");d.push({...g,$op:"match"});}let R=V.relation===g.$thing,E=R?g.$bzId:`LT_${v4()}`,w=er(c,B,Q).$bzId;if(!w)throw new Error("No parent id found");let F=()=>{if(g.$op==="delete")return R?"match":"delete";if(g.$op==="unlink")return R?"unlink":"delete";if(g.$op==="link"||g.$op==="create")return R?"link":"create";if(g.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},T=j(t,{$thing:V.relation,$thingType:"relation"});if(!Object.keys(T.roles).includes(V.plays))throw new Error(`[Wrong format] Field ${V.plays} is not a role of relation ${V.relation}`);let q={$bzId:E,$thing:V.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:F(),...R?{}:{[V.path]:g.$bzId},[V.plays]:w,[$e]:V,[Ee]:"linkField"};$(q),(g.$op==="unlink"||F()==="unlink")&&R&&$({$thing:V.relation,$thingType:"relation",$bzId:E,$op:"match",[V.plays]:w,[$e]:V,[Ee]:"linkField"});}if(g.$thingType==="relation"){let R=Ae(g,(w,F)=>A.includes(w)),E=mapEntries(R,(w,F)=>isArray(F)?[w,F]:isObject(F)?[w,F.$bzId]:[w,F]),M=Ae(m,(w,F)=>w.startsWith("$")||w.startsWith("Symbol"));if(Object.keys(R).filter(w=>!w.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let w=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},F=j(t,g).roles,T=mapEntries(E,(q,k)=>{let P=F[q]?.cardinality;if(!P)throw new Error(`Role ${q} not found in schema`);if(Array.isArray(k)){if(P==="ONE"){if(k.length>1)throw new Error(`[Error] Role ${q} is not a MANY relation`);return [q,k[0].$bzId||k[0]]}return [q,k.map(K=>K.$bzId||K)]}return [q,k.$bzId||k]}),S={...M,$thing:g.$thing,$thingType:"relation",$op:w(),...T,$bzId:g.$bzId,[Ee]:"roleField"};$(S);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(R).length>0){let w=0;Object.entries(R).forEach(([F,T])=>{let S=isArray(T)?T:[T],q=k=>k==="create"||k==="replace"?"link":k;S.forEach(k=>{if(!k)return;let P=q(k.$op);if(P==="replace")throw new Error("Not supported yet: replace on roleFields");if(P==="unlink"&&w>0)throw w+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let K={...M,$thing:g.$thing,$thingType:"relation",$op:P==="delete"?"unlink":P,[F]:k.$bzId,$bzId:g.$bzId,[Ee]:"roleField"};$(K);});});}}}}}),[d,a]},[i,o]=r(e),n=i.reduce((c,d)=>{if(!d.$bzId)return [...c,d];let a=c.findIndex(p=>p.$bzId===d.$bzId);if(a===-1)return [...c,d];if(c[a].$op==="create"&&d.$op==="match")return c;if(c[a].$op==="match"&&(d.$op==="create"||d.$op==="match"))return [...c.slice(0,a),d,...c.slice(a+1)];if(c[a].$op==="update"&&d.$op==="update")return [...c.slice(0,a),{...c[a],...d},...c.slice(a+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${d.$tempId||d.$id}". Existing: ${c[a].$op}. Current: ${d.$op}`)},[]),l=o.reduce((c,d)=>{let a=c.find(p=>(p.$id&&p.$id===d.$id||p.$bzId&&p.$bzId===d.$bzId)&&p.$thing===d.$thing&&p.$op===d.$op);if(a){let p={...a};return Object.keys(d).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let y=a[$],m=d[$];Array.isArray(y)&&Array.isArray(m)?p[$]=Array.from(new Set([...y,...m])):!Array.isArray(y)&&Array.isArray(m)?y!==void 0?p[$]=Array.from(new Set([y,...m])):p[$]=m:Array.isArray(y)&&!Array.isArray(m)?m!==void 0&&(p[$]=Array.from(new Set([...y,m]))):y!==null&&m!==null&&y!==void 0&&m!==void 0?p[$]=Array.from(new Set([y,m])):y==null&&(p[$]=m);}),[...c.filter($=>!(($.$id&&$.$id===d.$id||$.$bzId&&$.$bzId===d.$bzId)&&$.$thing===d.$thing&&$.$op===d.$op)),p]}return [...c,d]},[]);n.forEach(c=>{if((c.$thingType==="relation"||"relation"in c)&&l.filter(d=>d.$bzId===c.$bzId||d.$tempId&&d.$tempId===c.$tempId).length===0){if(c.$op==="delete"||c.$op==="match"||c.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(mr(c))}`)}});let s=[...n,...l],u=new Set(s.filter(c=>c.$tempId).map(c=>c.$tempId)),f=Array.from(u).filter(c=>!s.some(d=>d.$tempId===c&&d.$op==="create"));if(f.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${f.join(", ")}`);return {mergedThings:n,mergedEdges:l}};var $t=e=>{if(isDate(e))return {type:"datetime",value:e.toISOString().replace("Z","")};if(typeof e=="string")return {type:"string",value:`"${e}"`};if(typeof e=="number")return e%1!==0?{type:"double",value:e}:{type:"long",value:e};if(typeof e=="boolean")return {type:"boolean",value:e};throw new Error(`Unsupported type ${typeof e}`)};var wr=async(e,t,r)=>{let i=a=>{let p=a.$op,h=`$${a.$bzId}`,$=j(r,a),{idFields:y,defaultDBConnector:m}=$,B=m?.path||a.$thing,Q=a.$id,g=y?.[0],L=listify(a,(R,E)=>{if(R.startsWith("$")||R.startsWith("%")||R===g||E===void 0||E===null)return "";let M=$.dataFields?.find(T=>T.path===R);if(!M?.path)return "";let F=M.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(M.contentType))return `has ${F} '${E}'`;if(["NUMBER","BOOLEAN"].includes(M.contentType))return `has ${F} ${E}`;if(M.contentType==="DATE"){if(Number.isNaN(E.valueOf()))throw new Error("Invalid format, Nan Date");return E instanceof Date?`has ${F} ${E.toISOString().replace("Z","")}`:`has ${F} ${new Date(E).toISOString().replace("Z","")}`}if(M.contentType==="FLEX"){let T=`bza${nanoid()}`,S=isArray(E)?E.map(q=>$t(q)):$t(E);if(Array.isArray(S))throw new Error("Array in FLEX fields not supported yet");return `has ${F} $${T}; $${T} '${T}' isa ${F}, has ${S.type}Attribute ${S.value}`}throw new Error(`Unsupported contentType ${M.contentType}`)}).filter(R=>R),D=`${h}-atts`,A=listify(a,R=>{if(R.startsWith("$")||R.startsWith("%")||R===g)return "";let E=$.dataFields?.find(F=>F.path===R);if(!E?.path)return "";let w=E.dbPath;return `{${D} isa ${w};}`}).filter(R=>R),C=isArray(Q)?`like '${Q.join("|")}'`:`'${Q}'`,x=Q?[`has ${g} ${C}`]:[],N=[...x,...L].filter(R=>R).join(","),re=()=>{if(p==="delete"||p==="unlink"||p==="match")return `${h} isa ${[B,...x].filter(R=>R).join(",")};`;if(p==="update"){if(!A.length)throw new Error("update without attributes");return `${h} isa ${[B,...x].filter(R=>R).join(",")}, has ${D};
|
|
38
|
-
${A.join(" or ")};`}return ""},V=()=>p==="update"||p==="link"||p==="match"?`${h} isa ${[B,...x].filter(R=>R).join(",")};`:"";if(We(a))return {op:p,deletionMatch:re(),insertionMatch:V(),insertion:p==="create"?`${h} isa ${[B,N].filter(R=>R).join(",")};`:p==="update"&&L.length?`${h} ${L.join(",")};`:"",deletion:p==="delete"?`${h} isa ${B};`:p==="update"&&A.length?`${h} has ${D};`:""};throw new Error("in attributes")},o=a=>{let p=a.$op,h=j(r,a),$=`$${a.$bzId}`,y=a.$id,m=h.defaultDBConnector?.path||a.$thing,B="roles"in h?listify(h.roles,E=>E):[],Q="roles"in h?mapEntries(h.roles,(E,M)=>[E,M.dbConnector?.path||E]):{},g=listify(a,(E,M)=>{if(!B.includes(E))return null;if(!("roles"in h))throw new Error("This should have roles! ");let w=Q[E];return Array.isArray(M)?M.map(F=>({path:w,id:F})):{path:w,id:M}}).filter(E=>E).flat(),L=g.map(E=>{if(!E?.path)throw new Error("Object without path");return `${E.path}: $${E.id}`}),D=g.length>0?`( ${L.join(" , ")} )`:"",A=a[Ee];if(!A)throw new Error("[internal error] Symbol edgeType not defined");let C=D?`${$} ${D} ${A==="linkField"||p==="delete"||p==="unlink"?`isa ${m}`:""}`:"",x=`${$} ${A==="linkField"||p==="delete"?`isa ${m}`:""}`,N=()=>C?p==="link"?`${C};`:p==="create"?`${C}, has id '${y}';`:"":"",re=()=>C&&p==="match"?`${C};`:"",V=()=>C?p==="delete"?`${C};`:p==="match"?`${C};`:"":"",R=()=>C?p==="delete"?`${x};`:p==="unlink"?`${$} ${D};`:"":"";return {deletionMatch:V(),insertionMatch:re(),deletion:R(),insertion:N(),op:""}},n=(a,p)=>{let h=p==="edges"?o:i;if(Array.isArray(a))return a.map(g=>{let{preDeletionBatch:L,insertionMatch:D,deletionMatch:A,insertion:C,deletion:x}=h(g);return shake({preDeletionBatch:L,insertionMatch:D,deletionMatch:A,insertion:C,deletion:x},N=>!N)}).filter(g=>g);let{preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:Q}=h(a);return shake({preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:Q},g=>!g)},l=n(e),s=Array.isArray(l)?l:[l],u=n(t,"edges"),f=Array.isArray(u)?u:[u],c=[...s,...f];return shake({insertionMatches:c.map(a=>a.insertionMatch).join(" ").trim(),deletionMatches:c.map(a=>a.deletionMatch).join(" ").trim(),insertions:c.map(a=>a.insertion).join(" ").trim(),deletions:c.map(a=>a.deletion).join(" ").trim()},a=>!a)};var Tr=(e,t)=>{if(!t)return;let r=Yn(t);return Xn(r,e.query)},Yn=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),Xn=(e,t)=>produce(e,r=>traverse(r,({value:i})=>{if(isObject(i)){let o=i;Object.keys(o).forEach(n=>{(o[n]===void 0||o[n]===null||isArray(o[n])&&o[n].length===0)&&(t?.returnNulls?o[n]=null:delete o[n]),o[n]===void 0&&delete o[n];}),Object.getOwnPropertySymbols(o).forEach(n=>{delete o[n];}),t?.noMetadata===!0&&Object.keys(o).forEach(n=>{n.startsWith("$")&&delete o[n];});}}));var Sr=(e,t)=>{for(let o of e)if(!("$entity"in o)&&!("$relation"in o)&&(!("$thing"in o)||!("$thingType"in o)))throw new Error("No entity specified in query");let r=Array.isArray(e)?e:[e];return produce(r,o=>traverse(o,n=>{let{value:l,meta:s}=n,u=l;if(isObject(u)){if(u.$id){if(s.nodePath?.includes(".$filter"))return;let f=u.$entity||u.$relation?u:{[`$${u.$thingType}`]:u.$thing},c=j(t,f);if(!c?.name)throw new Error(`Schema not found for ${u.$thing}`);if(u.$path=c.name,Array.isArray(u.$id)||(u.$filterByUnique=!0),c?.idFields?.length!==1)throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in u||"$relation"in u||"$thing"in u){let f=j(t,u);if(!f?.name)throw new Error(`Schema not found for ${u.$thing}`);u.$path=f.name;}if(u.$entity?(u.$thing=u.$entity,u.$thingType="entity",delete u.$entity):u.$relation&&(u.$thing=u.$relation,u.$thingType="relation",delete u.$relation),isObject(u)&&"$thing"in u&&u.$thing){let f=u.$entity||u.$relation?u:{[`$${u.$thingType}`]:u.$thing};u[ne]=s.nodePath;let c=j(t,f);if(u.$filter&&(u.$filterByUnique=Et(u.$filter,c),u.$filter=ke(u.$filter,u.$thing,t)),u.$fields){u.$fields.some(p=>c?.idFields?.includes(p?.$path||p))||(u.$fields=[...u.$fields,...Array.isArray(c.idFields)?c.idFields:[]],u.$idNotIncluded=!0);let a=u.$fields?.flatMap(p=>{let h=Lr(p,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);u.$fields=a;}else {let a=Bt(c)?.flatMap(p=>{let h=Lr(p,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);u.$fields=a;}u.$excludedFields&&(u.$fields=u.$fields.filter(d=>Ue(c,d)?!0:!u.$excludedFields.includes(d.$path)));}}}))},Bt=e=>{let t=e.dataFields?.map(n=>n.path)||[],r=e.linkFields?.map(n=>n.path)||[],i=Object.keys(e.roles||{})||[];return [...t,...r,...i]},Et=(e,t)=>Object.keys(e||{}).some(i=>{if(!Array.isArray(e[i])){let o=t.idFields?.includes(i),n=t.dataFields?.some(s=>(s.dbPath===i||s.path===i)&&s?.validations?.unique),l=i==="$id"&&!Array.isArray(e[i]);return o||n||l}return !1}),Ue=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),ti=e=>{let{field:t,fieldStr:r,$justId:i,dbPath:o,isVirtual:n,fieldSchema:l}=e;return {$path:r,$dbPath:o,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:i,$id:t.$id,$isVirtual:n,[ie]:l}},ri=e=>{let{field:t,fieldStr:r,linkField:i,$justId:o,dbPath:n,schema:l,fieldSchema:s}=e,{target:u,oppositeLinkFieldsPlayedBy:f}=i;return f.map(c=>{let d=u==="role"?c.thingType:"relation",a=u==="role"?c.thing:i.relation,p={[`$${d}`]:a},h=j(l,p),$=t?.$fields?.filter(B=>Ue(h,B)).length===0,y=[];if(typeof t!="string")if(t.$fields)if($){let B=h.idFields||[];y=[...t.$fields,...B];}else y=t.$fields;else y=Bt(h);else y=["id"];t.$excludedFields&&(y=y.filter(B=>Ue(h,B)?!0:!t.$excludedFields.includes(B.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...ke(t.$filter,a,l)}:void 0;return {$thingType:d,$plays:i.plays,$playedBy:c,$path:c.path,$dbPath:n,$as:t.$as||r,$var:r,$thing:a,$fields:y,$excludedFields:t.$excludedFields,$fieldType:"link",$target:u,$intermediary:c.relation,$justId:o,$id:t.$id,$filter:m,$idNotIncluded:$,$filterByUnique:Et(t.$filter,h),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:s}})},ni=e=>{let{field:t,fieldStr:r,roleField:i,$justId:o,dbPath:n,schema:l,fieldSchema:s}=e;return i.playedBy.map(u=>{let{thing:f,thingType:c,relation:d}=u,a={[`$${c}`]:f},p=j(l,a),h=t?.$fields?.filter(m=>p?.idFields?.includes(m)||p?.idFields?.includes(m.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(h){let m=p.idFields||[];$=[...t.$fields,...m];}else $=t.$fields;else $=Bt(p);else $=["id"];t.$excludedFields&&($=$.filter(m=>Ue(p,m)?!0:!t.$excludedFields.includes(m.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...ke(t.$filter,f,l)}:void 0;return {$thingType:c,$path:r,$dbPath:n,$as:t.$as||r,$var:r,$thing:f,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:d,$justId:o,$id:t.$id,$filter:y,$idNotIncluded:h,$filterByUnique:Et(t.$filter,p),$playedBy:u,$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:s}})},Lr=(e,t,r)=>{let i=typeof e=="string"?e:e.$path,o=typeof e=="string",n=t.dataFields?.find(u=>u.path===i),l=t.linkFields?.find(u=>u.path===i),s=t.roles?.[i];if(n){let u=!!n.isVirtual&&!!n.default;return ti({field:e,fieldStr:i,$justId:o,dbPath:n.dbPath,isVirtual:u,fieldSchema:n})}else {if(l)return ri({field:e,fieldStr:i,linkField:l,$justId:o,dbPath:l.path,schema:r,fieldSchema:l});if(s)return ni({field:e,fieldStr:i,roleField:s,$justId:o,dbPath:i,schema:r,fieldSchema:s})}return null},ke=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(l=>Object.keys(l).reduce((f,c)=>{let d=l[c],a=isArray(d)?d:[d];if(c.startsWith("$"))["$id","$thing"].includes(c)?f[c]=d:f[c]=ke(d,t,r);else {let p=t in r.entities?r.entities[t]:r.relations[t],[h,$]=xe(p,c);if(h==="dataField")f[c]=d;else if(h==="linkField"||h==="roleField"){let y=$,[m]=y.$things;return a.every(B=>typeof B=="string")?f[c]={$id:a,$thing:m}:a.every(B=>isObject(B))&&(f[c]=isArray(d)?{$or:ke(d,m,r)}:ke(d,m,r)),f}else throw new Error(`Field ${c} not found in schema of ${t}`)}return f},{}));return i?n.length===1?n[0]:{$or:n}:n[0]};var kr=async(e,t,r)=>r?(n=>produce(n,l=>traverse(l,({value:s})=>{if(isObject(s)){let u=s;if(!u.$thing)return;if(u.$thing){let f=j(e,u),{virtualFields:c}=f,d=u[ne];if(!d)throw new Error("[Internal] QueryPath is missing");let a=getNodeByPath(t,d),p=a.$fields.map($=>$.$path),h=a.$excludedFields;c.forEach($=>{if(h?.includes($)||p.length>0&&!p.includes($))return;let y=f.dataFields?.find(m=>m.path===$);if(y?.default){let m=Le({currentThing:u,fieldSchema:y,mandatoryDependencies:!0});u[$]=m;}else if(u[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),h&&h.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete u[$];});}}})))(r):void 0;var Dr=e=>e.replace(/`/g,""),li=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],Rr=e=>li.some(t=>e.includes(t))?`\u27E8\`${e}\`\u27E9`:e;var Ir=e=>{let{queries:t,schema:r}=e;return t.map(i=>di({query:i,schema:r}))},di=e=>{let{query:t,schema:r}=e,{$thing:i,$fields:o,$filter:n,$offset:l,$limit:s,$sort:u}=t;if(o.length===0)return null;let f=[];f.push("SELECT");let c=Ft({parentQuery:t,queries:o,level:1,schema:r});c&&f.push(c);let d=r.entities[i]||r.relations[i];if(!d)throw new Error(`Schema for ${i} not found`);let p=(d.subTypes?[i,...d.subTypes]:[i]).map(h=>Rr(h));if(t.$id)if(typeof t.$id=="string")f.push(`FROM ${p.map(h=>`${h}:\`${t.$id}\``).join(",")}`);else if(isArray(t.$id)){let h=t.$id,$=p.flatMap(y=>h?.map(m=>`${y}:\`${m}\``));f.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else f.push(`FROM ${p.join(",")}`);if(n){let h=pe(n,i,r),$=be(h);f.push(`WHERE ${$}`);}return u&&f.push(Cr(u)),typeof s=="number"&&f.push(`LIMIT ${s}`),typeof l=="number"&&f.push(`START ${l}`),f.join(`
|
|
39
|
-
`)},
|
|
40
|
-
`)},
|
|
41
|
-
`)},
|
|
42
|
-
`)},
|
|
36
|
+
${y}`})(),n=e.dbConnectors[0].id,l=r.typeDB.get(n)?.session,s=r.typeDB.get(n)?.client;if(!l){console.log("Session Status: ","NO SESSION");return}await l.close();let[{dbName:u}]=e.dbConnectors;await(await s.databases.get(u)).delete(),await s.databases.create(u);let c=await s.session(e.dbConnectors[0].dbName,SessionType.SCHEMA),d=await c.transaction(TransactionType.WRITE);await d.query.define(o),await d.commit(),await d.close();let a=await c.transaction(TransactionType.READ);(await(await a.query.match("match $a sub thing;")).collect()).forEach(async y=>{y.get("a");}),await a.close();};var ae=Symbol.for("queryPath"),We=Symbol.for("stepPrint"),Te=Symbol.for("edgeType"),Be=Symbol.for("edgeSchema"),Ce=Symbol.for("dbNode"),ot=Symbol.for("isTransformed"),le=Symbol.for("fieldSchema"),$e=Symbol.for("sharedMetadata"),Qe=Symbol.for("suqlMetadata");var Kt={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Ht=({linkField:e,originalRelation:t,withExtensionsSchema:r})=>{if(e.isVirtual)return `$this.${e.path}.id`;let i=r.relations[e.relation].subTypes||[],o=[e.relation,...i],n=`<-\`${t}_${e.plays}\`<-(\`${o.join("`,`")}\`)`;if(e.target==="relation")return n;if(e.target==="role"){let[l]=e.oppositeLinkFieldsPlayedBy,s=r.entities[l.thing]?.subTypes||r.relations[l.thing]?.subTypes||[],u=[l.thing,...s],f=`->\`${t}_${l.plays}\`->(\`${u.join("`,`")}\`)`;return `${n}${f}`}else throw new Error("Unsupported linkField target")};var vt=(e,t,r)=>r?t:`${e}\xB7${t}`;var Gt=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))))[0],xe=(e,t)=>Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))),Yt=(e,t)=>{let r=[],i=produce(e,n=>traverse(n,({key:l,value:s,meta:u})=>{if(u.depth===2&&(l&&(s.dataFields=s.dataFields?.map(f=>({...f,cardinality:f.cardinality||"ONE",dbPath:vt(l,f.path,f.shared)}))),s.extends)){if(!s.defaultDBConnector.as)throw new Error(`[Schema] ${l} is extending a thing but missing the "as" property in its defaultDBConnector. Path:${u.nodePath}`);let f=n.entities[s.extends]||n.relations[s.extends],c=[s.extends,...f.allExtends||[]];if(s.allExtends=c,c.forEach(d=>{if(n.entities[d])n.entities[d].subTypes=[l,...n.entities[d].subTypes||[]];else if(n.relations[d])n.relations[d].subTypes=[l,...n.relations[d].subTypes||[]];else throw new Error(`[Schema] ${l} is extending a thing that does not exist in the schema: ${d}`)}),s.idFields=f.idFields?Array.from(new Set((s.idFields||[]).concat(f.idFields))):s.idFields,s.dataFields=f.dataFields?(s.dataFields||[]).concat(f.dataFields.map(d=>{let a=s.extends,p=e.entities[a]||e.relations[a];for(;!p.dataFields?.find(h=>h.path===d.path);)a="extends"in p?p.extends:void 0,p=e.entities[a]||e.relations[a];return {...d,dbPath:vt(a,d.path,d.shared),[$e]:{inheritanceOrigin:d[$e]?.inheritanceOrigin||s.extends}}})):s.dataFields,"roles"in f){let d=s,a=f;if(a.roles){let p=mapEntries(a.roles,(h,$)=>[h,{...$,[$e]:{inheritanceOrigin:$[$e]?.inheritanceOrigin||s.extends}}]);d.roles={...d.roles||{},...p};}}s.linkFields=f.linkFields?(s.linkFields||[]).concat(f.linkFields.map(d=>({...d,[$e]:{inheritanceOrigin:d[$e]?.inheritanceOrigin||s.extends}}))):s.linkFields,f?.hooks?.pre&&(s.hooks=s.hooks||{},s.hooks.pre=s.hooks.pre||[],s.hooks.pre=[...f?.hooks?.pre||[],...s?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:n,value:l,meta:s})=>{if(n==="linkFields"){let f=(()=>{if(!s.nodePath)throw new Error("No path");let[d,a]=s.nodePath.split(".");return {thing:a,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),c=Array.isArray(l)?l.map(d=>({...d,...f})):[{...l,...f}];r.push(...c);}}),produce(i,n=>traverse(n,({value:l,key:s,meta:u})=>{if(u.depth===2&&l.idFields&&!l.id){l.name=s;let f=()=>{if(u.nodePath?.split(".")[0]==="entities")return "entity";if(u.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};l.thingType=f();let c=Object.keys(t).find(d=>t[d]?.get(l.defaultDBConnector.id));if(l.db=c,l.dbContext=Kt[c],l.computedFields=[],l.virtualFields=[],l.requiredFields=[],l.enumFields=[],l.fnValidatedFields=[],"roles"in l&&Object.entries(l.roles).forEach(([a,p])=>{p.fieldType="roleField";let h=r.filter(M=>M.relation===s&&M.plays===a)||[];p.playedBy=h,p.name=a;let $=[...new Set(h.map(M=>M.thing))];p.$things=$;let y=p[$e]?.inheritanceOrigin||l.name;if($.length>1)throw new Error(`Not supported yet: Role ${a} in ${l.name} is played by multiple things: ${$.join(", ")}`);let m=$.flatMap(M=>{let S=Y(e,M)?.subTypes||[];return [M,...S]}),B=`->\`${y}_${a}\`->(\`${m.join("`,`")}\`)`;p[Qe]={queryPath:B};}),"linkFields"in l&&l.linkFields){let d=l;d.linkFields?.forEach(a=>{a.fieldType="linkField";let p=i.relations[a.relation];if(!a.isVirtual){if(!p)throw new Error(`The relation ${a.relation} does not exist in the schema`);if(p.roles?.[a.plays]===void 0)throw new Error(`The role ${a.plays} is not defined in the relation ${a.relation} (linkField: ${a.path})`)}if(a.target==="relation"){if(a.isVirtual)throw new Error(`[Schema] Virtual linkFields can't target a relation. Thing: "${d.name}" LinkField: "${a.path}. Path:${u.nodePath}."`);a.$things=[a.relation],a.oppositeLinkFieldsPlayedBy=[{plays:a.path,thing:a.relation,thingType:"relation"}];}if(a.target==="role"){let y=r.filter(m=>m.relation===a.relation&&m.plays!==a.plays)||[];if(a.oppositeLinkFieldsPlayedBy=y,a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter(m=>m.target==="role"),a.oppositeLinkFieldsPlayedBy.length===0)throw new Error(`[Schema] LinkFields require to have at least one opposite linkField playing an opposite role. Thing: "${d.name}" LinkField: "${a.path}. Path:${u.nodePath}."`);if(a.$things=a.oppositeLinkFieldsPlayedBy.map(m=>m.thing),a.oppositeLinkFieldsPlayedBy.length>1)throw new Error(`Not supported: LinkField ${a.path} in ${d.name} has multiple candidates ${a.oppositeLinkFieldsPlayedBy.map(m=>m.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`)}let h=p?.roles?.[a.plays][$e]?.inheritanceOrigin??a.relation,$=Ht({linkField:a,originalRelation:h,withExtensionsSchema:i});a[Qe]={queryPath:$};});}}if(typeof l=="object"&&"playedBy"in l){let f=[...new Set(l.playedBy.map(c=>c.thing))];if(f.length>1)throw new Error(`[Schema] roleFields can be only played by one thing. Role: ${s}, path:${u.nodePath}, played by: ${f.join(", ")}`);if(l.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${s}, path:${u.nodePath}`)}if(u.depth===4){let[f,c]=u.nodePath?.split(".")||[],d=n[f][c];!isArray(l)&&typeof l=="object"&&(l.validations&&(l.validations.required&&d.requiredFields.push(l.path),l.validations.enum&&d.enumFields.push(l.path),l.validations.fn&&d.fnValidatedFields.push(l.path)),l.default?l.isVirtual?d.virtualFields.push(l.path):d.computedFields.push(l.path):l.isVirtual&&d.virtualFields.push(l.path));}}))},Y=(e,t)=>{if(t in e.entities)return e.entities[t];if(t in e.relations)return e.relations[t];throw new Error(`${t} is not defined in the schema`)},x=(e,t)=>{if(!t)throw new Error("[Internal] No node for getCurrentSchema");if(t.$thing){if(t.$thingType==="entity"){if(!(t.$thing in e.entities))throw new Error(`Missing entity '${t.$thing}' in the schema`);return e.entities[t.$thing]}if(t.$thingType==="relation"){if(!(t.$thing in e.relations))throw new Error(`Missing relation '${t.$thing}' in the schema`);return e.relations[t.$thing]}if(t.$thing in e.entities&&t.$thing in e.relations)throw new Error(`Ambiguous $thing ${t.$thing}`);if(t.$thing in e.entities)return e.entities[t.$thing];if(t.$thing in e.relations)return e.relations[t.$thing];throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)}if(t.$entity){if(!(t.$entity in e.entities))throw new Error(`Missing entity '${t.$entity}' in the schema`);return e.entities[t.$entity]}if(t.$relation){if(!(t.$relation in e.relations))throw new Error(`Missing relation '${t.$relation}' in the schema`);return e.relations[t.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)},ze=(e,t)=>{let r=e.dataFields?.find(n=>n.path===t);if(r)return ["dataField",r];let i=e.linkFields?.find(n=>n.path===t);if(i)return ["linkField",i];let o="roles"in e?e.roles[t]:void 0;if(o)return ["roleField",o];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},Ve=(e,t)=>{let r=x(e,t);if(r?.idFields?.length&&r?.idFields?.length>1)throw new Error(`Multiple ids not yet enabled / composite ids: ${r?.idFields}`);let[i]=r.idFields;return i},Xt=(e,t)=>{let r=e.$thing||e.$entity||e.$relation;if(!r)throw new Error("[Internal] No thing found");if(e.$entity)return "entity";if(e.$relation)return "relation";if(t.entities[r])return "entity";if(t.relations[r])return "relation";throw new Error("No thing found")},lt=(e,t,r)=>{let i=x(e,t),o=i.linkFields?.find(s=>s.path===r);if(o)return o;let n=i.dataFields?.find(s=>s.path===r);if(n)return n;let l="roles"in i?i.roles?.[r]:void 0;if(l)return l;throw new Error(`Field ${r} not found in schema`)},ct=(e,t,r)=>lt(e,t,r)?.cardinality,ue=(e,t)=>{let r=e.dataFields?.map(h=>h.path)||[],i=e.linkFields?.map(h=>h.path)||[],o="roles"in e?listify(e.roles,h=>h):[],n=[...r||[],...i||[],...o||[]],s=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...n];if(!t)return {fields:n,dataFields:r,roleFields:o,linkFields:i};let u=t.$fields?t.$fields.map(h=>{if(typeof h=="string"){if(h.startsWith("$")||h.startsWith("%"))return;if(!n.includes(h))throw new Error(`Field ${h} not found in the schema`);return h}if("$path"in h&&typeof h.$path=="string")return h.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,h=>{if(!(h.startsWith("$")||h.startsWith("%"))){if(!n.includes(h))throw new Error(`[Schema] Field ${h} not found in the schema`);return h}}).filter(h=>h!==void 0),f=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&r?.includes(h)):[],c=t.$filter?listify(t.$filter,h=>h.toString().startsWith("$")?void 0:h.toString()).filter(h=>h&&[...o||[],...i||[]].includes(h)):[],d=[...u,...f].filter(h=>!h?.startsWith("%")).filter(h=>!s.includes(h)).filter(h=>h),a=t.$filter?xe(t.$filter,(h,$)=>f.includes(h)):{},p=t.$filter?xe(t.$filter,(h,$)=>c.includes(h)):{};return {fields:n,dataFields:r,roleFields:o,linkFields:i,usedFields:u,usedLinkFields:i.filter(h=>u.includes(h)),usedRoleFields:o.filter(h=>u.includes(h)),usedDataFields:r.filter(h=>u.includes(h)),unidentifiedFields:d,...f.length?{localFilters:a}:{},...c.length?{nestedFilters:p}:{}}};var er=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},tr=(e,t,r)=>{let o=(r.nodePath||"").split("."),n=isArray(t)?o.slice(0,-2).join("."):o.slice(0,-1).join(".");return t?getNodeByPath(e,n):{}},Ee=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var Ke=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),pe=e=>{if(Array.isArray(e))return e.map(t=>current(t));if(e&&typeof e=="object"){let t=isDraft(e)?current(e):e,r={};return Object.entries(t).forEach(([i,o])=>{r[i]=isDraft(o)?current(o):o;}),r}else return e},oe=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},w=(e,t)=>{let r="";for(let i=0;i<t;i++)r+=" ";return `${r}${e}`};var Re=(e,t)=>{if(t.fieldType==="linkField"){let r=t.oppositeLinkFieldsPlayedBy;if(r?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(r=>r.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!t.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return t.playedBy}else throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var rr=(e,t,r)=>{let i=isArray(e[t])?e[t]:[e[t]];if(!i.every(o=>typeof o=="object"))if(i.every(o=>typeof o=="string")){let o=Re(t,r),[n]=o,l=e.$op==="create"?"link":"replace",s=n.thing,u=n.thingType;if(i.some(f=>f.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:l,$thing:s,$thingType:u,$bzId:`S_${v4()}`};}else throw new Error(`[Mutation Error] Replace can only be used with a single id or an array of ids. (Field: ${t} Nodes: ${JSON.stringify(i)} Parent: ${JSON.stringify(e,null,2)})`)};var Se=(e,t,r)=>{let i=x(r,t),{usedDataFields:o}=ue(i,t);if(t.$op){if(t.$op==="create"&&t.$id)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(["unlink","delete","update"].includes(t.$op)&&e.$op==="create")throw new Error(`[Wrong format] Cannot ${t.$op} under a create`);if(t.$op==="delete"&&o.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&o.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var He=(e,t,r)=>{let i=x(r,t),{usedFields:o}=ue(i,t);return t.$op?(Se(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(Se(e,{...t,$op:"update"},r),"update"):(Se(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(Se(e,{...t,$op:"create"},r),"create"):(Se(e,{...t,$op:"create"},r),"link"):(Se(e,{...t,$op:"create"},r),"create")};var ir=(e,t)=>{let i=(isArray(e.$root)?e.$root:[e.$root]).map(o=>{let n=He(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:Xt(o,t)},...o.$op?{}:{$op:n},...o.$bzId?{}:{$bzId:`R_${v4()}`}},...o}});e.$root=isArray(e.$root)?i:i[0];};var Ue=(e,t)=>{let r=t[We];return isSet(r)?r.has("clean")?(Reflect.set(t,We,r.add("clean")),!0):!1:(Reflect.set(t,We,new Set(["clean"])),!0)};var or=(e,t,r)=>{if(Ue("split_ids",e)){let i=(isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(isObject(o)&&"$id"in o&&isArray(o.$id)){let n=o;if(x(r,n),!n.$bzId)throw new Error("[Internal Error] No bzId found");return n.$id.map((l,s)=>({...pe(n),$id:l,$bzId:`${n.$bzId}_${s}`,...Ee(n)}))}return o});(i.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=i);}};var ar=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{let l=Re(t,r),[s]=l,u=He(e,{...n,$thing:s.thing,$thingType:s.thingType},i),f=n.$bzId?n.$bzId:n.$tempId?n.$tempId:`N_${v4()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...n,[Be]:r,$thing:s.thing,$thingType:s.thingType,$op:u,$bzId:f}});e[t]=isArray(e[t])?o:o[0];};var In=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,On=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,lr=e=>{let r=e.toString().replace(In,"").trim().split("=>")[0].split("{")[0].replace(On,"").trim(),i=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return i?(i.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(n=>n.includes("{")&&n.includes("}")?(n.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(s=>s.split(":")[0].trim().replace(/['"[\]]/g,"")):n.trim()).filter(Boolean):[]};var De=({currentThing:e,fieldSchema:t,mandatoryDependencies:r=!1})=>{if(!t||!t.default||!("fn"in t.default||"value"in t.default))throw new Error(`[Internal] Virtual field: No field schema found, or wrongly configured. Field: ${JSON.stringify(t,null,3)}`);if(t.default.type==="value")return t.default.value;if(r){let{fn:o}=t.default,l=lr(o).filter(s=>!(s in e));if(l.length)throw new Error(`Virtual field: Missing arguments ${l.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");return "default"in t?t.default?.fn(e):void 0};var cr=(e,t,r)=>{let i=e[t];i&&(isArray(i)?i:[i]).forEach(o=>{let n=x(r,o),{unidentifiedFields:l}=ue(n,o),{computedFields:s,virtualFields:u}=n,f=listify(o,(a,p)=>p!==void 0?a:void 0),c=f.filter(a=>u?.includes(a));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(s.filter(a=>!f.includes(a)).forEach(a=>{let p=n.dataFields?.find(B=>B.path===a),$=n.linkFields?.find(B=>B.path===a)?.oppositeLinkFieldsPlayedBy[0],y="roles"in n?Gt(n.roles,(B,M)=>B===a):void 0,m=p||$||y;if(!m)throw new Error(`no field Def for ${a}`);if(o.$op==="create"&&!o[a]){let B=De({currentThing:o,fieldSchema:m,mandatoryDependencies:!0});o[a]=B;}}),l.length>0)throw new Error(`Unknown fields: [${l.join(",")}] in ${JSON.stringify(o)}`)});};var Je=(e,t)=>{let r=x(t,e).hooks;if(r?.pre){let i=`on${er(e.$op)}`;return r.pre.filter(l=>!l.triggers||l.triggers[i]?.()).flatMap(l=>l.actions)}return []};var hr=(e,t,r,i)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(n=>{if("$thing"in n){if(n.$fields)return n;let{requiredFields:l,enumFields:s,fnValidatedFields:u,dataFields:f}=x(r,n);if("$op"in n&&n.$op==="create"&&l.forEach(c=>{if(!(c in n))throw new Error(`[Validations] Required field "${c}" is missing.`)}),("$op"in n&&n.$op==="update"||n.$op==="create")&&s.forEach(c=>{if(c in n){let d=f?.find(a=>a.path===c)?.validations?.enum;if(!d)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(isArray(n[c]))n[c].some(a=>{if(!d.includes(a))throw new Error(`[Validations] Option "${a}" is not a valid option for field "${c}".`)});else if(d&&!d.includes(n[c]))throw new Error(`[Validations] Option "${n[c]}" is not a valid option for field "${c}".`)}}),("$op"in n&&n.$op==="update"||n.$op==="create")&&u.forEach(c=>{if(c in n)try{let d=f?.find(a=>a.path===c)?.validations?.fn;if(!d)throw new Error("Missing validation function.");if(!d(n[c]))throw new Error("Failed validation function.")}catch(d){throw new Error(`[Validations:attribute:${c}] ${d.message}`)}}),isObject(n)&&"$thing"in n){let c=n.$thing,d=n,a=clone(pe(e)),p=clone(pe(d)),h=i.mutation?.context||{},$=clone(pe(n[Ce]||{}));Je(d,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let B=m.fn(p,a,h,$);if(B===!1)throw new Error(`${m.message}.`);if(B!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(B){throw new Error(`[Validations:thing:${c}] ${B.message}`)}}});}}});};var pr=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{if(Ke(n)){if(n.$fields||n[ot])return n;let l=Je(n,r).filter(d=>d.type==="transform"),s=clone(pe(e)),u=clone(pe(n)),f=i.mutation?.context||{},c=clone(pe(n[Ce]||n.$dbNode));return l.forEach(d=>{let a=d.fn(u,s,f,c||{});Object.keys(a).length!==0&&(n={...u,...a,...Ee(n),[ot]:!0});}),n}});e[t]=isArray(e[t])?o:o[0];};var fr=(e,t,r)=>{let i=Re(t,r),[o]=i;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Be]:r};};var Ae=e=>{if(Array.isArray(e)){for(let t of e)if(Ae(t))return !0;return !1}if(e.$fields)return !0;for(let t in e){if(t.startsWith("$"))continue;let r=e[t];if(r&&typeof r=="object"&&Ae(e[t]))return !0}return !1};var Kn=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(Ue("set_tempId",e))if(e.$tempId?.startsWith("_:")){let r=e.$tempId.substring(2);e.$tempId=r,e.$bzId=r;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},Hn=(e,t)=>{},ft=(e,t,r)=>{let i={$rootWrap:{$root:e}},o=Ae(Array.isArray(e)?e:[e]),n=produce(i,l=>traverse(l,({value:s,parent:u,key:f,meta:c})=>{if(!(!u||!f)&&isObject(s)){let d=c.nodePath?.split(".")||[];if(!("$root"in s)){if(!("$thing"in s||"$entity"in s||"$relation"in s)){let h=["$fields","$dbNode","$filter"],$=d[d.length-1],y=d[d.length-2];if(f==="$root")throw new Error("Root things must specify $entity or $relation");if(!h.includes($)&&!h.includes(y))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(s)?current(s):s)}`)}}let a=s,p=d.includes("$filter");Object.keys(a).forEach(h=>{if(Kn(a,h),h!=="$root"&&p||h!=="$root"&&(h.startsWith("$")||h.startsWith("%")))return;let $=h!=="$root"?lt(t,a,h):{fieldType:"rootField"};if(!$)throw new Error(`[Internal] Field ${h} not found in schema`);if("contentType"in $)return Hn();if(["rootField","linkField","roleField"].includes($.fieldType)){if(["linkField","roleField"].includes($.fieldType)&&(a[h]===null?fr(a,h,$):rr(a,h,$)),$.fieldType==="rootField"){if(!("$root"in a))throw new Error(`[Internal] Field ${h} is a rootField but the object is not a root`);ir(a,t);}let y=isArray(a[h])?a[h]:[a[h]],m=d.slice(1).join(".");y.forEach(M=>{if(M){if($?.cardinality==="ONE"&&!M.$op&&!M.$id&&!M.$filter&&!M.$tempId&&a.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${m}.${h}`);if(M.$tempId&&!(M.$op===void 0||M.$op==="link"||M.$op==="create"||M.$op==="update"))throw new Error(`Invalid op ${M.$op} for tempId. TempIds can be created, or when created in another part of the same mutation. In the future maybe we can use them to catch stuff in the DB as well and group them under the same tempId.`)}}),["linkField","roleField"].includes($.fieldType)&&ar(a,h,$,t),or(a,h,t),["rootField","linkField","roleField"].includes($.fieldType)&&cr(a,h,t),(isArray(a[h])?a[h]:[a[h]]).forEach(M=>{let g=x(t,M),{unidentifiedFields:S,usedLinkFields:C,usedFields:D,fields:I}=ue(g,M);if(D.forEach(j=>{if(!I.includes(j))throw new Error(`[Schema] Field ${j} not found in the schema`)}),S.length>0)throw new Error(`Unknown fields: [${S.join(",")}] in ${JSON.stringify(s)}`);if(C.length>1){let j=g.linkFields?.filter(N=>C.includes(N.path));j?.some((N,se)=>j.some((H,R)=>{if(se!==R&&N.target!==H.target&&N.relation===H.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),o||(pr(a,h,t,r),hr(a,h,t,r));}});}}));return isArray(n.$rootWrap.$root),n.$rootWrap.$root};var ve=async(e,t)=>{let r=t.dbConnectors[0].id,i=e.typeDB?.get(r)?.session,o=e.typeDB?.get(r)?.client;if(!i||!i.isOpen()){if(!o)throw new Error("Client not found");i=await o.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:o,session:i});}return {client:o,session:i}};var $r=async(e,t,r)=>{if(!e)throw new Error("TQL request not built");if(!(e.deletions&&e.deletionMatches||e.insertions))throw new Error("TQL request error, no things");let{session:i}=await ve(t,r),o=await i.transaction(TransactionType.WRITE),n=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,l=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{n&&await o.query.delete(n);let s=l&&o.query.insert(l),u=s?await s.collect():void 0;return await o.commit(),{insertions:u}}catch(s){throw new Error(`Transaction failed: ${s.message}`)}finally{await o.close();}};var mr=async(e,t,r,i,o)=>{let n=[...t,...r],l=n.map(s=>{let u=e.insertions?.find(d=>d.get(`${s.$bzId}`))?.get(`${s.$bzId}`),f=s.$thing||s.$relation||s.$entity,c=f?Y(i,f):void 0;if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!u&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let d=u?.asThing().iid,a=Object.entries(s).filter(([h,$])=>!h.startsWith("$")).reduce((h,[$,y])=>{if(c?.dataFields?.find(B=>B.path===$)?.contentType==="JSON")return h[$]=JSON.parse(y),h;if(s.$thingType==="relation"){let B=n.filter(M=>M.$id&&M.$bzId===y);return B.length===1?(h[$]=B[0].$id,h):(h[$]=y,h)}return h[$]=y,h},{});if(o.mutation?.noMetadata)return a;let p=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:d,...s,...a,[s.path]:s.$id,...p}}if(s.$op==="delete"||s.$op==="unlink")return s;if(s.$op!=="match")throw new Error(`Unsupported op ${s.$op}`)}).filter(s=>s);return clone(l)};var yr=e=>{let t=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(n=>n.startsWith("$")).forEach(n=>delete r[n]),Object.keys(r).filter(n=>typeof n=="symbol").forEach(n=>delete r[n])),r);return produce(e,r=>traverse(r,t))};var Fr=async(e,t)=>{let r=c=>{let d=[],a=[],p=m=>{if(m.$id)return m.$id;let B=x(t,m),{idFields:M}=B;if(!M)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[g]=M;if(!g)throw new Error(`no idField: ${JSON.stringify(m)}`);let S=B.dataFields?.find(I=>I.path===g),C=De({currentThing:m,fieldSchema:S,mandatoryDependencies:!0}),D=m[g]||m.$id||C;if(!D)throw new Error(`no idValue: ${JSON.stringify(m)}`);return D},h=m=>{if(m.$op==="create"){let B=p(m);if(d.find(M=>M.$id===B&&M.$op==="create"))throw new Error(`Duplicate id ${B} for node ${JSON.stringify(m)}`);if(a.find(M=>M.$bzId===m.$bzId))throw new Error(`Duplicate $bzId ${m.$bzId} for node ${JSON.stringify(m)}`);d.push({...m,$id:B});return}m.$tempId&&m.$op==="match"||d.push(m);},$=m=>{if(m.$op==="create"){let B=p(m);if(d.find(M=>M.$id===B),a.find(M=>M.$bzId===m.$bzId))throw new Error(`Duplicate %bzId ${m.$bzIdd} for edge ${JSON.stringify(m)}`);a.push({...m,$id:B});return}a.push(m);};return traverse(c,({value:m,parent:B,meta:M})=>{if(!isObject(m))return;let g=m;if(g.$thing){if(!g.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(g)}`);if(!g.$bzId)throw new Error("[internal error] BzId not found");let S=x(t,g),{dataFields:C,roleFields:D,linkFields:I,usedFields:j}=ue(S,g),N=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let R=j.filter(b=>C?.includes(b)),E=j.filter(b=>D?.includes(b)),T=j.filter(b=>I?.includes(b));if(R.length>0)return "update";if(E.length>0||T.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},se={...g.$id&&{$id:g.$id},...g.$tempId&&{$tempId:g.$tempId},...g.$filter&&{$filter:g.$filter},$thing:g.$thing,...g.$thingType&&{$thingType:g.$thingType},...shake(pick(g,C||[""])),$op:N(),$bzId:g.$bzId};h(se);let H=g[Be];if(H?.fieldType==="linkField"){if((g.$op==="link"||g.$op==="unlink")&&(g.$id||g.$filter)){if(g.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");d.push({...g,$op:"match"});}let R=H.relation===g.$thing,E=R?g.$bzId:`LT_${v4()}`,b=tr(c,B,M).$bzId;if(!b)throw new Error("No parent id found");let F=()=>{if(g.$op==="delete")return R?"match":"delete";if(g.$op==="unlink")return R?"unlink":"delete";if(g.$op==="link"||g.$op==="create")return R?"link":"create";if(g.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},Q=x(t,{$thing:H.relation,$thingType:"relation"});if(!Object.keys(Q.roles).includes(H.plays))throw new Error(`[Wrong format] Field ${H.plays} is not a role of relation ${H.relation}`);let O={$bzId:E,$thing:H.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:F(),...R?{}:{[H.path]:g.$bzId},[H.plays]:b,[Be]:H,[Te]:"linkField"};$(O),(g.$op==="unlink"||F()==="unlink")&&R&&$({$thing:H.relation,$thingType:"relation",$bzId:E,$op:"match",[H.plays]:b,[Be]:H,[Te]:"linkField"});}if(g.$thingType==="relation"){let R=xe(g,(b,F)=>D.includes(b)),E=mapEntries(R,(b,F)=>isArray(F)?[b,F]:isObject(F)?[b,F.$bzId]:[b,F]),T=xe(m,(b,F)=>b.startsWith("$")||b.startsWith("Symbol"));if(Object.keys(R).filter(b=>!b.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let b=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},F=x(t,g).roles,Q=mapEntries(E,(O,k)=>{let q=F[O]?.cardinality;if(!q)throw new Error(`Role ${O} not found in schema`);if(Array.isArray(k)){if(q==="ONE"){if(k.length>1)throw new Error(`[Error] Role ${O} is not a MANY relation`);return [O,k[0].$bzId||k[0]]}return [O,k.map(J=>J.$bzId||J)]}return [O,k.$bzId||k]}),L={...T,$thing:g.$thing,$thingType:"relation",$op:b(),...Q,$bzId:g.$bzId,[Te]:"roleField"};$(L);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(R).length>0){let b=0;Object.entries(R).forEach(([F,Q])=>{let L=isArray(Q)?Q:[Q],O=k=>k==="create"||k==="replace"?"link":k;L.forEach(k=>{if(!k)return;let q=O(k.$op);if(q==="replace")throw new Error("Not supported yet: replace on roleFields");if(q==="unlink"&&b>0)throw b+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let J={...T,$thing:g.$thing,$thingType:"relation",$op:q==="delete"?"unlink":q,[F]:k.$bzId,$bzId:g.$bzId,[Te]:"roleField"};$(J);});});}}}}}),[d,a]},[i,o]=r(e),n=i.reduce((c,d)=>{if(!d.$bzId)return [...c,d];let a=c.findIndex(p=>p.$bzId===d.$bzId);if(a===-1)return [...c,d];if(c[a].$op==="create"&&d.$op==="match")return c;if(c[a].$op==="match"&&(d.$op==="create"||d.$op==="match"))return [...c.slice(0,a),d,...c.slice(a+1)];if(c[a].$op==="update"&&d.$op==="update")return [...c.slice(0,a),{...c[a],...d},...c.slice(a+1)];throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${d.$tempId||d.$id}". Existing: ${c[a].$op}. Current: ${d.$op}`)},[]),l=o.reduce((c,d)=>{let a=c.find(p=>(p.$id&&p.$id===d.$id||p.$bzId&&p.$bzId===d.$bzId)&&p.$thing===d.$thing&&p.$op===d.$op);if(a){let p={...a};return Object.keys(d).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let y=a[$],m=d[$];Array.isArray(y)&&Array.isArray(m)?p[$]=Array.from(new Set([...y,...m])):!Array.isArray(y)&&Array.isArray(m)?y!==void 0?p[$]=Array.from(new Set([y,...m])):p[$]=m:Array.isArray(y)&&!Array.isArray(m)?m!==void 0&&(p[$]=Array.from(new Set([...y,m]))):y!==null&&m!==null&&y!==void 0&&m!==void 0?p[$]=Array.from(new Set([y,m])):y==null&&(p[$]=m);}),[...c.filter($=>!(($.$id&&$.$id===d.$id||$.$bzId&&$.$bzId===d.$bzId)&&$.$thing===d.$thing&&$.$op===d.$op)),p]}return [...c,d]},[]);n.forEach(c=>{if((c.$thingType==="relation"||"relation"in c)&&l.filter(d=>d.$bzId===c.$bzId||d.$tempId&&d.$tempId===c.$tempId).length===0){if(c.$op==="delete"||c.$op==="match"||c.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(yr(c))}`)}});let s=[...n,...l],u=new Set(s.filter(c=>c.$tempId).map(c=>c.$tempId)),f=Array.from(u).filter(c=>!s.some(d=>d.$tempId===c&&d.$op==="create"));if(f.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${f.join(", ")}`);return {mergedThings:n,mergedEdges:l}};var $t=e=>{if(isDate(e))return {type:"datetime",value:e.toISOString().replace("Z","")};if(typeof e=="string")return {type:"string",value:`"${e}"`};if(typeof e=="number")return e%1!==0?{type:"double",value:e}:{type:"long",value:e};if(typeof e=="boolean")return {type:"boolean",value:e};throw new Error(`Unsupported type ${typeof e}`)};var wr=async(e,t,r)=>{let i=a=>{let p=a.$op,h=`$${a.$bzId}`,$=x(r,a),{idFields:y,defaultDBConnector:m}=$,B=m?.path||a.$thing,M=a.$id,g=y?.[0],S=listify(a,(R,E)=>{if(R.startsWith("$")||R.startsWith("%")||R===g||E===void 0||E===null)return "";let T=$.dataFields?.find(Q=>Q.path===R);if(!T?.path)return "";let F=T.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(T.contentType))return `has ${F} '${E}'`;if(["NUMBER","BOOLEAN"].includes(T.contentType))return `has ${F} ${E}`;if(T.contentType==="DATE"){if(Number.isNaN(E.valueOf()))throw new Error("Invalid format, Nan Date");return E instanceof Date?`has ${F} ${E.toISOString().replace("Z","")}`:`has ${F} ${new Date(E).toISOString().replace("Z","")}`}if(T.contentType==="FLEX"){let Q=`bza${nanoid()}`,L=isArray(E)?E.map(O=>$t(O)):$t(E);if(Array.isArray(L))throw new Error("Array in FLEX fields not supported yet");return `has ${F} $${Q}; $${Q} '${Q}' isa ${F}, has ${L.type}Attribute ${L.value}`}throw new Error(`Unsupported contentType ${T.contentType}`)}).filter(R=>R),C=`${h}-atts`,D=listify(a,R=>{if(R.startsWith("$")||R.startsWith("%")||R===g)return "";let E=$.dataFields?.find(F=>F.path===R);if(!E?.path)return "";let b=E.dbPath;return `{${C} isa ${b};}`}).filter(R=>R),I=isArray(M)?`like '${M.join("|")}'`:`'${M}'`,j=M?[`has ${g} ${I}`]:[],N=[...j,...S].filter(R=>R).join(","),se=()=>{if(p==="delete"||p==="unlink"||p==="match")return `${h} isa ${[B,...j].filter(R=>R).join(",")};`;if(p==="update"){if(!D.length)throw new Error("update without attributes");return `${h} isa ${[B,...j].filter(R=>R).join(",")}, has ${C};
|
|
37
|
+
${D.join(" or ")};`}return ""},H=()=>p==="update"||p==="link"||p==="match"?`${h} isa ${[B,...j].filter(R=>R).join(",")};`:"";if(Ke(a))return {op:p,deletionMatch:se(),insertionMatch:H(),insertion:p==="create"?`${h} isa ${[B,N].filter(R=>R).join(",")};`:p==="update"&&S.length?`${h} ${S.join(",")};`:"",deletion:p==="delete"?`${h} isa ${B};`:p==="update"&&D.length?`${h} has ${C};`:""};throw new Error("in attributes")},o=a=>{let p=a.$op,h=x(r,a),$=`$${a.$bzId}`,y=a.$id,m=h.defaultDBConnector?.path||a.$thing,B="roles"in h?listify(h.roles,E=>E):[],M="roles"in h?mapEntries(h.roles,(E,T)=>[E,T.dbConnector?.path||E]):{},g=listify(a,(E,T)=>{if(!B.includes(E))return null;if(!("roles"in h))throw new Error("This should have roles! ");let b=M[E];return Array.isArray(T)?T.map(F=>({path:b,id:F})):{path:b,id:T}}).filter(E=>E).flat(),S=g.map(E=>{if(!E?.path)throw new Error("Object without path");return `${E.path}: $${E.id}`}),C=g.length>0?`( ${S.join(" , ")} )`:"",D=a[Te];if(!D)throw new Error("[internal error] Symbol edgeType not defined");let I=C?`${$} ${C} ${D==="linkField"||p==="delete"||p==="unlink"?`isa ${m}`:""}`:"",j=`${$} ${D==="linkField"||p==="delete"?`isa ${m}`:""}`,N=()=>I?p==="link"?`${I};`:p==="create"?`${I}, has id '${y}';`:"":"",se=()=>I&&p==="match"?`${I};`:"",H=()=>I?p==="delete"?`${I};`:p==="match"?`${I};`:"":"",R=()=>I?p==="delete"?`${j};`:p==="unlink"?`${$} ${C};`:"":"";return {deletionMatch:H(),insertionMatch:se(),deletion:R(),insertion:N(),op:""}},n=(a,p)=>{let h=p==="edges"?o:i;if(Array.isArray(a))return a.map(g=>{let{preDeletionBatch:S,insertionMatch:C,deletionMatch:D,insertion:I,deletion:j}=h(g);return shake({preDeletionBatch:S,insertionMatch:C,deletionMatch:D,insertion:I,deletion:j},N=>!N)}).filter(g=>g);let{preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:M}=h(a);return shake({preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:M},g=>!g)},l=n(e),s=Array.isArray(l)?l:[l],u=n(t,"edges"),f=Array.isArray(u)?u:[u],c=[...s,...f];return shake({insertionMatches:c.map(a=>a.insertionMatch).join(" ").trim(),deletionMatches:c.map(a=>a.deletionMatch).join(" ").trim(),insertions:c.map(a=>a.insertion).join(" ").trim(),deletions:c.map(a=>a.deletion).join(" ").trim()},a=>!a)};var Ie={};function X(e){return {enumerable:!0,value:e}}function Mr(e){return {enumerable:!0,writable:!0,value:e}}var oi=()=>!0,Tr=()=>({}),Sr=e=>e,si=(e,t,r,i)=>e.apply(r,i)&&t.apply(r,i),ai=(e,t,r,[i,o])=>t.call(r,e.call(r,i,o),o),Fe=(e,t)=>Object.freeze(Object.create(e,t));function Qr(e,t,r){return e.reduce((i,o)=>function(...n){return r(i,o,this,n)},t)}function Lr(e){return Fe(this,{fn:X(e)})}var kr={},V=Lr.bind(kr);var Cr={},yt=Lr.bind(Cr);function Ge(e,t){return t.filter(r=>e.isPrototypeOf(r))}function Rr(e,t,...r){let i=Qr(Ge(Cr,r).map(n=>n.fn),oi,si),o=Qr(Ge(kr,r).map(n=>n.fn),Sr,ai);return Fe(this,{from:X(e),to:X(t),guards:X(i),reducers:X(o)})}var Dr={},Ar={},K=Rr.bind(Dr);Rr.bind(Ar,null);function li(e,t,r){return Bt(t,e,r,this.immediates)||e}function Ir(e){let t=new Map;for(let r of e)t.has(r.from)||t.set(r.from,[]),t.get(r.from).push(r);return t}var ci={enter:Sr};function he(...e){let t=Ge(Dr,e),r=Ge(Ar,e),i={final:X(e.length===0),transitions:X(Ir(t))};return r.length&&(i.immediates=X(r),i.enter=X(li)),Fe(ci,i)}var di={enter(e,t,r){let i=this.fn.call(t,t.context,r);return gt.isPrototypeOf(i)?Fe(Or,{machine:X(i),transitions:X(this.transitions)}).enter(e,t,r):(i.then(o=>t.send({type:"done",data:o})).catch(o=>t.send({type:"error",error:o})),e)}},Or={enter(e,t,r){if(t.child=me(this.machine,i=>{t.onChange(i),t.child==i&&i.machine.state.value.final&&(delete t.child,t.send({type:"done",data:i.context}));},t.context,r),t.child.machine.state.value.final){let i=t.child.context;return delete t.child,Bt(t,e,{type:"done",data:i},this.transitions.get("done"))}return e}};function Z(e,...t){let r=X(Ir(t));return gt.isPrototypeOf(e)?Fe(Or,{machine:X(e),transitions:r}):Fe(di,{fn:X(e),transitions:r})}var gt={get state(){return {name:this.current,value:this.states[this.current]}}};function be(e,t,r=Tr){return typeof e!="string"&&(r=t||Tr,t=e,e=Object.keys(t)[0]),Ie._create&&Ie._create(e,t),Fe(gt,{context:X(r),current:X(e),states:X(t)})}function Bt(e,t,r,i){let{context:o}=e;for(let{to:n,guards:l,reducers:s}of i)if(l(o,r)){e.context=s.call(e,o,r);let u=t.original||t,f=Fe(u,{current:X(n),original:{value:u}});Ie._onEnter&&Ie._onEnter(t,n,e.context,o,r);let c=f.state.value;return e.machine=f,e.onChange(e),c.enter(f,e,r)}}function hi(e,t){let r=t.type||t,{machine:i}=e,{value:o,name:n}=i.state;return o.transitions.has(r)?Bt(e,i,t,o.transitions.get(r))||i:(Ie._send&&Ie._send(r,n),i)}var ui={send(e){hi(this,e);}};function me(e,t,r,i){let o=Object.create(ui,{machine:Mr(e),context:Mr(e.context(r,i)),onChange:X(t)});return o.send=o.send.bind(o),o.machine=o.machine.state.value.enter(o.machine,o,i),o}var jr=(e,t)=>{if(!t)return;let r=fi(t);return $i(r,e.query)},fi=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),$i=(e,t)=>produce(e,r=>traverse(r,({value:i})=>{if(isObject(i)){let o=i;Object.keys(o).forEach(n=>{(o[n]===void 0||o[n]===null||isArray(o[n])&&o[n].length===0)&&(t?.returnNulls?o[n]=null:delete o[n]),o[n]===void 0&&delete o[n];}),Object.getOwnPropertySymbols(o).forEach(n=>{delete o[n];}),t?.noMetadata===!0&&Object.keys(o).forEach(n=>{n.startsWith("$")&&delete o[n];});}}));var Wr=(e,t)=>{for(let o of e)if(!("$entity"in o)&&!("$relation"in o)&&(!("$thing"in o)||!("$thingType"in o)))throw new Error("No entity specified in query");let r=Array.isArray(e)?e:[e];return produce(r,o=>traverse(o,n=>{let{value:l,meta:s}=n,u=l;if(isObject(u)){if(u.$id){if(s.nodePath?.includes(".$filter"))return;let f=u.$entity||u.$relation?u:{[`$${u.$thingType}`]:u.$thing},c=x(t,f);if(!c?.name)throw new Error(`Schema not found for ${u.$thing}`);if(u.$path=c.name,Array.isArray(u.$id)||(u.$filterByUnique=!0),c?.idFields?.length!==1)throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in u||"$relation"in u||"$thing"in u){let f=x(t,u);if(!f?.name)throw new Error(`Schema not found for ${u.$thing}`);u.$path=f.name;}if(u.$entity?(u.$thing=u.$entity,u.$thingType="entity",delete u.$entity):u.$relation&&(u.$thing=u.$relation,u.$thingType="relation",delete u.$relation),isObject(u)&&"$thing"in u&&u.$thing){let f=u.$entity||u.$relation?u:{[`$${u.$thingType}`]:u.$thing};u[ae]=s.nodePath;let c=x(t,f);if(u.$filter&&(u.$filterByUnique=wt(u.$filter,c),u.$filter=Oe(u.$filter,u.$thing,t)),u.$fields){u.$fields.some(p=>c?.idFields?.includes(p?.$path||p))||(u.$fields=[...u.$fields,...Array.isArray(c.idFields)?c.idFields:[]],u.$idNotIncluded=!0);let a=u.$fields?.flatMap(p=>{let h=Nr(p,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);u.$fields=a;}else {let a=bt(c)?.flatMap(p=>{let h=Nr(p,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);u.$fields=a;}u.$excludedFields&&(u.$fields=u.$fields.filter(d=>Ye(c,d)?!0:!u.$excludedFields.includes(d.$path)));}}}))},bt=e=>{let t=e.dataFields?.map(n=>n.path)||[],r=e.linkFields?.map(n=>n.path)||[],i=Object.keys(e.roles||{})||[];return [...t,...r,...i]},wt=(e,t)=>Object.keys(e||{}).some(i=>{if(!Array.isArray(e[i])){let o=t.idFields?.includes(i),n=t.dataFields?.some(s=>(s.dbPath===i||s.path===i)&&s?.validations?.unique),l=i==="$id"&&!Array.isArray(e[i]);return o||n||l}return !1}),Ye=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),gi=e=>{let{field:t,fieldStr:r,$justId:i,dbPath:o,isVirtual:n,fieldSchema:l}=e;return {$path:r,$dbPath:o,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:i,$id:t.$id,$isVirtual:n,[le]:l}},Bi=e=>{let{field:t,fieldStr:r,linkField:i,$justId:o,dbPath:n,schema:l,fieldSchema:s}=e,{target:u,oppositeLinkFieldsPlayedBy:f}=i;return f.map(c=>{let d=u==="role"?c.thingType:"relation",a=u==="role"?c.thing:i.relation,p={[`$${d}`]:a},h=x(l,p),$=t?.$fields?.filter(B=>Ye(h,B)).length===0,y=[];if(typeof t!="string")if(t.$fields)if($){let B=h.idFields||[];y=[...t.$fields,...B];}else y=t.$fields;else y=bt(h);else y=["id"];t.$excludedFields&&(y=y.filter(B=>Ye(h,B)?!0:!t.$excludedFields.includes(B.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...Oe(t.$filter,a,l)}:void 0;return {$thingType:d,$plays:i.plays,$playedBy:c,$path:c.path,$dbPath:n,$as:t.$as||r,$var:r,$thing:a,$fields:y,$excludedFields:t.$excludedFields,$fieldType:"link",$target:u,$intermediary:c.relation,$justId:o,$id:t.$id,$filter:m,$idNotIncluded:$,$filterByUnique:wt(t.$filter,h),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[le]:s}})},Ei=e=>{let{field:t,fieldStr:r,roleField:i,$justId:o,dbPath:n,schema:l,fieldSchema:s}=e;return i.playedBy.map(u=>{let{thing:f,thingType:c,relation:d}=u,a={[`$${c}`]:f},p=x(l,a),h=t?.$fields?.filter(m=>p?.idFields?.includes(m)||p?.idFields?.includes(m.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(h){let m=p.idFields||[];$=[...t.$fields,...m];}else $=t.$fields;else $=bt(p);else $=["id"];t.$excludedFields&&($=$.filter(m=>Ye(p,m)?!0:!t.$excludedFields.includes(m.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...Oe(t.$filter,f,l)}:void 0;return {$thingType:c,$path:r,$dbPath:n,$as:t.$as||r,$var:r,$thing:f,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:d,$justId:o,$id:t.$id,$filter:y,$idNotIncluded:h,$filterByUnique:wt(t.$filter,p),$playedBy:u,$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[le]:s}})},Nr=(e,t,r)=>{let i=typeof e=="string"?e:e.$path,o=typeof e=="string",n=t.dataFields?.find(u=>u.path===i),l=t.linkFields?.find(u=>u.path===i),s=t.roles?.[i];if(n){let u=!!n.isVirtual&&!!n.default;return gi({field:e,fieldStr:i,$justId:o,dbPath:n.dbPath,isVirtual:u,fieldSchema:n})}else {if(l)return Bi({field:e,fieldStr:i,linkField:l,$justId:o,dbPath:l.path,schema:r,fieldSchema:l});if(s)return Ei({field:e,fieldStr:i,roleField:s,$justId:o,dbPath:i,schema:r,fieldSchema:s})}return null},Oe=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(l=>Object.keys(l).reduce((f,c)=>{let d=l[c],a=isArray(d)?d:[d];if(c.startsWith("$"))["$id","$thing"].includes(c)?f[c]=d:f[c]=Oe(d,t,r);else {let p=t in r.entities?r.entities[t]:r.relations[t],[h,$]=ze(p,c);if(h==="dataField")f[c]=d;else if(h==="linkField"||h==="roleField"){let y=$,[m]=y.$things;return a.every(B=>typeof B=="string")?f[c]={$id:a,$thing:m}:a.every(B=>isObject(B))&&(f[c]=isArray(d)?{$or:Oe(d,m,r)}:Oe(d,m,r)),f}else throw new Error(`Field ${c} not found in schema of ${t}`)}return f},{}));return i?n.length===1?n[0]:{$or:n}:n[0]};var _r=async(e,t,r)=>r?(n=>produce(n,l=>traverse(l,({value:s})=>{if(isObject(s)){let u=s;if(!u.$thing)return;if(u.$thing){let f=x(e,u),{virtualFields:c}=f,d=u[ae];if(!d)throw new Error("[Internal] QueryPath is missing");let a=getNodeByPath(t,d),p=a.$fields.map($=>$.$path),h=a.$excludedFields;c.forEach($=>{if(h?.includes($)||p.length>0&&!p.includes($))return;let y=f.dataFields?.find(m=>m.path===$);if(y?.default){let m=De({currentThing:u,fieldSchema:y,mandatoryDependencies:!0});u[$]=m;}else if(u[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),h&&h.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete u[$];});}}})))(r):void 0;var zr=e=>e.replace(/`/g,""),Ti=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],Vr=e=>Ti.some(t=>e.includes(t))?`\u27E8\`${e}\`\u27E9`:e;var Hr=e=>{let{queries:t,schema:r}=e;return t.map(i=>Si({query:i,schema:r}))},Si=e=>{let{query:t,schema:r}=e,{$thing:i,$fields:o,$filter:n,$offset:l,$limit:s,$sort:u}=t;if(o.length===0)return null;let f=[];f.push("SELECT");let c=Mt({parentQuery:t,queries:o,level:1,schema:r});c&&f.push(c);let d=r.entities[i]||r.relations[i];if(!d)throw new Error(`Schema for ${i} not found`);let p=(d.subTypes?[i,...d.subTypes]:[i]).map(h=>Vr(h));if(t.$id)if(typeof t.$id=="string")f.push(`FROM ${p.map(h=>`${h}:\`${t.$id}\``).join(",")}`);else if(isArray(t.$id)){let h=t.$id,$=p.flatMap(y=>h?.map(m=>`${y}:\`${m}\``));f.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else f.push(`FROM ${p.join(",")}`);if(n){let h=ye(n,i,r),$=Le(h);f.push(`WHERE ${$}`);}return u&&f.push(Ur(u)),typeof s=="number"&&f.push(`LIMIT ${s}`),typeof l=="number"&&f.push(`START ${l}`),f.join(`
|
|
38
|
+
`)},Mt=e=>{let{queries:t,schema:r,level:i,parentQuery:o}=e,n=[],l=o[ae];return n.push(w(`"${l}" as \`$$queryPath\``,i)),n.push(w("meta::id(id) as `$id`",i)),n.push(w("meta::tb(id) as `$thing`",i)),t.forEach(s=>{let u=Li({query:s,level:i,schema:r});u&&n.push(u);}),n.length===0?null:n.join(`,
|
|
39
|
+
`)},Li=e=>{let{query:t,schema:r,level:i}=e;return t.$fieldType==="data"?ki({query:t,level:i}):t.$fieldType==="link"?Ci({query:t,level:i,schema:r}):t.$fieldType==="role"?Ri({query:t,level:i,schema:r}):null},ki=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?w(`meta::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?w(`\`${t.$path}\``,r):w(`\`${t.$path}\` AS \`${t.$as}\``,r)},Ci=e=>{let{query:t,schema:r,level:i}=e,{$fields:o,$filter:n,$offset:l,$limit:s,$sort:u}=t;if(o.length===0)return null;let f=[];f.push(w("(",i));let c=i+1;f.push(w("SELECT",c));let d=Mt({parentQuery:t,queries:o,level:c+1,schema:r});d&&f.push(d);let a=t[le][Qe].queryPath;if(f.push(w(`FROM ${a}`,c)),n){let p=ye(n,t.$thing,r),h=Le(p);f.push(`WHERE ${h}`);}return u&&f.push(w(Ur(u),c)),typeof s=="number"&&f.push(w(`LIMIT ${s}`,c)),typeof l=="number"&&f.push(w(`START ${l}`,c)),f.push(w(`) AS \`${t.$as}\``,i)),f.join(`
|
|
40
|
+
`)},Ri=e=>{let{query:t,schema:r,level:i}=e;if(t.$fields.length===0)return null;let o=[];o.push(w("(",i));let n=i+1;o.push(w("SELECT",n));let l=n+1,s=Mt({parentQuery:t,queries:t.$fields,level:l,schema:r});s&&o.push(s);let u=t[le][Qe].queryPath;if(o.push(w(`FROM ${u}`,n)),t.$filter){let f=ye(t.$filter,t.$playedBy.thing,r),c=Le(f);o.push(`WHERE ${c}`);}return o.push(w(`) AS \`${t.$as}\``,i)),o.join(`
|
|
41
|
+
`)},ye=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(l=>{let u=Object.keys(l).reduce((f,c)=>{let d=l[c];if(c.startsWith("$"))return c==="$not"?{...f,$not:void 0,"$!":ye(d,t,r)}:c==="$or"?{...f,$or:void 0,$OR:ye(d,t,r)}:c==="$and"?{...f,$and:void 0,$AND:ye(d,t,r)}:c==="$eq"?{...f,$nor:void 0,"$=":ye(d,t,r)}:c==="$id"?{...f,$id:void 0,"meta::id(id)":{$IN:isArray(d)?d:[d]}}:c==="$thing"?f:{...f,[c]:ye(d,t,r)};let a=t in r.entities?r.entities[t]:r.relations[t],[p,h]=ze(a,c);if(p==="dataField"){if(a.idFields.length>1)throw new Error("Multiple id fields not supported");return c===a.idFields[0]?{...f,"meta::id(id)":{$IN:isArray(d)?d:[d]}}:{...f,[c]:d}}if(p==="linkField"||p==="roleField"){let $=h,[y]=$.$things,m=$[Qe].queryPath;return {...f,[m]:ye(d,y,r)}}throw new Error(`Field ${c} not found in schema, Defined in $filter`)},{});return shake(u)});return i?n:n[0]},Le=e=>{if(e==null)return "";let t=Object.entries(e),r=[];return t.forEach(([i,o])=>{if(["$OR","$AND","$!"].includes(i)){let n=i.replace("$",""),l=Array.isArray(o)?o.map(s=>Le(s)):[Le(o)];n==="!"?r.push(`!(${l.join(` ${n} `)})`):r.push(`(${l.join(` ${n} `)})`);return}if(isObject(o))if(i.includes("<-")||i.includes("->")){let n=Le(o);r.push(`${i}[WHERE ${n}]`);}else {if(i.startsWith("$"))throw new Error(`Invalid key ${i}`);if(Object.keys.length===1&&Object.keys(o)[0].startsWith("$")){let[n]=Object.keys(o),l=o[n];if(isArray(l))r.push(`${i} ${n.replace("$","")} [${l.map(s=>`'${s}'`).join(", ")}]`);else if(isObject(l)){let s=Le(l);r.push(`${i} ${n.replace("$","")} ${s}`);}else r.push(`${i} ${n.replace("$","")} '${l}'`);}else throw new Error(`Invalid key ${i}`)}else if(Array.isArray(o)){let n=i.startsWith("$")?i.replace("$",""):"IN";r.push(`${i} ${n} [${o.map(l=>`'${l}'`).join(", ")}]`);}else {let n=i.startsWith("$")?i.replace("$",""):"=";r.push(`${i} ${n} '${o}'`);}}),r.join(" AND ")},Ur=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:i,desc:o}=r;return `${i}${o?" DESC":" ASC"}`}).join(", ")}`;var Jr=async e=>{let{client:t,queries:r}=e,i=`
|
|
43
42
|
BEGIN TRANSACTION;
|
|
44
43
|
${r.join(";")};
|
|
45
44
|
COMMIT TRANSACTION;
|
|
46
|
-
`;return await t.query(i)};var
|
|
47
|
-
${m}`);}let p=
|
|
45
|
+
`;return await t.query(i)};var vr=e=>{let{res:t,queries:r}=e;return t.map((o,n)=>Zr(r[n],o))},Zr=(e,t)=>{if(isArray(t)){if(t.length===0)return null;if(e.$filterByUnique){if(t.length>1)throw new Error("Multiple results found for unique query");return Qt(e,t[0])}if(t.length>=1)return t.map(r=>Qt(e,r))}else throw new Error("res is unexpectedly not an array")},Qt=(e,t)=>{let r={[ae]:t.$$queryPath,$id:t.$id,$thing:zr(t.$thing),$thingType:e.$thingType};return e.$fields.forEach(i=>{let o=i.$as,n=t[o];i.$path==="id"&&e.$idNotIncluded||(r[o]=Di(i,n));}),r},Di=(e,t)=>t==null||isArray(t)&&t.length===0?null:e.$fieldType==="data"?(e[le].cardinality==="ONE"&&isArray(t)&&t[0],t??null):e.$justId?e.$filterByUnique||e[le].cardinality==="ONE"?t[0]?.id??null:t?.map(r=>r.id)??[]:e.$filterByUnique||e[le].cardinality==="ONE"?Qt(e,t[0]):Zr(e,t);var St=K("error","error",V((e,t)=>({...e,error:t.error}))),Ai=be("build",{build:Z(async e=>Hr({queries:e.bql.queries,schema:e.schema}),K("done","run",V((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),St),run:Z(async e=>Jr({client:e.client,queries:oe(e.surql.queries)}),K("done","parse",V((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),St),parse:Z(async e=>vr({res:oe(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),K("done","success",V((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),St),success:he(),error:he()},e=>e),Ii=async e=>new Promise((t,r)=>{me(Ai,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),Gr=async(e,t,r,i)=>Ii({bql:{queries:e},surql:{},schema:t,config:r,client:i,error:null});var Lt="___",Xr=async e=>{let{queries:t,schema:r}=e;return t.map(i=>qi({query:i,schema:r}))},qi=e=>{let{query:t,schema:r}=e,{$path:i,$thing:o,$filter:n,$fields:l,$sort:s,$offset:u,$limit:f,$id:c}=t;if(!i)throw new Error("Path is not defined");let d=[],a=t[ae];if(d.push("match"),d.push(`$${i} isa ${o};`),n||c){let $=Ve(r,t),y={...n,...c?{[$]:c}:{}},m=Dt({$filter:y,$var:i,$thing:o,schema:r,depth:0});d.push(`
|
|
46
|
+
${m}`);}let p=At({schema:r,$thing:o,$var:i,$sort:s,depth:0});p&&d.push(p.match);let h=`M_${v4()}`;if(d.push(`?queryPath${h} = "${a}";`),d.push("fetch"),d.push(`?queryPath${h} as "queryPath";`),l){let $=l.filter(B=>B.$fieldType==="data");$&&$.length>0&&d.push(...kt($,i,0));let y=l.filter(B=>B.$fieldType==="link");y&&y.length>0&&d.push(...Rt(y,i,i,0,r));let m=l.filter(B=>B.$fieldType==="role");m&&m.length>0&&d.push(...Ct(m,i,i,0,r));}return p&&d.push(p.sort),typeof u=="number"&&d.push(`
|
|
48
47
|
offset ${u};`),typeof f=="number"&&d.push(`
|
|
49
48
|
limit ${f};`),d.join(`
|
|
50
|
-
`)},
|
|
51
|
-
?queryPath${
|
|
52
|
-
`)},Ze=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;let[t]=e;return t},G=e=>typeof e=="string"?`'${e}'`:e instanceof Date?`'${e.toISOString().replace("Z","")}'`:isObject(e)&&"$id"in e?isArray(e.$id)?`like "^(${e.$id.join("|")})$"`:`"${e.$id}"`:`${e}`,Qi=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},Rt=e=>{let{$var:t,$thing:r,schema:i,$sort:o,depth:n}=e,l=v(i,r),s=[],u=[];if(o?.forEach(f=>{let c=Qi(f),d=l.dataFields?.find(h=>h.path===c.field);if(!d)throw new Error(`"${r}" does not have data field "${c.field}"`);let a=`${c.field}_${v4()}`;s.push(b("{",n)),s.push(b(`$${t} has ${d.dbPath} $${a}_1;`,n+1)),s.push(b("not {",n+1)),s.push(b(`$${t} has ${d.dbPath} $${a}_2;`,n+2)),s.push(b(`$${a}_2 < $${a}_1;`,n+2)),s.push(b("};",n+1)),s.push(b(`?${a}_ = $${a}_1;`,n+1)),s.push(b("} or {",n)),s.push(b(`not { $${t} has ${d.dbPath} $${a}_1; };`,n+1)),s.push(b(`?${a}_ = "~";`,n+1)),s.push(b("};",n)),s.push(b(`?${a} = ?${a}_;`,n));let p=c.desc?"desc":"asc";u.push(`?${a} ${p}`);}),s.length!==0)return {match:s.join(""),sort:b(`sort ${u.join(", ")};`,n)}};var _r=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:i,config:o,rawTqlRes:n}=e;if(t){if(!n)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");return n.map((l,s)=>{let u=r[s],f=t[s];return Ti(l,u,f,i,o)})},Ti=(e,t,r,i,o)=>e.length===0?null:r.$filterByUnique?zr(e[0],t,i,o):e.map(n=>zr(n,t,i,o)),zr=(e,t,r,i)=>{let{dataFields:o,currentSchema:n,linkFields:l,roleFields:s,schemaValue:u}=At(e,r),f=It(o,n,i),c=qt(l,r,i),d=Ct(s,r,i),a=t?.$fields?.every(h=>!n?.idFields?.includes(typeof h=="string"?h:h.$path));return {...c,...d,...u,...!i.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?f.id:t.$id}:{},...a?Object.fromEntries(Object.entries(f).filter(([h])=>!n?.idFields?.includes(h))):f}},At=(e,t)=>{let r=Object.keys(e),i=r.find(p=>p.endsWith(".$dataFields")),o=r.filter(p=>p.endsWith(".$multiVal"));if(!i)throw new Error("No dataFields");o?.length>0&&o.forEach(p=>{let h=p.replace(/\.\$multiVal$/,""),$=e[p][0][h].attribute;e[i][h]=$;});let n=e[i],l=i.split(".")[i.split(".").length-2];if(n.$metaData=l,n.length===0)throw new Error("No dataFields");let s=n.type,u={$thing:s.label,$thingType:s.root,[ne]:e.queryPath.value},f={[`$${u.$thingType}`]:u.$thing},c=j(t,f),d=r.filter(p=>{let h=te(p.split(".").pop());return !p.endsWith(".$dataFields")&&c.linkFields?.some($=>$.path===h)}).map(p=>{let h=te(p.split(".").pop()),$=te(c.linkFields?.find(y=>y.path===h));return {$linkFields:e[p],$key:h,$metaData:p.split(".")[p.split(".").length-2],$cardinality:$.cardinality}}),a=r.filter(p=>{let h=p.split(".").pop();return h&&!p.endsWith(".$dataFields")&&c.thingType==="relation"&&c.roles?.[h]}).map(p=>{let h=te(p.split(".").pop());return {$roleFields:e[p],$key:h,$metaData:p.split(".")[p.split(".").length-2],$cardinality:c.roles[h].cardinality}});return {dataFields:n,schemaValue:u,currentSchema:c,linkFields:d,roleFields:a}},It=(e,t,r)=>{let{$metaData:i}=e,{as:o}=Li(i),n=Object.entries(e).filter(([l])=>l!=="type"&&!l.startsWith("$")).map(([l,s])=>{let u=t.dataFields?.find(a=>a.path===l||a.dbPath===l),f=l==="id",c=Array.isArray(o)?o.find(a=>a[l])?.[l]:l,d;if(u?.cardinality==="ONE"){if(d=s[0]?s[0].value:r.query?.returnNulls?null:void 0,u.contentType==="DATE"||u.contentType==="FLEX"&&s[0].type.value_type==="datetime"?d=d&&`${d}Z`:u.contentType==="JSON"&&(d=d&&JSON.parse(d)),f)return [[c,d],["$id",d]].filter(([a,p])=>p!==void 0)}else if(u?.cardinality==="MANY"){if(!isArray(s))throw new Error("Typedb fetch has changed its format");if(s.length===0)return r.query?.returnNulls?[[c,null]]:[];u.contentType==="DATE"?d=s.map(a=>`${a.value}Z`):u.contentType==="FLEX"?d=s.map(a=>a.type.value_type==="datetime"?`${a.value}Z`:a.value):u.contentType==="JSON"?d=s.map(a=>a.value&&JSON.parse(a.value)):d=s.map(a=>a.value);}return [[c,d]].filter(([a,p])=>p!==void 0)}).flat();return Object.fromEntries([...n])},Ct=(e,t,r)=>{let i={};return e.forEach(o=>{let{$roleFields:n,$metaData:l,$cardinality:s}=o,{as:u,justId:f,idNotIncluded:c,filterByUnique:d}=Vr(l);if(u===null)return;let a=n.map(p=>{let{dataFields:h,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=At(p,t),Q=It(h,$,r);if(f==="T")return Q.id;{let g=qt(y,t,r),L=Ct(m,t,r),D={...Q};return c==="true"&&$?.idFields?.forEach(A=>delete D[A]),{...D,...g,...L,...B}}});a.length>0?i[u]=s==="MANY"&&d==="false"?a:a[0]:r.query?.returnNulls&&(i[u]=null);}),i},qt=(e,t,r)=>{let i={};return e.forEach(o=>{let{$linkFields:n,$metaData:l,$cardinality:s}=o,{as:u,justId:f,idNotIncluded:c,filterByUnique:d}=Vr(l);if(u===null)return;let a=n.map(p=>{let{dataFields:h,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=At(p,t),Q=It(h,$,r);if(f==="T")return Q.id;{let g=qt(y,t,r),L=Ct(m,t,r),D={...Q};return c==="true"&&$.idFields?.forEach(A=>delete D[A]),{...D,...g,...L,...B}}});i[u]=a.length>0?s==="MANY"&&d==="false"?a:a[0]:r.query?.returnNulls?null:void 0;}),i},Vr=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,i=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,o=/filterByUnique:([a-zA-Z0-9_\-·]+)/,n=e.match(t),l=e.match(r),s=e.match(i),u=e.match(o);return {as:n?n[1]:null,justId:l?l[1]:null,idNotIncluded:s?s[1]:null,filterByUnique:u?u[1]:null}},Li=e=>{try{let r=(o=>{let n=o.replace("$metadata:","");return n=n.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),n=n.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(l,s,u)=>/^{.*}$/.test(u)?`:${u}`:`:${s}"${u}"`),n=n.replace(/\[([^\]]+)\]/g,(l,s)=>`[${s.split(",").map(u=>u.trim().startsWith("{")&&u.trim().endsWith("}")?u.trim():`"${u.trim()}"`).join(",")}]`),n})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var Hr=async e=>{let{tqlRequest:t,dbHandles:r,config:i}=e,o=new TypeDBOptions;o.infer=!0;let{session:n}=await He(r,i),l=await n.transaction(TransactionType.READ,o),[s,u]=await tryit(parallel)(t.length,t,async f=>await l.query.fetch(f).collect());if(s){await l.rollback();let f=s;throw new Error(`Error running TQL query: ${f.errors}`)}return await l.close(),u};var Ci=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,qi=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,Oi=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,Pt=transition("error","error",reduce((e,t)=>({...e,error:t.error}))),Pi=createMachine("build",{build:invoke(async e=>Wr({queries:e.bql.queries,schema:e.schema}),transition("done","run",reduce(qi)),Pt),run:invoke(async e=>Hr({dbHandles:e.handles,tqlRequest:te(e.tql.queries),config:e.config}),transition("done","parse",reduce(Oi)),Pt),parse:invoke(async e=>_r({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:te(e.tql.res)}),transition("done","success",reduce(Ci)),Pt),success:state(),error:state()},e=>e),ji=async e=>new Promise((t,r)=>{interpret(Pi,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),Ur=async(e,t,r,i,o)=>ji({bql:{raw:e,queries:t},tql:{},schema:r,config:i,handles:o,error:null});var Wi=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,jt=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,et=transition("error","error",reduce((e,t)=>({...e,error:t.error}))),zi=createMachine("enrich",{enrich:invoke(async e=>Sr(e.bql.raw,e.schema),transition("done","adapter",reduce(Wi)),et),adapter:invoke(async e=>{let t={};e.bql.queries?.forEach((s,u)=>{let f=e.bql.raw[u],c=v(e.schema,s.$thing),{id:d}=c.defaultDBConnector;if(c.db==="typeDB"){if(!t[d]){let p=e.handles.typeDB?.get(d)?.client;if(!p)throw new Error(`TypeDB client with id "${c.defaultDBConnector.id}" does not exist`);t[d]={db:"typeDB",client:p,rawBql:[],bqlQueries:[],indices:[]};}}else if(c.db==="surrealDB"){if(!t[d]){let p=e.handles.surrealDB?.get(d)?.client;if(!p)throw new Error(`SurrealDB client with id "${c.defaultDBConnector.id}" does not exist`);t[d]={db:"surrealDB",client:p,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${c.db}"`);let a=t[d];a.rawBql.push(f),a.bqlQueries.push(s),a.indices.push(u);});let r=Object.values(t),i=r.map(s=>s.db==="typeDB"?Ur(s.rawBql,s.bqlQueries,e.schema,e.config,e.handles):xr(s.bqlQueries,e.schema,e.config,s.client)),o=await Promise.all(i),n=r.flatMap((s,u)=>{let f=o[u];return s.indices.map((c,d)=>({index:c,result:f[d]}))});return n.sort((s,u)=>s.index<u.index?-1:s.index>u.index?1:0),n.map(({result:s})=>s)},transition("done","postHooks",reduce(jt)),et),postHooks:invoke(async e=>kr(e.schema,te(e.bql.queries),te(e.bql.res)),transition("done","clean",reduce(jt)),et),clean:invoke(async e=>Tr(e.config,te(e.bql.res)),transition("done","success",reduce(jt)),et),success:state(),error:state()},e=>e),_i=async e=>new Promise((t,r)=>{interpret(zi,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),De=async(e,t,r,i)=>_i({bql:{raw:e},schema:t,config:r,handles:i,error:null});var xt="___",Vi=Symbol.for("grandChildOfCreate"),vr=async(e,t,r,i)=>{let o=(E,M)=>Object.keys(E).filter(w=>!w.startsWith("$")&&E[w]!==void 0?M?!j(t,E).dataFields?.find(T=>T.path===w):!0:!1);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===!1)return;let n=[];if(traverse(e,({parent:E,key:M,value:w})=>{E&&M&&!M.includes("$")&&isObject(E)?(Array.isArray(E[M])?E[M]:[E[M]]).forEach(T=>{if(isObject(T)){if(E.$op!=="create")n.includes(T.$op)||n.push(T.$op);else if(T.$op==="delete"||T.$op==="unlink")throw new Error(`Cannot ${T.$op} under a create`)}}):!E&&isObject(w)&&(n.includes(w.$op)||n.push(w.$op));}),!n.includes("delete")&&!n.includes("unlink")&&!n.includes("replace")&&!n.includes("update")&&!n.includes("link"))return;let s=(E=>{let M=(w,F)=>{let T=[],S={},q=["$op","$bzId","$parentKey"],k=["$relation","$entity","$id",...q];for(let P in w)if(!q.includes(P)&&!(k.includes(P)&&!F))if(!P.includes("$")&&(isObject(w[P])||Array.isArray(w[P]))){let K=w[P];if(Array.isArray(K)&&K.length>0)K.forEach(oe=>{let Be={$path:P,...M(oe),...oe.$filter&&{$as:oe.$bzId}};T.find(H=>H.$path===Be.$path&&!H.$filter)||(T=[...T,Be]);});else {let oe={$path:P,...M(K),...!K.$filter&&{$as:K.$bzId}};T=[...T,oe];}}else S[P]=w[P];return {...S,$fields:T}};return E.map(w=>M(w,!0))})(Array.isArray(e)?e:[e]),f=(await De(s,t,r,i)).bql.res,c=(E,M)=>{let w=E.$id||E.id||E.$bzId;if(E.$objectPath){let{$objectPath:F}=E,T=F?.beforePath||"root",S=Array.isArray(F.ids)?`[${F.ids}]`:F.ids;return {beforePath:`${T}.${S}___${F.key}`,ids:w,key:M}}else return {beforePath:"root",ids:w,key:M}},d=(E,M)=>{let w=E?.beforePath||"root",F=(Array.isArray(E?.ids)?`[${E?.ids}]`:E?.ids);return `${w}.${F}___${E?.key}`},a=E=>{if(E.includes("[")&&E.includes("]")){let[M,w,F]=E.split(/[[\]]/);return w.split(",").map(S=>`${M}${S}${F}`)}else return [E]},p={};(E=>produce(E,M=>traverse(M,w=>{let{key:F,parent:T}=w;if(T&&F&&T.$id&&!F.includes("$")){let S=c(T,F),q=d(S);if(Array.isArray(T[F])){let k=[];T[F].forEach(P=>{isObject(P)?(P.$objectPath=S,k.push(P.$id.toString())):P&&k.push(P.toString());}),p[q]={$objectPath:S,$ids:k};}else {let k=T[F];isObject(k)?(p[q]={$objectPath:S,$ids:[k.$id.toString()]},k.$objectPath=S):k&&(p[q]={$objectPath:S,$ids:[k.toString()]});}}})))(f||{});let $=E=>produce(E,M=>traverse(M,w=>{let{key:F,value:T,parent:S}=w;S&&F&&!F.includes("$")&&(Array.isArray(T)||isObject(T))&&!Array.isArray(S)&&(Array.isArray(S[F])?S[F].forEach(q=>{typeof q!="string"&&(q.$objectPath=c(S,F),q.$parentIsCreate=S.$op==="create",q[Vi]=S.$parentIsCreate||S[Symbol.for("grandChildOfCreate")]);}):isObject(S[F])&&(S[F].$parentIsCreate=S.$op==="create",S[F][Symbol.for("grandChildOfCreate")]=S.$parentIsCreate||S[Symbol.for("grandChildOfCreate")],S[F].$objectPath=c(S,F)));})),y=$(e),m=E=>{let M=[];return E.forEach(F=>{if(!F.$id&&!F.id&&!F.$tempId)if(F.$filter){let T=d({...F.$objectPath,key:F.$bzId}),S=p[T];S&&(Array.isArray(S.$ids)?S.$ids:[S.$ids]).forEach(k=>{let P={...F,$id:k,$bzId:`T4_${v4()}`,$filterBzId:F.$bzId};M.push(P);});}else {let T=d(F.$objectPath),S=p[T];S?S?.$ids.forEach(q=>{let k={...F,$id:q,$bzId:`T4_${v4()}`};M.push(k);}):M.push(F);}else M.push(F);}),M.map(F=>{let T={...F};return o(T,!0).forEach(S=>{let q=Array.isArray(T[S])?T[S]:[T[S]],k=m(q);T[S]=k;}),T})},B=m(Array.isArray(y)?y:[y]),Q=$(B),L=(E=>{let M=w=>{let F=H=>{let Z=[],z=[],O=[];return H.forEach(_=>{let ee=o(_,!0);if(ee.length>0){let I=!1;ee.forEach(W=>{(Array.isArray(_[W])?_[W]:[_[W]]).filter(J=>!J.$id&&!J.id&&typeof _=="object").length&&(I=!0);}),I?Z.push(_):z.push(_);}else O.push({..._,$bzId:_.$tempId||`T_${v4()}`});}),{operationWithMultiples:Z,operationWithoutMultiples:z,otherOps:O}},{operationWithMultiples:T,operationWithoutMultiples:S,otherOps:q}=F(w),k=H=>{let z=(()=>{let W={};for(let Y in H){let U=j(t,H);!Y.startsWith("$")&&U.dataFields?.find(J=>J.path===Y)&&(W[Y]=H[Y]);}return W})(),O=Object.keys(H),_=o(H,!0),ee=[],I=(W,Y)=>{if(W===_.length){let J={...Y};O.forEach(X=>{X.startsWith("$")&&(J[X]=H[X]);}),ee.push({...J,...z});return}let U={...Y,[_[W]]:H[_[W]],...me(Y),...z};I(W+1,U),I(W+1,Y);};return I(0,{...me(H)}),ee},P=[];return T.forEach(H=>{let Z=k(H),z=[];Z.forEach(O=>{let _=o(O,!0);if(O.$op==="create")z.push(O);else if(O.$id){let ee=d(O.$objectPath),I=[];if(_.forEach(W=>{let Y=`${ee.includes("undefined")?"root":ee}.${O.$id}${xt}${W}`,U=p[Y];O[W].filter(X=>X.$op==="unlink"||X.$op==="delete"||X.$op==="update").length>0?U&&I.push({key:W,ids:U.$ids}):I.push({key:W,ids:[""]});}),I.length===_.length&&!z.find(W=>W.$id===O.$id))z.push(O);else {let W={...O,$bzId:O.$tempId||`T4_${v4()}`};_.forEach(U=>{let J=O[U].filter(X=>X.$id);J.length>0?W[U]=J:W[U]=void 0;}),o(W,!0).length>0&&z.push(W);}}else if(O.$objectPath){let ee=d(O.$objectPath),I=p[ee]?.$ids||[];I.forEach(W=>{let Y=[];_.forEach(U=>{let J=`${ee}.${W}${xt}${U}`,X=p[J];X&&Y.push({key:U,ids:X.$ids});}),_.length===0?I.filter(J=>!z.find(X=>X.$id===J)).forEach(J=>{z.push({...O,$id:J,$bzId:O.$tempId||`T_${v4()}`});}):Y.length===_.length&&!z.find(U=>U.$id===W)&&(_.forEach(U=>{let J=`${d(O.$objectPath)}.${W}${xt}${U}`,{$ids:X}=p[J],hn=O[U].find(Qe=>!Qe.$id),un=[...X.map(Qe=>({...hn,$id:Qe,$objectPath:{beforePath:O.$objectPath,ids:Qe,key:U}})),...O[U].filter(Qe=>Qe.$id)];O[U]=un;}),z.push({...O,$id:W,$bzId:O.$tempId||`T_${v4()}`}));});}else z.push(O);}),z.forEach(O=>{P.push(O);});}),[...P,...S,...q].filter(H=>o(H).length>0?!0:H.$op!=="update").map(H=>{let Z={...H};return o(Z,!0).forEach(z=>{let O=Array.isArray(Z[z])?Z[z]:[Z[z]],_=M(O);Z[z]=_;}),Z})};return M(E)})(Array.isArray(Q)?Q:[Q]),D=E=>E.map(M=>{let w=o(M,!0),F={...M};return w.forEach(T=>{let S=Array.isArray(M[T])?M[T]:[M[T]],q=[],k=[],P=[],K={},oe=ct(t,M,T);S.filter(I=>I).forEach(I=>{I.$op==="replace"&&I.$id?(K=I,Array.isArray(I.$id)?k=[...k,...I.$id]:k.push(I.$id)):I.$op==="create"&&oe==="ONE"&&I.id?(K=I,Array.isArray(I.id)?P=[...k,...I.id]:P.push(I.id)):q.push(I);});let Be=d(K.$objectPath),Z=a(Be).map(I=>p[I]),z=[];Z.filter(I=>I!=null).forEach(I=>{z=[...z,...I.$ids];});let O=z.filter(I=>!k.includes(I)),_=k.filter(I=>!z.includes(I)),ee=me(K);O.length>0&&q.push({...K,$op:"unlink",$id:O,$bzId:K.$tempId||`T4_${v4()}`,id:void 0,...ee}),_.length>0&&_.forEach(I=>{q.push({...K,$op:"link",$id:I,$bzId:K.$tempId||`T5_${v4()}`,...ee});}),P.length>0&&P.forEach(I=>{q.push({...K,$op:"create",id:I,$bzId:K.$tempId||`T6_${v4()}`,...ee});}),F[T]=D(q);}),F}),A=$(D($(L)));(E=>produce(E,M=>traverse(M,w=>{let{key:F,value:T,parent:S}=w;F&&S&&!F?.includes("$")&&(Array.isArray(T)||isObject(T))&&!Array.isArray(S)&&(Array.isArray(T)?T:[T]).forEach(k=>{let P=k.$filter?{...k.$objectPath,key:k.$filterBzId}:k.$objectPath,K=d(P),oe=p[K],Be=(z,O)=>z.every(_=>O.includes(_)),H=k.$id?Array.isArray(k.$id)?Be(k.$id,oe?oe.$ids:[]):oe?.$ids.includes(k.$id):oe,Z=ct(t,S,k.$objectPath.key);if(k.$op==="link"&&H&&Z==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${d(k.$objectPath)}" because it is already occupied.`);if(k.$op)switch(k.$op){case"delete":if(!H&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${k.$id}" because it is not linked to $id:"${S.$id}"`);break;case"update":if(!H&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${k.$id}" because it is not linked to $id:"${S.$id}"`);break;case"unlink":if(!H&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${k.$id}" because it is not linked to $id:"${S.$id}"`);break;case"link":if(H)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${k.$id}" because it is already linked to $id:"${S.$id}"`);break;}});})))(A);let N=(E=>produce(E,M=>traverse(M,w=>{let{value:F,meta:T}=w;isObject(F)&&(F[Symbol.for("path")]=T.nodePath,delete F.$objectPath,delete F.$parentIsCreate);})))(A);return [...Array.isArray(N)?N:[N]].sort((E,M)=>E.$op==="create"&&M.$op!=="create"?-1:E.$op!=="create"&&M.$op==="create"?1:0)};var Zr=(e,t)=>produce(e,i=>rt(t,i)),rt=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(o=>rt(e,o,r));return}let i=v(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([o])=>{o.startsWith("$")||Ki(e,t,o,i);});},Ki=(e,t,r,i)=>{let o=t[r];if(!o)return;let n=i.dataFields?.find(s=>s.path===r);if(n){n.contentType==="JSON"&&o!=null&&(t[r]=JSON.stringify(o));return}let l=i.linkFields?.find(s=>s.path===r);if(l){let s=l.oppositeLinkFieldsPlayedBy[0]?.thing;rt(e,o,s);return}if(i.thingType==="relation"){let s=i.roles[r],[u]=s.playedBy||[];if(!u)throw new Error(`Role ${s.name} in ${i} is not played by anything`);rt(e,o,u.thing);}};var en=async(e,t,r,i)=>{let o=Array.isArray(e)?e:[e],n=o.map(u=>Nt(u,!0)),s=(await De(n,t,r,i)).bql.res;return o.map((u,f)=>{let c=v(t,u.$thing);return rn({mut:u,node:s[f],schema:t,thing:c})})},tn=new Set(["$op","$bzId","$parentKey"]),Ji=new Set(["$relation","$entity","$id",...tn]),Nt=(e,t)=>{let r={};e.$fields?.forEach(o=>{typeof o=="string"?r[o]=o:r[o.$path]=o;});let i={};for(let o in e){if(tn.has(o)||Ji.has(o)&&!t)continue;let n=e[o];o.startsWith("$")?i[o]=n:Array.isArray(n)?n[0]&&typeof n[0]=="object"&&(r[o]={$path:o,...Nt(n[0],!1)}):isObject(n)&&(r[o]={$path:o,...Nt(n,!1)});}return i.$fields=Object.values(r),i},rn=e=>{let{mut:t,node:r,schema:i,thing:o}=e,n=on(o),l=Zi(r);if(Array.isArray(t))return t.map(u=>{let f=l[u.$id];return f?Yr({mut:u,node:f,schema:i,thing:o,...n}):u});let s=l[t.$id];return Yr({mut:t,node:s,schema:i,thing:o,...n})},Yr=e=>{let{mut:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}=e,{$fields:u,...f}=t;if(!r)return f;let c=nn({$fields:t.$fields,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}),d={...f,[Me]:c};for(let a in t){if(a.startsWith("$"))continue;let p=t[a];if(n[a]||!p||typeof p!="object"){d[a]=p;continue}let $=l[a]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[a]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${a}"`);let y=v(i,$);d[a]=rn({mut:p,schema:i,node:r[a],thing:y});}return d},nn=e=>{let{$fields:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}=e,u=t||vi(o),f={$id:r.$id};return u.forEach(c=>{let d=typeof c!="string",a=d?c.$path:c,p=r[a];if(n[a]){f[a]=p;return}let $=l[a]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[a]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${a}"`);if(!d){p&&(f[a]=Array.isArray(p)?p.map(Xr):Xr(p));return}let y=v(i,$),m=on(y);f[a]=Array.isArray(p)?p.map(B=>Gr({...m,$fields:c.$fields,value:B,schema:i,thing:y})):Gr({...m,$fields:c.$fields,value:p,schema:i,thing:y});}),f},vi=e=>{let t=[];return e.dataFields?.forEach(r=>{t.push(r.path);}),e.linkFields?.forEach(r=>{t.push(r.path);}),e.thingType==="relation"&&t.push(...Object.keys(e.roles)),t},Xr=e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);if(typeof e.$id!="string")throw new Error(`"${JSON.stringify(e)}" is does not have prop "$id"`);return e.$id},Gr=e=>{let{value:t}=e;if(!t||typeof t!="object"||!t.$id)throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);return nn({...e,node:t})},on=e=>{let t=Object.fromEntries(e.dataFields?.map(o=>[o.path,o])||[]),r=Object.fromEntries(e.linkFields?.map(o=>[o.path,o])||[]),i=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:r,roleFieldMap:i}},Zi=e=>{if(!Array.isArray(e))return e&&typeof e=="object"&&e.$id?{[e.$id]:e}:{};let t={};return e.forEach(r=>{!r||typeof r!="object"||!r.$id||(t[r.$id]=r);}),t};var an=state,Re=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,eo=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),to=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),ro=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),no=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),io=async e=>Object.keys(e.bql.current).length?ft(e.bql.current,e.schema,e.config):ft(e.bql.raw,e.schema,e.config),oo=async e=>vr(e.bql.current,e.schema,e.config,e.handles),so=async e=>en(e.bql.current,e.schema,e.config,e.handles),ao=async e=>Er(e.bql.current,e.schema),lo=async e=>wr(e.bql.things,e.bql.edges,e.schema),co=async e=>fr(e.typeDB.tqlMutation,e.handles,e.config),ho=async e=>$r(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.schema,e.config),uo=()=>!0,po=e=>Se(e.bql.current),ge=transition("error","error",reduce((e,t)=>({...e,error:t.error}))),fo=createMachine("stringify",{stringify:invoke(async e=>Zr(e.bql.raw,e.schema),transition("done","enrich",reduce(Re)),ge),enrich:invoke(io,transition("done","preQuery",guard(uo),reduce(Re)),transition("done","parseBQL",reduce(Re)),ge),preHookDependencies:invoke(so,transition("done","enrich",reduce(Re)),ge),preQuery:invoke(oo,transition("done","preHookDependencies",guard(po),reduce(Re)),transition("done","parseBQL",reduce(Re)),ge),parseBQL:invoke(ao,transition("done","buildMutation",reduce(to)),ge),buildMutation:invoke(lo,transition("done","runMutation",reduce(ro)),ge),runMutation:invoke(co,transition("done","parseMutation",reduce(no)),ge),parseMutation:invoke(ho,transition("done","success",reduce(eo)),ge),success:an(),error:an()},e=>e),$o=async e=>new Promise((t,r)=>{interpret(fo,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),ln=async(e,t,r,i)=>$o({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:r,handles:i,depthLevel:0,error:null});enableMapSet();var Wt=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 i=>{if(i.provider==="surrealDB"){let o=new Surreal;await o.connect(i.url,{namespace:i.namespace,database:i.dbName,auth:{namespace:i.namespace,database:i.dbName,username:i.username,password:i.password}}),t.surrealDB.set(i.id,{client:o});}if(i.provider==="typeDB"&&i.dbName){let[o,n]=await tryit(TypeDB.coreDriver)(i.url);if(o){let l=`[BORM:${i.provider}:${i.dbName}:core] ${o.message??"Can't create TypeDB Client"}`;throw new Error(l)}try{let l=await n.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:n,session:l});}catch(l){let s=`[BORM:${i.provider}:${i.dbName}:session] ${(l.messageTemplate?._messageBody()||l.message)??"Can't create TypeDB Session"}`;throw new Error(s)}}if(i.provider==="typeDBCluster"&&i.dbName){let o=new TypeDBCredential(i.username,i.password,i.tlsRootCAPath),[n,l]=await tryit(TypeDB.cloudDriver)(i.addresses,o);if(n){let s=`[BORM:${i.provider}:${i.dbName}:core] ${n.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await l.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:l,session:s});}catch(s){let u=`[BORM:${i.provider}:${i.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(u)}}}));let r=Yt(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()=>(await this.#e(),_t(this.config,this.schema,this.dbHandles));query=async(t,r)=>{await this.#e();let i={...this.config,query:{...it.query,...this.config.query,...r}},o=Array.isArray(t),n=o?t:[t],[l,s]=await tryit(De)(n,this.schema,i,this.dbHandles);if(l){let f=new Error(l.error);throw f.stack=l.error.stack,f}let u=s.bql.res;return o?u:u[0]};mutate=async(t,r)=>{await this.#e();let i={...this.config,mutation:{...it.mutation,...this.config.mutation,...r}},[o,n]=await tryit(ln)(t,this.schema,i,this.dbHandles);if(o){let s=new Error(o.error.message);throw s.stack=o.error.stack,s}return n.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();});}},gc=Wt;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
49
|
+
`)},kt=(e,t,r)=>{let i=[],o=[],n=[];for(let c=0;c<e.length;c++)e[c].$isVirtual||i.push(e[c].$dbPath),e[c][le].contentType==="FLEX"&&n.push({path:e[c][le].dbPath}),o.push(`{${e[c].$dbPath}:${e[c].$as}}`);let l=i.join(", "),u=`$metadata:{as:[${o.join(",")}]}`,f=[w(`$${t} as "${t}.${u}.$dataFields": ${l};`,r)];return n.length>0&&n.forEach(c=>{f.push(w(`"${c.path}.$multiVal": {match $${t} has ${c.path} $${c.path}; fetch $${c.path}: attribute;};`,r));}),f},Ct=(e,t,r,i,o)=>{let n=i+1,l=[];for(let s of e){let{$fields:u,$as:f,$justId:c,$idNotIncluded:d,$filterByUnique:a,$thing:p,$sort:h,$offset:$,$limit:y}=s,m=s[ae],B=`$metadata:{as:${f},justId:${c?"T":"F"},idNotIncluded:${d},filterByUnique:${a}}`;l.push(w(`"${r}.${B}.${s.$var}": {`,i)),l.push(w("match",n));let M=`${t}${Lt}${s.$var}`;if(l.push(w(`$${M} isa ${s.$thing};`,n)),l.push(w(`$${t} (${s.$var}: $${t}${Lt}${s.$var}) isa ${s.$intermediary};`,n)),s.$filter||s.$id){let S=Ve(o,s),C=s.$id?{[S]:s.$id}:{},D={...s.$filter,...C};l.push(Dt({$filter:D,$var:M,$thing:s.$thing,schema:o,depth:n}));}let g=At({schema:o,$thing:p,$var:M,$sort:h,depth:n});if(g&&l.push(g.match),u){let S=`M_${v4()}`;l.push(w(`
|
|
50
|
+
?queryPath${S} = "${m}";`,n)),l.push(w("fetch",n)),l.push(w(`?queryPath${S} as "queryPath";`,n));let C=u?.filter(j=>j.$fieldType==="data");C&&C.length>0&&l.push(...kt(C,M,n));let D=u?.filter(j=>j.$fieldType==="link");D&&D.length>0&&l.push(...Rt(D,M,`${t}.${s.$var}`,n,o));let I=u?.filter(j=>j.$fieldType==="role");I&&I.length>0&&l.push(...Ct(I,M,`${t}.${s.$var}`,n,o));}g&&l.push(g.sort),typeof $=="number"&&l.push(w(`offset ${$};`,n)),typeof y=="number"&&l.push(w(`limit ${y};`,n)),l.push(w("};",i));}return l},Rt=(e,t,r,i,o)=>{let n=i+1,l=[];for(let s of e){let{$fields:u,$as:f,$justId:c,$idNotIncluded:d,$filterByUnique:a,$playedBy:p,$thing:h,$sort:$,$offset:y,$limit:m}=s,B=s[ae],M=`$metadata:{as:${f},justId:${c?"T":"F"},idNotIncluded:${d},filterByUnique:${a}}`;l.push(w(`"${r}.${M}.${s.$var}": {`,i)),l.push(w("match",n));let g=`${t}${Lt}${s.$var}`;if(l.push(w(`$${g} isa ${s.$thing};`,n)),s.$filter||s.$id){let C=Ve(o,s),D=s.$id?{[C]:s.$id}:{},I={...s.$filter,...D};l.push(Dt({$filter:I,$var:g,$thing:s.$thing,schema:o,depth:n}));}let S=At({schema:o,$thing:h,$var:g,$sort:$,depth:n});if(S&&l.push(S.match),s.$target==="role"?l.push(w(`$${t}_intermediary (${s.$plays}: $${t}, ${p.plays}: $${g}) isa ${s.$intermediary};`,n)):l.push(w(`$${g} (${s.$plays}: $${t});`,n)),u){let C=`M_${v4()}`;l.push(w(`?queryPath${C} = "${B}";`,n)),l.push(w("fetch",n)),l.push(w(`?queryPath${C} as "queryPath";`,n));let D=u?.filter(N=>N.$fieldType==="data");D&&D.length>0&&l.push(...kt(D,g,n));let I=u?.filter(N=>N.$fieldType==="link");I&&I.length>0&&l.push(...Rt(I,g,`${t}.${s.$var}`,n,o));let j=u?.filter(N=>N.$fieldType==="role");j&&j.length>0&&l.push(...Ct(j,g,`${t}.${s.$var}`,n,o));}S&&l.push(S.sort),typeof y=="number"&&l.push(w(`offset ${y};`,n)),typeof m=="number"&&l.push(w(`limit ${m};`,n)),l.push(w("};",i));}return l},xi=(e,t)=>{let r={};if(t.dataFields?.forEach(l=>{l.path!==l.dbPath&&(r[l.path]=l.dbPath);}),Object.keys(r).length===0)return e;let{$not:i,...o}=e,n=Yr(o,r);return i&&(n.$not=Yr(i,r)),n},Yr=(e,t)=>{let r={};return Object.entries(e).forEach(([i,o])=>{let n=t[i]||i;r[n]=o;}),r},Dt=e=>{let{$filter:t,$var:r,$thing:i,schema:o,depth:n}=e,l=xi(t,Y(o,i)),{$not:s,...u}=l,f=Y(o,i),c=[];return Object.entries(s||{}).forEach(([d,a])=>{if(d.startsWith("$"))return;if(f.dataFields?.find($=>$.dbPath===d)){a===null?c.push(w(`$${r} has ${d} $${d}_${v4()};`,n)):Array.isArray(a)?a.forEach($=>{c.push(w(`not { $${r} has ${d} ${ne($)}; };`,n));}):c.push(w(`not { $${r} has ${d} ${ne(a)}; };`,n));return}let h=f.linkFields?.find($=>$.path===d);if(h){let[$]=h.oppositeLinkFieldsPlayedBy,m=Y(o,$.thing).idFields?.[0];if(!m)throw new Error(`"${$.thing}" does not have an id field`);if(h.target==="relation")a===null?c.push(w(`(${h.plays}: $${r}) isa ${h.relation};`,n)):Array.isArray(a)?a.forEach(B=>{c.push(w(`not { (${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ne(B)}; };`,n));}):c.push(w(`not { (${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ne(a)}; };`,n));else {let B=`${$.thing}_${v4()}`;a===null?c.push(w(`$${B} isa ${$.thing}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation};`,n)):Array.isArray(a)?a.forEach(M=>{c.push(w(`not { $${B} isa ${$.thing}, has ${m} ${ne(M)}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation}; };`,n));}):c.push(w(`not { $${B} isa ${$.thing}, has ${m} ${ne(a)}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation}; };`,n));}return}if(f.thingType==="relation"){let $=f.roles[d];if($){let[y]=$.playedBy||[],B=Y(o,y.thing).idFields?.[0];if(!B)throw new Error(`"${y.thing}" does not have an id field`);let M=`${y.thing}_${v4()}`,g=v4(),S=`${r}_${g}`;a===null?(c.push(w(`$${S} isa ${i};`,n)),c.push(w(`$${S} (${y.plays}: ${M});`,n)),c.push(w(`$${r} is $${S};`,n))):Array.isArray(a)?a.forEach(C=>{c.push(w(`$${S} isa ${i};`,n)),c.push(w(`not { $${M} isa ${y.thing}, has ${B} ${ne(C)}; $${S} (${y.plays}: $${M}); };`,n)),c.push(w(`$${r} is $${S};`,n));}):(c.push(w(`$${S} isa ${i};`,n)),c.push(w(`not { $${M} isa ${y.thing}, has ${B} ${ne(a)}; $${S} (${y.plays}: $${M}); };`,n)),c.push(w(`$${r} is $${S};`,n)));return}}}),Object.entries(u).forEach(([d,a])=>{if(d.startsWith("$"))return;if(f.dataFields?.find($=>$.dbPath===d)){if(a===null)c.push(w(`not { $${r} has ${d} $${d}_${v4()}; };`,n));else if(Array.isArray(a)){let $=a.map(m=>`$${r} has ${d} ${ne(m)};`),y=Xe($);y&&c.push(w(y,n));}else c.push(w(`$${r} has ${d} ${ne(a)};`,n));return}let h=f.linkFields?.find($=>$.path===d);if(h){let[$]=h.oppositeLinkFieldsPlayedBy,m=Y(o,$.thing).idFields?.[0];if(!m)throw new Error(`"${$.thing}" does not have an id field`);if(h.target==="relation")if(a===null)c.push(w(`not { (${h.plays}: $${r}) isa ${h.relation}; };`,n));else if(Array.isArray(a)){let B=a.map(g=>`(${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ne(g)};`),M=Xe(B);M&&c.push(w(M,n));}else c.push(w(`(${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ne(a)};`,n));else {let B=`${$.thing}_${v4()}`;if(a===null)c.push(w(`not { $${B} isa ${$.thing}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation}; };`,n));else if(Array.isArray(a)){let M=a.map(S=>`$${B} isa ${$.thing}, has ${m} ${ne(S)}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation};`),g=Xe(M);g&&c.push(w(g,n));}else c.push(w(`$${B} isa ${$.thing}, has ${m} ${ne(a)}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation};`,n));}return}if(f.thingType==="relation"){let $=f.roles[d];if($){let[y]=$.playedBy||[],B=Y(o,y.thing).idFields?.[0];if(!B)throw new Error(`"${y.thing}" does not have an id field`);let M=`${y.thing}_${v4()}`,g=v4(),S=`${r}_${g}`;if(a===null)c.push(w(`$${S} isa ${i};`,n)),c.push(w(`not { $${S} (${y.plays}: ${M}); };`,n)),c.push(w(`$${r} is $${S};`,n));else if(Array.isArray(a)){let C=a.map(I=>`$${M} isa ${y.thing}, has ${B} ${ne(I)}; $${S} (${y.plays}: $${M});`),D=Xe(C);D&&(c.push(w(`$${S} isa ${i};`,n)),c.push(w(D,n)),c.push(w(`$${r} is $${S};`,n)));}else c.push(w(`$${S} isa ${i};`,n)),c.push(w(`$${M} isa ${y.thing}, has ${B} ${ne(a)}; $${S} (${y.plays}: $${M});`,n)),c.push(w(`$${r} is $${S};`,n));return}}throw new Error(`"${i}" does not have property "${d}"`)}),c.join(`
|
|
51
|
+
`)},Xe=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;let[t]=e;return t},ne=e=>typeof e=="string"?`'${e}'`:e instanceof Date?`'${e.toISOString().replace("Z","")}'`:isObject(e)&&"$id"in e?isArray(e.$id)?`like "^(${e.$id.join("|")})$"`:`"${e.$id}"`:`${e}`,ji=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},At=e=>{let{$var:t,$thing:r,schema:i,$sort:o,depth:n}=e,l=Y(i,r),s=[],u=[];if(o?.forEach(f=>{let c=ji(f),d=l.dataFields?.find(h=>h.path===c.field);if(!d)throw new Error(`"${r}" does not have data field "${c.field}"`);let a=`${c.field}_${v4()}`;s.push(w("{",n)),s.push(w(`$${t} has ${d.dbPath} $${a}_1;`,n+1)),s.push(w("not {",n+1)),s.push(w(`$${t} has ${d.dbPath} $${a}_2;`,n+2)),s.push(w(`$${a}_2 < $${a}_1;`,n+2)),s.push(w("};",n+1)),s.push(w(`?${a}_ = $${a}_1;`,n+1)),s.push(w("} or {",n)),s.push(w(`not { $${t} has ${d.dbPath} $${a}_1; };`,n+1)),s.push(w(`?${a}_ = "~";`,n+1)),s.push(w("};",n)),s.push(w(`?${a} = ?${a}_;`,n));let p=c.desc?"desc":"asc";u.push(`?${a} ${p}`);}),s.length!==0)return {match:s.join(""),sort:w(`sort ${u.join(", ")};`,n)}};var tn=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:i,config:o,rawTqlRes:n}=e;if(t){if(!n)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");return n.map((l,s)=>{let u=r[s],f=t[s];return Wi(l,u,f,i,o)})},Wi=(e,t,r,i,o)=>e.length===0?null:r.$filterByUnique?en(e[0],t,i,o):e.map(n=>en(n,t,i,o)),en=(e,t,r,i)=>{let{dataFields:o,currentSchema:n,linkFields:l,roleFields:s,schemaValue:u}=It(e,r),f=Ot(o,n,i),c=qt(l,r,i),d=Pt(s,r,i),a=t?.$fields?.every(h=>!n?.idFields?.includes(typeof h=="string"?h:h.$path));return {...c,...d,...u,...!i.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?f.id:t.$id}:{},...a?Object.fromEntries(Object.entries(f).filter(([h])=>!n?.idFields?.includes(h))):f}},It=(e,t)=>{let r=Object.keys(e),i=r.find(p=>p.endsWith(".$dataFields")),o=r.filter(p=>p.endsWith(".$multiVal"));if(!i)throw new Error("No dataFields");o?.length>0&&o.forEach(p=>{let h=p.replace(/\.\$multiVal$/,""),$=e[p][0][h].attribute;e[i][h]=$;});let n=e[i],l=i.split(".")[i.split(".").length-2];if(n.$metaData=l,n.length===0)throw new Error("No dataFields");let s=n.type,u={$thing:s.label,$thingType:s.root,[ae]:e.queryPath.value},f={[`$${u.$thingType}`]:u.$thing},c=x(t,f),d=r.filter(p=>{let h=oe(p.split(".").pop());return !p.endsWith(".$dataFields")&&c.linkFields?.some($=>$.path===h)}).map(p=>{let h=oe(p.split(".").pop()),$=oe(c.linkFields?.find(y=>y.path===h));return {$linkFields:e[p],$key:h,$metaData:p.split(".")[p.split(".").length-2],$cardinality:$.cardinality}}),a=r.filter(p=>{let h=p.split(".").pop();return h&&!p.endsWith(".$dataFields")&&c.thingType==="relation"&&c.roles?.[h]}).map(p=>{let h=oe(p.split(".").pop());return {$roleFields:e[p],$key:h,$metaData:p.split(".")[p.split(".").length-2],$cardinality:c.roles[h].cardinality}});return {dataFields:n,schemaValue:u,currentSchema:c,linkFields:d,roleFields:a}},Ot=(e,t,r)=>{let{$metaData:i}=e,{as:o}=_i(i),n=Object.entries(e).filter(([l])=>l!=="type"&&!l.startsWith("$")).map(([l,s])=>{let u=t.dataFields?.find(a=>a.path===l||a.dbPath===l),f=l==="id",c=Array.isArray(o)?o.find(a=>a[l])?.[l]:l,d;if(u?.cardinality==="ONE"){if(d=s[0]?s[0].value:r.query?.returnNulls?null:void 0,u.contentType==="DATE"||u.contentType==="FLEX"&&s[0].type.value_type==="datetime"?d=d&&`${d}Z`:u.contentType==="JSON"&&(d=d&&JSON.parse(d)),f)return [[c,d],["$id",d]].filter(([a,p])=>p!==void 0)}else if(u?.cardinality==="MANY"){if(!isArray(s))throw new Error("Typedb fetch has changed its format");if(s.length===0)return r.query?.returnNulls?[[c,null]]:[];u.contentType==="DATE"?d=s.map(a=>`${a.value}Z`):u.contentType==="FLEX"?d=s.map(a=>a.type.value_type==="datetime"?`${a.value}Z`:a.value):u.contentType==="JSON"?d=s.map(a=>a.value&&JSON.parse(a.value)):d=s.map(a=>a.value);}return [[c,d]].filter(([a,p])=>p!==void 0)}).flat();return Object.fromEntries([...n])},Pt=(e,t,r)=>{let i={};return e.forEach(o=>{let{$roleFields:n,$metaData:l,$cardinality:s}=o,{as:u,justId:f,idNotIncluded:c,filterByUnique:d}=rn(l);if(u===null)return;let a=n.map(p=>{let{dataFields:h,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=It(p,t),M=Ot(h,$,r);if(f==="T")return M.id;{let g=qt(y,t,r),S=Pt(m,t,r),C={...M};return c==="true"&&$?.idFields?.forEach(D=>delete C[D]),{...C,...g,...S,...B}}});a.length>0?i[u]=s==="MANY"&&d==="false"?a:a[0]:r.query?.returnNulls&&(i[u]=null);}),i},qt=(e,t,r)=>{let i={};return e.forEach(o=>{let{$linkFields:n,$metaData:l,$cardinality:s}=o,{as:u,justId:f,idNotIncluded:c,filterByUnique:d}=rn(l);if(u===null)return;let a=n.map(p=>{let{dataFields:h,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=It(p,t),M=Ot(h,$,r);if(f==="T")return M.id;{let g=qt(y,t,r),S=Pt(m,t,r),C={...M};return c==="true"&&$.idFields?.forEach(D=>delete C[D]),{...C,...g,...S,...B}}});i[u]=a.length>0?s==="MANY"&&d==="false"?a:a[0]:r.query?.returnNulls?null:void 0;}),i},rn=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,i=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,o=/filterByUnique:([a-zA-Z0-9_\-·]+)/,n=e.match(t),l=e.match(r),s=e.match(i),u=e.match(o);return {as:n?n[1]:null,justId:l?l[1]:null,idNotIncluded:s?s[1]:null,filterByUnique:u?u[1]:null}},_i=e=>{try{let r=(o=>{let n=o.replace("$metadata:","");return n=n.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),n=n.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(l,s,u)=>/^{.*}$/.test(u)?`:${u}`:`:${s}"${u}"`),n=n.replace(/\[([^\]]+)\]/g,(l,s)=>`[${s.split(",").map(u=>u.trim().startsWith("{")&&u.trim().endsWith("}")?u.trim():`"${u.trim()}"`).join(",")}]`),n})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var nn=async e=>{let{tqlRequest:t,dbHandles:r,config:i}=e,o=new TypeDBOptions;o.infer=!0;let{session:n}=await ve(r,i),l=await n.transaction(TransactionType.READ,o),[s,u]=await tryit(parallel)(t.length,t,async f=>await l.query.fetch(f).collect());if(s){await l.rollback();let f=s;throw new Error(`Error running TQL query: ${f.errors}`)}return await l.close(),u};var Ui=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,Ji=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,vi=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,xt=K("error","error",V((e,t)=>({...e,error:t.error}))),Zi=be("build",{build:Z(async e=>Xr({queries:e.bql.queries,schema:e.schema}),K("done","run",V(Ji)),xt),run:Z(async e=>nn({dbHandles:e.handles,tqlRequest:oe(e.tql.queries),config:e.config}),K("done","parse",V(vi)),xt),parse:Z(async e=>tn({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:oe(e.tql.res)}),K("done","success",V(Ui)),xt),success:he(),error:he()},e=>e),Gi=async e=>new Promise((t,r)=>{me(Zi,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),on=async(e,t,r,i,o)=>Gi({bql:{raw:e,queries:t},tql:{},schema:r,config:i,handles:o,error:null});var Yi=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,jt=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,et=K("error","error",V((e,t)=>({...e,error:t.error}))),Xi=be("enrich",{enrich:Z(async e=>Wr(e.bql.raw,e.schema),K("done","adapter",V(Yi)),et),adapter:Z(async e=>{let t={};e.bql.queries?.forEach((s,u)=>{let f=e.bql.raw[u],c=Y(e.schema,s.$thing),{id:d}=c.defaultDBConnector;if(c.db==="typeDB"){if(!t[d]){let p=e.handles.typeDB?.get(d)?.client;if(!p)throw new Error(`TypeDB client with id "${c.defaultDBConnector.id}" does not exist`);t[d]={db:"typeDB",client:p,rawBql:[],bqlQueries:[],indices:[]};}}else if(c.db==="surrealDB"){if(!t[d]){let p=e.handles.surrealDB?.get(d)?.client;if(!p)throw new Error(`SurrealDB client with id "${c.defaultDBConnector.id}" does not exist`);t[d]={db:"surrealDB",client:p,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${c.db}"`);let a=t[d];a.rawBql.push(f),a.bqlQueries.push(s),a.indices.push(u);});let r=Object.values(t),i=r.map(s=>s.db==="typeDB"?on(s.rawBql,s.bqlQueries,e.schema,e.config,e.handles):Gr(s.bqlQueries,e.schema,e.config,s.client)),o=await Promise.all(i),n=r.flatMap((s,u)=>{let f=o[u];return s.indices.map((c,d)=>({index:c,result:f[d]}))});return n.sort((s,u)=>s.index<u.index?-1:s.index>u.index?1:0),n.map(({result:s})=>s)},K("done","postHooks",V(jt)),et),postHooks:Z(async e=>_r(e.schema,oe(e.bql.queries),oe(e.bql.res)),K("done","clean",V(jt)),et),clean:Z(async e=>jr(e.config,oe(e.bql.res)),K("done","success",V(jt)),et),success:he(),error:he()},e=>e),eo=async e=>new Promise((t,r)=>{me(Xi,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),Pe=async(e,t,r,i)=>eo({bql:{raw:e},schema:t,config:r,handles:i,error:null});var Nt="___",to=Symbol.for("grandChildOfCreate"),sn=async(e,t,r,i)=>{let o=(E,T)=>Object.keys(E).filter(b=>!b.startsWith("$")&&E[b]!==void 0?T?!x(t,E).dataFields?.find(Q=>Q.path===b):!0:!1);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===!1)return;let n=[];if(traverse(e,({parent:E,key:T,value:b})=>{E&&T&&!T.includes("$")&&isObject(E)?(Array.isArray(E[T])?E[T]:[E[T]]).forEach(Q=>{if(isObject(Q)){if(E.$op!=="create")n.includes(Q.$op)||n.push(Q.$op);else if(Q.$op==="delete"||Q.$op==="unlink")throw new Error(`Cannot ${Q.$op} under a create`)}}):!E&&isObject(b)&&(n.includes(b.$op)||n.push(b.$op));}),!n.includes("delete")&&!n.includes("unlink")&&!n.includes("replace")&&!n.includes("update")&&!n.includes("link"))return;let s=(E=>{let T=(b,F)=>{let Q=[],L={},O=["$op","$bzId","$parentKey"],k=["$relation","$entity","$id",...O];for(let q in b)if(!O.includes(q)&&!(k.includes(q)&&!F))if(!q.includes("$")&&(isObject(b[q])||Array.isArray(b[q]))){let J=b[q];if(Array.isArray(J)&&J.length>0)J.forEach(ce=>{let Me={$path:q,...T(ce),...ce.$filter&&{$as:ce.$bzId}};Q.find(U=>U.$path===Me.$path&&!U.$filter)||(Q=[...Q,Me]);});else {let ce={$path:q,...T(J),...!J.$filter&&{$as:J.$bzId}};Q=[...Q,ce];}}else L[q]=b[q];return {...L,$fields:Q}};return E.map(b=>T(b,!0))})(Array.isArray(e)?e:[e]),f=(await Pe(s,t,r,i)).bql.res,c=(E,T)=>{let b=E.$id||E.id||E.$bzId;if(E.$objectPath){let{$objectPath:F}=E,Q=F?.beforePath||"root",L=Array.isArray(F.ids)?`[${F.ids}]`:F.ids;return {beforePath:`${Q}.${L}___${F.key}`,ids:b,key:T}}else return {beforePath:"root",ids:b,key:T}},d=(E,T)=>{let b=E?.beforePath||"root",F=(Array.isArray(E?.ids)?`[${E?.ids}]`:E?.ids);return `${b}.${F}___${E?.key}`},a=E=>{if(E.includes("[")&&E.includes("]")){let[T,b,F]=E.split(/[[\]]/);return b.split(",").map(L=>`${T}${L}${F}`)}else return [E]},p={};(E=>produce(E,T=>traverse(T,b=>{let{key:F,parent:Q}=b;if(Q&&F&&Q.$id&&!F.includes("$")){let L=c(Q,F),O=d(L);if(Array.isArray(Q[F])){let k=[];Q[F].forEach(q=>{isObject(q)?(q.$objectPath=L,k.push(q.$id.toString())):q&&k.push(q.toString());}),p[O]={$objectPath:L,$ids:k};}else {let k=Q[F];isObject(k)?(p[O]={$objectPath:L,$ids:[k.$id.toString()]},k.$objectPath=L):k&&(p[O]={$objectPath:L,$ids:[k.toString()]});}}})))(f||{});let $=E=>produce(E,T=>traverse(T,b=>{let{key:F,value:Q,parent:L}=b;L&&F&&!F.includes("$")&&(Array.isArray(Q)||isObject(Q))&&!Array.isArray(L)&&(Array.isArray(L[F])?L[F].forEach(O=>{typeof O!="string"&&(O.$objectPath=c(L,F),O.$parentIsCreate=L.$op==="create",O[to]=L.$parentIsCreate||L[Symbol.for("grandChildOfCreate")]);}):isObject(L[F])&&(L[F].$parentIsCreate=L.$op==="create",L[F][Symbol.for("grandChildOfCreate")]=L.$parentIsCreate||L[Symbol.for("grandChildOfCreate")],L[F].$objectPath=c(L,F)));})),y=$(e),m=E=>{let T=[];return E.forEach(F=>{if(!F.$id&&!F.id&&!F.$tempId)if(F.$filter){let Q=d({...F.$objectPath,key:F.$bzId}),L=p[Q];L&&(Array.isArray(L.$ids)?L.$ids:[L.$ids]).forEach(k=>{let q={...F,$id:k,$bzId:`T4_${v4()}`,$filterBzId:F.$bzId};T.push(q);});}else {let Q=d(F.$objectPath),L=p[Q];L?L?.$ids.forEach(O=>{let k={...F,$id:O,$bzId:`T4_${v4()}`};T.push(k);}):T.push(F);}else T.push(F);}),T.map(F=>{let Q={...F};return o(Q,!0).forEach(L=>{let O=Array.isArray(Q[L])?Q[L]:[Q[L]],k=m(O);Q[L]=k;}),Q})},B=m(Array.isArray(y)?y:[y]),M=$(B),S=(E=>{let T=b=>{let F=U=>{let ee=[],_=[],P=[];return U.forEach(z=>{let ie=o(z,!0);if(ie.length>0){let A=!1;ie.forEach(W=>{(Array.isArray(z[W])?z[W]:[z[W]]).filter(G=>!G.$id&&!G.id&&typeof z=="object").length&&(A=!0);}),A?ee.push(z):_.push(z);}else P.push({...z,$bzId:z.$tempId||`T_${v4()}`});}),{operationWithMultiples:ee,operationWithoutMultiples:_,otherOps:P}},{operationWithMultiples:Q,operationWithoutMultiples:L,otherOps:O}=F(b),k=U=>{let _=(()=>{let W={};for(let te in U){let v=x(t,U);!te.startsWith("$")&&v.dataFields?.find(G=>G.path===te)&&(W[te]=U[te]);}return W})(),P=Object.keys(U),z=o(U,!0),ie=[],A=(W,te)=>{if(W===z.length){let G={...te};P.forEach(re=>{re.startsWith("$")&&(G[re]=U[re]);}),ie.push({...G,..._});return}let v={...te,[z[W]]:U[z[W]],...Ee(te),..._};A(W+1,v),A(W+1,te);};return A(0,{...Ee(U)}),ie},q=[];return Q.forEach(U=>{let ee=k(U),_=[];ee.forEach(P=>{let z=o(P,!0);if(P.$op==="create")_.push(P);else if(P.$id){let ie=d(P.$objectPath),A=[];if(z.forEach(W=>{let te=`${ie.includes("undefined")?"root":ie}.${P.$id}${Nt}${W}`,v=p[te];P[W].filter(re=>re.$op==="unlink"||re.$op==="delete"||re.$op==="update").length>0?v&&A.push({key:W,ids:v.$ids}):A.push({key:W,ids:[""]});}),A.length===z.length&&!_.find(W=>W.$id===P.$id))_.push(P);else {let W={...P,$bzId:P.$tempId||`T4_${v4()}`};z.forEach(v=>{let G=P[v].filter(re=>re.$id);G.length>0?W[v]=G:W[v]=void 0;}),o(W,!0).length>0&&_.push(W);}}else if(P.$objectPath){let ie=d(P.$objectPath),A=p[ie]?.$ids||[];A.forEach(W=>{let te=[];z.forEach(v=>{let G=`${ie}.${W}${Nt}${v}`,re=p[G];re&&te.push({key:v,ids:re.$ids});}),z.length===0?A.filter(G=>!_.find(re=>re.$id===G)).forEach(G=>{_.push({...P,$id:G,$bzId:P.$tempId||`T_${v4()}`});}):te.length===z.length&&!_.find(v=>v.$id===W)&&(z.forEach(v=>{let G=`${d(P.$objectPath)}.${W}${Nt}${v}`,{$ids:re}=p[G],En=P[v].find(ke=>!ke.$id),Fn=[...re.map(ke=>({...En,$id:ke,$objectPath:{beforePath:P.$objectPath,ids:ke,key:v}})),...P[v].filter(ke=>ke.$id)];P[v]=Fn;}),_.push({...P,$id:W,$bzId:P.$tempId||`T_${v4()}`}));});}else _.push(P);}),_.forEach(P=>{q.push(P);});}),[...q,...L,...O].filter(U=>o(U).length>0?!0:U.$op!=="update").map(U=>{let ee={...U};return o(ee,!0).forEach(_=>{let P=Array.isArray(ee[_])?ee[_]:[ee[_]],z=T(P);ee[_]=z;}),ee})};return T(E)})(Array.isArray(M)?M:[M]),C=E=>E.map(T=>{let b=o(T,!0),F={...T};return b.forEach(Q=>{let L=Array.isArray(T[Q])?T[Q]:[T[Q]],O=[],k=[],q=[],J={},ce=ct(t,T,Q);L.filter(A=>A).forEach(A=>{A.$op==="replace"&&A.$id?(J=A,Array.isArray(A.$id)?k=[...k,...A.$id]:k.push(A.$id)):A.$op==="create"&&ce==="ONE"&&A.id?(J=A,Array.isArray(A.id)?q=[...k,...A.id]:q.push(A.id)):O.push(A);});let Me=d(J.$objectPath),ee=a(Me).map(A=>p[A]),_=[];ee.filter(A=>A!=null).forEach(A=>{_=[..._,...A.$ids];});let P=_.filter(A=>!k.includes(A)),z=k.filter(A=>!_.includes(A)),ie=Ee(J);P.length>0&&O.push({...J,$op:"unlink",$id:P,$bzId:J.$tempId||`T4_${v4()}`,id:void 0,...ie}),z.length>0&&z.forEach(A=>{O.push({...J,$op:"link",$id:A,$bzId:J.$tempId||`T5_${v4()}`,...ie});}),q.length>0&&q.forEach(A=>{O.push({...J,$op:"create",id:A,$bzId:J.$tempId||`T6_${v4()}`,...ie});}),F[Q]=C(O);}),F}),D=$(C($(S)));(E=>produce(E,T=>traverse(T,b=>{let{key:F,value:Q,parent:L}=b;F&&L&&!F?.includes("$")&&(Array.isArray(Q)||isObject(Q))&&!Array.isArray(L)&&(Array.isArray(Q)?Q:[Q]).forEach(k=>{let q=k.$filter?{...k.$objectPath,key:k.$filterBzId}:k.$objectPath,J=d(q),ce=p[J],Me=(_,P)=>_.every(z=>P.includes(z)),U=k.$id?Array.isArray(k.$id)?Me(k.$id,ce?ce.$ids:[]):ce?.$ids.includes(k.$id):ce,ee=ct(t,L,k.$objectPath.key);if(k.$op==="link"&&U&&ee==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${d(k.$objectPath)}" because it is already occupied.`);if(k.$op)switch(k.$op){case"delete":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${k.$id}" because it is not linked to $id:"${L.$id}"`);break;case"update":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${k.$id}" because it is not linked to $id:"${L.$id}"`);break;case"unlink":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${k.$id}" because it is not linked to $id:"${L.$id}"`);break;case"link":if(U)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${k.$id}" because it is already linked to $id:"${L.$id}"`);break;}});})))(D);let N=(E=>produce(E,T=>traverse(T,b=>{let{value:F,meta:Q}=b;isObject(F)&&(F[Symbol.for("path")]=Q.nodePath,delete F.$objectPath,delete F.$parentIsCreate);})))(D);return [...Array.isArray(N)?N:[N]].sort((E,T)=>E.$op==="create"&&T.$op!=="create"?-1:E.$op!=="create"&&T.$op==="create"?1:0)};var an=(e,t)=>produce(e,i=>rt(t,i)),rt=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(o=>rt(e,o,r));return}let i=Y(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([o])=>{o.startsWith("$")||no(e,t,o,i);});},no=(e,t,r,i)=>{let o=t[r];if(!o)return;let n=i.dataFields?.find(s=>s.path===r);if(n){n.contentType==="JSON"&&o!=null&&(t[r]=JSON.stringify(o));return}let l=i.linkFields?.find(s=>s.path===r);if(l){let s=l.oppositeLinkFieldsPlayedBy[0]?.thing;rt(e,o,s);return}if(i.thingType==="relation"){let s=i.roles[r],[u]=s.playedBy||[];if(!u)throw new Error(`Role ${s.name} in ${i} is not played by anything`);rt(e,o,u.thing);}};var hn=async(e,t,r,i)=>{let o=Array.isArray(e)?e:[e],n=o.map(u=>Wt(u,!0)),s=(await Pe(n,t,r,i)).bql.res;return o.map((u,f)=>{let c=Y(t,u.$thing);return pn({mut:u,node:s[f],schema:t,thing:c})})},un=new Set(["$op","$bzId","$parentKey"]),oo=new Set(["$relation","$entity","$id",...un]),Wt=(e,t)=>{let r={};e.$fields?.forEach(o=>{typeof o=="string"?r[o]=o:r[o.$path]=o;});let i={};for(let o in e){if(un.has(o)||oo.has(o)&&!t)continue;let n=e[o];o.startsWith("$")?i[o]=n:Array.isArray(n)?n[0]&&typeof n[0]=="object"&&(r[o]={$path:o,...Wt(n[0],!1)}):isObject(n)&&(r[o]={$path:o,...Wt(n,!1)});}return i.$fields=Object.values(r),i},pn=e=>{let{mut:t,node:r,schema:i,thing:o}=e,n=$n(o),l=ao(r);if(Array.isArray(t))return t.map(u=>{let f=l[u.$id];return f?ln({mut:u,node:f,schema:i,thing:o,...n}):u});let s=l[t.$id];return ln({mut:t,node:s,schema:i,thing:o,...n})},ln=e=>{let{mut:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}=e,{$fields:u,...f}=t;if(!r)return f;let c=fn({$fields:t.$fields,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}),d={...f,[Ce]:c};for(let a in t){if(a.startsWith("$"))continue;let p=t[a];if(n[a]||!p||typeof p!="object"){d[a]=p;continue}let $=l[a]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[a]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${a}"`);let y=Y(i,$);d[a]=pn({mut:p,schema:i,node:r[a],thing:y});}return d},fn=e=>{let{$fields:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:l,roleFieldMap:s}=e,u=t||so(o),f={$id:r.$id};return u.forEach(c=>{let d=typeof c!="string",a=d?c.$path:c,p=r[a];if(n[a]){f[a]=p;return}let $=l[a]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[a]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${a}"`);if(!d){p&&(f[a]=Array.isArray(p)?p.map(cn):cn(p));return}let y=Y(i,$),m=$n(y);f[a]=Array.isArray(p)?p.map(B=>dn({...m,$fields:c.$fields,value:B,schema:i,thing:y})):dn({...m,$fields:c.$fields,value:p,schema:i,thing:y});}),f},so=e=>{let t=[];return e.dataFields?.forEach(r=>{t.push(r.path);}),e.linkFields?.forEach(r=>{t.push(r.path);}),e.thingType==="relation"&&t.push(...Object.keys(e.roles)),t},cn=e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);if(typeof e.$id!="string")throw new Error(`"${JSON.stringify(e)}" is does not have prop "$id"`);return e.$id},dn=e=>{let{value:t}=e;if(!t||typeof t!="object"||!t.$id)throw new Error(`"${JSON.stringify(e)}" is neither an id nor an object with prop "$id"`);return fn({...e,node:t})},$n=e=>{let t=Object.fromEntries(e.dataFields?.map(o=>[o.path,o])||[]),r=Object.fromEntries(e.linkFields?.map(o=>[o.path,o])||[]),i=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:r,roleFieldMap:i}},ao=e=>{if(!Array.isArray(e))return e&&typeof e=="object"&&e.$id?{[e.$id]:e}:{};let t={};return e.forEach(r=>{!r||typeof r!="object"||!r.$id||(t[r.$id]=r);}),t};var mn=he,qe=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,lo=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),co=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),ho=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),uo=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),po=async e=>Object.keys(e.bql.current).length?ft(e.bql.current,e.schema,e.config):ft(e.bql.raw,e.schema,e.config),fo=async e=>sn(e.bql.current,e.schema,e.config,e.handles),$o=async e=>hn(e.bql.current,e.schema,e.config,e.handles),mo=async e=>Fr(e.bql.current,e.schema),yo=async e=>wr(e.bql.things,e.bql.edges,e.schema),go=async e=>$r(e.typeDB.tqlMutation,e.handles,e.config),Bo=async e=>mr(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.schema,e.config),Eo=()=>!0,Fo=e=>Ae(e.bql.current),we=K("error","error",V((e,t)=>({...e,error:t.error}))),bo=be("stringify",{stringify:Z(async e=>an(e.bql.raw,e.schema),K("done","enrich",V(qe)),we),enrich:Z(po,K("done","preQuery",yt(Eo),V(qe)),K("done","parseBQL",V(qe)),we),preHookDependencies:Z($o,K("done","enrich",V(qe)),we),preQuery:Z(fo,K("done","preHookDependencies",yt(Fo),V(qe)),K("done","parseBQL",V(qe)),we),parseBQL:Z(mo,K("done","buildMutation",V(co)),we),buildMutation:Z(yo,K("done","runMutation",V(ho)),we),runMutation:Z(go,K("done","parseMutation",V(uo)),we),parseMutation:Z(Bo,K("done","success",V(lo)),we),success:mn(),error:mn()},e=>e),wo=async e=>new Promise((t,r)=>{me(bo,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),yn=async(e,t,r,i)=>wo({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:r,handles:i,depthLevel:0,error:null});enableMapSet();var _t=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 i=>{if(i.provider==="surrealDB"){let o=new Surreal;await o.connect(i.url,{namespace:i.namespace,database:i.dbName,auth:{namespace:i.namespace,database:i.dbName,username:i.username,password:i.password}}),t.surrealDB.set(i.id,{client:o});}if(i.provider==="typeDB"&&i.dbName){let[o,n]=await tryit(TypeDB.coreDriver)(i.url);if(o){let l=`[BORM:${i.provider}:${i.dbName}:core] ${o.message??"Can't create TypeDB Client"}`;throw new Error(l)}try{let l=await n.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:n,session:l});}catch(l){let s=`[BORM:${i.provider}:${i.dbName}:session] ${(l.messageTemplate?._messageBody()||l.message)??"Can't create TypeDB Session"}`;throw new Error(s)}}if(i.provider==="typeDBCluster"&&i.dbName){let o=new TypeDBCredential(i.username,i.password,i.tlsRootCAPath),[n,l]=await tryit(TypeDB.cloudDriver)(i.addresses,o);if(n){let s=`[BORM:${i.provider}:${i.dbName}:core] ${n.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await l.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:l,session:s});}catch(s){let u=`[BORM:${i.provider}:${i.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(u)}}}));let r=Yt(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()=>(await this.#e(),Vt(this.config,this.schema,this.dbHandles));query=async(t,r)=>{await this.#e();let i={...this.config,query:{...it.query,...this.config.query,...r}},o=Array.isArray(t),n=o?t:[t],[l,s]=await tryit(Pe)(n,this.schema,i,this.dbHandles);if(l){let f=new Error(l.error);throw f.stack=l.error.stack,f}let u=s.bql.res;return o?u:u[0]};mutate=async(t,r)=>{await this.#e();let i={...this.config,mutation:{...it.mutation,...this.config.mutation,...r}},[o,n]=await tryit(yn)(t,this.schema,i,this.dbHandles);if(o){let s=new Error(o.error.message);throw s.stack=o.error.stack,s}return n.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();});}},Lc=_t;//! Todo: delete when this works with the new $thing and $thingType fields
|
|
53
52
|
//! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
|
|
54
53
|
//! Todo: Sandbox the function in computeFunction()
|
|
55
54
|
//! reads all the insertions and gets the first match. This means each id must be unique
|
|
56
55
|
//!old
|
|
57
56
|
|
|
58
|
-
export {
|
|
57
|
+
export { Lc as default };
|
|
59
58
|
//# sourceMappingURL=out.js.map
|
|
60
59
|
//# sourceMappingURL=index.mjs.map
|