@blitznocode/blitz-orm 0.10.31 → 0.11.0

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 CHANGED
@@ -1,30 +1,30 @@
1
- import { isObject, isArray, shake, tryit, parallel, clone, mapEntries, listify, pick, isDate } from 'radash';
1
+ import { isObject, isArray, tryit, parallel, shake, clone, mapEntries, listify, pick, isDate, isSymbol } from 'radash';
2
2
  import { TypeDBOptions, TransactionType, SessionType, TypeDB, TypeDBCredential } from 'typedb-driver';
3
3
  import { Surreal } from 'surrealdb.js';
4
4
  import { enableMapSet, produce, isDraft, current } from 'immer';
5
5
  import { traverse, getNodeByPath } from 'object-traversal';
6
- import { nanoid } from 'nanoid';
7
- import { v4 } from 'uuid';
6
+ import { nanoid, customAlphabet } from 'nanoid';
8
7
  import { isSet } from 'util/types';
9
8
  import 'acorn';
9
+ import { v4 } from 'uuid';
10
10
 
11
- var ct={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var kn=e=>{let t=[],r=new Map;return e.forEach(i=>{let{dbPath:o,contentType:n}=i,c=`${o}-${n}`;r.has(c)||(r.set(c,!0),t.push(i));}),t},Zt=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:A,linkFields:O,name:x}=S,W=[],le=[],K=[];if("extends"in S){let F=t.entities[S.extends];F.dataFields&&F.dataFields.forEach(Q=>{W.push(Q.dbPath);}),F.linkFields&&F.linkFields.forEach(Q=>{le.push(Q.path);}),F.idFields&&F.idFields.forEach(Q=>{K.push(Q);});}y+=`${x} sub ${"extends"in S?S.extends:"entity"},
13
- `;let D=[];if(C&&C.length>0){let F=new Set(C),E=Array.from(F).map(b=>`${b}`).join(", ");K.includes(E)||(y+=` owns ${E} @key,
14
- `,D.push(E));}if(A&&A.length>0&&A.forEach(F=>{!W.includes(F.dbPath)&&!D.includes(F.dbPath)&&(y+=` owns ${F.dbPath},
15
- `),m.push({dbPath:F.dbPath,contentType:F.contentType});}),O&&O.length>0){let F=[];O.forEach(Q=>{let{relation:E,plays:b}=Q;!le.includes(Q.path)&&!F.includes(`${E}:${b}`)&&(y+=` plays ${E}:${b},
16
- `,F.push(`${E}:${b}`));});}y=y.replace(/,\s*$/,`;
11
+ var ht={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var Kn=e=>{let t=[],r=new Map;return e.forEach(i=>{let{dbPath:o,contentType:n}=i,s=`${o}-${n}`;r.has(s)||(r.set(s,!0),t.push(i));}),t},tr=async(e,t,r)=>{let o=(()=>{let y="",m=[];y+=`
12
+ `,Object.keys(t.entities).forEach(g=>{let Q=t.entities[g],{idFields:L,dataFields:R,linkFields:A,name:P}=Q,z=[],Z=[],W=[];if("extends"in Q){let M=t.entities[Q.extends];M.dataFields&&M.dataFields.forEach(b=>{z.push(b.dbPath);}),M.linkFields&&M.linkFields.forEach(b=>{Z.push(b.path);}),M.idFields&&M.idFields.forEach(b=>{W.push(b);});}y+=`${P} sub ${"extends"in Q?Q.extends:"entity"},
13
+ `;let I=[];if(L&&L.length>0){let M=new Set(L),E=Array.from(M).map(w=>`${w}`).join(", ");W.includes(E)||(y+=` owns ${E} @key,
14
+ `,I.push(E));}if(R&&R.length>0&&R.forEach(M=>{!z.includes(M.dbPath)&&!I.includes(M.dbPath)&&(y+=` owns ${M.dbPath},
15
+ `),m.push({dbPath:M.dbPath,contentType:M.contentType});}),A&&A.length>0){let M=[];A.forEach(b=>{let{relation:E,plays:w}=b;!Z.includes(b.path)&&!M.includes(`${E}:${w}`)&&(y+=` plays ${E}:${w},
16
+ `,M.push(`${E}:${w}`));});}y=y.replace(/,\s*$/,`;
17
17
  `),y+=`
18
- `;}),Object.keys(t.relations).forEach(g=>{let S=t.relations[g],{idFields:C,dataFields:A,roles:O,name:x,linkFields:W}=S,le=[],K=[],D=[],F=[];if("extends"in S){let E=t.relations[S.extends];E.dataFields&&E.dataFields.forEach(b=>{le.push(b.dbPath);}),E.linkFields&&E.linkFields.forEach(b=>{K.push(b.dbPath);}),E.roles&&Object.values(E.roles).forEach(M=>{D.push(M.name);}),E.idFields&&E.idFields.forEach(b=>{F.push(b);});}y+=`${x} sub ${"extends"in S?S.extends:"relation"},
19
- `;let Q=[];if(C&&C.length>0){let E=new Set(C),M=Array.from(E).map(R=>`${R}`).join(", ");F.includes(M)||(y+=` owns ${M} @key,
20
- `,Q.push(M));}if(A&&A.length>0&&A.forEach(E=>{!le.includes(E.dbPath)&&!Q.includes(E.dbPath)&&(y+=` owns ${E.dbPath},
21
- `),m.push({dbPath:E.dbPath,contentType:E.contentType});}),O&&Object.keys(O).forEach(E=>{D.includes(E)||(y+=` relates ${E},
22
- `);}),W&&W.length>0){let E=[];W.forEach(b=>{let{plays:M}=b;!K.includes(b.path)&&!E.includes(`${S}:${M}`)&&(y+=` plays ${b.relation}:${M},
23
- `,E.push(`${S}:${M}`));});}y=y.replace(/,\s*$/,`;
18
+ `;}),Object.keys(t.relations).forEach(g=>{let Q=t.relations[g],{idFields:L,dataFields:R,roles:A,name:P,linkFields:z}=Q,Z=[],W=[],I=[],M=[];if("extends"in Q){let E=t.relations[Q.extends];E.dataFields&&E.dataFields.forEach(w=>{Z.push(w.dbPath);}),E.linkFields&&E.linkFields.forEach(w=>{W.push(w.dbPath);}),E.roles&&Object.values(E.roles).forEach(T=>{I.push(T.name);}),E.idFields&&E.idFields.forEach(w=>{M.push(w);});}y+=`${P} sub ${"extends"in Q?Q.extends:"relation"},
19
+ `;let b=[];if(L&&L.length>0){let E=new Set(L),T=Array.from(E).map(C=>`${C}`).join(", ");M.includes(T)||(y+=` owns ${T} @key,
20
+ `,b.push(T));}if(R&&R.length>0&&R.forEach(E=>{!Z.includes(E.dbPath)&&!b.includes(E.dbPath)&&(y+=` owns ${E.dbPath},
21
+ `),m.push({dbPath:E.dbPath,contentType:E.contentType});}),A&&Object.keys(A).forEach(E=>{I.includes(E)||(y+=` relates ${E},
22
+ `);}),z&&z.length>0){let E=[];z.forEach(w=>{let{plays:T}=w;!W.includes(w.path)&&!E.includes(`${Q}:${T}`)&&(y+=` plays ${w.relation}:${T},
23
+ `,E.push(`${Q}:${T}`));});}y=y.replace(/,\s*$/,`;
24
24
  `),y+=`
25
25
  `;});let B=`define
26
26
 
27
- `;return kn(m).forEach(g=>{if(B+=`${g.dbPath} sub attribute,
27
+ `;return Kn(m).forEach(g=>{if(B+=`${g.dbPath} sub attribute,
28
28
  `,g.contentType==="TEXT"||g.contentType==="ID"||g.contentType==="JSON")B+=` value string;
29
29
  `;else if(g.contentType==="EMAIL")B+=` value string,
30
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,})$';
@@ -33,29 +33,39 @@ var ct={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},muta
33
33
  `;else if(g.contentType==="NUMBER")B+=` value long;
34
34
  `;else throw new Error(`Conversion of borm schema to TypeDB schema for data type "${g.contentType}" is not implemented`)}),`${B}
35
35
 
36
- ${y}`})(),n=e.dbConnectors[0].id,c=r.typeDB.get(n)?.session,a=r.typeDB.get(n)?.client;if(!c){console.log("Session Status: ","NO SESSION");return}await c.close();let[{dbName:h}]=e.dbConnectors;await(await a.databases.get(h)).delete(),await a.databases.create(h);let l=await a.session(e.dbConnectors[0].dbName,SessionType.SCHEMA),d=await l.transaction(TransactionType.WRITE);await d.query.define(o),await d.commit(),await d.close();let s=await l.transaction(TransactionType.READ);(await(await s.query.match("match $a sub thing;")).collect()).forEach(async y=>{y.get("a");}),await s.close();};var te=Symbol.for("queryPath"),Ve=Symbol.for("stepPrint"),Se=Symbol.for("edgeType"),Be=Symbol.for("edgeSchema"),Ae=Symbol.for("dbNode"),dt=Symbol.for("isTransformed"),ie=Symbol.for("fieldSchema"),$e=Symbol.for("sharedMetadata"),me=Symbol.for("suqlMetadata");var Yt={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Gt=({linkField:e,originalRelation:t,withExtensionsSchema:r,linkMode:i})=>{if(e.isVirtual)return `$this.${e.path}.id`;let o=r.relations[e.relation].subTypes||[],n=[e.relation,...o],c=`<-\`${t}_${e.plays}\`<-(\`${n.join("`,`")}\`)`;if(e.target==="relation"){if(i==="edges")return c;if(i==="refs")return `$parent.\`${e.path}\``;throw new Error("Unsupported linkMode")}else if(e.target==="role"){let[a]=e.oppositeLinkFieldsPlayedBy,h=r.entities[a.thing]?.subTypes||r.relations[a.thing]?.subTypes||[],p=[a.thing,...h],l=`->\`${t}_${a.plays}\`->(\`${p.join("`,`")}\`)`;return i==="edges"?`${c}${l}`:i==="refs"?`$parent.\`${a.plays}\``:`${c}${l}`}else throw new Error("Unsupported linkField target")};var tr=(e,t,r)=>r?t:`${e}\xB7${t}`;var nr=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))))[0],We=(e,t)=>Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))),ir=(e,t)=>{let r=[],i=produce(e,n=>traverse(n,({key:c,value:a,meta:h})=>{if(h.depth===2&&(c&&(a.dataFields=a.dataFields?.map(p=>({...p,cardinality:p.cardinality||"ONE",dbPath:"dbPath"in p?p.dbPath:tr(c,p.path,p.shared)}))),a.extends)){if(!a.defaultDBConnector.as)throw new Error(`[Schema] ${c} is extending a thing but missing the "as" property in its defaultDBConnector. Path:${h.nodePath}`);let p=n.entities[a.extends]||n.relations[a.extends],l=[a.extends,...p.allExtends||[]];if(a.allExtends=l,l.forEach(d=>{if(n.entities[d])n.entities[d].subTypes=[c,...n.entities[d].subTypes||[]];else if(n.relations[d])n.relations[d].subTypes=[c,...n.relations[d].subTypes||[]];else throw new Error(`[Schema] ${c} is extending a thing that does not exist in the schema: ${d}`)}),a.idFields=p.idFields?Array.from(new Set((a.idFields||[]).concat(p.idFields))):a.idFields,a.dataFields=p.dataFields?(a.dataFields||[]).concat(p.dataFields.map(d=>{let s=a.extends,f=e.entities[s]||e.relations[s];for(;!f.dataFields?.find(u=>u.path===d.path);)s="extends"in f?f.extends:void 0,f=e.entities[s]||e.relations[s];return {...d,dbPath:"dbPath"in d?d.dbPath:tr(s,d.path,d.shared),[$e]:{inheritanceOrigin:d[$e]?.inheritanceOrigin||a.extends}}})):a.dataFields,"roles"in p){let d=a,s=p;if(s.roles){let f=mapEntries(s.roles,(u,$)=>[u,{...$,[$e]:{inheritanceOrigin:$[$e]?.inheritanceOrigin||a.extends}}]);d.roles={...d.roles||{},...f};}}a.linkFields=p.linkFields?(a.linkFields||[]).concat(p.linkFields.map(d=>({...d,[$e]:{inheritanceOrigin:d[$e]?.inheritanceOrigin||a.extends}}))):a.linkFields,p?.hooks?.pre&&(a.hooks=a.hooks||{},a.hooks.pre=a.hooks.pre||[],a.hooks.pre=[...p?.hooks?.pre||[],...a?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:n,value:c,meta:a})=>{if(n==="linkFields"){let p=(()=>{if(!a.nodePath)throw new Error("No path");let[d,s]=a.nodePath.split(".");return {thing:s,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),l=Array.isArray(c)?c.map(d=>({...d,...p})):[{...c,...p}];r.push(...l);}}),produce(i,n=>traverse(n,({value:c,key:a,meta:h})=>{if(h.depth===2&&c.idFields&&!c.id){c.name=a;let p=()=>{if(h.nodePath?.split(".")[0]==="entities")return "entity";if(h.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};c.thingType=p();let l=Object.keys(t).find(d=>t[d]?.get(c.defaultDBConnector.id));if(c.db=l,c.dbContext=Yt[l],c.dbProviderConfig=l==="surrealDB"?t[l]?.get(c.defaultDBConnector.id)?.providerConfig:void 0,c.computedFields=[],c.virtualFields=[],c.requiredFields=[],c.enumFields=[],c.fnValidatedFields=[],"roles"in c&&Object.entries(c.roles).forEach(([s,f])=>{f.fieldType="roleField";let u=r.filter(w=>w.relation===a&&w.plays===s)||[];f.playedBy=u,f.path=s;let $=[...new Set(u.map(w=>w.thing))];f.$things=$;let y=f[$e]?.inheritanceOrigin||c.name;$.length>1&&console.warn(`Not supported yet: Role ${s} in ${c.name} is played by multiple things: ${$.join(", ")}`);let m=$.flatMap(w=>{let S=G(e,w)?.subTypes||[];return [w,...S]}),B=()=>{if(c.dbProviderConfig.linkMode==="edges")return `->\`${y}_${s}\`->(\`${m.join("`,`")}\`)`;if(c.dbProviderConfig.linkMode==="refs"){if(f.cardinality==="MANY")return `$parent.\`${s}\``;if(f.cardinality==="ONE")return `$parent.[\`${s}\`]`}throw new Error("Unsupported linkMode")};if(c.db==="surrealDB"){let w=B();f[me]={queryPath:w};}}),"linkFields"in c&&c.linkFields){let d=c;d.linkFields?.forEach(s=>{s.fieldType="linkField";let f=i.relations[s.relation];if(!s.isVirtual){if(!f)throw new Error(`The relation ${s.relation} does not exist in the schema`);if(f.roles?.[s.plays]===void 0)throw new Error(`The role ${s.plays} is not defined in the relation ${s.relation} (linkField: ${s.path})`)}if(s.target==="relation"){if(s.isVirtual)throw new Error(`[Schema] Virtual linkFields can't target a relation. Thing: "${d.name}" LinkField: "${s.path}. Path:${h.nodePath}."`);s.$things=[s.relation],s.oppositeLinkFieldsPlayedBy=[{plays:s.path,thing:s.relation,thingType:"relation"}];}if(s.target==="role"){let u=r.filter($=>$.relation===s.relation&&$.plays!==s.plays)||[];if(s.oppositeLinkFieldsPlayedBy=u,s.oppositeLinkFieldsPlayedBy=s.oppositeLinkFieldsPlayedBy.filter($=>$.target==="role"),s.oppositeLinkFieldsPlayedBy.length===0)throw new Error(`[Schema] LinkFields require to have at least one opposite linkField playing an opposite role. Thing: "${d.name}" LinkField: "${s.path}. Path:${h.nodePath}."`);s.$things=s.oppositeLinkFieldsPlayedBy.map($=>$.thing),s.oppositeLinkFieldsPlayedBy.length>1&&console.warn(`[Schema] LinkField ${s.path} in ${d.name} has multiple candidates ${s.oppositeLinkFieldsPlayedBy.map($=>$.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`);}if(c.db==="surrealDB"){let u=f?.roles?.[s.plays][$e]?.inheritanceOrigin??s.relation,$=Gt({linkField:s,originalRelation:u,withExtensionsSchema:i,linkMode:c.dbProviderConfig.linkMode});s[me]={queryPath:$};}});}}if(c&&typeof c=="object"&&"playedBy"in c){let p=[...new Set(c.playedBy.map(l=>l.thing))];if(p.length>1&&console.warn(`[Schema] roleFields can be only played by one thing. Role: ${a}, path:${h.nodePath}, played by: ${p.join(", ")}`),c.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${a}, path:${h.nodePath}`)}if(h.depth===4){let[p,l]=h.nodePath?.split(".")||[],d=n[p][l];!isArray(c)&&typeof c=="object"&&(c.validations&&(c.validations.required&&d.requiredFields.push(c.path),c.validations.enum&&d.enumFields.push(c.path),c.validations.fn&&d.fnValidatedFields.push(c.path)),c.default?c.isVirtual?d.virtualFields.push(c.path):d.computedFields.push(c.path):c.isVirtual&&d.virtualFields.push(c.path));}}))},G=(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`)},q=(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)}`)},Ie=(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`)},Ke=(e,t)=>{let r=q(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},or=(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")},pt=(e,t,r)=>{let i=q(e,t),o=i.linkFields?.find(a=>a.path===r);if(o)return o;let n=i.dataFields?.find(a=>a.path===r);if(n)return n;let c="roles"in i?i.roles?.[r]:void 0;if(c)return c;throw new Error(`Field ${r} not found in schema`)},ft=(e,t,r)=>pt(e,t,r)?.cardinality,ue=(e,t)=>{let r=e.dataFields?.map(u=>u.path)||[],i=e.linkFields?.map(u=>u.path)||[],o="roles"in e?listify(e.roles,u=>u):[],n=[...r||[],...i||[],...o||[]],a=[...["$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 h=t.$fields?t.$fields.map(u=>{if(typeof u=="string"){if(u.startsWith("$")||u.startsWith("%"))return;if(!n.includes(u))throw new Error(`Field ${u} not found in the schema`);return u}if("$path"in u&&typeof u.$path=="string")return u.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,u=>{if(!(u.startsWith("$")||u.startsWith("%"))){if(!n.includes(u))throw new Error(`[Schema] Field ${u} not found in the schema`);return u}}).filter(u=>u!==void 0),p=t.$filter?listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&r?.includes(u)):[],l=t.$filter?listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&[...o||[],...i||[]].includes(u)):[],d=[...h,...p].filter(u=>!u?.startsWith("%")).filter(u=>!a.includes(u)).filter(u=>u),s=t.$filter?We(t.$filter,(u,$)=>p.includes(u)):{},f=t.$filter?We(t.$filter,(u,$)=>l.includes(u)):{};return {fields:n,dataFields:r,roleFields:o,linkFields:i,usedFields:h,usedLinkFields:i.filter(u=>h.includes(u)),usedRoleFields:o.filter(u=>h.includes(u)),usedDataFields:r.filter(u=>h.includes(u)),unidentifiedFields:d,...p.length?{localFilters:s}:{},...l.length?{nestedFilters:f}:{}}};var sr=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},ar=(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):{}},Fe=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var Ue=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},ae=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},T=(e,t)=>{let r="";for(let i=0;i<t;i++)r+=" ";return `${r}${e}`};var ke=(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 cr=(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=ke(t,r),[n]=o,c=e.$op==="create"?"link":"replace",a=n.thing,h=n.thingType,p={$op:c,$thing:a,$thingType:h},l=i.filter(s=>s.startsWith("_:")),d=i.filter(s=>!s.startsWith("_:"));l.length&&!d.length?e[t]=l.map(s=>({...p,$tempId:s,$bzId:s})):l.length&&d.length?e[t]=[...l.map(s=>({...p,$tempId:s,$bzId:s})),{...p,$id:d,$bzId:`S_${nanoid()}`}]:e[t]={...p,$id:e[t],$bzId:`S_${nanoid()}`};}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 Le=(e,t,r)=>{let i=q(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 Je=(e,t,r)=>{let i=q(r,t),{usedFields:o}=ue(i,t);return t.$op?(Le(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(Le(e,{...t,$op:"update"},r),"update"):(Le(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(Le(e,{...t,$op:"create"},r),"create"):(Le(e,{...t,$op:"create"},r),"link"):(Le(e,{...t,$op:"create"},r),"create")};var hr=(e,t)=>{let i=(isArray(e.$root)?e.$root:[e.$root]).map(o=>{let n=Je(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:or(o,t)},...o.$op?{}:{$op:n},...o.$bzId?{}:{$bzId:`R_${v4()}`}},...o}});e.$root=isArray(e.$root)?i:i[0];};var ve=(e,t)=>{let r=t[Ve];return isSet(r)?r.has("clean")?(Reflect.set(t,Ve,r.add("clean")),!0):!1:(Reflect.set(t,Ve,new Set(["clean"])),!0)};var ur=(e,t,r)=>{if(ve("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(q(r,n),!n.$bzId)throw new Error("[Internal Error] No bzId found");return n.$id.map((c,a)=>({...pe(n),$id:c,$bzId:`${n.$bzId}_${a}`,...Fe(n)}))}return o});(i.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=i);}};var fr=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{let c=ke(t,r),[a]=c,h=Je(e,{...n,$thing:a.thing,$thingType:a.thingType},i),l=n.$bzId?n.$bzId:n.$tempId?n.$tempId:n.$id&&!isArray(n.$id)?`SN_ONE_${a.thing}_${n.$id}`:n.$id&&isArray(n.$id)?`SN_MANY_${a.thing}_${nanoid()}`:`SM_${nanoid()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...n,[Be]:r,$thing:a.thing,$thingType:a.thingType,$op:h,$bzId:l}});e[t]=isArray(e[t])?o:o[0];};var zn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Vn=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,$r=e=>{let r=e.toString().replace(zn,"").trim().split("=>")[0].split("{")[0].replace(Vn,"").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(a=>a.split(":")[0].trim().replace(/['"[\]]/g,"")):n.trim()).filter(Boolean):[]};var Oe=({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,c=$r(o).filter(a=>!(a in e));if(c.length)throw new Error(`Virtual field: Missing arguments ${c.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 mr=(e,t,r)=>{let i=e[t];i&&(isArray(i)?i:[i]).forEach(o=>{let n=q(r,o),{unidentifiedFields:c}=ue(n,o),{computedFields:a,virtualFields:h}=n,p=listify(o,(s,f)=>f!==void 0?s:void 0),l=p.filter(s=>h?.includes(s));if(l.length>0)throw new Error(`Virtual fields can't be sent to DB: "${l.join(",")}"`);if(a.filter(s=>!p.includes(s)).forEach(s=>{let f=n.dataFields?.find(B=>B.path===s),$=n.linkFields?.find(B=>B.path===s)?.oppositeLinkFieldsPlayedBy[0],y="roles"in n?nr(n.roles,(B,w)=>B===s):void 0,m=f||$||y;if(!m)throw new Error(`no field Def for ${s}`);if(o.$op==="create"&&!o[s]){let B=Oe({currentThing:o,fieldSchema:m,mandatoryDependencies:!0});o[s]=B;}}),c.length>0)throw new Error(`Unknown fields: [${c.join(",")}] in ${JSON.stringify(o)}`)});};var Ye=(e,t)=>{let r=q(t,e).hooks;if(r?.pre){let i=`on${sr(e.$op)}`;return r.pre.filter(c=>!c.triggers||c.triggers[i]?.()).flatMap(c=>c.actions)}return []};var gr=(e,t,r,i)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(n=>{if("$thing"in n){if(n.$fields)return n;let{requiredFields:c,enumFields:a,fnValidatedFields:h,dataFields:p}=q(r,n);if("$op"in n&&n.$op==="create"&&c.forEach(l=>{if(!(l in n))throw new Error(`[Validations] Required field "${l}" is missing.`)}),("$op"in n&&n.$op==="update"||n.$op==="create")&&a.forEach(l=>{if(l in n){let d=p?.find(s=>s.path===l)?.validations?.enum;if(!d)throw new Error(`[Validations] Enum field "${l}" is missing enum options.`);if(isArray(n[l]))n[l].some(s=>{if(!d.includes(s))throw new Error(`[Validations] Option "${s}" is not a valid option for field "${l}".`)});else if(d&&!d.includes(n[l]))throw new Error(`[Validations] Option "${n[l]}" is not a valid option for field "${l}".`)}}),("$op"in n&&n.$op==="update"||n.$op==="create")&&h.forEach(l=>{if(l in n)try{let d=p?.find(s=>s.path===l)?.validations?.fn;if(!d)throw new Error("Missing validation function.");if(!d(n[l]))throw new Error("Failed validation function.")}catch(d){throw new Error(`[Validations:attribute:${l}] ${d.message}`)}}),isObject(n)&&"$thing"in n){let l=n.$thing,d=n,s=clone(pe(e)),f=clone(pe(d)),u=i.mutation?.context||{},$=clone(pe(n[Ae]||{}));Ye(d,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let B=m.fn(f,s,u,$);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:${l}] ${B.message}`)}}});}}});};var Br=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{if(Ue(n)){if(n.$fields||n[dt])return n;let c=Ye(n,r).filter(d=>d.type==="transform"),a=clone(pe(e)),h=clone(pe(n)),p=i.mutation?.context||{},l=clone(pe(n[Ae]||n.$dbNode));return c.forEach(d=>{let s=d.fn(h,a,p,l||{});Object.keys(s).length!==0&&(n={...h,...s,...Fe(n),[dt]:!0});}),n}});e[t]=isArray(e[t])?o:o[0];};var Fr=(e,t,r)=>{let i=ke(t,r),[o]=i;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Be]:r};};var Pe=e=>{if(Array.isArray(e)){for(let t of e)if(Pe(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"&&Pe(e[t]))return !0}return !1};var ei=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(ve("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")},ti=(e,t)=>{},Et=(e,t,r)=>{let i={$rootWrap:{$root:e}},o=Pe(Array.isArray(e)?e:[e]),n=produce(i,c=>traverse(c,({value:a,parent:h,key:p,meta:l})=>{if(!(!h||!p)&&isObject(a)){let d=l.nodePath?.split(".")||[];if(!("$root"in a)){if(!("$thing"in a||"$entity"in a||"$relation"in a)){let u=["$fields","$dbNode","$filter"],$=d[d.length-1],y=d[d.length-2];if(p==="$root")throw new Error("Root things must specify $entity or $relation");if(!u.includes($)&&!u.includes(y))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(a)?current(a):a)}`)}}let s=a,f=d.includes("$filter");Object.keys(s).forEach(u=>{if(ei(s,u),u!=="$root"&&f||u!=="$root"&&(u.startsWith("$")||u.startsWith("%")))return;let $=u!=="$root"?pt(t,s,u):{fieldType:"rootField"};if(!$)throw new Error(`[Internal] Field ${u} not found in schema`);if("contentType"in $)return ti();if(["rootField","linkField","roleField"].includes($.fieldType)){if(["linkField","roleField"].includes($.fieldType)&&(s[u]===null?Fr(s,u,$):cr(s,u,$)),$.fieldType==="rootField"){if(!("$root"in s))throw new Error(`[Internal] Field ${u} is a rootField but the object is not a root`);hr(s,t);}let y=isArray(s[u])?s[u]:[s[u]],m=d.slice(1).join(".");y.forEach(w=>{if(w){if($?.cardinality==="ONE"&&!w.$op&&!w.$id&&!w.$filter&&!w.$tempId&&s.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${m}.${u}`);if(w.$tempId&&!(w.$op===void 0||w.$op==="link"||w.$op==="create"||w.$op==="update"))throw new Error(`Invalid op ${w.$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)&&fr(s,u,$,t),ur(s,u,t),["rootField","linkField","roleField"].includes($.fieldType)&&mr(s,u,t),(isArray(s[u])?s[u]:[s[u]]).forEach(w=>{let g=q(t,w),{unidentifiedFields:S,usedLinkFields:C,usedFields:A,fields:O}=ue(g,w);if(A.forEach(x=>{if(!O.includes(x))throw new Error(`[Schema] Field ${x} not found in the schema`)}),S.length>0)throw new Error(`Unknown fields: [${S.join(",")}] in ${JSON.stringify(a)}`);if(C.length>1){let x=g.linkFields?.filter(W=>C.includes(W.path));x?.some((W,le)=>x.some((K,D)=>{if(le!==D&&W.target!==K.target&&W.relation===K.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||(Br(s,u,t,r),gr(s,u,t,r));}});}}));return isArray(n.$rootWrap.$root),n.$rootWrap.$root};var Ge=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 br=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 Ge(t,r),o=await i.transaction(TransactionType.WRITE),n=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,c=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{n&&await o.query.delete(n);let a=c&&o.query.insert(c),h=a?await a.collect():void 0;return await o.commit(),{insertions:h}}catch(a){throw new Error(`Transaction failed: ${a.message}`)}finally{await o.close();}};var wr=async(e,t,r,i,o)=>{let n=[...t,...r],c=n.map(a=>{let h=e.insertions?.find(d=>d.get(`${a.$bzId}`))?.get(`${a.$bzId}`),p=a.$thing||a.$relation||a.$entity,l=p?G(i,p):void 0;if(a.$op==="create"||a.$op==="update"||a.$op==="link"){if(a.$op!=="update"&&!h&&a.$id)return {$id:a.$id,$error:"Does not exist or it's not linked to the parent"};let d=h?.asThing().iid,s=Object.entries(a).filter(([u,$])=>!u.startsWith("$")).reduce((u,[$,y])=>{if(l?.dataFields?.find(B=>B.path===$)?.contentType==="JSON")return u[$]=JSON.parse(y),u;if(a.$thingType==="relation"){let B=n.filter(w=>w.$id&&w.$bzId===y);return B.length===1?(u[$]=B[0].$id,u):(u[$]=y,u)}return u[$]=y,u},{});if(o.mutation?.noMetadata)return s;let f=a.$tempId&&!a.$tempId.startsWith("_:")?{$tempId:`_:${a.$tempId}`}:{};return {$dbId:d,...a,...s,[a.path]:a.$id,...f}}if(a.$op==="delete"||a.$op==="unlink")return a;if(a.$op!=="match")throw new Error(`Unsupported op ${a.$op}`)}).filter(a=>a);return clone(c)};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 Lr=async(e,t)=>{let r=l=>{let d=[],s=[],f=m=>{if(m.$id)return m.$id;let B=q(t,m),{idFields:w}=B;if(!w)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[g]=w;if(!g)throw new Error(`no idField: ${JSON.stringify(m)}`);let S=B.dataFields?.find(O=>O.path===g),C=Oe({currentThing:m,fieldSchema:S,mandatoryDependencies:!0}),A=m[g]||m.$id||C;if(!A)throw new Error(`no idValue: ${JSON.stringify(m)}`);return A},u=m=>{if(m.$op==="create"){let B=f(m);if(d.find(w=>w.$id===B&&w.$op==="create"))throw new Error(`Duplicate id ${B} for node ${JSON.stringify(m)}`);if(s.find(w=>w.$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=f(m);if(d.find(w=>w.$id===B),s.find(w=>w.$bzId===m.$bzId))throw new Error(`Duplicate %bzId ${m.$bzIdd} for edge ${JSON.stringify(m)}`);s.push({...m,$id:B});return}s.push(m);};return traverse(l,({value:m,parent:B,meta:w})=>{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=q(t,g),{dataFields:C,roleFields:A,linkFields:O,usedFields:x}=ue(S,g),W=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let D=x.filter(E=>C?.includes(E)),F=x.filter(E=>A?.includes(E)),Q=x.filter(E=>O?.includes(E));if(D.length>0)return "update";if(F.length>0||Q.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},le={...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:W(),$bzId:g.$bzId};u(le);let K=g[Be];if(K?.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 D=K.relation===g.$thing,F=D?g.$bzId:`LT_${v4()}`,E=ar(l,B,w).$bzId;if(!E)throw new Error("No parent id found");let b=()=>{if(g.$op==="delete")return D?"match":"delete";if(g.$op==="unlink")return D?"unlink":"delete";if(g.$op==="link"||g.$op==="create")return D?"link":"create";if(g.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},M=q(t,{$thing:K.relation,$thingType:"relation"});if(!Object.keys(M.roles).includes(K.plays))throw new Error(`[Wrong format] Field ${K.plays} is not a role of relation ${K.relation}`);let k={$bzId:F,$thing:K.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:b(),...D?{}:{[K.path]:g.$bzId},[K.plays]:E,[Be]:K,[Se]:"linkField"};$(k),(g.$op==="unlink"||b()==="unlink")&&D&&$({$thing:K.relation,$thingType:"relation",$bzId:F,$op:"match",[K.plays]:E,[Be]:K,[Se]:"linkField"});}if(g.$thingType==="relation"){let D=We(g,(E,b)=>A.includes(E)),F=mapEntries(D,(E,b)=>isArray(b)?[E,b]:isObject(b)?[E,b.$bzId]:[E,b]),Q=We(m,(E,b)=>E.startsWith("$")||E.startsWith("Symbol"));if(Object.keys(D).filter(E=>!E.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let E=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},b=q(t,g).roles,M=mapEntries(F,(k,L)=>{let N=b[k]?.cardinality;if(!N)throw new Error(`Role ${k} not found in schema`);if(Array.isArray(L)){if(N==="ONE"){if(L.length>1)throw new Error(`[Error] Role ${k} is not a MANY relation`);return [k,L[0].$bzId||L[0]]}return [k,L.map(J=>J.$bzId||J)]}return [k,L.$bzId||L]}),R={...Q,$thing:g.$thing,$thingType:"relation",$op:E(),...M,$bzId:g.$bzId,[Se]:"roleField"};$(R);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(D).length>0){let E=0;Object.entries(D).forEach(([b,M])=>{let R=isArray(M)?M:[M],k=L=>L==="create"||L==="replace"?"link":L;R.forEach(L=>{if(!L)return;let N=k(L.$op);if(N==="replace")throw new Error("Not supported yet: replace on roleFields");if(N==="unlink"&&E>0)throw E+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let J={...Q,$thing:g.$thing,$thingType:"relation",$op:N==="delete"?"unlink":N,[b]:L.$bzId,$bzId:g.$bzId,[Se]:"roleField"};$(J);});});}}}}}),[d,s]},[i,o]=r(e),n=i.reduce((l,d)=>{if(!d.$bzId)return [...l,d];let s=l.findIndex(f=>f.$bzId===d.$bzId);if(s===-1)return [...l,d];if(l[s].$op==="create"&&d.$op==="match")return l;if(l[s].$op==="match"&&(d.$op==="create"||d.$op==="match"))return [...l.slice(0,s),d,...l.slice(s+1)];if(l[s].$op==="update"&&d.$op==="update")return [...l.slice(0,s),{...l[s],...d},...l.slice(s+1)];if(l[s].$op==="update"&&d.$op==="match"||l[s].$op==="match"&&d.$op==="update")return [...l.slice(0,s),{...l[s],...d,$op:"update"},...l.slice(s+1)];if(l[s].$op==="delete"&&d.$op==="delete"){if(JSON.stringify(l[s].$filter)===JSON.stringify(d.$filter))return l;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${l[s].$filter}. Current: ${d.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${d.$tempId||d.$id}". Existing: ${l[s].$op}. Current: ${d.$op}`)},[]),c=o.reduce((l,d)=>{let s=l.find(f=>(f.$id&&f.$id===d.$id||f.$bzId&&f.$bzId===d.$bzId)&&f.$thing===d.$thing&&f.$op===d.$op);if(s){let f={...s};return Object.keys(d).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let y=s[$],m=d[$];Array.isArray(y)&&Array.isArray(m)?f[$]=Array.from(new Set([...y,...m])):!Array.isArray(y)&&Array.isArray(m)?y!==void 0?f[$]=Array.from(new Set([y,...m])):f[$]=m:Array.isArray(y)&&!Array.isArray(m)?m!==void 0&&(f[$]=Array.from(new Set([...y,m]))):y!==null&&m!==null&&y!==void 0&&m!==void 0?f[$]=Array.from(new Set([y,m])):y==null&&(f[$]=m);}),[...l.filter($=>!(($.$id&&$.$id===d.$id||$.$bzId&&$.$bzId===d.$bzId)&&$.$thing===d.$thing&&$.$op===d.$op)),f]}return [...l,d]},[]);n.forEach(l=>{if((l.$thingType==="relation"||"relation"in l)&&c.filter(d=>d.$bzId===l.$bzId||d.$tempId&&d.$tempId===l.$tempId).length===0){if(l.$op==="delete"||l.$op==="match"||l.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(Mr(l))}`)}});let a=[...n,...c],h=new Set(a.filter(l=>l.$tempId).map(l=>l.$tempId)),p=Array.from(h).filter(l=>!a.some(d=>d.$tempId===l&&d.$op==="create"));if(p.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${p.join(", ")}`);return {mergedThings:n,mergedEdges:c}};var Bt=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 Cr=async(e,t,r)=>{let i=s=>{let f=s.$op,u=`$${s.$bzId}`,$=q(r,s),{idFields:y,defaultDBConnector:m}=$,B=m?.path||s.$thing,w=s.$id,g=y?.[0],S=listify(s,(D,F)=>{if(D.startsWith("$")||D.startsWith("%")||D===g||F===void 0||F===null)return "";let Q=$.dataFields?.find(M=>M.path===D);if(!Q?.path)return "";let b=Q.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(Q.contentType))return `has ${b} '${F}'`;if(["NUMBER","BOOLEAN"].includes(Q.contentType))return `has ${b} ${F}`;if(Q.contentType==="DATE"){if(Number.isNaN(F.valueOf()))throw new Error("Invalid format, Nan Date");return F instanceof Date?`has ${b} ${F.toISOString().replace("Z","")}`:`has ${b} ${new Date(F).toISOString().replace("Z","")}`}if(Q.contentType==="FLEX"){let M=`bza${nanoid()}`,R=isArray(F)?F.map(k=>Bt(k)):Bt(F);if(Array.isArray(R))throw new Error("Array in FLEX fields not supported yet");return `has ${b} $${M}; $${M} '${M}' isa ${b}, has ${R.type}Attribute ${R.value}`}throw new Error(`Unsupported contentType ${Q.contentType}`)}).filter(D=>D),C=`${u}-atts`,A=listify(s,D=>{if(D.startsWith("$")||D.startsWith("%")||D===g)return "";let F=$.dataFields?.find(b=>b.path===D);if(!F?.path)return "";let E=F.dbPath;return `{${C} isa ${E};}`}).filter(D=>D),O=isArray(w)?`like '${w.join("|")}'`:`'${w}'`,x=w?[`has ${g} ${O}`]:[],W=[...x,...S].filter(D=>D).join(","),le=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${u} isa ${[B,...x].filter(D=>D).join(",")};`;if(f==="update"){if(!A.length)throw new Error("update without attributes");return `${u} isa ${[B,...x].filter(D=>D).join(",")}, has ${C};
37
- ${A.join(" or ")};`}return ""},K=()=>f==="update"||f==="link"||f==="match"?`${u} isa ${[B,...x].filter(D=>D).join(",")};`:"";if(Ue(s))return {op:f,deletionMatch:le(),insertionMatch:K(),insertion:f==="create"?`${u} isa ${[B,W].filter(D=>D).join(",")};`:f==="update"&&S.length?`${u} ${S.join(",")};`:"",deletion:f==="delete"?`${u} isa ${B};`:f==="update"&&A.length?`${u} has ${C};`:""};throw new Error("in attributes")},o=s=>{let f=s.$op,u=q(r,s),$=`$${s.$bzId}`,y=s.$id,m=u.defaultDBConnector?.path||s.$thing,B="roles"in u?listify(u.roles,F=>F):[],w="roles"in u?mapEntries(u.roles,(F,Q)=>[F,Q.dbConnector?.path||F]):{},g=listify(s,(F,Q)=>{if(!B.includes(F))return null;if(!("roles"in u))throw new Error("This should have roles! ");let E=w[F];return Array.isArray(Q)?Q.map(b=>({path:E,id:b})):{path:E,id:Q}}).filter(F=>F).flat(),S=g.map(F=>{if(!F?.path)throw new Error("Object without path");return `${F.path}: $${F.id}`}),C=g.length>0?`( ${S.join(" , ")} )`:"",A=s[Se];if(!A)throw new Error("[internal error] Symbol edgeType not defined");let O=C?`${$} ${C} ${A==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",x=`${$} ${A==="linkField"||f==="delete"?`isa ${m}`:""}`,W=()=>O?f==="link"?`${O};`:f==="create"?`${O}, has id '${y}';`:"":"",le=()=>O&&f==="match"?`${O};`:"",K=()=>O?f==="delete"?`${O};`:f==="match"?`${O};`:"":"",D=()=>O?f==="delete"?`${x};`:f==="unlink"?`${$} ${C};`:"":"";return {deletionMatch:K(),insertionMatch:le(),deletion:D(),insertion:W(),op:""}},n=(s,f)=>{let u=f==="edges"?o:i;if(Array.isArray(s))return s.map(g=>{let{preDeletionBatch:S,insertionMatch:C,deletionMatch:A,insertion:O,deletion:x}=u(g);return shake({preDeletionBatch:S,insertionMatch:C,deletionMatch:A,insertion:O,deletion:x},W=>!W)}).filter(g=>g);let{preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:w}=u(s);return shake({preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:w},g=>!g)},c=n(e),a=Array.isArray(c)?c:[c],h=n(t,"edges"),p=Array.isArray(h)?h:[h],l=[...a,...p];return shake({insertionMatches:l.map(s=>s.insertionMatch).join(" ").trim(),deletionMatches:l.map(s=>s.deletionMatch).join(" ").trim(),insertions:l.map(s=>s.insertion).join(" ").trim(),deletions:l.map(s=>s.deletion).join(" ").trim()},s=>!s)};var qe={};function X(e){return {enumerable:!0,value:e}}function Dr(e){return {enumerable:!0,writable:!0,value:e}}var fi=()=>!0,Ar=()=>({}),kr=e=>e,$i=(e,t,r,i)=>e.apply(r,i)&&t.apply(r,i),mi=(e,t,r,[i,o])=>t.call(r,e.call(r,i,o),o),be=(e,t)=>Object.freeze(Object.create(e,t));function Ir(e,t,r){return e.reduce((i,o)=>function(...n){return r(i,o,this,n)},t)}function Or(e){return be(this,{fn:X(e)})}var Pr={},V=Or.bind(Pr);var qr={},bt=Or.bind(qr);function et(e,t){return t.filter(r=>e.isPrototypeOf(r))}function xr(e,t,...r){let i=Ir(et(qr,r).map(n=>n.fn),fi,$i),o=Ir(et(Pr,r).map(n=>n.fn),kr,mi);return be(this,{from:X(e),to:X(t),guards:X(i),reducers:X(o)})}var jr={},Nr={},H=xr.bind(jr);xr.bind(Nr,null);function yi(e,t,r){return Mt(t,e,r,this.immediates)||e}function Wr(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 gi={enter:kr};function he(...e){let t=et(jr,e),r=et(Nr,e),i={final:X(e.length===0),transitions:X(Wr(t))};return r.length&&(i.immediates=X(r),i.enter=X(yi)),be(gi,i)}var Ei={enter(e,t,r){let i=this.fn.call(t,t.context,r);return wt.isPrototypeOf(i)?be(_r,{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)}},_r={enter(e,t,r){if(t.child=ye(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,Mt(t,e,{type:"done",data:i},this.transitions.get("done"))}return e}};function Z(e,...t){let r=X(Wr(t));return wt.isPrototypeOf(e)?be(_r,{machine:X(e),transitions:r}):be(Ei,{fn:X(e),transitions:r})}var wt={get state(){return {name:this.current,value:this.states[this.current]}}};function we(e,t,r=Ar){return typeof e!="string"&&(r=t||Ar,t=e,e=Object.keys(t)[0]),qe._create&&qe._create(e,t),be(wt,{context:X(r),current:X(e),states:X(t)})}function Mt(e,t,r,i){let{context:o}=e;for(let{to:n,guards:c,reducers:a}of i)if(c(o,r)){e.context=a.call(e,o,r);let h=t.original||t,p=be(h,{current:X(n),original:{value:h}});qe._onEnter&&qe._onEnter(t,n,e.context,o,r);let l=p.state.value;return e.machine=p,e.onChange(e),l.enter(p,e,r)}}function Bi(e,t){let r=t.type||t,{machine:i}=e,{value:o,name:n}=i.state;return o.transitions.has(r)?Mt(e,i,t,o.transitions.get(r))||i:(qe._send&&qe._send(r,n),i)}var Fi={send(e){Bi(this,e);}};function ye(e,t,r,i){let o=Object.create(Fi,{machine:Dr(e),context:Dr(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 Kr=(e,t)=>{if(!t)return;let r=wi(t);return Mi(r,e.query)},wi=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),Mi=(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 Jr=(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:c,meta:a}=n,h=c;if(isObject(h)){if(h.$id){if(a.nodePath?.includes(".$filter"))return;let p=h.$entity||h.$relation?h:{[`$${h.$thingType}`]:h.$thing},l=q(t,p);if(!l?.name)throw new Error(`Schema not found for ${h.$thing}`);if(h.$path=l.name,Array.isArray(h.$id)||(h.$filterByUnique=!0),l?.idFields?.length!==1)throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in h||"$relation"in h||"$thing"in h){let p=q(t,h);if(!p?.name)throw new Error(`Schema not found for ${h.$thing}`);h.$path=p.name;}if(h.$entity?(h.$thing=h.$entity,h.$thingType="entity",delete h.$entity):h.$relation&&(h.$thing=h.$relation,h.$thingType="relation",delete h.$relation),isObject(h)&&"$thing"in h&&h.$thing){let p=h.$entity||h.$relation?h:{[`$${h.$thingType}`]:h.$thing};h[te]=a.nodePath;let l=q(t,p);if(h.$filter&&(h.$filterByUnique=Lt(h.$filter,l),h.$filter=xe(h.$filter,h.$thing,t)),h.$fields){h.$fields.some(f=>l?.idFields?.includes(f?.$path||f))||(h.$fields=[...h.$fields,...Array.isArray(l.idFields)?l.idFields:[]],h.$idNotIncluded=!0);let s=h.$fields?.flatMap(f=>{let u=Ur(f,l,t);return Array.isArray(u)?u:[u]}).filter(Boolean);h.$fields=s;}else {let s=St(l)?.flatMap(f=>{let u=Ur(f,l,t);return Array.isArray(u)?u:[u]}).filter(Boolean);h.$fields=s;}h.$excludedFields&&(h.$fields=h.$fields.filter(d=>tt(l,d)?!0:!h.$excludedFields.includes(d.$path)));}}}))},St=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]},Lt=(e,t)=>Object.keys(e||{}).some(i=>{if(!Array.isArray(e[i])){let o=t.idFields?.includes(i),n=t.dataFields?.some(a=>(a.dbPath===i||a.path===i)&&a?.validations?.unique),c=i==="$id"&&!Array.isArray(e[i]);return o||n||c}return !1}),tt=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),Si=e=>{let{field:t,fieldStr:r,$justId:i,dbPath:o,isVirtual:n,fieldSchema:c}=e;return {$path:r,$dbPath:o,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:i,$id:t.$id,$isVirtual:n,[ie]:c}},Li=e=>{let{field:t,fieldStr:r,linkField:i,$justId:o,dbPath:n,schema:c,fieldSchema:a}=e,{target:h,oppositeLinkFieldsPlayedBy:p}=i;return p.map(l=>{let d=h==="role"?l.thingType:"relation",s=h==="role"?l.thing:i.relation,f={[`$${d}`]:s},u=q(c,f),$=t?.$fields?.filter(B=>tt(u,B)).length===0,y=[];if(typeof t!="string")if(t.$fields)if($){let B=u.idFields||[];y=[...t.$fields,...B];}else y=t.$fields;else y=St(u);else y=["id"];t.$excludedFields&&(y=y.filter(B=>tt(u,B)?!0:!t.$excludedFields.includes(B.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...xe(t.$filter,s,c)}:void 0;return {$thingType:d,$plays:i.plays,$playedBy:l,$path:l.path,$dbPath:n,$as:t.$as||r,$var:r,$thing:s,$fields:y,$excludedFields:t.$excludedFields,$fieldType:"link",$target:h,$intermediary:l.relation,$justId:o,$id:t.$id,$filter:m,$idNotIncluded:$,$filterByUnique:Lt(t.$filter,u),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:a}})},Ri=e=>{let{field:t,fieldStr:r,roleField:i,$justId:o,dbPath:n,schema:c,fieldSchema:a}=e;return i.playedBy.map(h=>{let{thing:p,thingType:l,relation:d}=h,s={[`$${l}`]:p},f=q(c,s),u=t?.$fields?.filter(m=>f?.idFields?.includes(m)||f?.idFields?.includes(m.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(u){let m=f.idFields||[];$=[...t.$fields,...m];}else $=t.$fields;else $=St(f);else $=["id"];t.$excludedFields&&($=$.filter(m=>tt(f,m)?!0:!t.$excludedFields.includes(m.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...xe(t.$filter,p,c)}:void 0;return {$thingType:l,$path:r,$dbPath:n,$as:t.$as||r,$var:r,$thing:p,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:d,$justId:o,$id:t.$id,$filter:y,$idNotIncluded:u,$filterByUnique:Lt(t.$filter,f),$playedBy:h,$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:a}})},Ur=(e,t,r)=>{let i=typeof e=="string"?e:e.$path,o=typeof e=="string",n=t.dataFields?.find(h=>h.path===i),c=t.linkFields?.find(h=>h.path===i),a=t.roles?.[i];if(n){let h=!!n.isVirtual&&!!n.default;return Si({field:e,fieldStr:i,$justId:o,dbPath:n.dbPath,isVirtual:h,fieldSchema:n})}else {if(c)return Li({field:e,fieldStr:i,linkField:c,$justId:o,dbPath:c.path,schema:r,fieldSchema:c});if(a)return Ri({field:e,fieldStr:i,roleField:a,$justId:o,dbPath:i,schema:r,fieldSchema:a})}return null},xe=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(c=>Object.keys(c).reduce((p,l)=>{let d=c[l],s=isArray(d)?d:[d];if(l.startsWith("$"))["$id","$thing"].includes(l)?p[l]=d:p[l]=xe(d,t,r);else {let f=t in r.entities?r.entities[t]:r.relations[t],[u,$]=Ie(f,l);if(u==="dataField")p[l]=d;else if(u==="linkField"||u==="roleField"){let y=$,[m]=y.$things;return s.every(B=>typeof B=="string")?p[l]={$id:s,$thing:m}:s.every(B=>isObject(B))&&(p[l]=isArray(d)?{$or:xe(d,m,r)}:xe(d,m,r)),p}else throw new Error(`Field ${l} not found in schema of ${t}`)}return p},{}));return i?n.length===1?n[0]:{$or:n}:n[0]};var vr=async(e,t,r)=>r?(n=>produce(n,c=>traverse(c,({value:a})=>{if(isObject(a)){let h=a;if(!h.$thing)return;if(h.$thing){let p=q(e,h),{virtualFields:l}=p,d=h[te];if(!d)throw new Error("[Internal] QueryPath is missing");let s=getNodeByPath(t,d),f=s.$fields.map($=>$.$path),u=s.$excludedFields;l.forEach($=>{if(u?.includes($)||f.length>0&&!f.includes($))return;let y=p.dataFields?.find(m=>m.path===$);if(y?.default){let m=Oe({currentThing:h,fieldSchema:y,mandatoryDependencies:!0});h[$]=m;}else if(h[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),u&&u.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete h[$];});}}})))(r):void 0;var Zr=e=>e.replace(/`/g,""),ki=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],rt=e=>ki.some(t=>e.includes(t))?`\u27E8\`${e}\`\u27E9`:e;var Gr=e=>{let{queries:t,schema:r}=e;return t.map(i=>Pi({query:i,schema:r}))},Pi=e=>{let{query:t,schema:r}=e,{$thing:i,$fields:o,$filter:n,$offset:c,$limit:a,$sort:h}=t;if(o.length===0)return null;let p=[];p.push("SELECT");let l=Rt({parentQuery:t,queries:o,level:1,schema:r});l&&p.push(l);let d=r.entities[i]||r.relations[i];if(!d)throw new Error(`Schema for ${i} not found`);let f=(d.subTypes?[i,...d.subTypes]:[i]).map(u=>rt(u));if(t.$id)if(typeof t.$id=="string")p.push(`FROM ${f.map(u=>`${u}:\`${t.$id}\``).join(",")}`);else if(isArray(t.$id)){let u=t.$id,$=f.flatMap(y=>u?.map(m=>`${y}:\`${m}\``));p.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else p.push(`FROM ${f.join(",")}`);if(n){let u=ge(n,i,r),$=Re(u);p.push(`WHERE ${$}`);}return h&&p.push(Xr(h)),typeof a=="number"&&p.push(`LIMIT ${a}`),typeof c=="number"&&p.push(`START ${c}`),p.join(`
38
- `)},Rt=e=>{let{queries:t,schema:r,level:i,parentQuery:o}=e,n=[],c=o[te];return n.push(T(`"${c}" as \`$$queryPath\``,i)),n.push(T("meta::id(id) as `$id`",i)),n.push(T("meta::tb(id) as `$thing`",i)),t.forEach(a=>{let h=qi({query:a,level:i,schema:r});h&&n.push(h);}),n.length===0?null:n.join(`,
39
- `)},qi=e=>{let{query:t,schema:r,level:i}=e;return t.$fieldType==="data"?xi({query:t,level:i}):t.$fieldType==="link"?ji({query:t,level:i,schema:r}):t.$fieldType==="role"?Ni({query:t,level:i,schema:r}):null},xi=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?T(`meta::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?T(`\`${t.$path}\``,r):T(`\`${t.$path}\` AS \`${t.$as}\``,r)},ji=e=>{let{query:t,schema:r,level:i}=e,{$fields:o,$filter:n,$offset:c,$limit:a,$sort:h}=t;if(o.length===0)return null;let p=[];p.push(T("(",i));let l=i+1;p.push(T("SELECT",l));let d=Rt({parentQuery:t,queries:o,level:l+1,schema:r});d&&p.push(d);let s=t[ie][me].queryPath;if(p.push(T(`FROM ${s}`,l)),n){let f=ge(n,t.$thing,r),u=Re(f);p.push(`WHERE ${u}`);}return h&&p.push(T(Xr(h),l)),typeof a=="number"&&p.push(T(`LIMIT ${a}`,l)),typeof c=="number"&&p.push(T(`START ${c}`,l)),p.push(T(`) AS \`${t.$as}\``,i)),p.join(`
40
- `)},Ni=e=>{let{query:t,schema:r,level:i}=e;if(t.$fields.length===0)return null;let o=[];o.push(T("(",i));let n=i+1;o.push(T("SELECT",n));let c=n+1,a=Rt({parentQuery:t,queries:t.$fields,level:c,schema:r});a&&o.push(a);let h=t[ie][me].queryPath;if(o.push(T(`FROM ${h}`,n)),t.$filter){let p=ge(t.$filter,t.$playedBy.thing,r),l=Re(p);o.push(`WHERE ${l}`);}return o.push(T(`) AS \`${t.$as}\``,i)),o.join(`
41
- `)},ge=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(c=>{let h=Object.keys(c).reduce((p,l)=>{let d=c[l];if(l.startsWith("$"))return l==="$not"?{...p,$not:void 0,"$!":ge(d,t,r)}:l==="$or"?{...p,$or:void 0,$OR:ge(d,t,r)}:l==="$and"?{...p,$and:void 0,$AND:ge(d,t,r)}:l==="$eq"?{...p,$nor:void 0,"$=":ge(d,t,r)}:l==="$id"?{...p,$id:void 0,"meta::id(id)":{$IN:isArray(d)?d:[d]}}:l==="$thing"?p:{...p,[l]:ge(d,t,r)};let s=t in r.entities?r.entities[t]:r.relations[t],[f,u]=Ie(s,l);if(f==="dataField"){if(s.idFields.length>1)throw new Error("Multiple id fields not supported");return l===s.idFields[0]?{...p,"meta::id(id)":{$IN:isArray(d)?d:[d]}}:{...p,[l]:d}}if(f==="linkField"||f==="roleField"){let $=u;if($.$things.length!==1)throw new Error(`Not supported yet: Role ${l} in ${d.name} is played by multiple things: ${$.$things.join(", ")}`);let[y]=$.$things,m=$[me].queryPath;return {...p,[m]:ge(d,y,r)}}throw new Error(`Field ${l} not found in schema, Defined in $filter`)},{});return shake(h)});return i?n:n[0]},Re=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("$",""),c=Array.isArray(o)?o.map(a=>Re(a)):[Re(o)];n==="!"?r.push(`!(${c.join(` ${n} `)})`):r.push(`(${c.join(` ${n} `)})`);return}if(isObject(o))if(i.includes("<-")||i.includes("->")){let n=Re(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),c=o[n];if(isArray(c))r.push(`${i} ${n.replace("$","")} [${c.map(a=>`'${a}'`).join(", ")}]`);else if(isObject(c)){let a=Re(c);r.push(`${i} ${n.replace("$","")} ${a}`);}else r.push(`${i} ${n.replace("$","")} '${c}'`);}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(c=>`'${c}'`).join(", ")}]`);}else {let n=i.startsWith("$")?i.replace("$",""):"=";r.push(`${i} ${n} '${o}'`);}}),r.join(" AND ")},Xr=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 en=async e=>{let{client:t,queries:r}=e,i=`
36
+ ${y}`})(),n=e.dbConnectors[0].id,s=r.typeDB.get(n)?.session,a=r.typeDB.get(n)?.client;if(!s){console.log("Session Status: ","NO SESSION");return}await s.close();let[{dbName:u}]=e.dbConnectors;await(await a.databases.get(u)).delete(),await a.databases.create(u);let c=await a.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 l=await c.transaction(TransactionType.READ);(await(await l.query.match("match $a sub thing;")).collect()).forEach(async y=>{y.get("a");}),await l.close();};var re=Symbol.for("queryPath"),Ve=Symbol.for("stepPrint"),Qe=Symbol.for("edgeType"),Me=Symbol.for("edgeSchema"),ke=Symbol.for("dbNode"),pt=Symbol.for("isTransformed"),Ue=Symbol.for("parent"),ne=Symbol.for("fieldSchema"),Be=Symbol.for("sharedMetadata"),be=Symbol.for("suqlMetadata");var rr={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var nr=({linkField:e,originalRelation:t,withExtensionsSchema:r,linkMode:i})=>{if(e.isVirtual)return `$this.${e.path}.id`;let o=r.relations[e.relation].subTypes||[],n=[e.relation,...o],s=`<-\u27E8${t}_${e.plays}\u27E9<-(\u27E8${n.join("\u27E9,\u27E8")}\u27E9)`;if(e.target==="relation"){if(i==="edges")return s;if(i==="refs")return `$parent.\`${e.path}\``;throw new Error("Unsupported linkMode")}else if(e.target==="role"){let[a]=e.oppositeLinkFieldsPlayedBy,u=r.entities[a.thing]?.subTypes||r.relations[a.thing]?.subTypes||[],f=[a.thing,...u],c=`->\u27E8${t}_${a.plays}\u27E9->(\u27E8${f.join("\u27E9,\u27E8")}\u27E9)`;return i==="edges"?`${s}${c}`:i==="refs"?`$parent.\`${a.plays}\``:`${s}${c}`}else throw new Error("Unsupported linkField target")};var sr=(e,t,r)=>r?t:`${e}\xB7${t}`;var lr=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))))[0],ae=(e,t)=>{let r=Reflect.ownKeys(e).map(i=>[i,e[i]]);return Object.fromEntries(r.filter(([i,o])=>{let[n,s]=tryit(()=>t(i,o))();return n?!1:s}))},cr=(e,t)=>{let r=[],i=produce(e,n=>traverse(n,({key:s,value:a,meta:u})=>{if(u.depth===2&&(s&&(a.dataFields=a.dataFields?.map(f=>({...f,cardinality:f.cardinality||"ONE",dbPath:"dbPath"in f?f.dbPath:sr(s,f.path,f.shared)}))),a.extends)){if(!a.defaultDBConnector.as)throw new Error(`[Schema] ${s} is extending a thing but missing the "as" property in its defaultDBConnector. Path:${u.nodePath}`);let f=n.entities[a.extends]||n.relations[a.extends],c=[a.extends,...f.allExtends||[]];if(a.allExtends=c,c.forEach(d=>{if(n.entities[d])n.entities[d].subTypes=[s,...n.entities[d].subTypes||[]];else if(n.relations[d])n.relations[d].subTypes=[s,...n.relations[d].subTypes||[]];else throw new Error(`[Schema] ${s} is extending a thing that does not exist in the schema: ${d}`)}),a.idFields=f.idFields?Array.from(new Set((a.idFields||[]).concat(f.idFields))):a.idFields,a.dataFields=f.dataFields?(a.dataFields||[]).concat(f.dataFields.map(d=>{let l=a.extends,p=e.entities[l]||e.relations[l];for(;!p.dataFields?.find(h=>h.path===d.path);)l="extends"in p?p.extends:void 0,p=e.entities[l]||e.relations[l];return {...d,dbPath:"dbPath"in d?d.dbPath:sr(l,d.path,d.shared),[Be]:{inheritanceOrigin:d[Be]?.inheritanceOrigin||a.extends}}})):a.dataFields,"roles"in f){let d=a,l=f;if(l.roles){let p=mapEntries(l.roles,(h,$)=>[h,{...$,[Be]:{inheritanceOrigin:$[Be]?.inheritanceOrigin||a.extends}}]);d.roles={...d.roles||{},...p};}}a.linkFields=f.linkFields?(a.linkFields||[]).concat(f.linkFields.map(d=>({...d,[Be]:{inheritanceOrigin:d[Be]?.inheritanceOrigin||a.extends}}))):a.linkFields,f?.hooks?.pre&&(a.hooks=a.hooks||{},a.hooks.pre=a.hooks.pre||[],a.hooks.pre=[...f?.hooks?.pre||[],...a?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:n,value:s,meta:a})=>{if(n==="linkFields"){let f=(()=>{if(!a.nodePath)throw new Error("No path");let[d,l]=a.nodePath.split(".");return {thing:l,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),c=Array.isArray(s)?s.map(d=>({...d,...f})):[{...s,...f}];r.push(...c);}}),produce(i,n=>traverse(n,({value:s,key:a,meta:u})=>{if(u.depth===2&&s.idFields&&!s.id){s.name=a;let f=()=>{if(u.nodePath?.split(".")[0]==="entities")return "entity";if(u.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};s.thingType=f();let c=Object.keys(t).find(d=>t[d]?.get(s.defaultDBConnector.id));if(s.db=c,s.dbContext=rr[c],s.dbProviderConfig=c==="surrealDB"?t[c]?.get(s.defaultDBConnector.id)?.providerConfig:void 0,s.computedFields=[],s.virtualFields=[],s.requiredFields=[],s.enumFields=[],s.fnValidatedFields=[],"roles"in s&&Object.entries(s.roles).forEach(([l,p])=>{p.fieldType="roleField";let h=r.filter(F=>F.relation===a&&F.plays===l)||[];p.playedBy=h,p.path=l;let $=[...new Set(h.map(F=>F.thing))];p.$things=$;let y=p[Be]?.inheritanceOrigin||s.name;$.length>1&&console.warn(`Not supported yet: Role ${l} in ${s.name} is played by multiple things: ${$.join(", ")}`);let m=$.flatMap(F=>{let Q=G(e,F)?.subTypes||[];return [F,...Q]}),B=()=>{if(s.dbProviderConfig.linkMode==="edges")return `->\`${y}_${l}\`->(\`${m.join("`,`")}\`)`;if(s.dbProviderConfig.linkMode==="refs"){if(p.cardinality==="MANY")return `$parent.\`${l}\``;if(p.cardinality==="ONE")return `$parent.[\`${l}\`]`}throw new Error("Unsupported linkMode")};if(s.db==="surrealDB"){let F=B();p[be]={queryPath:F};}}),"linkFields"in s&&s.linkFields){let d=s;d.linkFields?.forEach(l=>{l.fieldType="linkField";let p=i.relations[l.relation];if(!l.isVirtual){if(!p)throw new Error(`The relation ${l.relation} does not exist in the schema`);if(p.roles?.[l.plays]===void 0)throw new Error(`The role ${l.plays} is not defined in the relation ${l.relation} (linkField: ${l.path})`)}if(l.target==="relation"){if(l.isVirtual)throw new Error(`[Schema] Virtual linkFields can't target a relation. Thing: "${d.name}" LinkField: "${l.path}. Path:${u.nodePath}."`);l.$things=[l.relation],l.oppositeLinkFieldsPlayedBy=[{plays:l.path,thing:l.relation,thingType:"relation"}];}if(l.target==="role"){let h=r.filter($=>$.relation===l.relation&&$.plays!==l.plays)||[];if(l.oppositeLinkFieldsPlayedBy=h,l.oppositeLinkFieldsPlayedBy=l.oppositeLinkFieldsPlayedBy.filter($=>$.target==="role"),l.oppositeLinkFieldsPlayedBy.length===0)throw new Error(`[Schema] LinkFields require to have at least one opposite linkField playing an opposite role. Thing: "${d.name}" LinkField: "${l.path}. Path:${u.nodePath}."`);l.$things=l.oppositeLinkFieldsPlayedBy.map($=>$.thing),l.oppositeLinkFieldsPlayedBy.length>1&&console.warn(`[Schema] LinkField ${l.path} in ${d.name} has multiple candidates ${l.oppositeLinkFieldsPlayedBy.map($=>$.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`);}if(s.db==="surrealDB"){let h=p?.roles?.[l.plays][Be]?.inheritanceOrigin??l.relation,$=nr({linkField:l,originalRelation:h,withExtensionsSchema:i,linkMode:s.dbProviderConfig.linkMode});l[be]={queryPath:$};}});}}if(s&&typeof s=="object"&&"playedBy"in s){let f=[...new Set(s.playedBy.map(c=>c.thing))];if(f.length>1&&console.warn(`[Schema] roleFields can be only played by one thing. Role: ${a}, path:${u.nodePath}, played by: ${f.join(", ")}`),s.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${a}, path:${u.nodePath}`)}if(u.depth===4){let[f,c]=u.nodePath?.split(".")||[],d=n[f][c];!isArray(s)&&typeof s=="object"&&(s.validations&&(s.validations.required&&d.requiredFields.push(s.path),s.validations.enum&&d.enumFields.push(s.path),s.validations.fn&&d.fnValidatedFields.push(s.path)),s.default?s.isVirtual?d.virtualFields.push(s.path):d.computedFields.push(s.path):s.isVirtual&&d.virtualFields.push(s.path));}}))},G=(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)}`)},Ke=(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`)},Je=(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},dr=(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")},mt=(e,t,r)=>{let i=x(e,t),o=i.linkFields?.find(a=>a.path===r);if(o)return o;let n=i.dataFields?.find(a=>a.path===r);if(n)return n;let s="roles"in i?i.roles?.[r]:void 0;if(s)return s;throw new Error(`Field ${r} not found in schema`)},yt=(e,t,r)=>mt(e,t,r)?.cardinality,le=(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||[]],a=[...["$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=>!a.includes(h)).filter(h=>h),l=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:l}:{},...c.length?{nestedFilters:p}:{}}};var ur=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},hr=(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):{}},we=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var ve=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),ge=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},he=(e,t)=>{if(e===void 0)throw t?new Error(t):new Error("Value is undefined");return e},S=(e,t)=>{let r="";for(let i=0;i<t;i++)r+=" ";return `${r}${e}`},Le=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",e??21)();var Oe=(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 fr=(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=Oe(t,r),[n]=o,s=e.$op==="create"?"link":"replace",a=n.thing,u=n.thingType,f={$op:s,$thing:a,$thingType:u},c=i.filter(l=>l.startsWith("_:")),d=i.filter(l=>!l.startsWith("_:"));c.length&&!d.length?e[t]=c.map(l=>({...f,$tempId:l,$bzId:l})):c.length&&d.length?e[t]=[...c.map(l=>({...f,$tempId:l,$bzId:l})),{...f,$id:d,$bzId:`S_${nanoid()}`}]:e[t]={...f,$id:e[t],$bzId:`S_${nanoid()}`};}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 Re=(e,t,r)=>{let i=x(r,t),{usedDataFields:o}=le(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 Ye=(e,t,r)=>{let i=x(r,t),{usedFields:o}=le(i,t);return t.$op?(Re(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(Re(e,{...t,$op:"update"},r),"update"):(Re(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(Re(e,{...t,$op:"create"},r),"create"):(Re(e,{...t,$op:"create"},r),"link"):(Re(e,{...t,$op:"create"},r),"create")};var mr=(e,t)=>{let i=(isArray(e.$root)?e.$root:[e.$root]).map(o=>{let n=Ye(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:dr(o,t)},...o.$op?{}:{$op:n},...o.$bzId?{}:{$bzId:`R_${Le()}`}},...o}});e.$root=isArray(e.$root)?i:i[0];};var Ge=(e,t)=>{let r=t[Ve];return isSet(r)?r.has("clean")?(Reflect.set(t,Ve,r.add("clean")),!0):!1:(Reflect.set(t,Ve,new Set(["clean"])),!0)};var yr=(e,t,r)=>{if(Ge("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((s,a)=>({...ge(n),$id:s,$bzId:`${n.$bzId}_${a}`,...we(n)}))}return o});(i.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=i);}};var gr=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{let s=Oe(t,r),[a]=s,u=Ye(e,{...n,$thing:a.thing,$thingType:a.thingType},i),c=n.$bzId?n.$bzId:n.$tempId?n.$tempId:n.$id&&!isArray(n.$id)?`SN_ONE_${a.thing}_${n.$id}`:n.$id&&isArray(n.$id)?`SN_MANY_${a.thing}_${Le()}`:`SM_${Le()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...n,[Me]:r,$thing:a.thing,$thingType:a.thingType,$op:u,$bzId:c}});e[t]=isArray(e[t])?o:o[0];};var ni=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,ii=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Er=e=>{let r=e.toString().replace(ni,"").trim().split("=>")[0].split("{")[0].replace(ii,"").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(a=>a.split(":")[0].trim().replace(/['"[\]]/g,"")):n.trim()).filter(Boolean):[]};var qe=({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,s=Er(o).filter(a=>!(a in e));if(s.length)throw new Error(`Virtual field: Missing arguments ${s.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 Br=(e,t,r)=>{let i=e[t];if(i)return (isArray(i)?i:[i]).forEach(o=>{let n=x(r,o),{unidentifiedFields:s}=le(n,o),{computedFields:a,virtualFields:u}=n,f=listify(o,(l,p)=>p!==void 0?l:void 0),c=f.filter(l=>u?.includes(l));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(a.filter(l=>!f.includes(l)).forEach(l=>{let p=n.dataFields?.find(B=>B.path===l),$=n.linkFields?.find(B=>B.path===l)?.oppositeLinkFieldsPlayedBy[0],y="roles"in n?lr(n.roles,(B,F)=>B===l):void 0,m=p||$||y;if(!m)throw new Error(`no field Def for ${l}`);if(o.$op==="create"&&!o[l]){let B=qe({currentThing:o,fieldSchema:m,mandatoryDependencies:!0});o[l]=B;}}),s.length>0)throw new Error(`Unknown fields: [${s.join(",")}] in ${JSON.stringify(o)}`)}),e};var Xe=(e,t)=>{let r=x(t,e).hooks;if(r?.pre){let i=`on${ur(e.$op)}`;return r.pre.filter(s=>!s.triggers||s.triggers[i]?.()).flatMap(s=>s.actions)}return []};var Mr=(e,t,r,i)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(n=>{if("$thing"in n){if(n.$fields)return n;let{requiredFields:s,enumFields:a,fnValidatedFields:u,dataFields:f}=x(r,n);if("$op"in n&&n.$op==="create"&&s.forEach(c=>{if(!(c in n))throw new Error(`[Validations] Required field "${c}" is missing.`)}),("$op"in n&&n.$op==="update"||n.$op==="create")&&a.forEach(c=>{if(c in n){let d=f?.find(l=>l.path===c)?.validations?.enum;if(!d)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(isArray(n[c]))n[c].some(l=>{if(!d.includes(l))throw new Error(`[Validations] Option "${l}" 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(l=>l.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,l=clone(ge(e)),p=clone(ge(d)),h=i.mutation?.context||{},$=clone(ge(n[ke]||{}));Xe(d,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let B=m.fn(p,l,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 wr=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{if(ve(n)){if(n.$fields||n[pt])return n;let s=Xe(n,r).filter(d=>d.type==="transform"),a=clone(ge(e)),u=clone(ge(n)),f=i.mutation?.context||{},c=clone(ge(n[ke]||n.$dbNode));return s.forEach(d=>{let l=d.fn(u,a,f,c||{});Object.keys(l).length!==0&&(n={...u,...l,...we(n),[pt]:!0});}),n}});e[t]=isArray(e[t])?o:o[0];};var Tr=(e,t,r)=>{let i=Oe(t,r),[o]=i;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Me]:r};};var Pe=e=>{if(Array.isArray(e)){for(let t of e)if(Pe(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"&&Pe(e[t]))return !0}return !1};var fi=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(Ge("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")},$i=(e,t)=>{},Mt=(e,t,r)=>{let i={$rootWrap:{$root:e}},o=Pe(Array.isArray(e)?e:[e]),n=produce(i,s=>traverse(s,({value:a,parent:u,key:f,meta:c})=>{if(!(!u||!f)&&isObject(a)){let d=c.nodePath?.split(".")||[];if(!("$root"in a)){if(!("$thing"in a||"$entity"in a||"$relation"in a)){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(a)?current(a):a)}`)}}let l=a,p=d.includes("$filter");Object.keys(l).forEach(h=>{if(fi(l,h),h!=="$root"&&p||h!=="$root"&&(h.startsWith("$")||h.startsWith("%")))return;let $=h!=="$root"?mt(t,l,h):{fieldType:"rootField"};if(!$)throw new Error(`[Internal] Field ${h} not found in schema`);if("contentType"in $)return $i();if(["rootField","linkField","roleField"].includes($.fieldType)){if(["linkField","roleField"].includes($.fieldType)&&(l[h]===null?Tr(l,h,$):fr(l,h,$)),$.fieldType==="rootField"){if(!("$root"in l))throw new Error(`[Internal] Field ${h} is a rootField but the object is not a root`);mr(l,t);}let y=isArray(l[h])?l[h]:[l[h]],m=d.slice(1).join(".");y.forEach(F=>{if(F){if($?.cardinality==="ONE"&&!F.$op&&!F.$id&&!F.$filter&&!F.$tempId&&l.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${m}.${h}`);if(F.$tempId&&!(F.$op===void 0||F.$op==="link"||F.$op==="create"||F.$op==="update"))throw new Error(`Invalid op ${F.$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)&&gr(l,h,$,t),yr(l,h,t),["rootField","linkField","roleField"].includes($.fieldType)&&Br(l,h,t),(isArray(l[h])?l[h]:[l[h]]).forEach(F=>{let g=x(t,F),{unidentifiedFields:Q,usedLinkFields:L,usedFields:R,fields:A}=le(g,F);if(R.forEach(P=>{if(!A.includes(P))throw new Error(`[Schema] Field ${P} not found in the schema`)}),Q.length>0)throw new Error(`Unknown fields: [${Q.join(",")}] in ${JSON.stringify(a)}`);if(L.length>1){let P=g.linkFields?.filter(z=>L.includes(z.path));P?.some((z,Z)=>P.some((W,I)=>{if(Z!==I&&z.target!==W.target&&z.relation===W.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||(wr(l,h,t,r),Mr(l,h,t,r));}});}}));return isArray(n.$rootWrap.$root),n.$rootWrap.$root};var Sr=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 Dr=async(e,t)=>{let r=c=>{let d=[],l=[],p=m=>{if(m.$id)return m.$id;let B=x(t,m),{idFields:F}=B;if(!F)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[g]=F;if(!g)throw new Error(`no idField: ${JSON.stringify(m)}`);let Q=B.dataFields?.find(A=>A.path===g),L=qe({currentThing:m,fieldSchema:Q,mandatoryDependencies:!0}),R=m[g]||m.$id||L;if(!R)throw new Error(`no idValue: ${JSON.stringify(m)}`);return R},h=m=>{if(m.$op==="create"){let B=p(m);if(d.find(F=>F.$id===B&&F.$op==="create"))throw new Error(`Duplicate id ${B} for node ${JSON.stringify(m)}`);if(l.find(F=>F.$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(F=>F.$id===B),l.find(F=>F.$bzId===m.$bzId))throw new Error(`Duplicate %bzId ${m.$bzIdd} for edge ${JSON.stringify(m)}`);l.push({...m,$id:B});return}l.push(m);};return traverse(c,({value:m,parent:B,meta:F})=>{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 Q=x(t,g),{dataFields:L,roleFields:R,linkFields:A,usedFields:P}=le(Q,g),z=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let I=P.filter(E=>L?.includes(E)),M=P.filter(E=>R?.includes(E)),b=P.filter(E=>A?.includes(E));if(I.length>0)return "update";if(M.length>0||b.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},Z={...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,L||[""])),$op:z(),$bzId:g.$bzId};h(Z);let W=g[Me];if(W?.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 I=W.relation===g.$thing,M=I?g.$bzId:`LT_${v4()}`,E=hr(c,B,F).$bzId;if(!E)throw new Error("No parent id found");let w=()=>g.$op==="delete"?I?"match":"delete":g.$op==="unlink"?I?"unlink":"delete":g.$op==="link"||g.$op==="create"?I?"link":"create":g.$op==="replace"?"replace":"match",T=x(t,{$thing:W.relation,$thingType:"relation"});if(!Object.keys(T.roles).includes(W.plays))throw new Error(`[Wrong format] Field ${W.plays} is not a role of relation ${W.relation}`);let O={$bzId:M,$thing:W.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:w(),...I?{}:{[W.path]:g.$bzId},[W.plays]:E,[Me]:W,[Qe]:"linkField"};$(O),(g.$op==="unlink"||w()==="unlink")&&I&&$({$thing:W.relation,$thingType:"relation",$bzId:M,$op:"match",[W.plays]:E,[Me]:W,[Qe]:"linkField"});}if(g.$thingType==="relation"){let I=ae(g,(E,w)=>R.includes(E)),M=mapEntries(I,(E,w)=>isArray(w)?[E,w]:isObject(w)?[E,w.$bzId]:[E,w]),b=ae(m,(E,w)=>E.startsWith("$")||E.startsWith("Symbol"));if(Object.keys(I).filter(E=>!E.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let E=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},w=x(t,g).roles,T=mapEntries(M,(O,D)=>{let V=w[O]?.cardinality;if(!V)throw new Error(`Role ${O} not found in schema`);if(Array.isArray(D)){if(V==="ONE"){if(D.length>1)throw new Error(`[Error] Role ${O} is not a MANY relation`);return [O,D[0].$bzId||D[0]]}return [O,D.map(v=>v.$bzId||v)]}return [O,D.$bzId||D]}),C={...b,$thing:g.$thing,$thingType:"relation",$op:E(),...T,$bzId:g.$bzId,[Qe]:"roleField"};$(C);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(I).length>0){let E=0;Object.entries(I).forEach(([w,T])=>{let C=isArray(T)?T:[T],O=D=>D==="create"||D==="replace"?"link":D;C.forEach(D=>{if(!D)return;let V=O(D.$op);if(V==="replace")throw new Error("Not supported yet: replace on roleFields");if(V==="unlink"&&E>0)throw E+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let v={...b,$thing:g.$thing,$thingType:"relation",$op:V==="delete"?"unlink":V,[w]:D.$bzId,$bzId:g.$bzId,[Qe]:"roleField"};$(v);});});}}}}}),[d,l]},[i,o]=r(e),n=i.reduce((c,d)=>{if(!d.$bzId)return [...c,d];let l=c.findIndex(p=>p.$bzId===d.$bzId);if(l===-1)return [...c,d];if(c[l].$op==="create"&&d.$op==="match")return c;if(c[l].$op==="match"&&(d.$op==="create"||d.$op==="match"))return [...c.slice(0,l),d,...c.slice(l+1)];if(c[l].$op==="update"&&d.$op==="update")return [...c.slice(0,l),{...c[l],...d},...c.slice(l+1)];if(c[l].$op==="update"&&d.$op==="match"||c[l].$op==="match"&&d.$op==="update")return [...c.slice(0,l),{...c[l],...d,$op:"update"},...c.slice(l+1)];if(c[l].$op==="delete"&&d.$op==="delete"){if(JSON.stringify(c[l].$filter)===JSON.stringify(d.$filter))return c;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${c[l].$filter}. Current: ${d.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${d.$tempId||d.$id}". Existing: ${c[l].$op}. Current: ${d.$op}`)},[]),s=o.reduce((c,d)=>{let l=c.find(p=>(p.$id&&p.$id===d.$id||p.$bzId&&p.$bzId===d.$bzId)&&p.$thing===d.$thing&&p.$op===d.$op);if(l){let p={...l};return Object.keys(d).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let y=l[$],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)&&s.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(Sr(c))}`)}});let a=[...n,...s],u=new Set(a.filter(c=>c.$tempId).map(c=>c.$tempId)),f=Array.from(u).filter(c=>!a.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:s}};var xe={};function ee(e){return {enumerable:!0,value:e}}function Cr(e){return {enumerable:!0,writable:!0,value:e}}var Mi=()=>!0,Ir=()=>({}),kr=e=>e,bi=(e,t,r,i)=>e.apply(r,i)&&t.apply(r,i),wi=(e,t,r,[i,o])=>t.call(r,e.call(r,i,o),o),Te=(e,t)=>Object.freeze(Object.create(e,t));function Ar(e,t,r){return e.reduce((i,o)=>function(...n){return r(i,o,this,n)},t)}function Or(e){return Te(this,{fn:ee(e)})}var qr={},j=Or.bind(qr);var Pr={},bt=Or.bind(Pr);function et(e,t){return t.filter(r=>e.isPrototypeOf(r))}function xr(e,t,...r){let i=Ar(et(Pr,r).map(n=>n.fn),Mi,bi),o=Ar(et(qr,r).map(n=>n.fn),kr,wi);return Te(this,{from:ee(e),to:ee(t),guards:ee(i),reducers:ee(o)})}var jr={},Nr={},N=xr.bind(jr);xr.bind(Nr,null);function Ti(e,t,r){return Tt(t,e,r,this.immediates)||e}function zr(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 Si={enter:kr};function ie(...e){let t=et(jr,e),r=et(Nr,e),i={final:ee(e.length===0),transitions:ee(zr(t))};return r.length&&(i.immediates=ee(r),i.enter=ee(Ti)),Te(Si,i)}var Qi={enter(e,t,r){let i=this.fn.call(t,t.context,r);return wt.isPrototypeOf(i)?Te(Wr,{machine:ee(i),transitions:ee(this.transitions)}).enter(e,t,r):(i.then(o=>t.send({type:"done",data:o})).catch(o=>t.send({type:"error",error:o})),e)}},Wr={enter(e,t,r){if(t.child=$e(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,Tt(t,e,{type:"done",data:i},this.transitions.get("done"))}return e}};function H(e,...t){let r=ee(zr(t));return wt.isPrototypeOf(e)?Te(Wr,{machine:ee(e),transitions:r}):Te(Qi,{fn:ee(e),transitions:r})}var wt={get state(){return {name:this.current,value:this.states[this.current]}}};function me(e,t,r=Ir){return typeof e!="string"&&(r=t||Ir,t=e,e=Object.keys(t)[0]),xe._create&&xe._create(e,t),Te(wt,{context:ee(r),current:ee(e),states:ee(t)})}function Tt(e,t,r,i){let{context:o}=e;for(let{to:n,guards:s,reducers:a}of i)if(s(o,r)){e.context=a.call(e,o,r);let u=t.original||t,f=Te(u,{current:ee(n),original:{value:u}});xe._onEnter&&xe._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 Li(e,t){let r=t.type||t,{machine:i}=e,{value:o,name:n}=i.state;return o.transitions.has(r)?Tt(e,i,t,o.transitions.get(r))||i:(xe._send&&xe._send(r,n),i)}var Ri={send(e){Li(this,e);}};function $e(e,t,r,i){let o=Object.create(Ri,{machine:Cr(e),context:Cr(e.context(r,i)),onChange:ee(t)});return o.send=o.send.bind(o),o.machine=o.machine.state.value.enter(o.machine,o,i),o}var Hr=(e,t)=>{if(!t)return;let r=Ci(t);return Ii(r,e.query)},Ci=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),Ii=(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 Jr=(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:s,meta:a}=n,u=s;if(isObject(u)){if(u.$id){if(a.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[re]=a.nodePath;let c=x(t,f);if(u.$filter&&(u.$filterByUnique=Rt(u.$filter,c),u.$filter=je(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 l=u.$fields?.flatMap(p=>{let h=Kr(p,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);u.$fields=l;}else {let l=Lt(c)?.flatMap(p=>{let h=Kr(p,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);u.$fields=l;}u.$excludedFields&&(u.$fields=u.$fields.filter(d=>tt(c,d)?!0:!u.$excludedFields.includes(d.$path)));}}}))},Lt=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]},Rt=(e,t)=>Object.keys(e||{}).some(i=>{if(!Array.isArray(e[i])){let o=t.idFields?.includes(i),n=t.dataFields?.some(a=>(a.dbPath===i||a.path===i)&&a?.validations?.unique),s=i==="$id"&&!Array.isArray(e[i]);return o||n||s}return !1}),tt=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),Oi=e=>{let{field:t,fieldStr:r,$justId:i,dbPath:o,isVirtual:n,fieldSchema:s}=e;return {$path:r,$dbPath:o,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:i,$id:t.$id,$isVirtual:n,[ne]:s}},qi=e=>{let{field:t,fieldStr:r,linkField:i,$justId:o,dbPath:n,schema:s,fieldSchema:a}=e,{target:u,oppositeLinkFieldsPlayedBy:f}=i;return f.map(c=>{let d=u==="role"?c.thingType:"relation",l=u==="role"?c.thing:i.relation,p={[`$${d}`]:l},h=x(s,p),$=t?.$fields?.filter(B=>tt(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=Lt(h);else y=["id"];t.$excludedFields&&(y=y.filter(B=>tt(h,B)?!0:!t.$excludedFields.includes(B.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...je(t.$filter,l,s)}:void 0;return {$thingType:d,$plays:i.plays,$playedBy:c,$path:c.path,$dbPath:n,$as:t.$as||r,$var:r,$thing:l,$fields:y,$excludedFields:t.$excludedFields,$fieldType:"link",$target:u,$intermediary:c.relation,$justId:o,$id:t.$id,$filter:m,$idNotIncluded:$,$filterByUnique:Rt(t.$filter,h),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ne]:a}})},Pi=e=>{let{field:t,fieldStr:r,roleField:i,$justId:o,dbPath:n,schema:s,fieldSchema:a}=e;return i.playedBy.map(u=>{let{thing:f,thingType:c,relation:d}=u,l={[`$${c}`]:f},p=x(s,l),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 $=Lt(p);else $=["id"];t.$excludedFields&&($=$.filter(m=>tt(p,m)?!0:!t.$excludedFields.includes(m.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...je(t.$filter,f,s)}: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:Rt(t.$filter,p),$playedBy:u,$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ne]:a}})},Kr=(e,t,r)=>{let i=typeof e=="string"?e:e.$path,o=typeof e=="string",n=t.dataFields?.find(u=>u.path===i),s=t.linkFields?.find(u=>u.path===i),a=t.roles?.[i];if(n){let u=!!n.isVirtual&&!!n.default;return Oi({field:e,fieldStr:i,$justId:o,dbPath:n.dbPath,isVirtual:u,fieldSchema:n})}else {if(s)return qi({field:e,fieldStr:i,linkField:s,$justId:o,dbPath:s.path,schema:r,fieldSchema:s});if(a)return Pi({field:e,fieldStr:i,roleField:a,$justId:o,dbPath:i,schema:r,fieldSchema:a})}return null},je=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(s=>Object.keys(s).reduce((f,c)=>{let d=s[c],l=isArray(d)?d:[d];if(c.startsWith("$"))["$id","$thing"].includes(c)?f[c]=d:f[c]=je(d,t,r);else {let p=t in r.entities?r.entities[t]:r.relations[t],[h,$]=Ke(p,c);if(h==="dataField")f[c]=d;else if(h==="linkField"||h==="roleField"){let y=$,[m]=y.$things;return l.every(B=>typeof B=="string")?f[c]={$id:l,$thing:m}:l.every(B=>isObject(B))&&(f[c]=isArray(d)?{$or:je(d,m,r)}:je(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 vr=async(e,t,r)=>r?(n=>produce(n,s=>traverse(s,({value:a})=>{if(isObject(a)){let u=a;if(!u.$thing)return;if(u.$thing){let f=x(e,u),{virtualFields:c}=f,d=u[re];if(!d)throw new Error("[Internal] QueryPath is missing");let l=getNodeByPath(t,d),p=l.$fields.map($=>$.$path),h=l.$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=qe({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 Yr=e=>e.replace(/`/g,""),Wi=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],De=e=>Wi.some(t=>e.includes(t))?`\u27E8${e}\u27E9`:e;var ce=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(s=>{let u=Object.keys(s).reduce((f,c)=>{let d=s[c];if(c.startsWith("$"))return c==="$not"?{...f,$not:void 0,"$!":ce(d,t,r)}:c==="$or"?{...f,$or:void 0,$OR:ce(d,t,r)}:c==="$and"?{...f,$and:void 0,$AND:ce(d,t,r)}:c==="$eq"?{...f,$nor:void 0,"$=":ce(d,t,r)}:c==="$id"?{...f,$id:void 0,"record::id(id)":{$IN:isArray(d)?d:[d]}}:c==="$thing"?f:{...f,[c]:ce(d,t,r)};let l=t in r.entities?r.entities[t]:r.relations[t],[p,h]=Ke(l,c);if(p==="dataField"){if(l.idFields.length>1)throw new Error("Multiple id fields not supported");return c===l.idFields[0]?{...f,"record::id(id)":{$IN:isArray(d)?d:[d]}}:{...f,[c]:d}}if(p==="linkField"||p==="roleField"){let $=h;if($.$things.length!==1)throw new Error(`Not supported yet: Role ${c} in ${d.name} is played by multiple things: ${$.$things.join(", ")}`);let[y]=$.$things,m=$[be].queryPath;return {...f,[m]:ce(d,y,r)}}throw new Error(`Field ${c} not found in schema, Defined in $filter`)},{});return shake(u)});return i?n:n[0]},pe=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("$",""),s=Array.isArray(o)?o.map(a=>pe(a)):[pe(o)];n==="!"?r.push(`!(${s.join(` ${n} `)})`):r.push(`(${s.join(` ${n} `)})`);return}if(isObject(o))if(i.includes("<-")||i.includes("->")){let n=pe(o);r.push(`${i}[WHERE ${n}]`);}else if(i.startsWith("$parent")){let n=pe(o),s=i.replace("$parent.","");r.push(`${s}[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),s=o[n];if(isArray(s))r.push(`${i} ${n.replace("$","")} [${s.map(a=>`'${a}'`).join(", ")}]`);else if(isObject(s)){let a=pe(s);r.push(`${i} ${n.replace("$","")} ${a}`);}else r.push(`${i} ${n.replace("$","")} '${s}'`);}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(s=>`'${s}'`).join(", ")}]`);}else {let n=i.startsWith("$")?i.replace("$",""):"=";r.push(`${i} ${n} '${o}'`);}}),r.join(" AND ")},Ne=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 Zr=e=>{let{queries:t,schema:r}=e;return t.map(i=>Ui({query:i,schema:r}))},Ui=e=>{let{query:t,schema:r}=e,{$thing:i,$fields:o,$filter:n,$offset:s,$limit:a,$sort:u}=t;if(o.length===0)return null;let f=[];f.push("SELECT");let c=Dt({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=>De(h));if(t.$id)if(typeof t.$id=="string")f.push(`FROM ${p.map(h=>`${h}:\u27E8${t.$id}\u27E9`).join(",")}`);else if(isArray(t.$id)){let h=t.$id,$=p.flatMap(y=>h?.map(m=>`${y}:\u27E8${m}\u27E9`));f.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else f.push(`FROM ${p.join(",")}`);if(n){let h=ce(n,i,r),$=pe(h);f.push(`WHERE ${$}`);}return u&&f.push(Ne(u)),typeof a=="number"&&f.push(`LIMIT ${a}`),typeof s=="number"&&f.push(`START ${s}`),f.join(`
37
+ `)},Dt=e=>{let{queries:t,schema:r,level:i,parentQuery:o}=e,n=[],s=o[re];return n.push(S(`"${s}" as \`$$queryPath\``,i)),n.push(S("record::id(id) as `$id`",i)),n.push(S("record::tb(id) as `$thing`",i)),t.forEach(a=>{let u=Hi({query:a,level:i,schema:r});u&&n.push(u);}),n.length===0?null:n.join(`,
38
+ `)},Hi=e=>{let{query:t,schema:r,level:i}=e;return t.$fieldType==="data"?Ki({query:t,level:i}):t.$fieldType==="link"?Ji({query:t,level:i,schema:r}):t.$fieldType==="role"?vi({query:t,level:i,schema:r}):null},Ki=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?S(`record::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?S(`\`${t.$path}\``,r):S(`\`${t.$path}\` AS \`${t.$as}\``,r)},Ji=e=>{let{query:t,schema:r,level:i}=e,{$fields:o,$filter:n,$offset:s,$limit:a,$sort:u}=t;if(o.length===0)return null;let f=[];f.push(S("(",i));let c=i+1;f.push(S("SELECT",c));let d=Dt({parentQuery:t,queries:o,level:c+1,schema:r});d&&f.push(d);let l=t[ne][be].queryPath;if(f.push(S(`FROM ${l}`,c)),n){let p=ce(n,t.$thing,r),h=pe(p);f.push(`WHERE ${h}`);}return u&&f.push(S(Ne(u),c)),typeof a=="number"&&f.push(S(`LIMIT ${a}`,c)),typeof s=="number"&&f.push(S(`START ${s}`,c)),f.push(S(`) AS \`${t.$as}\``,i)),f.join(`
39
+ `)},vi=e=>{let{query:t,schema:r,level:i}=e;if(t.$fields.length===0)return null;let o=[];o.push(S("(",i));let n=i+1;o.push(S("SELECT",n));let s=n+1,a=Dt({parentQuery:t,queries:t.$fields,level:s,schema:r});a&&o.push(a);let u=t[ne][be].queryPath;if(o.push(S(`FROM ${u}`,n)),t.$filter){let f=ce(t.$filter,t.$playedBy.thing,r),c=pe(f);o.push(`WHERE ${c}`);}return o.push(S(`) AS \`${t.$as}\``,i)),o.join(`
40
+ `)};var Xr=async e=>{let{client:t,queries:r}=e,i=`
42
41
  BEGIN TRANSACTION;
43
42
  ${r.join(";")};
44
43
  COMMIT TRANSACTION;
45
- `;return await t.query(i)};var tn=e=>{let{res:t,queries:r}=e;return t.map((o,n)=>rn(r[n],o))},rn=(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 Dt(e,t[0])}if(t.length>=1)return t.map(r=>Dt(e,r))}else throw new Error("res is unexpectedly not an array")},Dt=(e,t)=>{let r={[te]: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]=Wi(i,n));}),r},Wi=(e,t)=>t==null||isArray(t)&&t.length===0?null:e.$fieldType==="data"?(e[ie].cardinality==="ONE"&&isArray(t)&&t[0],t??null):e.$justId?e.$filterByUnique||e[ie].cardinality==="ONE"?t[0]?.id??null:t?.map(r=>r.id)??[]:e.$filterByUnique||e[ie].cardinality==="ONE"?Dt(e,t[0]):rn(e,t);var on=e=>{let{queries:t,schema:r}=e;return t.map(i=>zi({query:i,schema:r}))},zi=e=>{let{query:t,schema:r}=e,{$thing:i,$fields:o,$filter:n,$offset:c,$limit:a,$sort:h}=t;if(o.length===0)return null;let p=r.entities[i]||r.relations[i];if(!p)throw new Error(`Schema for ${i} not found`);let l=t[te],d=sn(l),s=an(o.filter(g=>g.$fieldType==="data")),f=ln(o.filter(g=>g.$fieldType==="link"||g.$fieldType==="role"),r),u=[...d,...s,...f].join(`,
46
- `),$=Vi(t,p),y=n?`WHERE ${Ce(Me(n,i,r))}`:"WHERE id",m=h?cn(h):"",B=typeof a=="number"?`LIMIT ${a}`:"",w=typeof c=="number"?`START ${c}`:"";return `SELECT ${u} ${$} ${y} ${m} ${B} ${w}`},Vi=(e,t)=>{let i=(t.subTypes?[e.$thing,...t.subTypes]:[e.$thing]).map(c=>rt(c)),o=(c,a)=>`${c}:\`${a}\``,n=c=>i.flatMap(a=>c.map(h=>o(a,h))).join(",");if(!e.$id)return `FROM ${i.join(",")}`;if(typeof e.$id=="string")return `FROM ${n([e.$id])}`;if(Array.isArray(e.$id))return `FROM ${n(e.$id)}`;throw new Error("Invalid $id")},sn=e=>[`"${e}" as \`$$queryPath\``,"meta::id(id) as `$id`","meta::tb(id) as `$thing`"],an=e=>e.map(t=>t.$path==="id"?`meta::id(${t.$path}) AS ${t.$as}`:t.$path===t.$as?`\`${t.$path}\``:`\`${t.$path}\` AS \`${t.$as}\``),ln=(e,t)=>e.map(r=>{let i=sn(r[te]),o=an(r.$fields.filter(s=>s.$fieldType==="data")),n=ln(r.$fields.filter(s=>s.$fieldType==="link"||s.$fieldType==="role"),t),c=[...i,...o,...n].join(`,
47
- `),a=`FROM $parent.\`${r[ie].path}\`[*]`,h=r.$filter?`WHERE ${Ce(Me(r.$filter,r.$thing,t))}`:"WHERE id",p=r.$sort?cn(r.$sort):"",l=typeof r.$limit=="number"?`LIMIT ${r.$limit}`:"",d=typeof r.$offset=="number"?`START ${r.$offset}`:"";return `( SELECT ${c} ${a} ${h} ${p} ${l} ${d} ) AS \`${r.$as}\``}).filter(r=>r),Me=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(c=>{let h=Object.keys(c).reduce((p,l)=>{let d=c[l];if(l.startsWith("$"))return l==="$not"?{...p,$not:void 0,"$!":Me(d,t,r)}:l==="$or"?{...p,$or:void 0,$OR:Me(d,t,r)}:l==="$and"?{...p,$and:void 0,$AND:Me(d,t,r)}:l==="$eq"?{...p,$nor:void 0,"$=":Me(d,t,r)}:l==="$id"?{...p,$id:void 0,"meta::id(id)":{$IN:isArray(d)?d:[d]}}:l==="$thing"?p:{...p,[l]:Me(d,t,r)};let s=t in r.entities?r.entities[t]:r.relations[t],[f,u]=Ie(s,l);if(f==="dataField"){if(s.idFields.length>1)throw new Error("Multiple id fields not supported");return l===s.idFields[0]?{...p,"meta::id(id)":{$IN:isArray(d)?d:[d]}}:{...p,[l]:d}}if(f==="linkField"||f==="roleField"){let $=u;if($.$things.length!==1)throw new Error(`Not supported yet: Role ${l} in ${d.name} is played by multiple things: ${$.$things.join(", ")}`);let[y]=$.$things,m=$[me].queryPath;return {...p,[m]:Me(d,y,r)}}throw new Error(`Field ${l} not found in schema, Defined in $filter`)},{});return shake(h)});return i?n:n[0]},Ce=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("$",""),c=Array.isArray(o)?o.map(a=>Ce(a)):[Ce(o)];n==="!"?r.push(`!(${c.join(` ${n} `)})`):r.push(`(${c.join(` ${n} `)})`);return}if(isObject(o))if(i.includes("<-")||i.includes("->")){let n=Ce(o);r.push(`${i}[WHERE ${n}]`);}else if(i.startsWith("$parent")){let n=Ce(o),c=i.replace("$parent.","");r.push(`${c}[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),c=o[n];if(isArray(c))r.push(`${i} ${n.replace("$","")} [${c.map(a=>`'${a}'`).join(", ")}]`);else if(isObject(c)){let a=Ce(c);r.push(`${i} ${n.replace("$","")} ${a}`);}else r.push(`${i} ${n.replace("$","")} '${c}'`);}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(c=>`'${c}'`).join(", ")}]`);}else {let n=i.startsWith("$")?i.replace("$",""):"=";r.push(`${i} ${n} '${o}'`);}}),r.join(" AND ")},cn=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 At=H("error","error",V((e,t)=>({...e,error:t.error}))),Hi=we("build",{build:Z(async e=>{let{linkMode:t}=e.config.dbConnectors.find(r=>r.provider==="surrealDB").providerConfig;if(t==="edges")return Gr({queries:e.bql.queries,schema:e.schema});if(t==="refs")return on({queries:e.bql.queries,schema:e.schema})},H("done","run",V((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),At),run:Z(async e=>en({client:e.client,queries:ae(e.surql.queries)}),H("done","parse",V((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),At),parse:Z(async e=>tn({res:ae(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),H("done","success",V((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),At),success:he(),error:he()},e=>e),Ki=async e=>new Promise((t,r)=>{ye(Hi,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),dn=async(e,t,r,i)=>Ki({bql:{queries:e},surql:{},schema:t,config:r,client:i,error:null});var It="___",un=async e=>{let{queries:t,schema:r}=e;return t.map(i=>vi({query:i,schema:r}))},vi=e=>{let{query:t,schema:r}=e,{$path:i,$thing:o,$filter:n,$fields:c,$sort:a,$offset:h,$limit:p,$id:l}=t;if(!i)throw new Error("Path is not defined");let d=[],s=t[te];if(d.push("match"),d.push(`$${i} isa ${o};`),n||l){let $=Ke(r,t),y={...n,...l?{[$]:l}:{}},m=qt({$filter:y,$var:i,$thing:o,schema:r,depth:0});d.push(`
48
- ${m}`);}let f=xt({schema:r,$thing:o,$var:i,$sort:a,depth:0});f&&d.push(f.match);let u=`M_${v4()}`;if(d.push(`?queryPath${u} = "${s}";`),d.push("fetch"),d.push(`?queryPath${u} as "queryPath";`),c){let $=c.filter(B=>B.$fieldType==="data");$&&$.length>0&&d.push(...kt($,i,0));let y=c.filter(B=>B.$fieldType==="link");y&&y.length>0&&d.push(...Pt(y,i,i,0,r));let m=c.filter(B=>B.$fieldType==="role");m&&m.length>0&&d.push(...Ot(m,i,i,0,r));}return f&&d.push(f.sort),typeof h=="number"&&d.push(`
49
- offset ${h};`),typeof p=="number"&&d.push(`
50
- limit ${p};`),d.join(`
51
- `)},kt=(e,t,r)=>{let i=[],o=[],n=[];for(let l=0;l<e.length;l++)e[l].$isVirtual||i.push(e[l].$dbPath),e[l][ie].contentType==="FLEX"&&n.push({path:e[l][ie].dbPath}),o.push(`{${e[l].$dbPath}:${e[l].$as}}`);let c=i.join(", "),h=`$metadata:{as:[${o.join(",")}]}`,p=[T(`$${t} as "${t}.${h}.$dataFields": ${c};`,r)];return n.length>0&&n.forEach(l=>{p.push(T(`"${l.path}.$multiVal": {match $${t} has ${l.path} $${l.path}; fetch $${l.path}: attribute;};`,r));}),p},Ot=(e,t,r,i,o)=>{let n=i+1,c=[];for(let a of e){let{$fields:h,$as:p,$justId:l,$idNotIncluded:d,$filterByUnique:s,$thing:f,$sort:u,$offset:$,$limit:y}=a,m=a[te],B=`$metadata:{as:${p},justId:${l?"T":"F"},idNotIncluded:${d},filterByUnique:${s}}`;c.push(T(`"${r}.${B}.${a.$var}": {`,i)),c.push(T("match",n));let w=`${t}${It}${a.$var}`;if(c.push(T(`$${w} isa ${a.$thing};`,n)),c.push(T(`$${t} (${a.$var}: $${t}${It}${a.$var}) isa ${a.$intermediary};`,n)),a.$filter||a.$id){let S=Ke(o,a),C=a.$id?{[S]:a.$id}:{},A={...a.$filter,...C};c.push(qt({$filter:A,$var:w,$thing:a.$thing,schema:o,depth:n}));}let g=xt({schema:o,$thing:f,$var:w,$sort:u,depth:n});if(g&&c.push(g.match),h){let S=`M_${v4()}`;c.push(T(`
52
- ?queryPath${S} = "${m}";`,n)),c.push(T("fetch",n)),c.push(T(`?queryPath${S} as "queryPath";`,n));let C=h?.filter(x=>x.$fieldType==="data");C&&C.length>0&&c.push(...kt(C,w,n));let A=h?.filter(x=>x.$fieldType==="link");A&&A.length>0&&c.push(...Pt(A,w,`${t}.${a.$var}`,n,o));let O=h?.filter(x=>x.$fieldType==="role");O&&O.length>0&&c.push(...Ot(O,w,`${t}.${a.$var}`,n,o));}g&&c.push(g.sort),typeof $=="number"&&c.push(T(`offset ${$};`,n)),typeof y=="number"&&c.push(T(`limit ${y};`,n)),c.push(T("};",i));}return c},Pt=(e,t,r,i,o)=>{let n=i+1,c=[];for(let a of e){let{$fields:h,$as:p,$justId:l,$idNotIncluded:d,$filterByUnique:s,$playedBy:f,$thing:u,$sort:$,$offset:y,$limit:m}=a,B=a[te],w=`$metadata:{as:${p},justId:${l?"T":"F"},idNotIncluded:${d},filterByUnique:${s}}`;c.push(T(`"${r}.${w}.${a.$var}": {`,i)),c.push(T("match",n));let g=`${t}${It}${a.$var}`;if(c.push(T(`$${g} isa ${a.$thing};`,n)),a.$filter||a.$id){let C=Ke(o,a),A=a.$id?{[C]:a.$id}:{},O={...a.$filter,...A};c.push(qt({$filter:O,$var:g,$thing:a.$thing,schema:o,depth:n}));}let S=xt({schema:o,$thing:u,$var:g,$sort:$,depth:n});if(S&&c.push(S.match),a.$target==="role"?c.push(T(`$${t}_intermediary (${a.$plays}: $${t}, ${f.plays}: $${g}) isa ${a.$intermediary};`,n)):c.push(T(`$${g} (${a.$plays}: $${t});`,n)),h){let C=`M_${v4()}`;c.push(T(`?queryPath${C} = "${B}";`,n)),c.push(T("fetch",n)),c.push(T(`?queryPath${C} as "queryPath";`,n));let A=h?.filter(W=>W.$fieldType==="data");A&&A.length>0&&c.push(...kt(A,g,n));let O=h?.filter(W=>W.$fieldType==="link");O&&O.length>0&&c.push(...Pt(O,g,`${t}.${a.$var}`,n,o));let x=h?.filter(W=>W.$fieldType==="role");x&&x.length>0&&c.push(...Ot(x,g,`${t}.${a.$var}`,n,o));}S&&c.push(S.sort),typeof y=="number"&&c.push(T(`offset ${y};`,n)),typeof m=="number"&&c.push(T(`limit ${m};`,n)),c.push(T("};",i));}return c},Zi=(e,t)=>{let r={};if(t.dataFields?.forEach(c=>{c.path!==c.dbPath&&(r[c.path]=c.dbPath);}),Object.keys(r).length===0)return e;let{$not:i,...o}=e,n=hn(o,r);return i&&(n.$not=hn(i,r)),n},hn=(e,t)=>{let r={};return Object.entries(e).forEach(([i,o])=>{let n=t[i]||i;r[n]=o;}),r},qt=e=>{let{$filter:t,$var:r,$thing:i,schema:o,depth:n}=e,c=Zi(t,G(o,i)),{$not:a,...h}=c,p=G(o,i),l=[];return Object.entries(a||{}).forEach(([d,s])=>{if(d.startsWith("$"))return;if(p.dataFields?.find($=>$.dbPath===d)){s===null?l.push(T(`$${r} has ${d} $${d}_${v4()};`,n)):Array.isArray(s)?s.forEach($=>{l.push(T(`not { $${r} has ${d} ${oe($)}; };`,n));}):l.push(T(`not { $${r} has ${d} ${oe(s)}; };`,n));return}let u=p.linkFields?.find($=>$.path===d);if(u){let[$]=u.oppositeLinkFieldsPlayedBy,m=G(o,$.thing).idFields?.[0];if(!m)throw new Error(`"${$.thing}" does not have an id field`);if(u.target==="relation")s===null?l.push(T(`(${u.plays}: $${r}) isa ${u.relation};`,n)):Array.isArray(s)?s.forEach(B=>{l.push(T(`not { (${u.plays}: $${r}) isa ${u.relation}, has ${m} ${oe(B)}; };`,n));}):l.push(T(`not { (${u.plays}: $${r}) isa ${u.relation}, has ${m} ${oe(s)}; };`,n));else {let B=`${$.thing}_${v4()}`;s===null?l.push(T(`$${B} isa ${$.thing}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation};`,n)):Array.isArray(s)?s.forEach(w=>{l.push(T(`not { $${B} isa ${$.thing}, has ${m} ${oe(w)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation}; };`,n));}):l.push(T(`not { $${B} isa ${$.thing}, has ${m} ${oe(s)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation}; };`,n));}return}if(p.thingType==="relation"){let $=p.roles[d];if($){let[y]=$.playedBy||[],B=G(o,y.thing).idFields?.[0];if(!B)throw new Error(`"${y.thing}" does not have an id field`);let w=`${y.thing}_${v4()}`,g=v4(),S=`${r}_${g}`;s===null?(l.push(T(`$${S} isa ${i};`,n)),l.push(T(`$${S} (${y.plays}: ${w});`,n)),l.push(T(`$${r} is $${S};`,n))):Array.isArray(s)?s.forEach(C=>{l.push(T(`$${S} isa ${i};`,n)),l.push(T(`not { $${w} isa ${y.thing}, has ${B} ${oe(C)}; $${S} (${y.plays}: $${w}); };`,n)),l.push(T(`$${r} is $${S};`,n));}):(l.push(T(`$${S} isa ${i};`,n)),l.push(T(`not { $${w} isa ${y.thing}, has ${B} ${oe(s)}; $${S} (${y.plays}: $${w}); };`,n)),l.push(T(`$${r} is $${S};`,n)));return}}}),Object.entries(h).forEach(([d,s])=>{if(d.startsWith("$"))return;if(p.dataFields?.find($=>$.dbPath===d)){if(s===null)l.push(T(`not { $${r} has ${d} $${d}_${v4()}; };`,n));else if(Array.isArray(s)){let $=s.map(m=>`$${r} has ${d} ${oe(m)};`),y=it($);y&&l.push(T(y,n));}else l.push(T(`$${r} has ${d} ${oe(s)};`,n));return}let u=p.linkFields?.find($=>$.path===d);if(u){let[$]=u.oppositeLinkFieldsPlayedBy,m=G(o,$.thing).idFields?.[0];if(!m)throw new Error(`"${$.thing}" does not have an id field`);if(u.target==="relation")if(s===null)l.push(T(`not { (${u.plays}: $${r}) isa ${u.relation}; };`,n));else if(Array.isArray(s)){let B=s.map(g=>`(${u.plays}: $${r}) isa ${u.relation}, has ${m} ${oe(g)};`),w=it(B);w&&l.push(T(w,n));}else l.push(T(`(${u.plays}: $${r}) isa ${u.relation}, has ${m} ${oe(s)};`,n));else {let B=`${$.thing}_${v4()}`;if(s===null)l.push(T(`not { $${B} isa ${$.thing}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation}; };`,n));else if(Array.isArray(s)){let w=s.map(S=>`$${B} isa ${$.thing}, has ${m} ${oe(S)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation};`),g=it(w);g&&l.push(T(g,n));}else l.push(T(`$${B} isa ${$.thing}, has ${m} ${oe(s)}; (${u.plays}: $${r}, ${$.plays}: $${B}) isa ${u.relation};`,n));}return}if(p.thingType==="relation"){let $=p.roles[d];if($){let[y]=$.playedBy||[],B=G(o,y.thing).idFields?.[0];if(!B)throw new Error(`"${y.thing}" does not have an id field`);let w=`${y.thing}_${v4()}`,g=v4(),S=`${r}_${g}`;if(s===null)l.push(T(`$${S} isa ${i};`,n)),l.push(T(`not { $${S} (${y.plays}: ${w}); };`,n)),l.push(T(`$${r} is $${S};`,n));else if(Array.isArray(s)){let C=s.map(O=>`$${w} isa ${y.thing}, has ${B} ${oe(O)}; $${S} (${y.plays}: $${w});`),A=it(C);A&&(l.push(T(`$${S} isa ${i};`,n)),l.push(T(A,n)),l.push(T(`$${r} is $${S};`,n)));}else l.push(T(`$${S} isa ${i};`,n)),l.push(T(`$${w} isa ${y.thing}, has ${B} ${oe(s)}; $${S} (${y.plays}: $${w});`,n)),l.push(T(`$${r} is $${S};`,n));return}}throw new Error(`"${i}" does not have property "${d}"`)}),l.join(`
53
- `)},it=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;let[t]=e;return t},oe=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}`,Yi=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},xt=e=>{let{$var:t,$thing:r,schema:i,$sort:o,depth:n}=e,c=G(i,r),a=[],h=[];if(o?.forEach(p=>{let l=Yi(p),d=c.dataFields?.find(u=>u.path===l.field);if(!d)throw new Error(`"${r}" does not have data field "${l.field}"`);let s=`${l.field}_${v4()}`;a.push(T("{",n)),a.push(T(`$${t} has ${d.dbPath} $${s}_1;`,n+1)),a.push(T("not {",n+1)),a.push(T(`$${t} has ${d.dbPath} $${s}_2;`,n+2)),a.push(T(`$${s}_2 < $${s}_1;`,n+2)),a.push(T("};",n+1)),a.push(T(`?${s}_ = $${s}_1;`,n+1)),a.push(T("} or {",n)),a.push(T(`not { $${t} has ${d.dbPath} $${s}_1; };`,n+1)),a.push(T(`?${s}_ = "~";`,n+1)),a.push(T("};",n)),a.push(T(`?${s} = ?${s}_;`,n));let f=l.desc?"desc":"asc";h.push(`?${s} ${f}`);}),a.length!==0)return {match:a.join(""),sort:T(`sort ${h.join(", ")};`,n)}};var fn=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((c,a)=>{let h=r[a],p=t[a];return Xi(c,h,p,i,o)})},Xi=(e,t,r,i,o)=>e.length===0?null:r.$filterByUnique?pn(e[0],t,i,o):e.map(n=>pn(n,t,i,o)),pn=(e,t,r,i)=>{let{dataFields:o,currentSchema:n,linkFields:c,roleFields:a,schemaValue:h}=jt(e,r),p=Nt(o,n,i),l=_t(c,r,i),d=Wt(a,r,i),s=t?.$fields?.every(u=>!n?.idFields?.includes(typeof u=="string"?u:u.$path));return {...l,...d,...h,...!i.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?p.id:t.$id}:{},...s?Object.fromEntries(Object.entries(p).filter(([u])=>!n?.idFields?.includes(u))):p}},jt=(e,t)=>{let r=Object.keys(e),i=r.find(f=>f.endsWith(".$dataFields")),o=r.filter(f=>f.endsWith(".$multiVal"));if(!i)throw new Error("No dataFields");o?.length>0&&o.forEach(f=>{let u=f.replace(/\.\$multiVal$/,""),$=e[f][0][u].attribute;e[i][u]=$;});let n=e[i],c=i.split(".")[i.split(".").length-2];if(n.$metaData=c,n.length===0)throw new Error("No dataFields");let a=n.type,h={$thing:a.label,$thingType:a.root,[te]:e.queryPath.value},p={[`$${h.$thingType}`]:h.$thing},l=q(t,p),d=r.filter(f=>{let u=ae(f.split(".").pop());return !f.endsWith(".$dataFields")&&l.linkFields?.some($=>$.path===u)}).map(f=>{let u=ae(f.split(".").pop()),$=ae(l.linkFields?.find(y=>y.path===u));return {$linkFields:e[f],$key:u,$metaData:f.split(".")[f.split(".").length-2],$cardinality:$.cardinality}}),s=r.filter(f=>{let u=f.split(".").pop();return u&&!f.endsWith(".$dataFields")&&l.thingType==="relation"&&l.roles?.[u]}).map(f=>{let u=ae(f.split(".").pop());return {$roleFields:e[f],$key:u,$metaData:f.split(".")[f.split(".").length-2],$cardinality:l.roles[u].cardinality}});return {dataFields:n,schemaValue:h,currentSchema:l,linkFields:d,roleFields:s}},Nt=(e,t,r)=>{let{$metaData:i}=e,{as:o}=eo(i),n=Object.entries(e).filter(([c])=>c!=="type"&&!c.startsWith("$")).map(([c,a])=>{let h=t.dataFields?.find(s=>s.path===c||s.dbPath===c),p=c==="id",l=Array.isArray(o)?o.find(s=>s[c])?.[c]:c,d;if(h?.cardinality==="ONE"){if(d=a[0]?a[0].value:r.query?.returnNulls?null:void 0,h.contentType==="DATE"||h.contentType==="FLEX"&&a[0].type.value_type==="datetime"?d=d&&`${d}Z`:h.contentType==="JSON"&&(d=d&&JSON.parse(d)),p)return [[l,d],["$id",d]].filter(([s,f])=>f!==void 0)}else if(h?.cardinality==="MANY"){if(!isArray(a))throw new Error("Typedb fetch has changed its format");if(a.length===0)return r.query?.returnNulls?[[l,null]]:[];h.contentType==="DATE"?d=a.map(s=>`${s.value}Z`):h.contentType==="FLEX"?d=a.map(s=>s.type.value_type==="datetime"?`${s.value}Z`:s.value):h.contentType==="JSON"?d=a.map(s=>s.value&&JSON.parse(s.value)):d=a.map(s=>s.value);}return [[l,d]].filter(([s,f])=>f!==void 0)}).flat();return Object.fromEntries([...n])},Wt=(e,t,r)=>{let i={};return e.forEach(o=>{let{$roleFields:n,$metaData:c,$cardinality:a}=o,{as:h,justId:p,idNotIncluded:l,filterByUnique:d}=$n(c);if(h===null)return;let s=n.map(f=>{let{dataFields:u,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=jt(f,t),w=Nt(u,$,r);if(p==="T")return w.id;{let g=_t(y,t,r),S=Wt(m,t,r),C={...w};return l==="true"&&$?.idFields?.forEach(A=>delete C[A]),{...C,...g,...S,...B}}});s.length>0?i[h]=a==="MANY"&&d==="false"?s:s[0]:r.query?.returnNulls&&(i[h]=null);}),i},_t=(e,t,r)=>{let i={};return e.forEach(o=>{let{$linkFields:n,$metaData:c,$cardinality:a}=o,{as:h,justId:p,idNotIncluded:l,filterByUnique:d}=$n(c);if(h===null)return;let s=n.map(f=>{let{dataFields:u,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=jt(f,t),w=Nt(u,$,r);if(p==="T")return w.id;{let g=_t(y,t,r),S=Wt(m,t,r),C={...w};return l==="true"&&$.idFields?.forEach(A=>delete C[A]),{...C,...g,...S,...B}}});i[h]=s.length>0?a==="MANY"&&d==="false"?s:s[0]:r.query?.returnNulls?null:void 0;}),i},$n=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),c=e.match(r),a=e.match(i),h=e.match(o);return {as:n?n[1]:null,justId:c?c[1]:null,idNotIncluded:a?a[1]:null,filterByUnique:h?h[1]:null}},eo=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,(c,a,h)=>/^{.*}$/.test(h)?`:${h}`:`:${a}"${h}"`),n=n.replace(/\[([^\]]+)\]/g,(c,a)=>`[${a.split(",").map(h=>h.trim().startsWith("{")&&h.trim().endsWith("}")?h.trim():`"${h.trim()}"`).join(",")}]`),n})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var mn=async e=>{let{tqlRequest:t,dbHandles:r,config:i}=e,o=new TypeDBOptions;o.infer=!0;let{session:n}=await Ge(r,i),c=await n.transaction(TransactionType.READ,o),[a,h]=await tryit(parallel)(t.length,t,async p=>await c.query.fetch(p).collect());if(a){await c.rollback();let p=a;throw new Error(`Error running TQL query: ${p.errors}`)}return await c.close(),h};var oo=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,so=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,ao=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,zt=H("error","error",V((e,t)=>({...e,error:t.error}))),lo=we("build",{build:Z(async e=>un({queries:e.bql.queries,schema:e.schema}),H("done","run",V(so)),zt),run:Z(async e=>mn({dbHandles:e.handles,tqlRequest:ae(e.tql.queries),config:e.config}),H("done","parse",V(ao)),zt),parse:Z(async e=>fn({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:ae(e.tql.res)}),H("done","success",V(oo)),zt),success:he(),error:he()},e=>e),co=async e=>new Promise((t,r)=>{ye(lo,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),yn=async(e,t,r,i,o)=>co({bql:{raw:e,queries:t},tql:{},schema:r,config:i,handles:o,error:null});var ho=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Vt=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,ot=H("error","error",V((e,t)=>({...e,error:t.error}))),uo=we("enrich",{enrich:Z(async e=>Jr(e.bql.raw,e.schema),H("done","adapter",V(ho)),ot),adapter:Z(async e=>{let t={};e.bql.queries?.forEach((a,h)=>{let p=e.bql.raw[h],l=G(e.schema,a.$thing),{id:d}=l.defaultDBConnector;if(l.db==="typeDB"){if(!t[d]){let f=e.handles.typeDB?.get(d)?.client;if(!f)throw new Error(`TypeDB client with id "${l.defaultDBConnector.id}" does not exist`);t[d]={db:"typeDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else if(l.db==="surrealDB"){if(!t[d]){let f=e.handles.surrealDB?.get(d)?.client;if(!f)throw new Error(`SurrealDB client with id "${l.defaultDBConnector.id}" does not exist`);t[d]={db:"surrealDB",client:f,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${l.db}"`);let s=t[d];s.rawBql.push(p),s.bqlQueries.push(a),s.indices.push(h);});let r=Object.values(t),i=r.map(a=>{if(a.db==="typeDB")return yn(a.rawBql,a.bqlQueries,e.schema,e.config,e.handles);if(a.db==="surrealDB")return dn(a.bqlQueries,e.schema,e.config,a.client);throw new Error("Unsupported DB provider")}),o=await Promise.all(i),n=r.flatMap((a,h)=>{let p=o[h];return a.indices.map((l,d)=>({index:l,result:p[d]}))});return n.sort((a,h)=>a.index<h.index?-1:a.index>h.index?1:0),n.map(({result:a})=>a)},H("done","postHooks",V(Vt)),ot),postHooks:Z(async e=>vr(e.schema,ae(e.bql.queries),ae(e.bql.res)),H("done","clean",V(Vt)),ot),clean:Z(async e=>Kr(e.config,ae(e.bql.res)),H("done","success",V(Vt)),ot),success:he(),error:he()},e=>e),po=async e=>new Promise((t,r)=>{ye(uo,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),je=async(e,t,r,i)=>po({bql:{raw:e},schema:t,config:r,handles:i,error:null});var Ht="___",fo=Symbol.for("grandChildOfCreate"),gn=async(e,t,r,i)=>{let o=(F,Q)=>Object.keys(F).filter(E=>!E.startsWith("$")&&F[E]!==void 0?Q?!q(t,F).dataFields?.find(M=>M.path===E):!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:F,key:Q,value:E})=>{F&&Q&&!Q.includes("$")&&isObject(F)?(Array.isArray(F[Q])?F[Q]:[F[Q]]).forEach(M=>{if(isObject(M)){if(F.$op!=="create")n.includes(M.$op)||n.push(M.$op);else if(M.$op==="delete"||M.$op==="unlink")throw new Error(`Cannot ${M.$op} under a create`)}}):!F&&isObject(E)&&(n.includes(E.$op)||n.push(E.$op));}),!n.includes("delete")&&!n.includes("unlink")&&!n.includes("replace")&&!n.includes("update")&&!n.includes("link"))return;let a=(F=>{let Q=(E,b)=>{let M=[],R={},k=["$op","$bzId","$parentKey"],L=["$relation","$entity","$id",...k];for(let N in E)if(!k.includes(N)&&!(L.includes(N)&&!b))if(!N.includes("$")&&(isObject(E[N])||Array.isArray(E[N]))){let J=E[N];if(Array.isArray(J)&&J.length>0)J.forEach(ce=>{let Qe={$path:N,...Q(ce),...ce.$filter&&{$as:ce.$bzId}};M.find(U=>U.$path===Qe.$path&&!U.$filter)||(M=[...M,Qe]);});else {let ce={$path:N,...Q(J),...!J.$filter&&{$as:J.$bzId}};M=[...M,ce];}}else R[N]=E[N];return {...R,$fields:M}};return F.map(E=>Q(E,!0))})(Array.isArray(e)?e:[e]),p=(await je(a,t,{...r,query:{...r.query,returnNulls:!0}},i)).bql.res,l=(F,Q)=>{let E=F.$id||F.id||F.$bzId;if(F.$objectPath){let{$objectPath:b}=F,M=b?.beforePath||"root",R=Array.isArray(b.ids)?`[${b.ids}]`:b.ids;return {beforePath:`${M}.${R}___${b.key}`,ids:E,key:Q}}else return {beforePath:"root",ids:E,key:Q}},d=(F,Q)=>{let E=F?.beforePath||"root";if(typeof E!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let b=(Array.isArray(F?.ids)?`[${F?.ids}]`:F?.ids);return `${E}.${b}___${F?.key}`},s=F=>{if(F.includes("[")&&F.includes("]")){let[Q,E,b]=F.split(/[[\]]/);return E.split(",").map(R=>`${Q}${R}${b}`)}else return [F]},f={};(F=>produce(F,Q=>traverse(Q,({key:E,parent:b})=>{if(b&&E&&b.$id&&!E.includes("$")){let M=l(b,E),R=d(M);if(Array.isArray(b[E])){let k=[];b[E].forEach(L=>{isObject(L)?(L.$objectPath=M,k.push(L.$id.toString())):L&&k.push(L.toString());}),f[R]={$objectPath:M,$ids:k};}else {let k=b[E];isObject(k)?(f[R]={$objectPath:M,$ids:[k.$id.toString()]},k.$objectPath=M):k?f[R]={$objectPath:M,$ids:[k.toString()]}:k===null&&(f[R]=null);}}})))(p||{});let $=F=>produce(F,Q=>traverse(Q,({key:E,value:b,parent:M})=>{M&&E&&!E.includes("$")&&(Array.isArray(b)||isObject(b))&&!Array.isArray(M)&&(Array.isArray(M[E])?M[E].forEach(R=>{typeof R!="string"&&(R.$objectPath=l(M,E),R.$parentIsCreate=M.$op==="create",R[fo]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")]);}):isObject(M[E])&&(M[E].$parentIsCreate=M.$op==="create",M[E][Symbol.for("grandChildOfCreate")]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")],M[E].$objectPath=l(M,E)));})),y=$(e),m=F=>{let Q=[];return F.forEach(b=>{if(!b.$id&&!b.id&&!b.$tempId)if(b.$filter){let M=d({...b.$objectPath,key:b.$bzId}),R=f[M];R&&(Array.isArray(R.$ids)?R.$ids:[R.$ids]).forEach(L=>{let N={...b,$id:L,$bzId:`T4_${v4()}`,$filterBzId:b.$bzId};Q.push(N);});}else {let M=d(b.$objectPath),R=f[M];R?R?.$ids?.forEach(k=>{let L={...b,$id:k,$bzId:`T4_${v4()}`};Q.push(L);}):Q.push(b);}else Q.push(b);}),Q.map(b=>{let M={...b};return o(M,!0).forEach(R=>{let k=Array.isArray(M[R])?M[R]:[M[R]],L=m(k);M[R]=L;}),M})},B=m(Array.isArray(y)?y:[y]),w=$(B),S=(F=>{let Q=E=>{let b=U=>{let ee=[],z=[],P=[];return U.forEach(j=>{let se=o(j,!0);if(se.length>0){let I=!1;se.forEach(_=>{(Array.isArray(j[_])?j[_]:[j[_]]).filter(Y=>!Y.$id&&!Y.id&&typeof j=="object").length&&(I=!0);}),I?ee.push(j):z.push(j);}else j.$id?P.push({...j,$bzId:j.$tempId||j.$bzId}):P.push({...j,$bzId:j.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:ee,operationWithoutMultiples:z,otherOps:P}},{operationWithMultiples:M,operationWithoutMultiples:R,otherOps:k}=b(E),L=U=>{let z=(()=>{let _={};for(let re in U){let v=q(t,U);!re.startsWith("$")&&v.dataFields?.find(Y=>Y.path===re)&&(_[re]=U[re]);}return _})(),P=Object.keys(U),j=o(U,!0),se=[],I=(_,re)=>{if(_===j.length){let Y={...re};P.forEach(ne=>{ne.startsWith("$")&&(Y[ne]=U[ne]);}),se.push({...Y,...z});return}let v={...re,[j[_]]:U[j[_]],...Fe(re),...z};I(_+1,v),I(_+1,re);};return I(0,{...Fe(U)}),se},N=[];return M.forEach(U=>{let ee=L(U),z=[];ee.forEach(P=>{let j=o(P,!0);if(P.$op==="create")z.push(P);else if(P.$id){let se=d(P.$objectPath),I=[];if(j.forEach(_=>{let re=`${se.includes("undefined")?"root":se}.${P.$id}${Ht}${_}`,v=f[re];P[_].filter(ne=>ne.$op==="unlink"||ne.$op==="delete"||ne.$op==="update").length>0?v?.$ids&&I.push({key:_,ids:v.$ids}):I.push({key:_,ids:[""]});}),I.length===j.length&&!z.find(_=>_.$id===P.$id))z.push(P);else {let _={...P,$bzId:P.$tempId||`T4_${v4()}`};j.forEach(v=>{let Y=P[v].filter(ne=>ne.$id);Y.length>0?_[v]=Y:_[v]=void 0;}),o(_,!0).length>0&&z.push(_);}}else if(P.$objectPath){let se=d(P.$objectPath),I=f[se]?.$ids||[];I.forEach(_=>{let re=[];j.forEach(v=>{let Y=`${se}.${_}${Ht}${v}`,ne=f[Y];ne&&re.push({key:v,ids:ne.$ids});}),j.length===0?I.filter(Y=>!z.find(ne=>ne.$id===Y)).forEach(Y=>{z.push({...P,$id:Y,$bzId:P.$tempId||`PQT2_${v4()}`});}):re.length===j.length&&!z.find(v=>v.$id===_)&&(j.forEach(v=>{let Y=`${d(P.$objectPath)}.${_}${Ht}${v}`,ne=f[Y]?.$ids||[],An=P[v].find(De=>!De.$id),Jt=[...ne.map(De=>({...An,$id:De,$objectPath:{beforePath:P.$objectPath.beforePath,ids:De,key:v}})),...P[v].filter(De=>De.$id)];Jt.length>0&&(P[v]=Jt);}),z.push({...P,$id:_,$bzId:P.$tempId||`PQ3_${v4()}`}));});}else z.push(P);}),z.forEach(P=>{N.push(P);});}),[...N,...R,...k].filter(U=>o(U).length>0?!0:U.$op!=="update").map(U=>{let ee={...U};return o(ee,!0).forEach(z=>{let P=Array.isArray(ee[z])?ee[z]:[ee[z]],j=Q(P);ee[z]=j;}),ee})};return Q(F)})(Array.isArray(w)?w:[w]),C=F=>F.map(Q=>{let E=o(Q,!0),b={...Q};return E.forEach(M=>{let R=Array.isArray(Q[M])?Q[M]:[Q[M]],k=[],L=[],N=[],J={},ce=ft(t,Q,M);R.filter(I=>I).forEach(I=>{I.$op==="replace"&&I.$id?(J=I,Array.isArray(I.$id)?L=[...L,...I.$id]:L.push(I.$id)):I.$op==="create"&&ce==="ONE"&&I.id?(J=I,Array.isArray(I.id)?N=[...L,...I.id]:N.push(I.id)):k.push(I);});let Qe=d(J.$objectPath),ee=s(Qe).map(I=>f[I]),z=[];ee.filter(I=>I!=null).forEach(I=>{z=[...z,...I?.$ids||[]];});let P=z.filter(I=>!L.includes(I)),j=L.filter(I=>!z.includes(I)),se=Fe(J);P.length>0&&k.push({...J,$op:"unlink",$id:P,$bzId:J.$tempId||`T4_${v4()}`,id:void 0,...se}),j.length>0&&j.forEach(I=>{k.push({...J,$op:"link",$id:I,$bzId:J.$tempId||`T5_${v4()}`,...se});}),N.length>0&&N.forEach(I=>{k.push({...J,$op:"create",id:I,$bzId:J.$tempId||`T6_${v4()}`,...se});}),b[M]=C(k);}),b}),A=$(C($(S)));(F=>produce(F,Q=>traverse(Q,E=>{let{key:b,value:M,parent:R}=E;b&&R&&!b?.includes("$")&&(Array.isArray(M)||isObject(M))&&!Array.isArray(R)&&(Array.isArray(M)?M:[M]).forEach(L=>{let N=L.$filter?{...L.$objectPath,key:L.$filterBzId}:L.$objectPath,J=d(N),ce=f[J],Qe=(z,P)=>z.every(j=>P.includes(j)),U=L.$id?Array.isArray(L.$id)?Qe(L.$id,ce&&ce.$ids?ce.$ids:[]):ce?.$ids?.includes(L.$id):ce,ee=ft(t,R,L.$objectPath.key);if(L.$op==="link"&&U&&ee==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${d(L.$objectPath)}" because it is already occupied.`);if(L.$op)switch(L.$op){case"delete":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${L.$id}" because it is not linked to $id:"${R.$id}"`);break;case"update":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${L.$id}" because it is not linked to $id:"${R.$id}"`);break;case"unlink":if(!U&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${L.$id}" because it is not linked to $id:"${R.$id}"`);break;case"link":if(U)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${L.$id}" because it is already linked to $id:"${R.$id}"`);break;}});})))(A);let W=(F=>produce(F,Q=>traverse(Q,E=>{let{value:b,meta:M}=E;isObject(b)&&(b[Symbol.for("path")]=M.nodePath,delete b.$objectPath,delete b.$parentIsCreate);})))(A);return [...Array.isArray(W)?W:[W]].sort((F,Q)=>F.$op==="create"&&Q.$op!=="create"?-1:F.$op!=="create"&&Q.$op==="create"?1:0)};var En=(e,t)=>produce(e,i=>at(t,i)),at=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(o=>at(e,o,r));return}let i=G(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([o])=>{o.startsWith("$")||mo(e,t,o,i);});},mo=(e,t,r,i)=>{let o=t[r];if(!o)return;let n=i.dataFields?.find(a=>a.path===r);if(n){n.contentType==="JSON"&&o!=null&&(t[r]=JSON.stringify(o));return}let c=i.linkFields?.find(a=>a.path===r);if(c){let a=c.oppositeLinkFieldsPlayedBy[0]?.thing;at(e,o,a);return}if(i.thingType==="relation"){let a=i.roles[r];if(!a)throw new Error(`[Schema] Role ${r} in ${i.name} is not defined`);let[h]=a.playedBy||[];if(!h)throw new Error(`Role ${a.path} in ${i} is not played by anything`);at(e,o,h.thing);}};var wn=async(e,t,r,i)=>{let o=Array.isArray(e)?e:[e],n=o.map(h=>Kt(h,!0)),a=(await je(n,t,r,i)).bql.res;return o.map((h,p)=>{let l=G(t,h.$thing);return Tn({mut:h,node:a[p],schema:t,thing:l})})},Mn=new Set(["$op","$bzId","$parentKey"]),go=new Set(["$relation","$entity","$id",...Mn]),Kt=(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(Mn.has(o)||go.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,...Kt(n[0],!1)}):isObject(n)&&(r[o]={$path:o,...Kt(n,!1)});}return i.$fields=Object.values(r),i},Tn=e=>{let{mut:t,node:r,schema:i,thing:o}=e,n=Sn(o),c=Bo(r);if(Array.isArray(t))return t.map(h=>{let p=c[h.$id];return p?Bn({mut:h,node:p,schema:i,thing:o,...n}):h});let a=c[t.$id];return Bn({mut:t,node:a,schema:i,thing:o,...n})},Bn=e=>{let{mut:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:c,roleFieldMap:a}=e,{$fields:h,...p}=t;if(!r)return p;let l=Qn({$fields:t.$fields,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:c,roleFieldMap:a}),d={...p,[Ae]:l};for(let s in t){if(s.startsWith("$"))continue;let f=t[s];if(n[s]||!f||typeof f!="object"){d[s]=f;continue}let $=c[s]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[s]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${s}"`);let y=G(i,$);d[s]=Tn({mut:f,schema:i,node:r[s],thing:y});}return d},Qn=e=>{let{$fields:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:c,roleFieldMap:a}=e,h=t||Eo(o),p={$id:r.$id};return h.forEach(l=>{let d=typeof l!="string",s=d?l.$path:l,f=r[s];if(n[s]){p[s]=f;return}let $=c[s]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[s]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${s}"`);if(!d){f&&(p[s]=Array.isArray(f)?f.map(Fn):Fn(f));return}let y=G(i,$),m=Sn(y);p[s]=Array.isArray(f)?f.map(B=>bn({...m,$fields:l.$fields,value:B,schema:i,thing:y})):bn({...m,$fields:l.$fields,value:f,schema:i,thing:y});}),p},Eo=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},Fn=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},bn=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 Qn({...e,node:t})},Sn=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}},Bo=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 Ln=he,Ne=(e,t)=>t.data?{...e,bql:{...e.bql,current:t.data}}:e,Fo=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),bo=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),wo=(e,t)=>({...e,typeDB:{...e.typeDB,tqlMutation:t.data}}),Mo=(e,t)=>({...e,typeDB:{...e.typeDB,tqlRes:t.data}}),To=async e=>Object.keys(e.bql.current).length?Et(e.bql.current,e.schema,e.config):Et(e.bql.raw,e.schema,e.config),Qo=async e=>gn(e.bql.current,e.schema,e.config,e.handles),So=async e=>wn(e.bql.current,e.schema,e.config,e.handles),Lo=async e=>Lr(e.bql.current,e.schema),Ro=async e=>Cr(e.bql.things,e.bql.edges,e.schema),Co=async e=>br(e.typeDB.tqlMutation,e.handles,e.config),Do=async e=>wr(e.typeDB.tqlRes,e.bql.things,e.bql.edges,e.schema,e.config),Ao=()=>!0,Io=e=>Pe(e.bql.current),Te=H("error","error",V((e,t)=>({...e,error:t.error}))),ko=we("stringify",{stringify:Z(async e=>En(e.bql.raw,e.schema),H("done","enrich",V(Ne)),Te),enrich:Z(To,H("done","preQuery",bt(Ao),V(Ne)),H("done","parseBQL",V(Ne)),Te),preQuery:Z(Qo,H("done","preHookDependencies",bt(Io),V(Ne)),H("done","parseBQL",V(Ne)),Te),preHookDependencies:Z(So,H("done","enrich",V(Ne)),Te),parseBQL:Z(Lo,H("done","buildMutation",V(bo)),Te),buildMutation:Z(Ro,H("done","runMutation",V(wo)),Te),runMutation:Z(Co,H("done","parseMutation",V(Mo)),Te),parseMutation:Z(Do,H("done","success",V(Fo)),Te),success:Ln(),error:Ln()},e=>e),Oo=async e=>new Promise((t,r)=>{ye(ko,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),Rn=async(e,t,r,i)=>Oo({bql:{raw:e,current:{},things:[],edges:[],res:[]},typeDB:{tqlMutation:{},tqlRes:{}},schema:t,config:r,handles:i,depthLevel:0,error:null});enableMapSet();var Ut=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,providerConfig:i.providerConfig});}if(i.provider==="typeDB"&&i.dbName){let[o,n]=await tryit(TypeDB.coreDriver)(i.url);if(o){let c=`[BORM:${i.provider}:${i.dbName}:core] ${o.message??"Can't create TypeDB Client"}`;throw new Error(c)}try{let c=await n.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:n,session:c});}catch(c){let a=`[BORM:${i.provider}:${i.dbName}:session] ${(c.messageTemplate?._messageBody()||c.message)??"Can't create TypeDB Session"}`;throw new Error(a)}}if(i.provider==="typeDBCluster"&&i.dbName){let o=new TypeDBCredential(i.username,i.password,i.tlsRootCAPath),[n,c]=await tryit(TypeDB.cloudDriver)(i.addresses,o);if(n){let a=`[BORM:${i.provider}:${i.dbName}:core] ${n.message??"Can't create TypeDB Cluster Client"}`;throw new Error(a)}try{let a=await c.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:c,session:a});}catch(a){let h=`[BORM:${i.provider}:${i.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(h)}}}));let r=ir(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(),Zt(this.config,this.schema,this.dbHandles));query=async(t,r)=>{await this.#e();let i={...this.config,query:{...ct.query,...this.config.query,...r}},o=Array.isArray(t),n=o?t:[t],[c,a]=await tryit(je)(n,this.schema,i,this.dbHandles);if(c){let p=new Error(c.error);throw p.stack=c.error.stack,p}let h=a.bql.res;return o?h:h[0]};mutate=async(t,r)=>{await this.#e();let i={...this.config,mutation:{...ct.mutation,...this.config.mutation,...r}},[o,n]=await tryit(Rn)(t,this.schema,i,this.dbHandles);if(o){let a=new Error(o.error.message);throw a.stack=o.error.stack,a}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();});}},Kc=Ut;//! Todo: delete when this works with the new $thing and $thingType fields
44
+ `;return await t.query(i)};var tn=e=>{let{res:t,queries:r}=e;return t.map((o,n)=>rn(r[n],o))},rn=(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 Ct(e,t[0])}if(t.length>=1)return t.map(r=>Ct(e,r))}else throw new Error("res is unexpectedly not an array")},Ct=(e,t)=>{let r={[re]:t.$$queryPath,$id:t.$id,$thing:Yr(t.$thing),$thingType:e.$thingType};return e.$fields.forEach(i=>{let o=i.$as,n=t[o];i.$path==="id"&&e.$idNotIncluded||(r[o]=Yi(i,n));}),r},Yi=(e,t)=>{if(t==null||isArray(t)&&t.length===0)return null;if(e.$fieldType==="data"){let{contentType:r}=e[ne];return e[ne].cardinality==="ONE"&&en(t,r),en(t,r)??null}return e.$justId?e.$filterByUnique||e[ne].cardinality==="ONE"?t[0]?.id??null:t?.map(r=>r.id)??[]:e.$filterByUnique||e[ne].cardinality==="ONE"?Ct(e,t[0]):rn(e,t)},en=(e,t)=>{let r=isArray(e)?e:[e];if(t==="DATE"){let i=r.map(o=>new Date(o).toISOString());return isArray(e)?i:i[0]}return e};var nn=e=>{let{queries:t,schema:r}=e;return t.map(i=>Gi({query:i,schema:r}))},Gi=e=>{let{query:t,schema:r}=e,{$thing:i,$fields:o,$filter:n,$offset:s,$limit:a,$sort:u}=t;if(o.length===0)return null;let f=r.entities[i]||r.relations[i];if(!f)throw new Error(`Schema for ${i} not found`);let c=t[re],d=on(c),l=sn(o.filter(g=>g.$fieldType==="data")),p=an(o.filter(g=>g.$fieldType==="link"||g.$fieldType==="role"),r),h=[...d,...l,...p].join(`,
45
+ `),$=Zi(t,f),y=n?`WHERE ${pe(ce(n,i,r))}`:"WHERE id",m=u?Ne(u):"",B=typeof a=="number"?`LIMIT ${a}`:"",F=typeof s=="number"?`START ${s}`:"";return `SELECT ${h} ${$} ${y} ${m} ${B} ${F}`},Zi=(e,t)=>{let i=(t.subTypes?[e.$thing,...t.subTypes]:[e.$thing]).map(s=>De(s)),o=(s,a)=>`${s}:\`${a}\``,n=s=>i.flatMap(a=>s.map(u=>o(a,u))).join(",");if(!e.$id)return `FROM ${i.join(",")}`;if(typeof e.$id=="string")return `FROM ${n([e.$id])}`;if(Array.isArray(e.$id))return `FROM ${n(e.$id)}`;throw new Error("Invalid $id")},on=e=>[`"${e}" as \`$$queryPath\``,"record::id(id) as `$id`","record::tb(id) as `$thing`"],sn=e=>e.map(t=>t.$path==="id"?`record::id(${t.$path}) AS ${t.$as}`:t.$path===t.$as?`\`${t.$path}\``:`\`${t.$path}\` AS \`${t.$as}\``),an=(e,t)=>e.map(r=>{let i=on(r[re]),o=sn(r.$fields.filter(l=>l.$fieldType==="data")),n=an(r.$fields.filter(l=>l.$fieldType==="link"||l.$fieldType==="role"),t),s=[...i,...o,...n].join(`,
46
+ `),a=`FROM $parent.\`${r[ne].path}\`[*]`,u=r.$filter?`WHERE ${pe(ce(r.$filter,r.$thing,t))}`:"WHERE id",f=r.$sort?Ne(r.$sort):"",c=typeof r.$limit=="number"?`LIMIT ${r.$limit}`:"",d=typeof r.$offset=="number"?`START ${r.$offset}`:"";return `( SELECT ${s} ${a} ${u} ${f} ${c} ${d} ) AS \`${r.$as}\``}).filter(r=>r);var It=N("error","error",j((e,t)=>({...e,error:t.error}))),Xi=me("build",{build:H(async e=>{let{linkMode:t}=e.config.dbConnectors.find(r=>r.provider==="surrealDB").providerConfig;if(t==="edges")return Zr({queries:e.bql.queries,schema:e.schema});if(t==="refs")return nn({queries:e.bql.queries,schema:e.schema})},N("done","run",j((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),It),run:H(async e=>Xr({client:e.client,queries:he(e.surql.queries)}),N("done","parse",j((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),It),parse:H(async e=>tn({res:he(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),N("done","success",j((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),It),success:ie(),error:ie()},e=>e),eo=async e=>new Promise((t,r)=>{$e(Xi,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),ln=async(e,t,r,i)=>eo({bql:{queries:e},surql:{},schema:t,config:r,client:i,error:null});var At="___",dn=async e=>{let{queries:t,schema:r}=e;return t.map(i=>no({query:i,schema:r}))},no=e=>{let{query:t,schema:r}=e,{$path:i,$thing:o,$filter:n,$fields:s,$sort:a,$offset:u,$limit:f,$id:c}=t;if(!i)throw new Error("Path is not defined");let d=[],l=t[re];if(d.push("match"),d.push(`$${i} isa ${o};`),n||c){let $=Je(r,t),y={...n,...c?{[$]:c}:{}},m=Pt({$filter:y,$var:i,$thing:o,schema:r,depth:0});d.push(`
47
+ ${m}`);}let p=xt({schema:r,$thing:o,$var:i,$sort:a,depth:0});p&&d.push(p.match);let h=`M_${v4()}`;if(d.push(`?queryPath${h} = "${l}";`),d.push("fetch"),d.push(`?queryPath${h} as "queryPath";`),s){let $=s.filter(B=>B.$fieldType==="data");$&&$.length>0&&d.push(...kt($,i,0));let y=s.filter(B=>B.$fieldType==="link");y&&y.length>0&&d.push(...qt(y,i,i,0,r));let m=s.filter(B=>B.$fieldType==="role");m&&m.length>0&&d.push(...Ot(m,i,i,0,r));}return p&&d.push(p.sort),typeof u=="number"&&d.push(`
48
+ offset ${u};`),typeof f=="number"&&d.push(`
49
+ limit ${f};`),d.join(`
50
+ `)},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][ne].contentType==="FLEX"&&n.push({path:e[c][ne].dbPath}),o.push(`{${e[c].$dbPath}:${e[c].$as}}`);let s=i.join(", "),u=`$metadata:{as:[${o.join(",")}]}`,f=[S(`$${t} as "${t}.${u}.$dataFields": ${s};`,r)];return n.length>0&&n.forEach(c=>{f.push(S(`"${c.path}.$multiVal": {match $${t} has ${c.path} $${c.path}; fetch $${c.path}: attribute;};`,r));}),f},Ot=(e,t,r,i,o)=>{let n=i+1,s=[];for(let a of e){let{$fields:u,$as:f,$justId:c,$idNotIncluded:d,$filterByUnique:l,$thing:p,$sort:h,$offset:$,$limit:y}=a,m=a[re],B=`$metadata:{as:${f},justId:${c?"T":"F"},idNotIncluded:${d},filterByUnique:${l}}`;s.push(S(`"${r}.${B}.${a.$var}": {`,i)),s.push(S("match",n));let F=`${t}${At}${a.$var}`;if(s.push(S(`$${F} isa ${a.$thing};`,n)),s.push(S(`$${t} (${a.$var}: $${t}${At}${a.$var}) isa ${a.$intermediary};`,n)),a.$filter||a.$id){let Q=Je(o,a),L=a.$id?{[Q]:a.$id}:{},R={...a.$filter,...L};s.push(Pt({$filter:R,$var:F,$thing:a.$thing,schema:o,depth:n}));}let g=xt({schema:o,$thing:p,$var:F,$sort:h,depth:n});if(g&&s.push(g.match),u){let Q=`M_${v4()}`;s.push(S(`
51
+ ?queryPath${Q} = "${m}";`,n)),s.push(S("fetch",n)),s.push(S(`?queryPath${Q} as "queryPath";`,n));let L=u?.filter(P=>P.$fieldType==="data");L&&L.length>0&&s.push(...kt(L,F,n));let R=u?.filter(P=>P.$fieldType==="link");R&&R.length>0&&s.push(...qt(R,F,`${t}.${a.$var}`,n,o));let A=u?.filter(P=>P.$fieldType==="role");A&&A.length>0&&s.push(...Ot(A,F,`${t}.${a.$var}`,n,o));}g&&s.push(g.sort),typeof $=="number"&&s.push(S(`offset ${$};`,n)),typeof y=="number"&&s.push(S(`limit ${y};`,n)),s.push(S("};",i));}return s},qt=(e,t,r,i,o)=>{let n=i+1,s=[];for(let a of e){let{$fields:u,$as:f,$justId:c,$idNotIncluded:d,$filterByUnique:l,$playedBy:p,$thing:h,$sort:$,$offset:y,$limit:m}=a,B=a[re],F=`$metadata:{as:${f},justId:${c?"T":"F"},idNotIncluded:${d},filterByUnique:${l}}`;s.push(S(`"${r}.${F}.${a.$var}": {`,i)),s.push(S("match",n));let g=`${t}${At}${a.$var}`;if(s.push(S(`$${g} isa ${a.$thing};`,n)),a.$filter||a.$id){let L=Je(o,a),R=a.$id?{[L]:a.$id}:{},A={...a.$filter,...R};s.push(Pt({$filter:A,$var:g,$thing:a.$thing,schema:o,depth:n}));}let Q=xt({schema:o,$thing:h,$var:g,$sort:$,depth:n});if(Q&&s.push(Q.match),a.$target==="role"?s.push(S(`$${t}_intermediary (${a.$plays}: $${t}, ${p.plays}: $${g}) isa ${a.$intermediary};`,n)):s.push(S(`$${g} (${a.$plays}: $${t});`,n)),u){let L=`M_${v4()}`;s.push(S(`?queryPath${L} = "${B}";`,n)),s.push(S("fetch",n)),s.push(S(`?queryPath${L} as "queryPath";`,n));let R=u?.filter(z=>z.$fieldType==="data");R&&R.length>0&&s.push(...kt(R,g,n));let A=u?.filter(z=>z.$fieldType==="link");A&&A.length>0&&s.push(...qt(A,g,`${t}.${a.$var}`,n,o));let P=u?.filter(z=>z.$fieldType==="role");P&&P.length>0&&s.push(...Ot(P,g,`${t}.${a.$var}`,n,o));}Q&&s.push(Q.sort),typeof y=="number"&&s.push(S(`offset ${y};`,n)),typeof m=="number"&&s.push(S(`limit ${m};`,n)),s.push(S("};",i));}return s},io=(e,t)=>{let r={};if(t.dataFields?.forEach(s=>{s.path!==s.dbPath&&(r[s.path]=s.dbPath);}),Object.keys(r).length===0)return e;let{$not:i,...o}=e,n=cn(o,r);return i&&(n.$not=cn(i,r)),n},cn=(e,t)=>{let r={};return Object.entries(e).forEach(([i,o])=>{let n=t[i]||i;r[n]=o;}),r},Pt=e=>{let{$filter:t,$var:r,$thing:i,schema:o,depth:n}=e,s=io(t,G(o,i)),{$not:a,...u}=s,f=G(o,i),c=[];return Object.entries(a||{}).forEach(([d,l])=>{if(d.startsWith("$"))return;if(f.dataFields?.find($=>$.dbPath===d)){l===null?c.push(S(`$${r} has ${d} $${d}_${v4()};`,n)):Array.isArray(l)?l.forEach($=>{c.push(S(`not { $${r} has ${d} ${de($)}; };`,n));}):c.push(S(`not { $${r} has ${d} ${de(l)}; };`,n));return}let h=f.linkFields?.find($=>$.path===d);if(h){let[$]=h.oppositeLinkFieldsPlayedBy,m=G(o,$.thing).idFields?.[0];if(!m)throw new Error(`"${$.thing}" does not have an id field`);if(h.target==="relation")l===null?c.push(S(`(${h.plays}: $${r}) isa ${h.relation};`,n)):Array.isArray(l)?l.forEach(B=>{c.push(S(`not { (${h.plays}: $${r}) isa ${h.relation}, has ${m} ${de(B)}; };`,n));}):c.push(S(`not { (${h.plays}: $${r}) isa ${h.relation}, has ${m} ${de(l)}; };`,n));else {let B=`${$.thing}_${v4()}`;l===null?c.push(S(`$${B} isa ${$.thing}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation};`,n)):Array.isArray(l)?l.forEach(F=>{c.push(S(`not { $${B} isa ${$.thing}, has ${m} ${de(F)}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation}; };`,n));}):c.push(S(`not { $${B} isa ${$.thing}, has ${m} ${de(l)}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation}; };`,n));}return}if(f.thingType==="relation"){let $=f.roles[d];if($){let[y]=$.playedBy||[],B=G(o,y.thing).idFields?.[0];if(!B)throw new Error(`"${y.thing}" does not have an id field`);let F=`${y.thing}_${v4()}`,g=v4(),Q=`${r}_${g}`;l===null?(c.push(S(`$${Q} isa ${i};`,n)),c.push(S(`$${Q} (${y.plays}: ${F});`,n)),c.push(S(`$${r} is $${Q};`,n))):Array.isArray(l)?l.forEach(L=>{c.push(S(`$${Q} isa ${i};`,n)),c.push(S(`not { $${F} isa ${y.thing}, has ${B} ${de(L)}; $${Q} (${y.plays}: $${F}); };`,n)),c.push(S(`$${r} is $${Q};`,n));}):(c.push(S(`$${Q} isa ${i};`,n)),c.push(S(`not { $${F} isa ${y.thing}, has ${B} ${de(l)}; $${Q} (${y.plays}: $${F}); };`,n)),c.push(S(`$${r} is $${Q};`,n)));return}}}),Object.entries(u).forEach(([d,l])=>{if(d.startsWith("$"))return;if(f.dataFields?.find($=>$.dbPath===d)){if(l===null)c.push(S(`not { $${r} has ${d} $${d}_${v4()}; };`,n));else if(Array.isArray(l)){let $=l.map(m=>`$${r} has ${d} ${de(m)};`),y=it($);y&&c.push(S(y,n));}else c.push(S(`$${r} has ${d} ${de(l)};`,n));return}let h=f.linkFields?.find($=>$.path===d);if(h){let[$]=h.oppositeLinkFieldsPlayedBy,m=G(o,$.thing).idFields?.[0];if(!m)throw new Error(`"${$.thing}" does not have an id field`);if(h.target==="relation")if(l===null)c.push(S(`not { (${h.plays}: $${r}) isa ${h.relation}; };`,n));else if(Array.isArray(l)){let B=l.map(g=>`(${h.plays}: $${r}) isa ${h.relation}, has ${m} ${de(g)};`),F=it(B);F&&c.push(S(F,n));}else c.push(S(`(${h.plays}: $${r}) isa ${h.relation}, has ${m} ${de(l)};`,n));else {let B=`${$.thing}_${v4()}`;if(l===null)c.push(S(`not { $${B} isa ${$.thing}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation}; };`,n));else if(Array.isArray(l)){let F=l.map(Q=>`$${B} isa ${$.thing}, has ${m} ${de(Q)}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation};`),g=it(F);g&&c.push(S(g,n));}else c.push(S(`$${B} isa ${$.thing}, has ${m} ${de(l)}; (${h.plays}: $${r}, ${$.plays}: $${B}) isa ${h.relation};`,n));}return}if(f.thingType==="relation"){let $=f.roles[d];if($){let[y]=$.playedBy||[],B=G(o,y.thing).idFields?.[0];if(!B)throw new Error(`"${y.thing}" does not have an id field`);let F=`${y.thing}_${v4()}`,g=v4(),Q=`${r}_${g}`;if(l===null)c.push(S(`$${Q} isa ${i};`,n)),c.push(S(`not { $${Q} (${y.plays}: ${F}); };`,n)),c.push(S(`$${r} is $${Q};`,n));else if(Array.isArray(l)){let L=l.map(A=>`$${F} isa ${y.thing}, has ${B} ${de(A)}; $${Q} (${y.plays}: $${F});`),R=it(L);R&&(c.push(S(`$${Q} isa ${i};`,n)),c.push(S(R,n)),c.push(S(`$${r} is $${Q};`,n)));}else c.push(S(`$${Q} isa ${i};`,n)),c.push(S(`$${F} isa ${y.thing}, has ${B} ${de(l)}; $${Q} (${y.plays}: $${F});`,n)),c.push(S(`$${r} is $${Q};`,n));return}}throw new Error(`"${i}" does not have property "${d}"`)}),c.join(`
52
+ `)},it=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;let[t]=e;return t},de=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}`,oo=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},xt=e=>{let{$var:t,$thing:r,schema:i,$sort:o,depth:n}=e,s=G(i,r),a=[],u=[];if(o?.forEach(f=>{let c=oo(f),d=s.dataFields?.find(h=>h.path===c.field);if(!d)throw new Error(`"${r}" does not have data field "${c.field}"`);let l=`${c.field}_${v4()}`;a.push(S("{",n)),a.push(S(`$${t} has ${d.dbPath} $${l}_1;`,n+1)),a.push(S("not {",n+1)),a.push(S(`$${t} has ${d.dbPath} $${l}_2;`,n+2)),a.push(S(`$${l}_2 < $${l}_1;`,n+2)),a.push(S("};",n+1)),a.push(S(`?${l}_ = $${l}_1;`,n+1)),a.push(S("} or {",n)),a.push(S(`not { $${t} has ${d.dbPath} $${l}_1; };`,n+1)),a.push(S(`?${l}_ = "~";`,n+1)),a.push(S("};",n)),a.push(S(`?${l} = ?${l}_;`,n));let p=c.desc?"desc":"asc";u.push(`?${l} ${p}`);}),a.length!==0)return {match:a.join(""),sort:S(`sort ${u.join(", ")};`,n)}};var hn=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((s,a)=>{let u=r[a],f=t[a];return ao(s,u,f,i,o)})},ao=(e,t,r,i,o)=>e.length===0?null:r.$filterByUnique?un(e[0],t,i,o):e.map(n=>un(n,t,i,o)),un=(e,t,r,i)=>{let{dataFields:o,currentSchema:n,linkFields:s,roleFields:a,schemaValue:u}=jt(e,r),f=Nt(o,n,i),c=Wt(s,r,i),d=zt(a,r,i),l=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}:{},...l?Object.fromEntries(Object.entries(f).filter(([h])=>!n?.idFields?.includes(h))):f}},jt=(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],s=i.split(".")[i.split(".").length-2];if(n.$metaData=s,n.length===0)throw new Error("No dataFields");let a=n.type,u={$thing:a.label,$thingType:a.root,[re]:e.queryPath.value},f={[`$${u.$thingType}`]:u.$thing},c=x(t,f),d=r.filter(p=>{let h=he(p.split(".").pop());return !p.endsWith(".$dataFields")&&c.linkFields?.some($=>$.path===h)}).map(p=>{let h=he(p.split(".").pop()),$=he(c.linkFields?.find(y=>y.path===h));return {$linkFields:e[p],$key:h,$metaData:p.split(".")[p.split(".").length-2],$cardinality:$.cardinality}}),l=r.filter(p=>{let h=p.split(".").pop();return h&&!p.endsWith(".$dataFields")&&c.thingType==="relation"&&c.roles?.[h]}).map(p=>{let h=he(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:l}},Nt=(e,t,r)=>{let{$metaData:i}=e,{as:o}=lo(i),n=Object.entries(e).filter(([s])=>s!=="type"&&!s.startsWith("$")).map(([s,a])=>{let u=t.dataFields?.find(l=>l.path===s||l.dbPath===s),f=s==="id",c=Array.isArray(o)?o.find(l=>l[s])?.[s]:s,d;if(u?.cardinality==="ONE"){if(d=a[0]?a[0].value:r.query?.returnNulls?null:void 0,u.contentType==="DATE"||u.contentType==="FLEX"&&a[0].type.value_type==="datetime"?d=d&&`${d}Z`:u.contentType==="JSON"&&(d=d&&JSON.parse(d)),f)return [[c,d],["$id",d]].filter(([l,p])=>p!==void 0)}else if(u?.cardinality==="MANY"){if(!isArray(a))throw new Error("Typedb fetch has changed its format");if(a.length===0)return r.query?.returnNulls?[[c,null]]:[];u.contentType==="DATE"?d=a.map(l=>`${l.value}Z`):u.contentType==="FLEX"?d=a.map(l=>l.type.value_type==="datetime"?`${l.value}Z`:l.value):u.contentType==="JSON"?d=a.map(l=>l.value&&JSON.parse(l.value)):d=a.map(l=>l.value);}return [[c,d]].filter(([l,p])=>p!==void 0)}).flat();return Object.fromEntries([...n])},zt=(e,t,r)=>{let i={};return e.forEach(o=>{let{$roleFields:n,$metaData:s,$cardinality:a}=o,{as:u,justId:f,idNotIncluded:c,filterByUnique:d}=pn(s);if(u===null)return;let l=n.map(p=>{let{dataFields:h,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=jt(p,t),F=Nt(h,$,r);if(f==="T")return F.id;{let g=Wt(y,t,r),Q=zt(m,t,r),L={...F};return c==="true"&&$?.idFields?.forEach(R=>delete L[R]),{...L,...g,...Q,...B}}});l.length>0?i[u]=a==="MANY"&&d==="false"?l:l[0]:r.query?.returnNulls&&(i[u]=null);}),i},Wt=(e,t,r)=>{let i={};return e.forEach(o=>{let{$linkFields:n,$metaData:s,$cardinality:a}=o,{as:u,justId:f,idNotIncluded:c,filterByUnique:d}=pn(s);if(u===null)return;let l=n.map(p=>{let{dataFields:h,currentSchema:$,linkFields:y,roleFields:m,schemaValue:B}=jt(p,t),F=Nt(h,$,r);if(f==="T")return F.id;{let g=Wt(y,t,r),Q=zt(m,t,r),L={...F};return c==="true"&&$.idFields?.forEach(R=>delete L[R]),{...L,...g,...Q,...B}}});i[u]=l.length>0?a==="MANY"&&d==="false"?l:l[0]:r.query?.returnNulls?null:void 0;}),i},pn=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),s=e.match(r),a=e.match(i),u=e.match(o);return {as:n?n[1]:null,justId:s?s[1]:null,idNotIncluded:a?a[1]:null,filterByUnique:u?u[1]:null}},lo=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,(s,a,u)=>/^{.*}$/.test(u)?`:${u}`:`:${a}"${u}"`),n=n.replace(/\[([^\]]+)\]/g,(s,a)=>`[${a.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 ot=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 fn=async e=>{let{tqlRequest:t,dbHandles:r,config:i}=e,o=new TypeDBOptions;o.infer=!0;let{session:n}=await ot(r,i),s=await n.transaction(TransactionType.READ,o),[a,u]=await tryit(parallel)(t.length,t,async f=>await s.query.fetch(f).collect());if(a){await s.rollback();let f=a;throw new Error(`Error running TQL query: ${f.errors}`)}return await s.close(),u};var $o=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,mo=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,yo=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,_t=N("error","error",j((e,t)=>({...e,error:t.error}))),go=me("build",{build:H(async e=>dn({queries:e.bql.queries,schema:e.schema}),N("done","run",j(mo)),_t),run:H(async e=>fn({dbHandles:e.handles,tqlRequest:he(e.tql.queries),config:e.config}),N("done","parse",j(yo)),_t),parse:H(async e=>hn({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:he(e.tql.res)}),N("done","success",j($o)),_t),success:ie(),error:ie()},e=>e),Eo=async e=>new Promise((t,r)=>{$e(go,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),$n=async(e,t,r,i,o)=>Eo({bql:{raw:e,queries:t},tql:{},schema:r,config:i,handles:o,error:null});var Bo=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Vt=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,st=N("error","error",j((e,t)=>({...e,error:t.error}))),Fo=me("enrich",{enrich:H(async e=>Jr(e.bql.raw,e.schema),N("done","adapter",j(Bo)),st),adapter:H(async e=>{let t={};e.bql.queries?.forEach((a,u)=>{let f=e.bql.raw[u],c=G(e.schema,a.$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 l=t[d];l.rawBql.push(f),l.bqlQueries.push(a),l.indices.push(u);});let r=Object.values(t),i=r.map(a=>{if(a.db==="typeDB")return $n(a.rawBql,a.bqlQueries,e.schema,e.config,e.handles);if(a.db==="surrealDB")return ln(a.bqlQueries,e.schema,e.config,a.client);throw new Error(`Unsupported DB "${JSON.stringify(a,null,2)}"`)}),o=await Promise.all(i),n=r.flatMap((a,u)=>{let f=o[u];return a.indices.map((c,d)=>({index:c,result:f[d]}))});return n.sort((a,u)=>a.index<u.index?-1:a.index>u.index?1:0),n.map(({result:a})=>a)},N("done","postHooks",j(Vt)),st),postHooks:H(async e=>vr(e.schema,he(e.bql.queries),he(e.bql.res)),N("done","clean",j(Vt)),st),clean:H(async e=>Hr(e.config,he(e.bql.res)),N("done","success",j(Vt)),st),success:ie(),error:ie()},e=>e),Mo=async e=>new Promise((t,r)=>{$e(Fo,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),ze=async(e,t,r,i)=>Mo({bql:{raw:e},schema:t,config:r,handles:i,error:null});var Ut="___",bo=Symbol.for("grandChildOfCreate"),mn=async(e,t,r,i)=>{let o=(M,b)=>Object.keys(M).filter(E=>!E.startsWith("$")&&M[E]!==void 0?b?!x(t,M).dataFields?.find(T=>T.path===E):!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:M,key:b,value:E})=>{M&&b&&!b.includes("$")&&isObject(M)?(Array.isArray(M[b])?M[b]:[M[b]]).forEach(T=>{if(isObject(T)){if(M.$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`)}}):!M&&isObject(E)&&(n.includes(E.$op)||n.push(E.$op));}),!n.includes("delete")&&!n.includes("unlink")&&!n.includes("replace")&&!n.includes("update")&&!n.includes("link"))return;let a=(M=>{let b=(E,w)=>{let T=[],C={},O=["$op","$bzId","$parentKey"],D=["$relation","$entity","$id",...O];for(let V in E)if(!O.includes(V)&&!(D.includes(V)&&!w))if(!V.includes("$")&&(isObject(E[V])||Array.isArray(E[V]))){let v=E[V];if(Array.isArray(v)&&v.length>0)v.forEach(fe=>{let Se={$path:V,...b(fe),...fe.$filter&&{$as:fe.$bzId}};T.find(J=>J.$path===Se.$path&&!J.$filter)||(T=[...T,Se]);});else {let fe={$path:V,...b(v),...!v.$filter&&{$as:v.$bzId}};T=[...T,fe];}}else C[V]=E[V];return {...C,$fields:T}};return M.map(E=>b(E,!0))})(Array.isArray(e)?e:[e]),f=(await ze(a,t,{...r,query:{...r.query,returnNulls:!0}},i)).bql.res,c=(M,b)=>{let E=M.$id||M.id||M.$bzId;if(M.$objectPath){let{$objectPath:w}=M,T=w?.beforePath||"root",C=Array.isArray(w.ids)?`[${w.ids}]`:w.ids;return {beforePath:`${T}.${C}___${w.key}`,ids:E,key:b}}else return {beforePath:"root",ids:E,key:b}},d=(M,b)=>{let E=M?.beforePath||"root";if(typeof E!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let w=b||(Array.isArray(M?.ids)?`[${M?.ids}]`:M?.ids);return `${E}.${w}___${M?.key}`},l=M=>{if(M.includes("[")&&M.includes("]")){let[b,E,w]=M.split(/[[\]]/);return E.split(",").map(C=>`${b}${C}${w}`)}else return [M]},p={};(M=>produce(M,b=>traverse(b,({key:E,parent:w})=>{if(w&&E&&w.$id&&!E.includes("$")){let T=c(w,E),C=d(T);if(Array.isArray(w[E])){let O=[];w[E].forEach(D=>{isObject(D)?(D.$objectPath=T,O.push(D.$id.toString())):D&&O.push(D.toString());}),p[C]={$objectPath:T,$ids:O};}else {let O=w[E];isObject(O)?(p[C]={$objectPath:T,$ids:[O.$id.toString()]},O.$objectPath=T):O?p[C]={$objectPath:T,$ids:[O.toString()]}:O===null&&(p[C]=null);}}})))(f||{});let $=M=>produce(M,b=>traverse(b,({key:E,value:w,parent:T})=>{T&&E&&!E.includes("$")&&(Array.isArray(w)||isObject(w))&&!Array.isArray(T)&&(Array.isArray(T[E])?T[E].forEach(C=>{typeof C!="string"&&(C.$objectPath=c(T,E),C.$parentIsCreate=T.$op==="create",C[bo]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")]);}):isObject(T[E])&&(T[E].$parentIsCreate=T.$op==="create",T[E][Symbol.for("grandChildOfCreate")]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")],T[E].$objectPath=c(T,E)));})),y=$(e),m=M=>{let b=[];return M.forEach(w=>{if(!w.$id&&!w.id&&!w.$tempId)if(w.$filter){let T=d({...w.$objectPath,key:w.$bzId}),C=p[T];C&&(Array.isArray(C.$ids)?C.$ids:[C.$ids]).forEach(D=>{let V={...w,$id:D,$bzId:`T4_${v4()}`,$filterBzId:w.$bzId};b.push(V);});}else {let T=d(w.$objectPath),C=p[T];C?C?.$ids?.forEach(O=>{let D={...w,$id:O,$bzId:`T4_${v4()}`};b.push(D);}):b.push(w);}else b.push(w);}),b.map(w=>{let T={...w};return o(T,!0).forEach(C=>{let O=Array.isArray(T[C])?T[C]:[T[C]],D=m(O);T[C]=D;}),T})},B=m(Array.isArray(y)?y:[y]),F=$(B),Q=(M=>{let b=E=>{let w=J=>{let te=[],K=[],q=[];return J.forEach(_=>{let ue=o(_,!0);if(ue.length>0){let k=!1;ue.forEach(U=>{(Array.isArray(_[U])?_[U]:[_[U]]).filter(X=>!X.$id&&!X.id&&typeof _=="object").length&&(k=!0);}),k?te.push(_):K.push(_);}else _.$id?q.push({..._,$bzId:_.$tempId||_.$bzId}):q.push({..._,$bzId:_.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:te,operationWithoutMultiples:K,otherOps:q}},{operationWithMultiples:T,operationWithoutMultiples:C,otherOps:O}=w(E),D=J=>{let K=(()=>{let U={};for(let oe in J){let Y=x(t,J);!oe.startsWith("$")&&Y.dataFields?.find(X=>X.path===oe)&&(U[oe]=J[oe]);}return U})(),q=Object.keys(J),_=o(J,!0),ue=[],k=(U,oe)=>{if(U===_.length){let X={...oe};q.forEach(se=>{se.startsWith("$")&&(X[se]=J[se]);}),ue.push({...X,...K});return}let Y={...oe,[_[U]]:J[_[U]],...we(oe),...K};k(U+1,Y),k(U+1,oe);};return k(0,{...we(J)}),ue},V=[];return T.forEach(J=>{let te=D(J),K=[];te.forEach(q=>{let _=o(q,!0);if(q.$op==="create")K.push(q);else if(q.$id){let ue=d(q.$objectPath),k=[];if(_.forEach(U=>{let oe=`${ue.includes("undefined")?"root":ue}.${q.$id}${Ut}${U}`,Y=p[oe];q[U].filter(se=>se.$op==="unlink"||se.$op==="delete"||se.$op==="update").length>0?Y?.$ids&&k.push({key:U,ids:Y.$ids}):k.push({key:U,ids:[""]});}),k.length===_.length&&!K.find(U=>U.$id===q.$id))K.push(q);else {let U={...q,$bzId:q.$tempId||`T4_${v4()}`};_.forEach(Y=>{let X=q[Y].filter(se=>se.$id);X.length>0?U[Y]=X:U[Y]=void 0;}),o(U,!0).length>0&&K.push(U);}}else if(q.$objectPath){let ue=d(q.$objectPath),k=p[ue]?.$ids||[];k.forEach(U=>{let oe=[];_.forEach(Y=>{let X=`${ue}.${U}${Ut}${Y}`,se=p[X];se&&oe.push({key:Y,ids:se.$ids});}),_.length===0?k.filter(X=>!K.find(se=>se.$id===X)).forEach(X=>{K.push({...q,$id:X,$bzId:q.$tempId||`PQT2_${v4()}`});}):oe.length===_.length&&!K.find(Y=>Y.$id===U)&&(_.forEach(Y=>{let X=`${d(q.$objectPath)}.${U}${Ut}${Y}`,se=p[X]?.$ids||[],Un=q[Y].find(Ae=>!Ae.$id),Xt=[...se.map(Ae=>({...Un,$id:Ae,$objectPath:{beforePath:q.$objectPath.beforePath,ids:Ae,key:Y}})),...q[Y].filter(Ae=>Ae.$id)];Xt.length>0&&(q[Y]=Xt);}),K.push({...q,$id:U,$bzId:q.$tempId||`PQ3_${v4()}`}));});}else K.push(q);}),K.forEach(q=>{V.push(q);});}),[...V,...C,...O].filter(J=>o(J).length>0?!0:J.$op!=="update").map(J=>{let te={...J};return o(te,!0).forEach(K=>{let q=Array.isArray(te[K])?te[K]:[te[K]],_=b(q);te[K]=_;}),te})};return b(M)})(Array.isArray(F)?F:[F]),L=M=>M.map(b=>{let E=o(b,!0),w={...b};return E.forEach(T=>{let C=Array.isArray(b[T])?b[T]:[b[T]],O=[],D=[],V=[],v={},fe=yt(t,b,T);C.filter(k=>k).forEach(k=>{k.$op==="replace"&&k.$id?(v=k,Array.isArray(k.$id)?D=[...D,...k.$id]:D.push(k.$id)):k.$op==="create"&&fe==="ONE"&&k.id?(v=k,Array.isArray(k.id)?V=[...D,...k.id]:V.push(k.id)):O.push(k);});let Se=d(v.$objectPath),te=l(Se).map(k=>p[k]),K=[];te.filter(k=>k!=null).forEach(k=>{K=[...K,...k?.$ids||[]];});let q=K.filter(k=>!D.includes(k)),_=D.filter(k=>!K.includes(k)),ue=we(v);q.length>0&&O.push({...v,$op:"unlink",$id:q,$bzId:v.$tempId||`T4_${v4()}`,id:void 0,...ue}),_.length>0&&_.forEach(k=>{O.push({...v,$op:"link",$id:k,$bzId:v.$tempId||`T5_${v4()}`,...ue});}),V.length>0&&V.forEach(k=>{O.push({...v,$op:"create",id:k,$bzId:v.$tempId||`T6_${v4()}`,...ue});}),w[T]=L(O);}),w}),R=$(L($(Q)));(M=>produce(M,b=>traverse(b,E=>{let{key:w,value:T,parent:C}=E;w&&C&&!w?.includes("$")&&(Array.isArray(T)||isObject(T))&&!Array.isArray(C)&&(Array.isArray(T)?T:[T]).forEach(D=>{let V=D.$filter?{...D.$objectPath,key:D.$filterBzId}:D.$objectPath,v=d(V),fe=p[v],Se=(K,q)=>K.every(_=>q.includes(_)),J=D.$id?Array.isArray(D.$id)?Se(D.$id,fe&&fe.$ids?fe.$ids:[]):fe?.$ids?.includes(D.$id):fe,te=yt(t,C,D.$objectPath.key);if(D.$op==="link"&&J&&te==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${d(D.$objectPath)}" because it is already occupied.`);if(D.$op)switch(D.$op){case"delete":if(!J&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${D.$id}" because it is not linked to $id:"${C.$id}"`);break;case"update":if(!J&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${D.$id}" because it is not linked to $id:"${C.$id}"`);break;case"unlink":if(!J&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${D.$id}" because it is not linked to $id:"${C.$id}"`);break;case"link":if(J)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${D.$id}" because it is already linked to $id:"${C.$id}"`);break;}});})))(R);let z=(M=>produce(M,b=>traverse(b,E=>{let{value:w,meta:T}=E;isObject(w)&&(w[Symbol.for("path")]=T.nodePath,delete w.$objectPath,delete w.$parentIsCreate);})))(R);return [...Array.isArray(z)?z:[z]].sort((M,b)=>M.$op==="create"&&b.$op!=="create"?-1:M.$op!=="create"&&b.$op==="create"?1:0)};var yn=(e,t)=>produce(e,i=>lt(t,i)),lt=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(o=>lt(e,o,r));return}let i=G(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([o])=>{o.startsWith("$")||To(e,t,o,i);});},To=(e,t,r,i)=>{let o=t[r];if(!o)return;let n=i.dataFields?.find(a=>a.path===r);if(n){n.contentType==="JSON"&&o!=null&&(t[r]=JSON.stringify(o));return}let s=i.linkFields?.find(a=>a.path===r);if(s){let a=s.oppositeLinkFieldsPlayedBy[0]?.thing;lt(e,o,a);return}if(i.thingType==="relation"){let a=i.roles[r];if(!a)throw new Error(`[Schema] Role ${r} in ${i.name} is not defined`);let[u]=a.playedBy||[];if(!u)throw new Error(`Role ${a.path} in ${i} is not played by anything`);lt(e,o,u.thing);}};var Fn=async(e,t,r,i)=>{let o=Array.isArray(e)?e:[e],n=o.map(u=>Ht(u,!0)),a=(await ze(n,t,r,i)).bql.res;return o.map((u,f)=>{let c=G(t,u.$thing);return bn({mut:u,node:a[f],schema:t,thing:c})})},Mn=new Set(["$op","$bzId","$parentKey"]),Qo=new Set(["$relation","$entity","$id",...Mn]),Ht=(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(Mn.has(o)||Qo.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,...Ht(n[0],!1)}):isObject(n)&&(r[o]={$path:o,...Ht(n,!1)});}return i.$fields=Object.values(r),i},bn=e=>{let{mut:t,node:r,schema:i,thing:o}=e,n=Tn(o),s=Ro(r);if(Array.isArray(t))return t.map(u=>{let f=s[u.$id];return f?gn({mut:u,node:f,schema:i,thing:o,...n}):u});let a=s[t.$id];return gn({mut:t,node:a,schema:i,thing:o,...n})},gn=e=>{let{mut:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:s,roleFieldMap:a}=e,{$fields:u,...f}=t;if(!r)return f;let c=wn({$fields:t.$fields,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:s,roleFieldMap:a}),d={...f,[ke]:c};for(let l in t){if(l.startsWith("$"))continue;let p=t[l];if(n[l]||!p||typeof p!="object"){d[l]=p;continue}let $=s[l]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[l]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${l}"`);let y=G(i,$);d[l]=bn({mut:p,schema:i,node:r[l],thing:y});}return d},wn=e=>{let{$fields:t,node:r,schema:i,thing:o,dataFieldMap:n,linkFieldMap:s,roleFieldMap:a}=e,u=t||Lo(o),f={$id:r.$id};return u.forEach(c=>{let d=typeof c!="string",l=d?c.$path:c,p=r[l];if(n[l]){f[l]=p;return}let $=s[l]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||a[l]?.playedBy?.[0]?.thing;if(!$)throw new Error(`"${o.name}" does not have field "${l}"`);if(!d){p&&(f[l]=Array.isArray(p)?p.map(En):En(p));return}let y=G(i,$),m=Tn(y);f[l]=Array.isArray(p)?p.map(B=>Bn({...m,$fields:c.$fields,value:B,schema:i,thing:y})):Bn({...m,$fields:c.$fields,value:p,schema:i,thing:y});}),f},Lo=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},En=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},Bn=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 wn({...e,node:t})},Tn=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}},Ro=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 Kt=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 Qn=async(e,t,r)=>{if(!e&&!t||!e.length&&!t.length)throw new Error("TQL request error, no things");if(!r)throw new Error("No schema provided");let i=l=>{let p=l.$op,h=`$${l.$bzId}`,$=x(r,l),{idFields:y,defaultDBConnector:m}=$,B=m?.path||l.$thing,F=l.$id,g=y?.[0],Q=listify(l,(I,M)=>{if(I.startsWith("$")||I.startsWith("%")||I===g||M===void 0||M===null)return "";let b=$.dataFields?.find(T=>T.path===I);if(!b?.path)return "";let w=b.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(b.contentType))return `has ${w} '${M}'`;if(["NUMBER","BOOLEAN"].includes(b.contentType))return `has ${w} ${M}`;if(b.contentType==="DATE"){if(Number.isNaN(M.valueOf()))throw new Error("Invalid format, Nan Date");return M instanceof Date?`has ${w} ${M.toISOString().replace("Z","")}`:`has ${w} ${new Date(M).toISOString().replace("Z","")}`}if(b.contentType==="FLEX"){let T=`bza${Le()}`,C=isArray(M)?M.map(O=>Kt(O)):Kt(M);if(Array.isArray(C))throw new Error("Array in FLEX fields not supported yet");return `has ${w} $${T}; $${T} '${T}' isa ${w}, has ${C.type}Attribute ${C.value}`}throw new Error(`Unsupported contentType ${b.contentType}`)}).filter(I=>I),L=`${h}-atts`,R=listify(l,I=>{if(I.startsWith("$")||I.startsWith("%")||I===g)return "";let M=$.dataFields?.find(w=>w.path===I);if(!M?.path)return "";let E=M.dbPath;return `{${L} isa ${E};}`}).filter(I=>I),A=isArray(F)?`like '${F.join("|")}'`:`'${F}'`,P=F?[`has ${g} ${A}`]:[],z=[...P,...Q].filter(I=>I).join(","),Z=()=>{if(p==="delete"||p==="unlink"||p==="match")return `${h} isa ${[B,...P].filter(I=>I).join(",")};`;if(p==="update"){if(!R.length)throw new Error("update without attributes");return `${h} isa ${[B,...P].filter(I=>I).join(",")}, has ${L};
53
+ ${R.join(" or ")};`}return ""},W=()=>p==="update"||p==="link"||p==="match"?`${h} isa ${[B,...P].filter(I=>I).join(",")};`:"";if(ve(l))return {op:p,deletionMatch:Z(),insertionMatch:W(),insertion:p==="create"?`${h} isa ${[B,z].filter(I=>I).join(",")};`:p==="update"&&Q.length?`${h} ${Q.join(",")};`:"",deletion:p==="delete"?`${h} isa ${B};`:p==="update"&&R.length?`${h} has ${L};`:""};throw new Error("in attributes")},o=l=>{let p=l.$op,h=x(r,l),$=`$${l.$bzId}`,y=l.$id,m=h.defaultDBConnector?.path||l.$thing,B="roles"in h?listify(h.roles,M=>M):[],F="roles"in h?mapEntries(h.roles,(M,b)=>[M,b.dbConnector?.path||M]):{},g=listify(l,(M,b)=>{if(!B.includes(M))return null;if(!("roles"in h))throw new Error("This should have roles! ");let E=F[M];return Array.isArray(b)?b.map(w=>({path:E,id:w})):{path:E,id:b}}).filter(M=>M).flat(),Q=g.map(M=>{if(!M?.path)throw new Error("Object without path");return `${M.path}: $${M.id}`}),L=g.length>0?`( ${Q.join(" , ")} )`:"",R=l[Qe];if(!R)throw new Error("[internal error] Symbol edgeType not defined");let A=L?`${$} ${L} ${R==="linkField"||p==="delete"||p==="unlink"?`isa ${m}`:""}`:"",P=`${$} ${R==="linkField"||p==="delete"?`isa ${m}`:""}`,z=()=>A?p==="link"?`${A};`:p==="create"?`${A}, has id '${y}';`:"":"",Z=()=>A&&p==="match"?`${A};`:"",W=()=>A?p==="delete"?`${A};`:p==="match"?`${A};`:"":"",I=()=>A?p==="delete"?`${P};`:p==="unlink"?`${$} ${L};`:"":"";return {deletionMatch:W(),insertionMatch:Z(),deletion:I(),insertion:z(),op:""}},n=(l,p)=>{let h=p==="edges"?o:i;if(Array.isArray(l))return l.map(g=>{let{preDeletionBatch:Q,insertionMatch:L,deletionMatch:R,insertion:A,deletion:P}=h(g);return shake({preDeletionBatch:Q,insertionMatch:L,deletionMatch:R,insertion:A,deletion:P},z=>!z)}).filter(g=>g);let{preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:F}=h(l);return shake({preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:F},g=>!g)},s=n(e),a=Array.isArray(s)?s:[s],u=n(t,"edges"),f=Array.isArray(u)?u:[u],c=[...a,...f];return shake({insertionMatches:c.map(l=>l.insertionMatch).join(" ").trim(),deletionMatches:c.map(l=>l.deletionMatch).join(" ").trim(),insertions:c.map(l=>l.insertion).join(" ").trim(),deletions:c.map(l=>l.deletion).join(" ").trim()},l=>!l)};var Ln=async(e,t,r,i,o)=>{let n=[...t,...r],s=n.map(a=>{let u=e.insertions?.find(d=>d.get(`${a.$bzId}`))?.get(`${a.$bzId}`),f=a.$thing||a.$relation||a.$entity,c=f?G(i,f):void 0;if(a.$op==="create"||a.$op==="update"||a.$op==="link"){if(a.$op!=="update"&&!u&&a.$id)return {$id:a.$id,$error:"Does not exist or it's not linked to the parent"};let d=u?.asThing().iid,l=Object.entries(a).filter(([h,$])=>!h.startsWith("$")).reduce((h,[$,y])=>{if(c?.dataFields?.find(B=>B.path===$)?.contentType==="JSON")return h[$]=JSON.parse(y),h;if(a.$thingType==="relation"){let B=n.filter(F=>F.$id&&F.$bzId===y);return B.length===1?(h[$]=B[0].$id,h):(h[$]=y,h)}return h[$]=y,h},{});if(o.mutation?.noMetadata)return l;let p=a.$tempId&&!a.$tempId.startsWith("_:")?{$tempId:`_:${a.$tempId}`}:{};return {$dbId:d,...a,...l,[a.path]:a.$id,...p}}if(a.$op==="delete"||a.$op==="unlink")return a;if(a.$op!=="match")throw new Error(`Unsupported op ${a.$op}`)}).filter(a=>a);return clone(s)};var Rn=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 ot(t,r),o=await i.transaction(TransactionType.WRITE),n=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,s=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{n&&await o.query.delete(n);let a=s&&o.query.insert(s),u=a?await a.collect():void 0;return await o.commit(),{insertions:u}}catch(a){throw new Error(`Transaction failed: ${a.message}`)}finally{await o.close();}};var ko=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Oo=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),qo=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),vt=N("error","error",j((e,t)=>({...e,error:t.error}))),Po=me("buildMutation",{buildMutation:H(async e=>Qn(e.bql.things,e.bql.edges,e.schema),N("done","runMutation",j(Oo)),vt),runMutation:H(async e=>Rn(e.tql.mutation,e.handles,e.config),N("done","parseMutation",j(qo)),vt),parseMutation:H(async e=>Ln(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),N("done","success",j(ko)),vt),success:ie(),error:ie()},e=>e),xo=async e=>new Promise((t,r)=>{$e(Po,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),Dn=async(e,t,r,i,o,n,s)=>xo({bql:{raw:e,enriched:t,things:r,edges:i,flat:{things:[],edges:[],arcs:[]},res:[]},tql:{},schema:o,config:n,handles:s,error:null});var Yt=e=>{if(isDate(e))return `d"${e.toISOString()}"`;if(typeof e=="string")return `'${e}'`;if(["number","boolean"].includes(typeof e))return e;throw new Error(`Unsupported type ${typeof e}`)};var Cn=async(e,t)=>{let r=s=>{let{$filter:a,$thing:u,$bzId:f,$op:c,$id:d,$tempId:l}=s,p=G(t,u),{usedDataFields:h}=le(p,s),{idFields:$}=p,y=d||s[$[0]],m=De(u),B=ae(s,b=>b.startsWith("$")),F=ae(s,b=>!b.startsWith("$")),g=JSON.stringify(F),Q=Object.entries(B).map(([b,E])=>b=="$tempId"?`'$tempId': '_:${E}'`:`'${b}': '${E}'`).join(","),L=s[Ue],R=h.map(b=>{let E=p.dataFields?.find(T=>T.path===b||T.dbPath===b);if(!E)throw new Error(`Data field schema not found for ${b}`);if($.includes(b))return;if(s[b]===null)return `${b} = NONE`;let w=s[b];if(["JSON","NUMBER","BOOLEAN"].includes(E.contentType))return `${b} = ${w}`;if(["TEXT","EMAIL"].includes(E.contentType))return `${b} = '${w}'`;if(E.contentType==="DATE")return `${b} = d"${w.toISOString()}"`;if(E.contentType==="FLEX"){let T=isArray(w)?w.map(C=>Yt(C)):Yt(w);return `${b} = ${isArray(T)?T.map(C=>C):T}`}throw new Error(`Unsupported data field type ${E.contentType} for key ${b} in mutation`)}).filter(Boolean),A=`$\u27E8${l||f}\u27E9`,P=L?.bzId?`$\u27E8${L.bzId}\u27E9.\u27E8${L.edgeField}\u27E9`:y?`${m}:\u27E8${y}\u27E9`:`${m}`,z=(()=>{if(L?.bzId){let b=`array::flatten($\u27E8${L.bzId}\u27E9.\u27E8${L.edgeField}\u27E9)`;return y?isArray(y)?`${b}[? $this.id() IN [${y.map(E=>`'${E}'`).join(", ")}] ]`:`${b}[? $this.id() IN ['${y}'] ]`:b}else {if(y){if(isArray(y))throw new Error("Multiple ids not supported");return `${m}:\u27E8${y}\u27E9`}return `${m}`}})(),Z=a?`WHERE ${pe(ce(a,u,t))}`:"",W=R.length>0?`SET ${R.join(", ")}`:"",I=`VALUE (CREATE ONLY Delta SET input = ${g}, meta = {${Q}, "$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,M="BEFORE";if(["link","unlink","replace"].includes(c))throw new Error("Edge ops don't belong to things");if(s.$op==="match")return `LET ${A} = (SELECT VALUE id FROM ${z} ${Z});`;if(s.$op==="create")return `LET ${A} = (CREATE ONLY ${m}:\u27E8${y}\u27E9 ${W} RETURN ${I});`;if(s.$op==="update")return `LET ${A} = IF (${P}) THEN (UPDATE ${z} ${W} ${Z} RETURN ${I}) END;`;if(s.$op==="delete")return `LET ${A} = IF (${P}) THEN (DELETE ${z} ${Z} RETURN ${M}) END;`;throw new Error(`Unsupported operation ${s.$op}`)},i=s=>{let {$filter:a,$thing:u,$bzId:f,$op:c,$tempId:d}=s,l=G(t,u),{usedRoleFields:p}=le(l,s),h=`$\u27E8${d||f}\u27E9`;a?`WHERE ${pe(ce(a,u,t))}`:"";let y="roles"in l?p.flatMap(F=>{let g=l.roles[F];if(!g)throw new Error(`Role field schema not found for ${F}`);let{cardinality:Q}=g,L=isArray(s[F])?s[F].map(R=>`$\u27E8${R}\u27E9`):[`$\u27E8${s[F]}\u27E9`];if(Q==="ONE"){if(L.length>1)throw new Error(`${c==="link"?"Linking":"Replacing"} multiple values to a ONE field ${F}`);switch(c){case"link":case"replace":return `${F} = ((type::is::array(${L[0]}) && array::len(${L[0]})==1) && ${L[0]}[0]) || ${L[0]}`;case"unlink":return `${F} = NONE`;default:throw new Error(`Unsupported operation ${c} for ONE cardinality`)}}else if(Q==="MANY"){let R=`array::flatten([${L}])`;switch(c){case"link":return `${F} += ${R}`;case"unlink":return `${F} -= ${R}`;case"replace":return `${F} = ${R}`;default:throw new Error(`Unsupported operation ${c} for MANY cardinality`)}}else throw new Error(`Unsupported cardinality ${Q}`)}):[],m=y.length>0?`${y.join(", ")}`:"",B=m?`SET ${m}`:"";return `IF ${h} THEN (UPDATE ${h} ${B} RETURN VALUE id) END; ${h};`},o=s=>{let{$filter:a,$thing:u,$bzId:f,$op:c,$id:d,$tempId:l}=s,p=G(t,u),h=De(u),{usedRoleFields:$}=le(p,s);if(!["create","delete"].includes(c))throw new Error("Arcs can only be created or deleted");let[y,m]=$,B=isArray(s[y])?s[y]:[s[y]],F=isArray(s[m])?s[m]:[s[m]];if(c==="create"){if($.length!==2)throw new Error("Not supported: Arcs must have exactly 2 roles");let g=ae(s,W=>!W.startsWith("$")),L=`(CREATE ONLY Delta SET input = ${JSON.stringify(g)}, meta = {"$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,A=p.roles[y].cardinality==="MANY",z=p.roles[m].cardinality==="MANY";return B.flatMap(W=>F.flatMap(I=>`FOR $node1 IN fn::as_array($\u27E8${W}\u27E9) { FOR $node2 IN fn::as_array($\u27E8${I}\u27E9) { CREATE ONLY ${h} SET ${y} = ${A?"fn::as_array($node1)":"$node1"}, ${m} = ${z?"fn::as_array($node2)":"$node2"} RETURN ${L}; } }`))}if(c==="delete")return `DELETE FROM ${h} WHERE fn::as_array(${y}) CONTAINSANY $\u27E8${B}\u27E9 AND fn::as_array(${m}) CONTAINSANY $\u27E8${F}\u27E9 RETURN BEFORE`};return [...e.things.map(r),...e.edges.map(i),...e.arcs.flatMap(o)]};var In=async(e,t)=>{let r=`
54
+ BEGIN TRANSACTION;
55
+ ${t.join(";")};
56
+ LET $DELTAS = SELECT * FROM Delta;
57
+ DELETE Delta;
58
+ RETURN $DELTAS;
59
+
60
+ LET $LOGS = SELECT * FROM LOG;
61
+ RETURN $LOGS;
62
+ COMMIT TRANSACTION;
63
+ `;try{return (await e.query(r)).filter(Boolean)}catch(i){let n=(await e.query_raw(r)).filter(s=>s.result!=="The query was not executed due to a failed transaction"&&s.result!=="There was an error when starting a new datastore transaction"&&s.status==="ERR");throw n.length>0?new Error(`Error running SURQL mutation: ${JSON.stringify(n)}`):i}};var qn=e=>{let{res:t,config:r}=e;return t.flat().filter(Boolean).flatMap(o=>{if(isArray(o))return o.map(n=>{if(!isObject(n)||!("meta"in n))throw new Error("Internal error: Invalid response from DB");return kn(n,r)});if(!isObject(o)||!("meta"in o))throw new Error("Internal error: Invalid response from DB");return kn(o,r)})},kn=(e,t)=>{let r=mapEntries(e.after||{},(n,s)=>[n,isArray(s)&&s.length===0?void 0:s]),i=ae(e.input||{},(n,s)=>s===null),o={...r,...e.meta,...i};return t.mutation?.noMetadata?ae(o,n=>!n.startsWith("$")):o};var zo=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Wo=(e,t)=>{if(!t.data||!isArray(t.data)||t.data.some(r=>typeof r!="string"))throw new Error("Invalid event data");return {...e,surql:{...e.surql,mutations:t.data}}},_o=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},Gt=N("error","error",j((e,t)=>({...e,error:t.error}))),Vo=me("buildMutation",{buildMutation:H(async e=>Cn(e.bql.flat,e.schema),N("done","runMutation",j(Wo)),Gt),runMutation:H(async e=>In(e.handles.surrealDB?.get(e.handles.surrealDB?.keys().next().value)?.client,e.surql.mutations),N("done","parseMutation",j(_o)),Gt),parseMutation:H(async e=>qn({res:e.surql.res,config:e.config,schema:e.schema}),N("done","success",j(zo)),Gt),success:ie(),error:ie()},e=>e),Uo=async e=>new Promise((t,r)=>{$e(Vo,i=>{i.machine.state.name==="success"&&t(i.context.bql.res),i.machine.state.name==="error"&&r(i.context.error);},e);}),xn=async(e,t,r,i,o,n)=>Uo({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:i,config:o,handles:n,error:null});var Nn=(e,t)=>{let r={things:[],edges:[],arcs:[]},i=(n,s)=>{if(!n?.$thing){console.log("block without $thing",n);return}let{$op:a,$bzId:u,$tempId:f}=n,c=t.relations[n.$thing]||t.entities[n.$thing];if(!c)throw new Error(`[Internal] No schema found for ${n.$thing}`);let d=s?.bzId?s:{bzId:"",edgeField:"root"},{usedDataFields:l,usedLinkFields:p,usedRoleFields:h}=le(c,n);if(["create","update","delete","link","unlink","match","replace"].includes(a)){let y={...ae(n,m=>![...h,...p].includes(m)),...a==="link"||a==="unlink"||a==="replace"||a==="update"&&l.length===0?{$op:"match"}:{},...a==="link"||a==="replace"?{}:{[Ue]:d}};r.things.push(y);}let $={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if(h){let y=ae(n,m=>isSymbol(m)||m.startsWith("$"));h.forEach(m=>{isArray(n[m])?n[m].forEach(F=>i(F,{bzId:u,edgeField:m,tempId:f})):i(n[m],{bzId:u,edgeField:m,tempId:f});let B=(isArray(n[m])?n[m]:[n[m]]).filter(Boolean);Object.entries($).forEach(([F,g])=>{let Q=B.filter(L=>g.includes(L.$op)).map(L=>L.$bzId);Q.length>0&&r.edges.push({...y,[m]:Q,$op:F});});});}p&&p.forEach(y=>{isArray(n[y])?n[y].forEach(F=>i(F,{bzId:u,edgeField:y,tempId:f})):i(n[y],{bzId:u,edgeField:y,tempId:f});let m=c.linkFields?.find(F=>F.path===y),B=isArray(n[y])?n[y]:[n[y]];m.target==="relation"&&Object.entries($).forEach(([F,g])=>{B.filter(L=>g.includes(L.$op)).forEach(L=>{let R=ae(L,A=>isSymbol(A)||A.startsWith("$"));r.edges.push({...R,[m.plays]:u,$op:F});});}),m.target==="role"&&Object.entries({create:["link","create"],delete:["unlink","delete"],replace:["replace"]}).forEach(([g,Q])=>{B.filter(R=>Q.includes(R.$op)).forEach(R=>{let A={$thing:m.relation,$thingType:"relation",$bzId:`arc_${R.$bzId}`,[m.plays]:u,[m.oppositeLinkFieldsPlayedBy[0].plays]:R.$bzId,$op:g};r.arcs.push(A);});});});};return (Array.isArray(e)?e:[e]).forEach(n=>i(n)),r};var zn=ie,We=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,Ho=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),Ko=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),Jo=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),vo=async e=>Object.keys(e.bql.enriched).length?Mt(e.bql.enriched,e.schema,e.config):Mt(e.bql.raw,e.schema,e.config),Yo=async e=>mn(e.bql.enriched,e.schema,e.config,e.handles),Go=async e=>Fn(e.bql.enriched,e.schema,e.config,e.handles),Zo=async e=>Dr(e.bql.enriched,e.schema),Xo=async e=>Nn(e.bql.enriched,e.schema),es=e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return !0;if(r==="surrealDB")return !1;throw new Error(`Unsupported provider ${r}.`)},ts=e=>Pe(e.bql.enriched),Ie=N("error","error",j((e,t)=>({...e,error:t.error}))),rs=me("stringify",{stringify:H(async e=>yn(e.bql.raw,e.schema),N("done","enrich",j(We)),Ie),enrich:H(vo,N("done","preQuery",bt(es),j(We)),N("done","parseBQL",j(We)),Ie),preQuery:H(Yo,N("done","preHookDependencies",bt(ts),j(We)),N("done","parseBQL",j(We)),Ie),preHookDependencies:H(Go,N("done","enrich",j(We)),Ie),parseBQL:H(Zo,N("done","flattenBQL",j(Ho)),Ie),flattenBQL:H(Xo,N("done","adapter",j(Ko)),Ie),adapter:H(async e=>{let{dbConnectors:t}=e.config;if(t.length!==1)throw new Error("Multiple providers not supported yet in mutations");let[{provider:r}]=t;if(r==="typeDB")return Dn(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return xn(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},N("done","success",j(Jo)),Ie),success:zn(),error:zn()},e=>e),ns=async e=>new Promise((t,r)=>{$e(rs,i=>{i.machine.state.name==="success"&&t(i.context),i.machine.state.name==="error"&&r(i.context);},e);}),Wn=async(e,t,r,i)=>ns({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[]},res:[]},schema:t,config:r,handles:i,depthLevel:0,error:null});enableMapSet();var Zt=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:{username:i.username,password:i.password},versionCheck:!1}),t.surrealDB.set(i.id,{client:o,providerConfig:i.providerConfig});}if(i.provider==="typeDB"&&i.dbName){let[o,n]=await tryit(TypeDB.coreDriver)(i.url);if(o){let s=`[BORM:${i.provider}:${i.dbName}:core] ${o.message??"Can't create TypeDB Client"}`;throw new Error(s)}try{let s=await n.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:n,session:s});}catch(s){let a=`[BORM:${i.provider}:${i.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(a)}}if(i.provider==="typeDBCluster"&&i.dbName){let o=new TypeDBCredential(i.username,i.password,i.tlsRootCAPath),[n,s]=await tryit(TypeDB.cloudDriver)(i.addresses,o);if(n){let a=`[BORM:${i.provider}:${i.dbName}:core] ${n.message??"Can't create TypeDB Cluster Client"}`;throw new Error(a)}try{let a=await s.session(i.dbName,SessionType.DATA);t.typeDB.set(i.id,{client:s,session:a});}catch(a){let u=`[BORM:${i.provider}:${i.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(u)}}}));let r=cr(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(),tr(this.config,this.schema,this.dbHandles));query=async(t,r)=>{await this.#e();let i={...this.config,query:{...ht.query,...this.config.query,...r}},o=Array.isArray(t),n=o?t:[t],[s,a]=await tryit(ze)(n,this.schema,i,this.dbHandles);if(s){let f=new Error(s.error);throw f.stack=s.error.stack,f}let u=a.bql.res;return o?u:u[0]};mutate=async(t,r)=>{await this.#e();let i={...this.config,mutation:{...ht.mutation,...this.config.mutation,...r}},[o,n]=await tryit(Wn)(t,this.schema,i,this.dbHandles);if(o){let a=new Error(o.error.message);throw a.stack=o.error.stack,a}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();});}},Hd=Zt;//! Todo: delete when this works with the new $thing and $thingType fields
54
64
  //! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
55
65
  //! Todo: Sandbox the function in computeFunction()
56
66
  //! reads all the insertions and gets the first match. This means each id must be unique
57
67
  //!old
58
68
 
59
- export { Kc as default };
69
+ export { Hd as default };
60
70
  //# sourceMappingURL=out.js.map
61
71
  //# sourceMappingURL=index.mjs.map