@blitznocode/blitz-orm 0.11.0 → 0.11.1

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
@@ -8,49 +8,116 @@ import { isSet } from 'util/types';
8
8
  import 'acorn';
9
9
  import { v4 } from 'uuid';
10
10
 
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
- `),y+=`
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
- `),y+=`
25
- `;});let B=`define
11
+ var $t={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},mutation:{noMetadata:!1,preQuery:!0,ignoreNonexistingThings:!1}};var Zn=e=>{let t=[],r=new Map;return e.forEach(n=>{let{dbPath:o,contentType:i}=n,a=`${o}-${i}`;r.has(a)||(r.set(a,!0),t.push(n));}),t},Xn=(e="default",t)=>{let r="",n=[];r+=`
12
+ `,Object.keys(t.entities).filter(s=>t.entities[s].defaultDBConnector.id===e).forEach(s=>{let u=t.entities[s],{dataFields:$,linkFields:c,name:d}=u;if(r+=`${d} sub ${"extends"in u?u.extends:"entity"},
13
+ `,$&&$.length>0&&$.forEach(l=>{l.inherited||(l.isIdField?r+=` owns ${l.dbPath} @key,
14
+ `:r+=` owns ${l.dbPath},
15
+ `,n.push({dbPath:l.dbPath,contentType:l.contentType}));}),c&&c.length>0){let l=[];c.forEach(p=>{let{relation:h,plays:f,inherited:y}=p;if(y)return;!t.relations[h].roles[f].inherited&&!l.includes(`${h}:${f}`)&&(r+=` plays ${h}:${f},
16
+ `,l.push(`${h}:${f}`));});}r=r.replace(/,\s*$/,`;
17
+ `),r+=`
18
+ `;}),Object.keys(t.relations).filter(s=>t.relations[s].defaultDBConnector.id===e).forEach(s=>{let u=t.relations[s],{dataFields:$,roles:c,name:d,linkFields:l}=u;if(r+=`${d} sub ${"extends"in u?u.extends:"relation"},
19
+ `,$&&$.length>0&&$.forEach(p=>{p.inherited||(p.isIdField?r+=` owns ${p.dbPath} @key,
20
+ `:r+=` owns ${p.dbPath},
21
+ `,n.push({dbPath:p.dbPath,contentType:p.contentType}));}),c&&Object.keys(c).forEach(p=>{c[p].inherited||(r+=` relates ${p},
22
+ `);}),l&&l.length>0){let p=[];l.forEach(h=>{let{plays:f,relation:y}=h;!t.relations[y].roles[f].inherited&&!h.inherited&&!p.includes(`${y}:${f}`)&&(r+=` plays ${h.relation}:${f},
23
+ `,p.push(`${y}:${f}`));});}r=r.replace(/,\s*$/,`;
24
+ `),r+=`
25
+ `;});let o=`define
26
26
 
27
- `;return Kn(m).forEach(g=>{if(B+=`${g.dbPath} sub attribute,
28
- `,g.contentType==="TEXT"||g.contentType==="ID"||g.contentType==="JSON")B+=` value string;
29
- `;else if(g.contentType==="EMAIL")B+=` value string,
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,})$';
31
- `;else if(g.contentType==="DATE")B+=` value datetime;
32
- `;else if(g.contentType==="BOOLEAN")B+=` value boolean;
33
- `;else if(g.contentType==="NUMBER")B+=` value long;
34
- `;else throw new Error(`Conversion of borm schema to TypeDB schema for data type "${g.contentType}" is not implemented`)}),`${B}
27
+ `;return Zn(n).forEach(s=>{if(s.contentType==="TEXT"||s.contentType==="ID"||s.contentType==="JSON")o+=`${s.dbPath} sub attribute, value string;
28
+ `;else if(s.contentType==="EMAIL")o+=`${s.dbPath} sub attribute, value string,
29
+ `,o+=` regex '^(?=.{1,64}@)[A-Za-z0-9_-]+(\\\\.[A-Za-z0-9_-]+)*@[^-][A-Za-z0-9-]+(\\\\.[A-Za-z0-9-]+)*(\\\\.[A-Za-z]{2,})$';
30
+ `;else if(s.contentType==="DATE")o+=`${s.dbPath} sub attribute, value datetime;
31
+ `;else if(s.contentType==="BOOLEAN")o+=`${s.dbPath} sub attribute, value boolean;
32
+ `;else if(s.contentType==="NUMBER")o+=`${s.dbPath} sub attribute, value long;
33
+ `;else if(s.contentType==="FLEX")o+=`${s.dbPath} sub flexAttribute;
34
+ `;else throw new Error(`Conversion of borm schema to TypeDB schema for data type "${s.contentType}" is not implemented`)}),`${o}
35
35
 
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=`
36
+ ${r}
37
+ #Tools, reserved for every schema using borm
38
+
39
+ stringAttribute sub attribute, value string;
40
+ longAttribute sub attribute, value long;
41
+ doubleAttribute sub attribute, value double;
42
+ booleanAttribute sub attribute, value boolean;
43
+ datetimeAttribute sub attribute, value datetime;
44
+ flexAttribute sub attribute, abstract, value string,
45
+ owns stringAttribute,
46
+ owns longAttribute,
47
+ owns doubleAttribute,
48
+ owns booleanAttribute,
49
+ owns datetimeAttribute;
50
+ `},rr=async(e,t,r,n)=>{if(!n.typeDB)throw new Error("No TypeDB handles found");let o=Xn(e,r),i=n.typeDB.get(e)?.session,a=n.typeDB.get(e)?.client;if(!i){console.log("Session Status: ","NO SESSION");return}if(!a)throw new Error("No TypeDB client found");await i.close();let[{dbName:s}]=t.dbConnectors;await(await a.databases.get(s)).delete(),await a.databases.create(s);let c=await(await a.session(t.dbConnectors[0].dbName,SessionType.SCHEMA)).transaction(TransactionType.WRITE);return await c.query.define(o),await c.commit(),await c.close(),o};var nr=e=>e.replace(/`/g,""),ei=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],X=e=>ei.some(t=>e.includes(t))?`\u27E8${e}\u27E9`:e;var ti=" ",Qe=e=>ti.repeat(e),Ve=(e,t)=>e.split(`
51
+ `).map(r=>r.trim()?`${Qe(t)}${r}`:r).join(`
52
+ `),ri=e=>{let t=`USE NS test;
53
+ USE DB test;
54
+
55
+ BEGIN TRANSACTION;
56
+ `,r=`-- ENTITIES
57
+ ${ir(e.entities)}`,n=`
58
+ -- RELATIONS
59
+ ${ir(e.relations)}`,o=ci();return `${t}${r}${n}${o}COMMIT TRANSACTION;`},ir=e=>Object.entries(e).map(([t,r])=>ni(X(t),r,1)).join(`
60
+
61
+ `),ni=(e,t,r)=>{let n=`${Qe(r)}DEFINE TABLE ${e} SCHEMAFULL PERMISSIONS FULL;${"extends"in t&&t.extends?` //EXTENDS ${t.extends};`:""}`,o=Ve(`-- DATA FIELDS
62
+ ${ii(t.dataFields??[],e,r)}`,r+1),i=Ve(`
63
+ -- LINK FIELDS
64
+ ${oi(t.linkFields??[],e,r)}`,r+1),a="roles"in t?Ve(`
65
+ -- ROLES
66
+ ${si(t.roles,e,r)}`,r+1):"";return `${n}
67
+ ${o}${i}${a}`},ii=(e,t,r)=>e.map(n=>{if(n.path==="id")return "";let o=li(n.contentType,n.validations),i=`${Qe(r)}DEFINE FIELD ${n.path} ON TABLE ${t}${["FLEX","JSON"].includes(n.contentType)?" FLEXIBLE":""}`;if(n.isVirtual){let a=n.dbValue?.surrealDB;return a?`${i} VALUE ${a};`:""}return `${i} TYPE ${o};`}).filter(Boolean).join(`
68
+ `),oi=(e,t,r)=>e.map(n=>{let o=n.cardinality==="MANY"?`option<array<record<${n.$things.map(X).join("|")}>>>`:`option<record<${n.$things.map(X).join("|")}>>`,i=`${Qe(r)}DEFINE FIELD ${X(n.path)} ON TABLE ${t}`;if(n.isVirtual){let a=n.dbValue?.surrealDB;return a?`${i} VALUE ${a};`:""}if(n.target==="role"){let a=e.find(h=>h.target==="relation"&&h.relation===n.relation),u=(n.oppositeLinkFieldsPlayedBy?.[0]).plays;if(!u||n.oppositeLinkFieldsPlayedBy?.length!==1)throw new Error(`Invalid link field: ${n.path}`);let $=n.cardinality==="ONE"?`record<${X(n.relation)}>`:`array<record<${X(n.relation)}>>`,c=X(n.pathToRelation||""),d=`${c}.${u}`,l=n.cardinality==="ONE"?`${i} VALUE <future> {RETURN SELECT VALUE ${d} FROM ONLY $this};`:`${i} VALUE <future> {array::distinct(SELECT VALUE array::flatten(${d} || []) FROM ONLY $this)};`,p=a?.path?"":`${Qe(r+1)}DEFINE FIELD ${c} ON TABLE ${t} TYPE option<${$}>;`;return [l,p].join(`
69
+ `)}if(n.target==="relation")return `${`${Qe(r)}DEFINE FIELD ${X(n.path)} ON TABLE ${t} TYPE ${o};`}`;throw new Error(`Invalid link field: ${JSON.stringify(n)}`)}).join(`
70
+ `),si=(e,t,r)=>Object.entries(e).map(([n,o])=>{let i=o.cardinality==="MANY"?`array<record<${o.$things.map(X).join("|")}>>`:`record<${o.$things.map(X).join("|")}>`,a=`${Qe(r)}DEFINE FIELD ${n} ON TABLE ${t} TYPE option<${i}>;`,s=ai(n,t,o,r);return `${a}
71
+ ${s}`}).join(`
72
+ `),ai=(e,t,r,n)=>{let o=`update_${e}`,i=r.playedBy?.find(B=>B.target==="relation"),a=i?.pathToRelation,s=r.playedBy?.find(B=>B.target==="role"),u=s?.pathToRelation,$=i??s;if(!$)throw new Error(`Invalid link field: ${JSON.stringify(r)}`);let c=X(a??u),d=(B,g)=>B.map(({path:L,cardinality:Q})=>`${L} ${g==="remove"?Q==="ONE"?"=":"-=":Q==="ONE"?"=":"+="} ${g==="remove"?Q==="ONE"?"NONE":"$before.id":"$after.id"}`).join(", "),l=r.impactedLinkFields?.map(B=>({path:B.path,cardinality:B.cardinality}))||[],h=[{path:c,cardinality:$.cardinality},...l],f=d(h,"remove"),y=d(h,"add"),m=`
73
+ IF ($before.${e}) THEN {UPDATE $before.${e} SET ${f}} END;
74
+ IF ($after.${e}) THEN {UPDATE $after.${e} SET ${y}} END;`,E=`
75
+ LET $edges = fn::get_mutated_edges($before.${e}, $after.${e});
76
+ FOR $unlink IN $edges.deletions {UPDATE $unlink SET ${f};};
77
+ FOR $link IN $edges.additions {${$.cardinality==="ONE"?`
78
+ IF ($link.${c}) THEN {UPDATE $link.${c} SET ${e} ${r.cardinality==="ONE"?"= NONE":"-= $link.id"}} END;`:""}
79
+ UPDATE $link SET ${y};
80
+ };`;return Ve(`DEFINE EVENT ${o} ON TABLE ${t} WHEN $before.${e} != $after.${e} THEN {${r.cardinality==="ONE"?m:E}
81
+ };`,n+1)},li=(e,t)=>{let r={TEXT:"string",ID:"string",EMAIL:"string",NUMBER:"number",BOOLEAN:"bool",DATE:"datetime",JSON:"object",FLEX:"bool|bytes|datetime|duration|geometry|number|object|string"},n=(i,a)=>{switch(i){case"TEXT":case"ID":case"EMAIL":return `"${a}"`;case"NUMBER":case"BOOLEAN":return a;case"DATE":return `d"${a}"`;case"FLEX":return a;default:return a}},o=t?.enum?`${t.enum.map(i=>n(e,i)).join("|")}`:r[e];if(!o)throw new Error(`Unknown content type: ${e}`);return t?.required?`${o}`:`option<${o}>`},ci=()=>`
82
+ -- BORM TOOLS
83
+ DEFINE FUNCTION fn::get_mutated_edges(
84
+ $before_relation: option<array|record>,
85
+ $after_relation: option<array|record>,
86
+ ) {
87
+ LET $notEmptyCurrent = $before_relation ?? [];
88
+ LET $current = array::flatten([$notEmptyCurrent]);
89
+ LET $notEmptyResult = $after_relation ?? [];
90
+ LET $result = array::flatten([$notEmptyResult]);
91
+ LET $links = array::complement($result, $current);
92
+ LET $unlinks = array::complement($current, $result);
93
+
94
+ RETURN {
95
+ additions: $links,
96
+ deletions: $unlinks
97
+ };
98
+ };
99
+
100
+ DEFINE FUNCTION fn::as_array($var: option<array<record>|record>) {
101
+ RETURN (type::is::array($var) AND $var) OR [$var]
102
+ };
103
+ `,or=e=>ri(e);var sr=async(e,t,r)=>await(async()=>{let i=(await Promise.all([...r.typeDB||[]].map(async([u])=>[u,await rr(u,e,t,r)]))).map(u=>[u[0],u[1]]),s=(await Promise.all([...r.surrealDB||[]].map(async([u])=>[u,or(t)]))).map(u=>[u[0],u[1]]);return {typeDB:new Map(i),surrealDB:new Map(s)}})();var re=Symbol.for("queryPath"),He=Symbol.for("stepPrint"),Re=Symbol.for("edgeType"),Te=Symbol.for("edgeSchema"),ke=Symbol.for("dbNode"),ft=Symbol.for("isTransformed"),Ke=Symbol.for("parent"),ne=Symbol.for("fieldSchema"),Fe=Symbol.for("sharedMetadata"),Me=Symbol.for("suqlMetadata");var ar={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var lr=({linkField:e,originalRelation:t,withExtensionsSchema:r,linkMode:n})=>{if(e.isVirtual)return `$this.${e.path}.id`;let o=r.relations[e.relation].subTypes||[],i=[e.relation,...o],a=`<-\u27E8${t}_${e.plays}\u27E9<-(\u27E8${i.join("\u27E9,\u27E8")}\u27E9)`;if(e.target==="relation"){if(n==="edges")return a;if(n==="refs")return `$parent.\`${e.path}\``;throw new Error("Unsupported linkMode")}else if(e.target==="role"){let[s]=e.oppositeLinkFieldsPlayedBy,u=r.entities[s.thing]?.subTypes||r.relations[s.thing]?.subTypes||[],$=[s.thing,...u],c=`->\u27E8${t}_${s.plays}\u27E9->(\u27E8${$.join("\u27E9,\u27E8")}\u27E9)`;return n==="edges"?`${a}${c}`:n==="refs"?`$parent.\`${s.plays}\``:`${a}${c}`}else throw new Error("Unsupported linkField target")};var ur=(e,t,r)=>r?t:`${e}\xB7${t}`;var pr=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,n])=>t(r,n))))[0],ae=(e,t)=>{let r=Reflect.ownKeys(e).map(n=>[n,e[n]]);return Object.fromEntries(r.filter(([n,o])=>{let[i,a]=tryit(()=>t(n,o))();return i?!1:a}))},$r=(e,t)=>{let r=[],n=produce(e,i=>traverse(i,({key:a,value:s,meta:u})=>{if(u.depth===2&&(a&&(s.dataFields=s.dataFields?.map($=>({...$,...s.idFields?.includes($.path)?{isIdField:!0}:{isIdField:!1},cardinality:$.cardinality||"ONE",dbPath:"dbPath"in $?$.dbPath:ur(a,$.path,$.shared)}))),s.extends)){if(!s.defaultDBConnector.as)throw new Error(`[Schema] ${a} is extending a thing but missing the "as" property in its defaultDBConnector. Path:${u.nodePath}`);let $=i.entities[s.extends]||i.relations[s.extends],c=[s.extends,...$.allExtends||[]];if(s.allExtends=c,c.forEach(d=>{if(i.entities[d])i.entities[d].subTypes=[a,...i.entities[d].subTypes||[]];else if(i.relations[d])i.relations[d].subTypes=[a,...i.relations[d].subTypes||[]];else throw new Error(`[Schema] ${a} is extending a thing that does not exist in the schema: ${d}`)}),s.idFields=$.idFields?Array.from(new Set((s.idFields||[]).concat($.idFields))):s.idFields,s.dataFields=$.dataFields?(s.dataFields||[]).concat($.dataFields.map(d=>{let l=s.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,inherited:!0,dbPath:"dbPath"in d?d.dbPath:ur(l,d.path,d.shared),[Fe]:{inheritanceOrigin:d[Fe]?.inheritanceOrigin||s.extends}}})):s.dataFields,"roles"in $){let d=s,l=$;if(l.roles){let p=mapEntries(l.roles,(h,f)=>[h,{...f,inherited:!0,[Fe]:{inheritanceOrigin:f[Fe]?.inheritanceOrigin||s.extends}}]);d.roles={...d.roles||{},...p};}}s.linkFields=$.linkFields?(s.linkFields||[]).concat($.linkFields.map(d=>({...d,inherited:!0,[Fe]:{inheritanceOrigin:d[Fe]?.inheritanceOrigin||s.extends}}))):s.linkFields,$?.hooks?.pre&&(s.hooks=s.hooks||{},s.hooks.pre=s.hooks.pre||[],s.hooks.pre=[...$?.hooks?.pre||[],...s?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:i,value:a,meta:s})=>{if(i==="linkFields"){let $=(()=>{if(!s.nodePath)throw new Error("No path");let[d,l]=s.nodePath.split(".");return {thing:l,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),c=Array.isArray(a)?a.map(d=>({...d,...$})):[{...a,...$}];r.push(...c);}}),produce(n,i=>traverse(i,({value:a,key:s,meta:u})=>{if(u.depth===2&&a.idFields&&!a.id){a.name=s;let $=()=>{if(u.nodePath?.split(".")[0]==="entities")return "entity";if(u.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};a.thingType=$();let c=Object.keys(t).find(d=>t[d]?.get(a.defaultDBConnector.id));if(a.db=c,a.dbContext=ar[c],a.dbProviderConfig=c==="surrealDB"?t[c]?.get(a.defaultDBConnector.id)?.providerConfig:void 0,a.computedFields=[],a.virtualFields=[],a.requiredFields=[],a.enumFields=[],a.fnValidatedFields=[],"linkFields"in a&&a.linkFields){let d=a;d.linkFields?.forEach(l=>{l.fieldType="linkField";let p=n.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,...p.subTypes||[]],l.oppositeLinkFieldsPlayedBy=[{plays:l.path,thing:l.relation,thingType:"relation"}];}if(l.target==="role"){let h=r.filter(f=>f.relation===l.relation&&f.plays!==l.plays)||[];if(l.oppositeLinkFieldsPlayedBy=h,l.oppositeLinkFieldsPlayedBy=l.oppositeLinkFieldsPlayedBy.filter(f=>f.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.pathToRelation=d.linkFields?.find(f=>f.target==="relation"&&f.relation===l.relation)?.path??l.relation.toLocaleLowerCase(),l.$things=l.oppositeLinkFieldsPlayedBy.map(f=>f.thing),l.oppositeLinkFieldsPlayedBy.length>1&&console.warn(`[Schema] LinkField ${l.path} in ${d.name} has multiple candidates ${l.oppositeLinkFieldsPlayedBy.map(f=>f.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`);}if(a.db==="surrealDB"){let h=p?.roles?.[l.plays][Fe]?.inheritanceOrigin??l.relation,f=lr({linkField:l,originalRelation:h,withExtensionsSchema:n,linkMode:a.dbProviderConfig.linkMode});l[Me]={queryPath:f};}});}if("roles"in a){let d=a;Object.entries(d.roles).forEach(([l,p])=>{p.fieldType="roleField";let h=r.filter(g=>g.relation===s&&g.plays===l)||[];p.playedBy=h.map(g=>({...g,pathToRelation:g.target==="relation"?g.path:d.linkFields?.find(L=>L.target==="relation"&&L.relation===s&&L.plays===l)?.path??g.relation.toLocaleLowerCase()}));let f=r.filter(g=>g.target==="relation"&&g.plays===l&&d.allExtends?.includes(g.relation));p.impactedLinkFields=f,p.path=l;let y=[...new Set(h.flatMap(g=>[...Y(n,g.thing).subTypes||[],g.thing]).flat().filter(Boolean))];p.$things=y;let m=p[Fe]?.inheritanceOrigin||a.name;y.length>1&&console.warn(`Not supported yet: Role ${l} in ${a.name} is played by multiple things: ${y.join(", ")}`);let E=y.flatMap(g=>{let Q=Y(e,g)?.subTypes||[];return [g,...Q]}),B=()=>{if(a.dbProviderConfig.linkMode==="edges")return `->\`${m}_${l}\`->(\`${E.join("`,`")}\`)`;if(a.dbProviderConfig.linkMode==="refs"){if(p.cardinality==="MANY")return `$parent.\`${l}\``;if(p.cardinality==="ONE")return `$parent.[\`${l}\`]`}throw new Error("Unsupported linkMode")};if(a.db==="surrealDB"){let g=B();p[Me]={queryPath:g};}});}}if(a&&typeof a=="object"&&"playedBy"in a){let $=[...new Set(a.playedBy.map(c=>c.thing))];if($.length>1&&console.warn(`[Schema] roleFields can be only played by one thing. Role: ${s}, path:${u.nodePath}, played by: ${$.join(", ")}`),a.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${s}, path:${u.nodePath}`)}if(u.depth===4){let[$,c]=u.nodePath?.split(".")||[],d=i[$][c];!isArray(a)&&typeof a=="object"&&(a.validations&&(a.validations.required&&d.requiredFields.push(a.path),a.validations.enum&&d.enumFields.push(a.path),a.validations.fn&&d.fnValidatedFields.push(a.path)),a.default?a.isVirtual?d.virtualFields.push(a.path):d.computedFields.push(a.path):a.isVirtual&&d.virtualFields.push(a.path));}}))},Y=(e,t)=>{if(t in e.entities)return e.entities[t];if(t in e.relations)return e.relations[t];throw new Error(`${t} is not defined in the schema`)},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)}`)},ve=(e,t)=>{let r=e.dataFields?.find(i=>i.path===t);if(r)return ["dataField",r];let n=e.linkFields?.find(i=>i.path===t);if(n)return ["linkField",n];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`)},Ye=(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[n]=r.idFields;return n},fr=(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")},gt=(e,t,r)=>{let n=q(e,t),o=n.linkFields?.find(s=>s.path===r);if(o)return o;let i=n.dataFields?.find(s=>s.path===r);if(i)return i;let a="roles"in n?n.roles?.[r]:void 0;if(a)return a;throw new Error(`Field ${r} not found in schema`)},Et=(e,t,r)=>gt(e,t,r)?.cardinality,le=(e,t)=>{let r=e.dataFields?.map(h=>h.path)||[],n=e.linkFields?.map(h=>h.path)||[],o="roles"in e?listify(e.roles,h=>h):[],i=[...r||[],...n||[],...o||[]],s=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...i];if(!t)return {fields:i,dataFields:r,roleFields:o,linkFields:n};let u=t.$fields?t.$fields.map(h=>{if(typeof h=="string"){if(h.startsWith("$")||h.startsWith("%"))return;if(!i.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(!i.includes(h))throw new Error(`[Schema] Field ${h} not found in the schema`);return h}}).filter(h=>h!==void 0),$=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||[],...n||[]].includes(h)):[],d=[...u,...$].filter(h=>!h?.startsWith("%")).filter(h=>!s.includes(h)).filter(h=>h),l=t.$filter?ae(t.$filter,(h,f)=>$.includes(h)):{},p=t.$filter?ae(t.$filter,(h,f)=>c.includes(h)):{};return {fields:i,dataFields:r,roleFields:o,linkFields:n,usedFields:u,usedLinkFields:n.filter(h=>u.includes(h)),usedRoleFields:o.filter(h=>u.includes(h)),usedDataFields:r.filter(h=>u.includes(h)),unidentifiedFields:d,...$.length?{localFilters:l}:{},...c.length?{nestedFilters:p}:{}}};var mr=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},yr=(e,t,r)=>{let o=(r.nodePath||"").split("."),i=isArray(t)?o.slice(0,-2).join("."):o.slice(0,-1).join(".");return t?getNodeByPath(e,i):{}},we=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var Ge=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),Ee=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(([n,o])=>{r[n]=isDraft(o)?current(o):o;}),r}else return e},ue=(e,t)=>{if(e===void 0)throw t?new Error(t):new Error("Value is undefined");return e},M=(e,t)=>{let r="";for(let n=0;n<t;n++)r+=" ";return `${r}${e}`},De=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",e??21)();var Pe=(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 Er=(e,t,r)=>{let n=isArray(e[t])?e[t]:[e[t]];if(!n.every(o=>typeof o=="object"))if(n.every(o=>typeof o=="string")){let o=Pe(t,r),[i]=o,a=e.$op==="create"?"link":"replace",s=i.thing,u=i.thingType,$={$op:a,$thing:s,$thingType:u},c=n.filter(l=>l.startsWith("_:")),d=n.filter(l=>!l.startsWith("_:"));c.length&&!d.length?e[t]=c.map(l=>({...$,$tempId:l,$bzId:l})):c.length&&d.length?e[t]=[...c.map(l=>({...$,$tempId:l,$bzId:l})),{...$,$id:d,$bzId:`S_${nanoid()}`}]:e[t]={...$,$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(n)} Parent: ${JSON.stringify(e,null,2)})`)};var Ie=(e,t,r)=>{let n=q(r,t),{usedDataFields:o}=le(n,t);if(t.$op){if(t.$op==="create"&&t.$id)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(["unlink","delete","update"].includes(t.$op)&&e.$op==="create")throw new Error(`[Wrong format] Cannot ${t.$op} under a create`);if(t.$op==="delete"&&o.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&o.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Ze=(e,t,r)=>{let n=q(r,t),{usedFields:o}=le(n,t);return t.$op?(Ie(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(Ie(e,{...t,$op:"update"},r),"update"):(Ie(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(Ie(e,{...t,$op:"create"},r),"create"):(Ie(e,{...t,$op:"create"},r),"link"):(Ie(e,{...t,$op:"create"},r),"create")};var Fr=(e,t)=>{let n=(isArray(e.$root)?e.$root:[e.$root]).map(o=>{let i=Ze(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:fr(o,t)},...o.$op?{}:{$op:i},...o.$bzId?{}:{$bzId:`R_${De()}`}},...o}});e.$root=isArray(e.$root)?n:n[0];};var Xe=(e,t)=>{let r=t[He];return isSet(r)?r.has("clean")?(Reflect.set(t,He,r.add("clean")),!0):!1:(Reflect.set(t,He,new Set(["clean"])),!0)};var br=(e,t,r)=>{if(Xe("split_ids",e)){let n=(isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(isObject(o)&&"$id"in o&&isArray(o.$id)){let i=o;if(q(r,i),!i.$bzId)throw new Error("[Internal Error] No bzId found");return i.$id.map((a,s)=>({...Ee(i),$id:a,$bzId:`${i.$bzId}_${s}`,...we(i)}))}return o});(n.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=n);}};var Tr=(e,t,r,n)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(i=>{let a=Pe(t,r),[s]=a,u=Ze(e,{...i,$thing:s.thing,$thingType:s.thingType},n),c=i.$bzId?i.$bzId:i.$tempId?i.$tempId:i.$id&&!isArray(i.$id)?`SN_ONE_${s.thing}_${i.$id}`:i.$id&&isArray(i.$id)?`SN_MANY_${s.thing}_${De()}`:`SM_${De()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...i,[Te]:r,$thing:s.thing,$thingType:s.thingType,$op:u,$bzId:c}});e[t]=isArray(e[t])?o:o[0];};var Ei=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Bi=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Mr=e=>{let r=e.toString().replace(Ei,"").trim().split("=>")[0].split("{")[0].replace(Bi,"").trim(),n=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return n?(n.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(i=>i.includes("{")&&i.includes("}")?(i.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(s=>s.split(":")[0].trim().replace(/['"[\]]/g,"")):i.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,a=Mr(o).filter(s=>!(s in e));if(a.length)throw new Error(`Virtual field: Missing arguments ${a.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 wr=(e,t,r)=>{let n=e[t];if(n)return (isArray(n)?n:[n]).forEach(o=>{let i=q(r,o),{unidentifiedFields:a}=le(i,o),{computedFields:s,virtualFields:u}=i,$=listify(o,(l,p)=>p!==void 0?l:void 0),c=$.filter(l=>u?.includes(l));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(s.filter(l=>!$.includes(l)).forEach(l=>{let p=i.dataFields?.find(E=>E.path===l),f=i.linkFields?.find(E=>E.path===l)?.oppositeLinkFieldsPlayedBy[0],y="roles"in i?pr(i.roles,(E,B)=>E===l):void 0,m=p||f||y;if(!m)throw new Error(`no field Def for ${l}`);if(o.$op==="create"&&!o[l]){let E=qe({currentThing:o,fieldSchema:m,mandatoryDependencies:!0});o[l]=E;}}),a.length>0)throw new Error(`Unknown fields: [${a.join(",")}] in ${JSON.stringify(o)}`)}),e};var tt=(e,t)=>{let r=q(t,e).hooks;if(r?.pre){let n=`on${mr(e.$op)}`;return r.pre.filter(a=>!a.triggers||a.triggers[n]?.()).flatMap(a=>a.actions)}return []};var Lr=(e,t,r,n)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(i=>{if("$thing"in i){if(i.$fields)return i;let{requiredFields:a,enumFields:s,fnValidatedFields:u,dataFields:$}=q(r,i);if("$op"in i&&i.$op==="create"&&a.forEach(c=>{if(!(c in i))throw new Error(`[Validations] Required field "${c}" is missing.`)}),("$op"in i&&i.$op==="update"||i.$op==="create")&&s.forEach(c=>{if(c in i){let d=$?.find(l=>l.path===c)?.validations?.enum;if(!d)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(isArray(i[c]))i[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(i[c]))throw new Error(`[Validations] Option "${i[c]}" is not a valid option for field "${c}".`)}}),("$op"in i&&i.$op==="update"||i.$op==="create")&&u.forEach(c=>{if(c in i)try{let d=$?.find(l=>l.path===c)?.validations?.fn;if(!d)throw new Error("Missing validation function.");if(!d(i[c]))throw new Error("Failed validation function.")}catch(d){throw new Error(`[Validations:attribute:${c}] ${d.message}`)}}),isObject(i)&&"$thing"in i){let c=i.$thing,d=i,l=clone(Ee(e)),p=clone(Ee(d)),h=n.mutation?.context||{},f=clone(Ee(i[ke]||{}));tt(d,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let E=m.fn(p,l,h,f);if(E===!1)throw new Error(`${m.message}.`);if(E!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(E){throw new Error(`[Validations:thing:${c}] ${E.message}`)}}});}}});};var Rr=(e,t,r,n)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(i=>{if(Ge(i)){if(i.$fields||i[ft])return i;let a=tt(i,r).filter(d=>d.type==="transform"),s=clone(Ee(e)),u=clone(Ee(i)),$=n.mutation?.context||{},c=clone(Ee(i[ke]||i.$dbNode));return a.forEach(d=>{let l=d.fn(u,s,$,c||{});Object.keys(l).length!==0&&(i={...u,...l,...we(i),[ft]:!0});}),i}});e[t]=isArray(e[t])?o:o[0];};var Dr=(e,t,r)=>{let n=Pe(t,r),[o]=n;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Te]:r};};var xe=e=>{if(Array.isArray(e)){for(let t of e)if(xe(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"&&xe(e[t]))return !0}return !1};var Di=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(Xe("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")},Ii=(e,t)=>{},Mt=(e,t,r)=>{let n={$rootWrap:{$root:e}},o=xe(Array.isArray(e)?e:[e]),i=produce(n,a=>traverse(a,({value:s,parent:u,key:$,meta:c})=>{if(!(!u||!$)&&isObject(s)){let d=c.nodePath?.split(".")||[];if(!("$root"in s)){if(!("$thing"in s||"$entity"in s||"$relation"in s)){let h=["$fields","$dbNode","$filter"],f=d[d.length-1],y=d[d.length-2];if($==="$root")throw new Error("Root things must specify $entity or $relation");if(!h.includes(f)&&!h.includes(y))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(s)?current(s):s)}`)}}let l=s,p=d.includes("$filter");Object.keys(l).forEach(h=>{if(Di(l,h),h!=="$root"&&p||h!=="$root"&&(h.startsWith("$")||h.startsWith("%")))return;let f=h!=="$root"?gt(t,l,h):{fieldType:"rootField"};if(!f)throw new Error(`[Internal] Field ${h} not found in schema`);if("contentType"in f)return Ii();if(["rootField","linkField","roleField"].includes(f.fieldType)){if(["linkField","roleField"].includes(f.fieldType)&&(l[h]===null?Dr(l,h,f):Er(l,h,f)),f.fieldType==="rootField"){if(!("$root"in l))throw new Error(`[Internal] Field ${h} is a rootField but the object is not a root`);Fr(l,t);}let y=isArray(l[h])?l[h]:[l[h]],m=d.slice(1).join(".");y.forEach(B=>{if(B){if(f?.cardinality==="ONE"&&!B.$op&&!B.$id&&!B.$filter&&!B.$tempId&&l.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${m}.${h}`);if(B.$tempId&&!(B.$op===void 0||B.$op==="link"||B.$op==="create"||B.$op==="update"))throw new Error(`Invalid op ${B.$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(f.fieldType)&&Tr(l,h,f,t),br(l,h,t),["rootField","linkField","roleField"].includes(f.fieldType)&&wr(l,h,t),(isArray(l[h])?l[h]:[l[h]]).forEach(B=>{let g=q(t,B),{unidentifiedFields:L,usedLinkFields:Q,usedFields:I,fields:A}=le(g,B);if(I.forEach(j=>{if(!A.includes(j))throw new Error(`[Schema] Field ${j} not found in the schema`)}),L.length>0)throw new Error(`Unknown fields: [${L.join(",")}] in ${JSON.stringify(s)}`);if(Q.length>1){let j=g.linkFields?.filter(K=>Q.includes(K.path));j?.some((K,me)=>j.some((v,C)=>{if(me!==C&&K.target!==v.target&&K.relation===v.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),o||(Rr(l,h,t,r),Lr(l,h,t,r));}});}}));return isArray(i.$rootWrap.$root),i.$rootWrap.$root};var Ir=e=>{let t=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(i=>i.startsWith("$")).forEach(i=>delete r[i]),Object.keys(r).filter(i=>typeof i=="symbol").forEach(i=>delete r[i])),r);return produce(e,r=>traverse(r,t))};var kr=async(e,t)=>{let r=c=>{let d=[],l=[],p=m=>{if(m.$id)return m.$id;let E=q(t,m),{idFields:B}=E;if(!B)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[g]=B;if(!g)throw new Error(`no idField: ${JSON.stringify(m)}`);let L=E.dataFields?.find(A=>A.path===g),Q=qe({currentThing:m,fieldSchema:L,mandatoryDependencies:!0}),I=m[g]||m.$id||Q;if(!I)throw new Error(`no idValue: ${JSON.stringify(m)}`);return I},h=m=>{if(m.$op==="create"){let E=p(m);if(d.find(B=>B.$id===E&&B.$op==="create"))throw new Error(`Duplicate id ${E} for node ${JSON.stringify(m)}`);if(l.find(B=>B.$bzId===m.$bzId))throw new Error(`Duplicate $bzId ${m.$bzId} for node ${JSON.stringify(m)}`);d.push({...m,$id:E});return}m.$tempId&&m.$op==="match"||d.push(m);},f=m=>{if(m.$op==="create"){let E=p(m);if(d.find(B=>B.$id===E),l.find(B=>B.$bzId===m.$bzId))throw new Error(`Duplicate %bzId ${m.$bzIdd} for edge ${JSON.stringify(m)}`);l.push({...m,$id:E});return}l.push(m);};return traverse(c,({value:m,parent:E,meta:B})=>{if(!isObject(m))return;let g=m;if(g.$thing){if(!g.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(g)}`);if(!g.$bzId)throw new Error("[internal error] BzId not found");let L=q(t,g),{dataFields:Q,roleFields:I,linkFields:A,usedFields:j}=le(L,g),K=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let C=j.filter(F=>Q?.includes(F)),w=j.filter(F=>I?.includes(F)),b=j.filter(F=>A?.includes(F));if(C.length>0)return "update";if(w.length>0||b.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},me={...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,Q||[""])),$op:K(),$bzId:g.$bzId};h(me);let v=g[Te];if(v?.fieldType==="linkField"){if((g.$op==="link"||g.$op==="unlink")&&(g.$id||g.$filter)){if(g.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");d.push({...g,$op:"match"});}let C=v.relation===g.$thing,w=C?g.$bzId:`LT_${v4()}`,F=yr(c,E,B).$bzId;if(!F)throw new Error("No parent id found");let S=()=>g.$op==="delete"?C?"match":"delete":g.$op==="unlink"?C?"unlink":"delete":g.$op==="link"||g.$op==="create"?C?"link":"create":g.$op==="replace"?"replace":"match",T=q(t,{$thing:v.relation,$thingType:"relation"});if(!Object.keys(T.roles).includes(v.plays))throw new Error(`[Wrong format] Field ${v.plays} is not a role of relation ${v.relation}`);let k={$bzId:w,$thing:v.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:S(),...C?{}:{[v.path]:g.$bzId},[v.plays]:F,[Te]:v,[Re]:"linkField"};f(k),(g.$op==="unlink"||S()==="unlink")&&C&&f({$thing:v.relation,$thingType:"relation",$bzId:w,$op:"match",[v.plays]:F,[Te]:v,[Re]:"linkField"});}if(g.$thingType==="relation"){let C=ae(g,(F,S)=>I.includes(F)),w=mapEntries(C,(F,S)=>isArray(S)?[F,S]:isObject(S)?[F,S.$bzId]:[F,S]),b=ae(m,(F,S)=>F.startsWith("$")||F.startsWith("Symbol"));if(Object.keys(C).filter(F=>!F.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let F=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},S=q(t,g).roles,T=mapEntries(w,(k,R)=>{let z=S[k]?.cardinality;if(!z)throw new Error(`Role ${k} not found in schema`);if(Array.isArray(R)){if(z==="ONE"){if(R.length>1)throw new Error(`[Error] Role ${k} is not a MANY relation`);return [k,R[0].$bzId||R[0]]}return [k,R.map(J=>J.$bzId||J)]}return [k,R.$bzId||R]}),D={...b,$thing:g.$thing,$thingType:"relation",$op:F(),...T,$bzId:g.$bzId,[Re]:"roleField"};f(D);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(C).length>0){let F=0;Object.entries(C).forEach(([S,T])=>{let D=isArray(T)?T:[T],k=R=>R==="create"||R==="replace"?"link":R;D.forEach(R=>{if(!R)return;let z=k(R.$op);if(z==="replace")throw new Error("Not supported yet: replace on roleFields");if(z==="unlink"&&F>0)throw F+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let J={...b,$thing:g.$thing,$thingType:"relation",$op:z==="delete"?"unlink":z,[S]:R.$bzId,$bzId:g.$bzId,[Re]:"roleField"};f(J);});});}}}}}),[d,l]},[n,o]=r(e),i=n.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}`)},[]),a=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(f=>{if(typeof f=="symbol"||f.startsWith("$"))return;let y=l[f],m=d[f];Array.isArray(y)&&Array.isArray(m)?p[f]=Array.from(new Set([...y,...m])):!Array.isArray(y)&&Array.isArray(m)?y!==void 0?p[f]=Array.from(new Set([y,...m])):p[f]=m:Array.isArray(y)&&!Array.isArray(m)?m!==void 0&&(p[f]=Array.from(new Set([...y,m]))):y!==null&&m!==null&&y!==void 0&&m!==void 0?p[f]=Array.from(new Set([y,m])):y==null&&(p[f]=m);}),[...c.filter(f=>!((f.$id&&f.$id===d.$id||f.$bzId&&f.$bzId===d.$bzId)&&f.$thing===d.$thing&&f.$op===d.$op)),p]}return [...c,d]},[]);i.forEach(c=>{if((c.$thingType==="relation"||"relation"in c)&&a.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(Ir(c))}`)}});let s=[...i,...a],u=new Set(s.filter(c=>c.$tempId).map(c=>c.$tempId)),$=Array.from(u).filter(c=>!s.some(d=>d.$tempId===c&&d.$op==="create"));if($.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${$.join(", ")}`);return {mergedThings:i,mergedEdges:a}};var Ne={};function ee(e){return {enumerable:!0,value:e}}function Pr(e){return {enumerable:!0,writable:!0,value:e}}var xi=()=>!0,qr=()=>({}),Nr=e=>e,Ni=(e,t,r,n)=>e.apply(r,n)&&t.apply(r,n),ji=(e,t,r,[n,o])=>t.call(r,e.call(r,n,o),o),Se=(e,t)=>Object.freeze(Object.create(e,t));function xr(e,t,r){return e.reduce((n,o)=>function(...i){return r(n,o,this,i)},t)}function jr(e){return Se(this,{fn:ee(e)})}var _r={},x=jr.bind(_r);var zr={},wt=jr.bind(zr);function rt(e,t){return t.filter(r=>e.isPrototypeOf(r))}function Ur(e,t,...r){let n=xr(rt(zr,r).map(i=>i.fn),xi,Ni),o=xr(rt(_r,r).map(i=>i.fn),Nr,ji);return Se(this,{from:ee(e),to:ee(t),guards:ee(n),reducers:ee(o)})}var Wr={},Vr={},N=Ur.bind(Wr);Ur.bind(Vr,null);function _i(e,t,r){return Lt(t,e,r,this.immediates)||e}function Hr(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 zi={enter:Nr};function ie(...e){let t=rt(Wr,e),r=rt(Vr,e),n={final:ee(e.length===0),transitions:ee(Hr(t))};return r.length&&(n.immediates=ee(r),n.enter=ee(_i)),Se(zi,n)}var Ui={enter(e,t,r){let n=this.fn.call(t,t.context,r);return St.isPrototypeOf(n)?Se(Kr,{machine:ee(n),transitions:ee(this.transitions)}).enter(e,t,r):(n.then(o=>t.send({type:"done",data:o})).catch(o=>t.send({type:"error",error:o})),e)}},Kr={enter(e,t,r){if(t.child=fe(this.machine,n=>{t.onChange(n),t.child==n&&n.machine.state.value.final&&(delete t.child,t.send({type:"done",data:n.context}));},t.context,r),t.child.machine.state.value.final){let n=t.child.context;return delete t.child,Lt(t,e,{type:"done",data:n},this.transitions.get("done"))}return e}};function W(e,...t){let r=ee(Hr(t));return St.isPrototypeOf(e)?Se(Kr,{machine:ee(e),transitions:r}):Se(Ui,{fn:ee(e),transitions:r})}var St={get state(){return {name:this.current,value:this.states[this.current]}}};function ye(e,t,r=qr){return typeof e!="string"&&(r=t||qr,t=e,e=Object.keys(t)[0]),Ne._create&&Ne._create(e,t),Se(St,{context:ee(r),current:ee(e),states:ee(t)})}function Lt(e,t,r,n){let{context:o}=e;for(let{to:i,guards:a,reducers:s}of n)if(a(o,r)){e.context=s.call(e,o,r);let u=t.original||t,$=Se(u,{current:ee(i),original:{value:u}});Ne._onEnter&&Ne._onEnter(t,i,e.context,o,r);let c=$.state.value;return e.machine=$,e.onChange(e),c.enter($,e,r)}}function Wi(e,t){let r=t.type||t,{machine:n}=e,{value:o,name:i}=n.state;return o.transitions.has(r)?Lt(e,n,t,o.transitions.get(r))||n:(Ne._send&&Ne._send(r,i),n)}var Vi={send(e){Wi(this,e);}};function fe(e,t,r,n){let o=Object.create(Vi,{machine:Pr(e),context:Pr(e.context(r,n)),onChange:ee(t)});return o.send=o.send.bind(o),o.machine=o.machine.state.value.enter(o.machine,o,n),o}var Gr=(e,t)=>{if(!t)return;let r=Ki(t);return Ji(r,e.query)},Ki=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),Ji=(e,t)=>produce(e,r=>traverse(r,({value:n})=>{if(isObject(n)){let o=n;Object.keys(o).forEach(i=>{(o[i]===void 0||o[i]===null||isArray(o[i])&&o[i].length===0)&&(t?.returnNulls?o[i]=null:delete o[i]),o[i]===void 0&&delete o[i];}),Object.getOwnPropertySymbols(o).forEach(i=>{delete o[i];}),t?.noMetadata===!0&&Object.keys(o).forEach(i=>{i.startsWith("$")&&delete o[i];});}}));var Xr=(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,i=>{let{value:a,meta:s}=i,u=a;if(isObject(u)){if(u.$id){if(s.nodePath?.includes(".$filter"))return;let $=u.$entity||u.$relation?u:{[`$${u.$thingType}`]:u.$thing},c=q(t,$);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 $=q(t,u);if(!$?.name)throw new Error(`Schema not found for ${u.$thing}`);u.$path=$.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 $=u.$entity||u.$relation?u:{[`$${u.$thingType}`]:u.$thing};u[re]=s.nodePath;let c=q(t,$);if(u.$filter&&(u.$filterByUnique=It(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=Zr(p,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);u.$fields=l;}else {let l=Dt(c)?.flatMap(p=>{let h=Zr(p,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);u.$fields=l;}u.$excludedFields&&(u.$fields=u.$fields.filter(d=>nt(c,d)?!0:!u.$excludedFields.includes(d.$path)));}}}))},Dt=e=>{let t=e.dataFields?.map(i=>i.path)||[],r=e.linkFields?.map(i=>i.path)||[],n=Object.keys(e.roles||{})||[];return [...t,...r,...n]},It=(e,t)=>Object.keys(e||{}).some(n=>{if(!Array.isArray(e[n])){let o=t.idFields?.includes(n),i=t.dataFields?.some(s=>(s.dbPath===n||s.path===n)&&s?.validations?.unique),a=n==="$id"&&!Array.isArray(e[n]);return o||i||a}return !1}),nt=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),Gi=e=>{let{field:t,fieldStr:r,$justId:n,dbPath:o,isVirtual:i,fieldSchema:a}=e;return {$path:r,$dbPath:o,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:n,$id:t.$id,$isVirtual:i,[ne]:a}},Zi=e=>{let{field:t,fieldStr:r,linkField:n,$justId:o,dbPath:i,schema:a,fieldSchema:s}=e,{target:u,oppositeLinkFieldsPlayedBy:$}=n;return $.map(c=>{let d=u==="role"?c.thingType:"relation",l=u==="role"?c.thing:n.relation,p={[`$${d}`]:l},h=q(a,p),f=t?.$fields?.filter(E=>nt(h,E)).length===0,y=[];if(typeof t!="string")if(t.$fields)if(f){let E=h.idFields||[];y=[...t.$fields,...E];}else y=t.$fields;else y=Dt(h);else y=["id"];t.$excludedFields&&(y=y.filter(E=>nt(h,E)?!0:!t.$excludedFields.includes(E.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...je(t.$filter,l,a)}:void 0;return {$thingType:d,$plays:n.plays,$playedBy:c,$path:c.path,$dbPath:i,$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:f,$filterByUnique:It(t.$filter,h),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ne]:s}})},Xi=e=>{let{field:t,fieldStr:r,roleField:n,$justId:o,dbPath:i,schema:a,fieldSchema:s}=e;return n.playedBy.map(u=>{let{thing:$,thingType:c,relation:d}=u,l={[`$${c}`]:$},p=q(a,l),h=t?.$fields?.filter(m=>p?.idFields?.includes(m)||p?.idFields?.includes(m.$path)).length===0,f=[];if(typeof t!="string")if(t.$fields)if(h){let m=p.idFields||[];f=[...t.$fields,...m];}else f=t.$fields;else f=Dt(p);else f=["id"];t.$excludedFields&&(f=f.filter(m=>nt(p,m)?!0:!t.$excludedFields.includes(m.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...je(t.$filter,$,a)}:void 0;return {$thingType:c,$path:r,$dbPath:i,$as:t.$as||r,$var:r,$thing:$,$fields:f,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:d,$justId:o,$id:t.$id,$filter:y,$idNotIncluded:h,$filterByUnique:It(t.$filter,p),$playedBy:u,$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ne]:s}})},Zr=(e,t,r)=>{let n=typeof e=="string"?e:e.$path,o=typeof e=="string",i=t.dataFields?.find(u=>u.path===n),a=t.linkFields?.find(u=>u.path===n),s=t.roles?.[n];if(i){let u=!!i.isVirtual&&!!i.default;return Gi({field:e,fieldStr:n,$justId:o,dbPath:i.dbPath,isVirtual:u,fieldSchema:i})}else {if(a)return Zi({field:e,fieldStr:n,linkField:a,$justId:o,dbPath:a.path,schema:r,fieldSchema:a});if(s)return Xi({field:e,fieldStr:n,roleField:s,$justId:o,dbPath:n,schema:r,fieldSchema:s})}return null},je=(e,t,r)=>{if(e==null)return e;let n=isArray(e),i=(n?e:[e]).map(a=>Object.keys(a).reduce(($,c)=>{let d=a[c],l=isArray(d)?d:[d];if(c.startsWith("$"))["$id","$thing"].includes(c)?$[c]=d:$[c]=je(d,t,r);else {let p=t in r.entities?r.entities[t]:r.relations[t],[h,f]=ve(p,c);if(h==="dataField")$[c]=d;else if(h==="linkField"||h==="roleField"){let y=f,[m]=y.$things;return l.every(E=>typeof E=="string")?$[c]={$id:l,$thing:m}:l.every(E=>isObject(E))&&($[c]=isArray(d)?{$or:je(d,m,r)}:je(d,m,r)),$}else throw new Error(`Field ${c} not found in schema of ${t}`)}return $},{}));return n?i.length===1?i[0]:{$or:i}:i[0]};var en=async(e,t,r)=>r?(i=>produce(i,a=>traverse(a,({value:s})=>{if(isObject(s)){let u=s;if(!u.$thing)return;if(u.$thing){let $=q(e,u),{virtualFields:c}=$,d=u[re];if(!d)throw new Error("[Internal] QueryPath is missing");let l=getNodeByPath(t,d),p=l.$fields.map(f=>f.$path),h=l.$excludedFields;c.forEach(f=>{if(h?.includes(f)||p.length>0&&!p.includes(f))return;let y=$.dataFields?.find(m=>m.path===f);if(y?.default){let m=qe({currentThing:u,fieldSchema:y,mandatoryDependencies:!0});u[f]=m;}else if(u[f]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${f}`)}),h&&h.forEach(f=>{if(typeof f!="string")throw new Error("[Internal] ExcludedField is not a string");delete u[f];});}}})))(r):void 0;var he=(e,t,r)=>{if(e==null)return e;let n=isArray(e),i=(n?e:[e]).map(a=>{let u=Object.keys(a).reduce(($,c)=>{let d=a[c];if(c.startsWith("$"))return c==="$not"?{...$,$not:void 0,"$!":he(d,t,r)}:c==="$or"?{...$,$or:void 0,$OR:he(d,t,r)}:c==="$and"?{...$,$and:void 0,$AND:he(d,t,r)}:c==="$eq"?{...$,$nor:void 0,"$=":he(d,t,r)}:c==="$id"?{...$,$id:void 0,"record::id(id)":{$IN:isArray(d)?d:[d]}}:c==="$thing"?$:{...$,[c]:he(d,t,r)};let l=t in r.entities?r.entities[t]:r.relations[t],[p,h]=ve(l,c);if(p==="dataField"){if(l.idFields.length>1)throw new Error("Multiple id fields not supported");return c===l.idFields[0]?{...$,"record::id(id)":{$IN:isArray(d)?d:[d]}}:{...$,[c]:d}}if(p==="linkField"||p==="roleField"){let f=h;if(f.$things.length!==1)throw new Error(`Not supported yet: Role ${c} in ${d.name} is played by multiple things: ${f.$things.join(", ")}`);let[y]=f.$things,m=f[Me].queryPath;return {...$,[m]:he(d,y,r)}}throw new Error(`Field ${c} not found in schema, Defined in $filter`)},{});return shake(u)});return n?i:i[0]},$e=e=>{if(e==null)return "";let t=Object.entries(e),r=[];return t.forEach(([n,o])=>{if(["$OR","$AND","$!"].includes(n)){let i=n.replace("$",""),a=Array.isArray(o)?o.map(s=>$e(s)):[$e(o)];i==="!"?r.push(`!(${a.join(` ${i} `)})`):r.push(`(${a.join(` ${i} `)})`);return}if(isObject(o))if(n.includes("<-")||n.includes("->")){let i=$e(o);r.push(`${n}[WHERE ${i}]`);}else if(n.startsWith("$parent")){let i=$e(o),a=n.replace("$parent.","");r.push(`${a}[WHERE ${i}]`);}else {if(n.startsWith("$"))throw new Error(`Invalid key ${n}`);if(Object.keys.length===1&&Object.keys(o)[0].startsWith("$")){let[i]=Object.keys(o),a=o[i];if(isArray(a))r.push(`${n} ${i.replace("$","")} [${a.map(s=>`'${s}'`).join(", ")}]`);else if(isObject(a)){let s=$e(a);r.push(`${n} ${i.replace("$","")} ${s}`);}else r.push(`${n} ${i.replace("$","")} '${a}'`);}else throw new Error(`Invalid key ${n}`)}else if(Array.isArray(o)){let i=n.startsWith("$")?n.replace("$",""):"IN";r.push(`${n} ${i} [${o.map(a=>`'${a}'`).join(", ")}]`);}else {let i=n.startsWith("$")?n.replace("$",""):"=";r.push(`${n} ${i} '${o}'`);}}),r.join(" AND ")},_e=e=>`ORDER BY ${e.map(r=>{if(typeof r=="string")return r;let{field:n,desc:o}=r;return `${n}${o?" DESC":" ASC"}`}).join(", ")}`;var rn=e=>{let{queries:t,schema:r}=e;return t.map(n=>so({query:n,schema:r}))},so=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:o,$filter:i,$offset:a,$limit:s,$sort:u}=t;if(o.length===0)return null;let $=[];$.push("SELECT");let c=At({parentQuery:t,queries:o,level:1,schema:r});c&&$.push(c);let d=r.entities[n]||r.relations[n];if(!d)throw new Error(`Schema for ${n} not found`);let p=(d.subTypes?[n,...d.subTypes]:[n]).map(h=>X(h));if(t.$id)if(typeof t.$id=="string")$.push(`FROM ${p.map(h=>`${h}:\u27E8${t.$id}\u27E9`).join(",")}`);else if(isArray(t.$id)){let h=t.$id,f=p.flatMap(y=>h?.map(m=>`${y}:\u27E8${m}\u27E9`));$.push(`FROM ${f.join(",")}`);}else throw new Error("Invalid $id");else $.push(`FROM ${p.join(",")}`);if(i){let h=he(i,n,r),f=$e(h);$.push(`WHERE ${f}`);}return u&&$.push(_e(u)),typeof s=="number"&&$.push(`LIMIT ${s}`),typeof a=="number"&&$.push(`START ${a}`),$.join(`
104
+ `)},At=e=>{let{queries:t,schema:r,level:n,parentQuery:o}=e,i=[],a=o[re];return i.push(M(`"${a}" as \`$$queryPath\``,n)),i.push(M("record::id(id) as `$id`",n)),i.push(M("record::tb(id) as `$thing`",n)),t.forEach(s=>{let u=ao({query:s,level:n,schema:r});u&&i.push(u);}),i.length===0?null:i.join(`,
105
+ `)},ao=e=>{let{query:t,schema:r,level:n}=e;return t.$fieldType==="data"?lo({query:t,level:n}):t.$fieldType==="link"?co({query:t,level:n,schema:r}):t.$fieldType==="role"?uo({query:t,level:n,schema:r}):null},lo=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?M(`record::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?M(`\`${t.$path}\``,r):M(`\`${t.$path}\` AS \`${t.$as}\``,r)},co=e=>{let{query:t,schema:r,level:n}=e,{$fields:o,$filter:i,$offset:a,$limit:s,$sort:u}=t;if(o.length===0)return null;let $=[];$.push(M("(",n));let c=n+1;$.push(M("SELECT",c));let d=At({parentQuery:t,queries:o,level:c+1,schema:r});d&&$.push(d);let l=t[ne][Me].queryPath;if($.push(M(`FROM ${l}`,c)),i){let p=he(i,t.$thing,r),h=$e(p);$.push(`WHERE ${h}`);}return u&&$.push(M(_e(u),c)),typeof s=="number"&&$.push(M(`LIMIT ${s}`,c)),typeof a=="number"&&$.push(M(`START ${a}`,c)),$.push(M(`) AS \`${t.$as}\``,n)),$.join(`
106
+ `)},uo=e=>{let{query:t,schema:r,level:n}=e;if(t.$fields.length===0)return null;let o=[];o.push(M("(",n));let i=n+1;o.push(M("SELECT",i));let a=i+1,s=At({parentQuery:t,queries:t.$fields,level:a,schema:r});s&&o.push(s);let u=t[ne][Me].queryPath;if(o.push(M(`FROM ${u}`,i)),t.$filter){let $=he(t.$filter,t.$playedBy.thing,r),c=$e($);o.push(`WHERE ${c}`);}return o.push(M(`) AS \`${t.$as}\``,n)),o.join(`
107
+ `)};var nn=async e=>{let{client:t,queries:r}=e,n=`
41
108
  BEGIN TRANSACTION;
42
109
  ${r.join(";")};
43
110
  COMMIT TRANSACTION;
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=`
111
+ `;return await t.query(n)};var sn=e=>{let{res:t,queries:r}=e;return t.map((o,i)=>an(r[i],o))},an=(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:nr(t.$thing),$thingType:e.$thingType};return e.$fields.forEach(n=>{let o=n.$as,i=t[o];n.$path==="id"&&e.$idNotIncluded||(r[o]=ho(n,i));}),r},ho=(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"&&on(t,r),on(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]):an(e,t)},on=(e,t)=>{let r=isArray(e)?e:[e];if(t==="DATE"){let n=r.map(o=>new Date(o).toISOString());return isArray(e)?n:n[0]}return e};var ln=e=>{let{queries:t,schema:r}=e;return t.map(n=>po({query:n,schema:r}))},po=e=>{let{query:t,schema:r}=e,{$thing:n,$fields:o,$filter:i,$offset:a,$limit:s,$sort:u}=t;if(o.length===0)return null;let $=r.entities[n]||r.relations[n];if(!$)throw new Error(`Schema for ${n} not found`);let c=t[re],d=cn(c),l=dn(o.filter(g=>g.$fieldType==="data")),p=un(o.filter(g=>g.$fieldType==="link"||g.$fieldType==="role"),r),h=[...d,...l,...p].join(`,
112
+ `),f=$o(t,$),y=i?`WHERE ${$e(he(i,n,r))}`:"WHERE id",m=u?_e(u):"",E=typeof s=="number"?`LIMIT ${s}`:"",B=typeof a=="number"?`START ${a}`:"";return `SELECT ${h} ${f} ${y} ${m} ${E} ${B}`},$o=(e,t)=>{let n=(t.subTypes?[e.$thing,...t.subTypes]:[e.$thing]).map(a=>X(a)),o=(a,s)=>`${a}:\`${s}\``,i=a=>n.flatMap(s=>a.map(u=>o(s,u))).join(",");if(!e.$id)return `FROM ${n.join(",")}`;if(typeof e.$id=="string")return `FROM ${i([e.$id])}`;if(Array.isArray(e.$id))return `FROM ${i(e.$id)}`;throw new Error("Invalid $id")},cn=e=>[`"${e}" as \`$$queryPath\``,"record::id(id) as `$id`","record::tb(id) as `$thing`"],dn=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}\``),un=(e,t)=>e.map(r=>{let n=cn(r[re]),o=dn(r.$fields.filter(l=>l.$fieldType==="data")),i=un(r.$fields.filter(l=>l.$fieldType==="link"||l.$fieldType==="role"),t),a=[...n,...o,...i].join(`,
113
+ `),s=`FROM $parent.\`${r[ne].path}\`[*]`,u=r.$filter?`WHERE ${$e(he(r.$filter,r.$thing,t))}`:"WHERE id",$=r.$sort?_e(r.$sort):"",c=typeof r.$limit=="number"?`LIMIT ${r.$limit}`:"",d=typeof r.$offset=="number"?`START ${r.$offset}`:"";return `( SELECT ${a} ${s} ${u} ${$} ${c} ${d} ) AS \`${r.$as}\``}).filter(r=>r);var Ot=N("error","error",x((e,t)=>({...e,error:t.error}))),fo=ye("build",{build:W(async e=>{let{linkMode:t}=e.config.dbConnectors.find(r=>r.provider==="surrealDB").providerConfig;if(t==="edges")return rn({queries:e.bql.queries,schema:e.schema});if(t==="refs")return ln({queries:e.bql.queries,schema:e.schema})},N("done","run",x((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),Ot),run:W(async e=>nn({client:e.client,queries:ue(e.surql.queries)}),N("done","parse",x((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),Ot),parse:W(async e=>sn({res:ue(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),N("done","success",x((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),Ot),success:ie(),error:ie()},e=>e),mo=async e=>new Promise((t,r)=>{fe(fo,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),hn=async(e,t,r,n)=>mo({bql:{queries:e},surql:{},schema:t,config:r,client:n,error:null});var kt="___",$n=async e=>{let{queries:t,schema:r}=e;return t.map(n=>Eo({query:n,schema:r}))},Eo=e=>{let{query:t,schema:r}=e,{$path:n,$thing:o,$filter:i,$fields:a,$sort:s,$offset:u,$limit:$,$id:c}=t;if(!n)throw new Error("Path is not defined");let d=[],l=t[re];if(d.push("match"),d.push(`$${n} isa ${o};`),i||c){let f=Ye(r,t),y={...i,...c?{[f]:c}:{}},m=Nt({$filter:y,$var:n,$thing:o,schema:r,depth:0});d.push(`
114
+ ${m}`);}let p=jt({schema:r,$thing:o,$var:n,$sort:s,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";`),a){let f=a.filter(E=>E.$fieldType==="data");f&&f.length>0&&d.push(...Pt(f,n,0));let y=a.filter(E=>E.$fieldType==="link");y&&y.length>0&&d.push(...xt(y,n,n,0,r));let m=a.filter(E=>E.$fieldType==="role");m&&m.length>0&&d.push(...qt(m,n,n,0,r));}return p&&d.push(p.sort),typeof u=="number"&&d.push(`
115
+ offset ${u};`),typeof $=="number"&&d.push(`
116
+ limit ${$};`),d.join(`
117
+ `)},Pt=(e,t,r)=>{let n=[],o=[],i=[];for(let c=0;c<e.length;c++)e[c].$isVirtual||n.push(e[c].$dbPath),e[c][ne].contentType==="FLEX"&&i.push({path:e[c][ne].dbPath}),o.push(`{${e[c].$dbPath}:${e[c].$as}}`);let a=n.join(", "),u=`$metadata:{as:[${o.join(",")}]}`,$=[M(`$${t} as "${t}.${u}.$dataFields": ${a};`,r)];return i.length>0&&i.forEach(c=>{$.push(M(`"${c.path}.$multiVal": {match $${t} has ${c.path} $${c.path}; fetch $${c.path}: attribute;};`,r));}),$},qt=(e,t,r,n,o)=>{let i=n+1,a=[];for(let s of e){let{$fields:u,$as:$,$justId:c,$idNotIncluded:d,$filterByUnique:l,$thing:p,$sort:h,$offset:f,$limit:y}=s,m=s[re],E=`$metadata:{as:${$},justId:${c?"T":"F"},idNotIncluded:${d},filterByUnique:${l}}`;a.push(M(`"${r}.${E}.${s.$var}": {`,n)),a.push(M("match",i));let B=`${t}${kt}${s.$var}`;if(a.push(M(`$${B} isa ${s.$thing};`,i)),a.push(M(`$${t} (${s.$var}: $${t}${kt}${s.$var}) isa ${s.$intermediary};`,i)),s.$filter||s.$id){let L=Ye(o,s),Q=s.$id?{[L]:s.$id}:{},I={...s.$filter,...Q};a.push(Nt({$filter:I,$var:B,$thing:s.$thing,schema:o,depth:i}));}let g=jt({schema:o,$thing:p,$var:B,$sort:h,depth:i});if(g&&a.push(g.match),u){let L=`M_${v4()}`;a.push(M(`
118
+ ?queryPath${L} = "${m}";`,i)),a.push(M("fetch",i)),a.push(M(`?queryPath${L} as "queryPath";`,i));let Q=u?.filter(j=>j.$fieldType==="data");Q&&Q.length>0&&a.push(...Pt(Q,B,i));let I=u?.filter(j=>j.$fieldType==="link");I&&I.length>0&&a.push(...xt(I,B,`${t}.${s.$var}`,i,o));let A=u?.filter(j=>j.$fieldType==="role");A&&A.length>0&&a.push(...qt(A,B,`${t}.${s.$var}`,i,o));}g&&a.push(g.sort),typeof f=="number"&&a.push(M(`offset ${f};`,i)),typeof y=="number"&&a.push(M(`limit ${y};`,i)),a.push(M("};",n));}return a},xt=(e,t,r,n,o)=>{let i=n+1,a=[];for(let s of e){let{$fields:u,$as:$,$justId:c,$idNotIncluded:d,$filterByUnique:l,$playedBy:p,$thing:h,$sort:f,$offset:y,$limit:m}=s,E=s[re],B=`$metadata:{as:${$},justId:${c?"T":"F"},idNotIncluded:${d},filterByUnique:${l}}`;a.push(M(`"${r}.${B}.${s.$var}": {`,n)),a.push(M("match",i));let g=`${t}${kt}${s.$var}`;if(a.push(M(`$${g} isa ${s.$thing};`,i)),s.$filter||s.$id){let Q=Ye(o,s),I=s.$id?{[Q]:s.$id}:{},A={...s.$filter,...I};a.push(Nt({$filter:A,$var:g,$thing:s.$thing,schema:o,depth:i}));}let L=jt({schema:o,$thing:h,$var:g,$sort:f,depth:i});if(L&&a.push(L.match),s.$target==="role"?a.push(M(`$${t}_intermediary (${s.$plays}: $${t}, ${p.plays}: $${g}) isa ${s.$intermediary};`,i)):a.push(M(`$${g} (${s.$plays}: $${t});`,i)),u){let Q=`M_${v4()}`;a.push(M(`?queryPath${Q} = "${E}";`,i)),a.push(M("fetch",i)),a.push(M(`?queryPath${Q} as "queryPath";`,i));let I=u?.filter(K=>K.$fieldType==="data");I&&I.length>0&&a.push(...Pt(I,g,i));let A=u?.filter(K=>K.$fieldType==="link");A&&A.length>0&&a.push(...xt(A,g,`${t}.${s.$var}`,i,o));let j=u?.filter(K=>K.$fieldType==="role");j&&j.length>0&&a.push(...qt(j,g,`${t}.${s.$var}`,i,o));}L&&a.push(L.sort),typeof y=="number"&&a.push(M(`offset ${y};`,i)),typeof m=="number"&&a.push(M(`limit ${m};`,i)),a.push(M("};",n));}return a},Bo=(e,t)=>{let r={};if(t.dataFields?.forEach(a=>{a.path!==a.dbPath&&(r[a.path]=a.dbPath);}),Object.keys(r).length===0)return e;let{$not:n,...o}=e,i=pn(o,r);return n&&(i.$not=pn(n,r)),i},pn=(e,t)=>{let r={};return Object.entries(e).forEach(([n,o])=>{let i=t[n]||n;r[i]=o;}),r},Nt=e=>{let{$filter:t,$var:r,$thing:n,schema:o,depth:i}=e,a=Bo(t,Y(o,n)),{$not:s,...u}=a,$=Y(o,n),c=[];return Object.entries(s||{}).forEach(([d,l])=>{if(d.startsWith("$"))return;if($.dataFields?.find(f=>f.dbPath===d)){l===null?c.push(M(`$${r} has ${d} $${d}_${v4()};`,i)):Array.isArray(l)?l.forEach(f=>{c.push(M(`not { $${r} has ${d} ${ce(f)}; };`,i));}):c.push(M(`not { $${r} has ${d} ${ce(l)}; };`,i));return}let h=$.linkFields?.find(f=>f.path===d);if(h){let[f]=h.oppositeLinkFieldsPlayedBy,m=Y(o,f.thing).idFields?.[0];if(!m)throw new Error(`"${f.thing}" does not have an id field`);if(h.target==="relation")l===null?c.push(M(`(${h.plays}: $${r}) isa ${h.relation};`,i)):Array.isArray(l)?l.forEach(E=>{c.push(M(`not { (${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ce(E)}; };`,i));}):c.push(M(`not { (${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ce(l)}; };`,i));else {let E=`${f.thing}_${v4()}`;l===null?c.push(M(`$${E} isa ${f.thing}; (${h.plays}: $${r}, ${f.plays}: $${E}) isa ${h.relation};`,i)):Array.isArray(l)?l.forEach(B=>{c.push(M(`not { $${E} isa ${f.thing}, has ${m} ${ce(B)}; (${h.plays}: $${r}, ${f.plays}: $${E}) isa ${h.relation}; };`,i));}):c.push(M(`not { $${E} isa ${f.thing}, has ${m} ${ce(l)}; (${h.plays}: $${r}, ${f.plays}: $${E}) isa ${h.relation}; };`,i));}return}if($.thingType==="relation"){let f=$.roles[d];if(f){let[y]=f.playedBy||[],E=Y(o,y.thing).idFields?.[0];if(!E)throw new Error(`"${y.thing}" does not have an id field`);let B=`${y.thing}_${v4()}`,g=v4(),L=`${r}_${g}`;l===null?(c.push(M(`$${L} isa ${n};`,i)),c.push(M(`$${L} (${y.plays}: ${B});`,i)),c.push(M(`$${r} is $${L};`,i))):Array.isArray(l)?l.forEach(Q=>{c.push(M(`$${L} isa ${n};`,i)),c.push(M(`not { $${B} isa ${y.thing}, has ${E} ${ce(Q)}; $${L} (${y.plays}: $${B}); };`,i)),c.push(M(`$${r} is $${L};`,i));}):(c.push(M(`$${L} isa ${n};`,i)),c.push(M(`not { $${B} isa ${y.thing}, has ${E} ${ce(l)}; $${L} (${y.plays}: $${B}); };`,i)),c.push(M(`$${r} is $${L};`,i)));return}}}),Object.entries(u).forEach(([d,l])=>{if(d.startsWith("$"))return;if($.dataFields?.find(f=>f.dbPath===d)){if(l===null)c.push(M(`not { $${r} has ${d} $${d}_${v4()}; };`,i));else if(Array.isArray(l)){let f=l.map(m=>`$${r} has ${d} ${ce(m)};`),y=st(f);y&&c.push(M(y,i));}else c.push(M(`$${r} has ${d} ${ce(l)};`,i));return}let h=$.linkFields?.find(f=>f.path===d);if(h){let[f]=h.oppositeLinkFieldsPlayedBy,m=Y(o,f.thing).idFields?.[0];if(!m)throw new Error(`"${f.thing}" does not have an id field`);if(h.target==="relation")if(l===null)c.push(M(`not { (${h.plays}: $${r}) isa ${h.relation}; };`,i));else if(Array.isArray(l)){let E=l.map(g=>`(${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ce(g)};`),B=st(E);B&&c.push(M(B,i));}else c.push(M(`(${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ce(l)};`,i));else {let E=`${f.thing}_${v4()}`;if(l===null)c.push(M(`not { $${E} isa ${f.thing}; (${h.plays}: $${r}, ${f.plays}: $${E}) isa ${h.relation}; };`,i));else if(Array.isArray(l)){let B=l.map(L=>`$${E} isa ${f.thing}, has ${m} ${ce(L)}; (${h.plays}: $${r}, ${f.plays}: $${E}) isa ${h.relation};`),g=st(B);g&&c.push(M(g,i));}else c.push(M(`$${E} isa ${f.thing}, has ${m} ${ce(l)}; (${h.plays}: $${r}, ${f.plays}: $${E}) isa ${h.relation};`,i));}return}if($.thingType==="relation"){let f=$.roles[d];if(f){let[y]=f.playedBy||[],E=Y(o,y.thing).idFields?.[0];if(!E)throw new Error(`"${y.thing}" does not have an id field`);let B=`${y.thing}_${v4()}`,g=v4(),L=`${r}_${g}`;if(l===null)c.push(M(`$${L} isa ${n};`,i)),c.push(M(`not { $${L} (${y.plays}: ${B}); };`,i)),c.push(M(`$${r} is $${L};`,i));else if(Array.isArray(l)){let Q=l.map(A=>`$${B} isa ${y.thing}, has ${E} ${ce(A)}; $${L} (${y.plays}: $${B});`),I=st(Q);I&&(c.push(M(`$${L} isa ${n};`,i)),c.push(M(I,i)),c.push(M(`$${r} is $${L};`,i)));}else c.push(M(`$${L} isa ${n};`,i)),c.push(M(`$${B} isa ${y.thing}, has ${E} ${ce(l)}; $${L} (${y.plays}: $${B});`,i)),c.push(M(`$${r} is $${L};`,i));return}}throw new Error(`"${n}" does not have property "${d}"`)}),c.join(`
119
+ `)},st=e=>{if(e.length>1)return `{ ${e.join(" } or { ")} };`;let[t]=e;return t},ce=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}`,Fo=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},jt=e=>{let{$var:t,$thing:r,schema:n,$sort:o,depth:i}=e,a=Y(n,r),s=[],u=[];if(o?.forEach($=>{let c=Fo($),d=a.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()}`;s.push(M("{",i)),s.push(M(`$${t} has ${d.dbPath} $${l}_1;`,i+1)),s.push(M("not {",i+1)),s.push(M(`$${t} has ${d.dbPath} $${l}_2;`,i+2)),s.push(M(`$${l}_2 < $${l}_1;`,i+2)),s.push(M("};",i+1)),s.push(M(`?${l}_ = $${l}_1;`,i+1)),s.push(M("} or {",i)),s.push(M(`not { $${t} has ${d.dbPath} $${l}_1; };`,i+1)),s.push(M(`?${l}_ = "~";`,i+1)),s.push(M("};",i)),s.push(M(`?${l} = ?${l}_;`,i));let p=c.desc?"desc":"asc";u.push(`?${l} ${p}`);}),s.length!==0)return {match:s.join(""),sort:M(`sort ${u.join(", ")};`,i)}};var mn=async e=>{let{enrichedBqlQuery:t,rawBqlRequest:r,schema:n,config:o,rawTqlRes:i}=e;if(t){if(!i)throw new Error("TQL query not executed")}else throw new Error("BQL request not enriched");return i.map((a,s)=>{let u=r[s],$=t[s];return To(a,u,$,n,o)})},To=(e,t,r,n,o)=>e.length===0?null:r.$filterByUnique?fn(e[0],t,n,o):e.map(i=>fn(i,t,n,o)),fn=(e,t,r,n)=>{let{dataFields:o,currentSchema:i,linkFields:a,roleFields:s,schemaValue:u}=_t(e,r),$=zt(o,i,n),c=Wt(a,r,n),d=Ut(s,r,n),l=t?.$fields?.every(h=>!i?.idFields?.includes(typeof h=="string"?h:h.$path));return {...c,...d,...u,...!n.query?.noMetadata&&t.$id?{$id:Array.isArray(t.$id)?$.id:t.$id}:{},...l?Object.fromEntries(Object.entries($).filter(([h])=>!i?.idFields?.includes(h))):$}},_t=(e,t)=>{let r=Object.keys(e),n=r.find(p=>p.endsWith(".$dataFields")),o=r.filter(p=>p.endsWith(".$multiVal"));if(!n)throw new Error("No dataFields");o?.length>0&&o.forEach(p=>{let h=p.replace(/\.\$multiVal$/,""),f=e[p][0][h].attribute;e[n][h]=f;});let i=e[n],a=n.split(".")[n.split(".").length-2];if(i.$metaData=a,i.length===0)throw new Error("No dataFields");let s=i.type,u={$thing:s.label,$thingType:s.root,[re]:e.queryPath.value},$={[`$${u.$thingType}`]:u.$thing},c=q(t,$),d=r.filter(p=>{let h=ue(p.split(".").pop());return !p.endsWith(".$dataFields")&&c.linkFields?.some(f=>f.path===h)}).map(p=>{let h=ue(p.split(".").pop()),f=ue(c.linkFields?.find(y=>y.path===h));return {$linkFields:e[p],$key:h,$metaData:p.split(".")[p.split(".").length-2],$cardinality:f.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=ue(p.split(".").pop());return {$roleFields:e[p],$key:h,$metaData:p.split(".")[p.split(".").length-2],$cardinality:c.roles[h].cardinality}});return {dataFields:i,schemaValue:u,currentSchema:c,linkFields:d,roleFields:l}},zt=(e,t,r)=>{let{$metaData:n}=e,{as:o}=Mo(n),i=Object.entries(e).filter(([a])=>a!=="type"&&!a.startsWith("$")).map(([a,s])=>{let u=t.dataFields?.find(l=>l.path===a||l.dbPath===a),$=a==="id",c=Array.isArray(o)?o.find(l=>l[a])?.[a]:a,d;if(u?.cardinality==="ONE"){if(d=s[0]?s[0].value:r.query?.returnNulls?null:void 0,u.contentType==="DATE"||u.contentType==="FLEX"&&s[0].type.value_type==="datetime"?d=d&&`${d}Z`:u.contentType==="JSON"&&(d=d&&JSON.parse(d)),$)return [[c,d],["$id",d]].filter(([l,p])=>p!==void 0)}else if(u?.cardinality==="MANY"){if(!isArray(s))throw new Error("Typedb fetch has changed its format");if(s.length===0)return r.query?.returnNulls?[[c,null]]:[];u.contentType==="DATE"?d=s.map(l=>`${l.value}Z`):u.contentType==="FLEX"?d=s.map(l=>l.type.value_type==="datetime"?`${l.value}Z`:l.value):u.contentType==="JSON"?d=s.map(l=>l.value&&JSON.parse(l.value)):d=s.map(l=>l.value);}return [[c,d]].filter(([l,p])=>p!==void 0)}).flat();return Object.fromEntries([...i])},Ut=(e,t,r)=>{let n={};return e.forEach(o=>{let{$roleFields:i,$metaData:a,$cardinality:s}=o,{as:u,justId:$,idNotIncluded:c,filterByUnique:d}=yn(a);if(u===null)return;let l=i.map(p=>{let{dataFields:h,currentSchema:f,linkFields:y,roleFields:m,schemaValue:E}=_t(p,t),B=zt(h,f,r);if($==="T")return B.id;{let g=Wt(y,t,r),L=Ut(m,t,r),Q={...B};return c==="true"&&f?.idFields?.forEach(I=>delete Q[I]),{...Q,...g,...L,...E}}});l.length>0?n[u]=s==="MANY"&&d==="false"?l:l[0]:r.query?.returnNulls&&(n[u]=null);}),n},Wt=(e,t,r)=>{let n={};return e.forEach(o=>{let{$linkFields:i,$metaData:a,$cardinality:s}=o,{as:u,justId:$,idNotIncluded:c,filterByUnique:d}=yn(a);if(u===null)return;let l=i.map(p=>{let{dataFields:h,currentSchema:f,linkFields:y,roleFields:m,schemaValue:E}=_t(p,t),B=zt(h,f,r);if($==="T")return B.id;{let g=Wt(y,t,r),L=Ut(m,t,r),Q={...B};return c==="true"&&f.idFields?.forEach(I=>delete Q[I]),{...Q,...g,...L,...E}}});n[u]=l.length>0?s==="MANY"&&d==="false"?l:l[0]:r.query?.returnNulls?null:void 0;}),n},yn=e=>{let t=/as:([a-zA-Z0-9_\-·]+)/,r=/justId:([a-zA-Z0-9_\-·]+)/,n=/idNotIncluded:([a-zA-Z0-9_\-·]+)/,o=/filterByUnique:([a-zA-Z0-9_\-·]+)/,i=e.match(t),a=e.match(r),s=e.match(n),u=e.match(o);return {as:i?i[1]:null,justId:a?a[1]:null,idNotIncluded:s?s[1]:null,filterByUnique:u?u[1]:null}},Mo=e=>{try{let r=(o=>{let i=o.replace("$metadata:","");return i=i.replace(/([a-zA-Z0-9_\-·]+)(?=:)/g,'"$1"'),i=i.replace(/:(\s*)([a-zA-Z0-9_\-·]+)/g,(a,s,u)=>/^{.*}$/.test(u)?`:${u}`:`:${s}"${u}"`),i=i.replace(/\[([^\]]+)\]/g,(a,s)=>`[${s.split(",").map(u=>u.trim().startsWith("{")&&u.trim().endsWith("}")?u.trim():`"${u.trim()}"`).join(",")}]`),i})(e);return JSON.parse(r)}catch(t){return console.error(t),{as:[]}}};var at=async(e,t)=>{let r=t.dbConnectors[0].id,n=e.typeDB?.get(r)?.session,o=e.typeDB?.get(r)?.client;if(!n||!n.isOpen()){if(!o)throw new Error("Client not found");n=await o.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:o,session:n});}return {client:o,session:n}};var gn=async e=>{let{tqlRequest:t,dbHandles:r,config:n}=e,o=new TypeDBOptions;o.infer=!0;let{session:i}=await at(r,n),a=await i.transaction(TransactionType.READ,o),[s,u]=await tryit(parallel)(t.length,t,async $=>await a.query.fetch($).collect());if(s){await a.rollback();let $=s;throw new Error(`Error running TQL query: ${$.errors}`)}return await a.close(),u};var Do=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,Io=(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,Vt=N("error","error",x((e,t)=>({...e,error:t.error}))),Co=ye("build",{build:W(async e=>$n({queries:e.bql.queries,schema:e.schema}),N("done","run",x(Io)),Vt),run:W(async e=>gn({dbHandles:e.handles,tqlRequest:ue(e.tql.queries),config:e.config}),N("done","parse",x(Ao)),Vt),parse:W(async e=>mn({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:ue(e.tql.res)}),N("done","success",x(Do)),Vt),success:ie(),error:ie()},e=>e),Oo=async e=>new Promise((t,r)=>{fe(Co,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),En=async(e,t,r,n,o)=>Oo({bql:{raw:e,queries:t},tql:{},schema:r,config:n,handles:o,error:null});var ko=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Ht=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,lt=N("error","error",x((e,t)=>({...e,error:t.error}))),Po=ye("enrich",{enrich:W(async e=>Xr(e.bql.raw,e.schema),N("done","adapter",x(ko)),lt),adapter:W(async e=>{let t={};e.bql.queries?.forEach((s,u)=>{let $=e.bql.raw[u],c=Y(e.schema,s.$thing),{id:d}=c.defaultDBConnector;if(c.db==="typeDB"){if(!t[d]){let p=e.handles.typeDB?.get(d)?.client;if(!p)throw new Error(`TypeDB client with id "${c.defaultDBConnector.id}" does not exist`);t[d]={db:"typeDB",client:p,rawBql:[],bqlQueries:[],indices:[]};}}else if(c.db==="surrealDB"){if(!t[d]){let p=e.handles.surrealDB?.get(d)?.client;if(!p)throw new Error(`SurrealDB client with id "${c.defaultDBConnector.id}" does not exist`);t[d]={db:"surrealDB",client:p,rawBql:[],bqlQueries:[],indices:[]};}}else throw new Error(`Unsupported DB "${c.db}"`);let l=t[d];l.rawBql.push($),l.bqlQueries.push(s),l.indices.push(u);});let r=Object.values(t),n=r.map(s=>{if(s.db==="typeDB")return En(s.rawBql,s.bqlQueries,e.schema,e.config,e.handles);if(s.db==="surrealDB")return hn(s.bqlQueries,e.schema,e.config,s.client);throw new Error(`Unsupported DB "${JSON.stringify(s,null,2)}"`)}),o=await Promise.all(n),i=r.flatMap((s,u)=>{let $=o[u];return s.indices.map((c,d)=>({index:c,result:$[d]}))});return i.sort((s,u)=>s.index<u.index?-1:s.index>u.index?1:0),i.map(({result:s})=>s)},N("done","postHooks",x(Ht)),lt),postHooks:W(async e=>en(e.schema,ue(e.bql.queries),ue(e.bql.res)),N("done","clean",x(Ht)),lt),clean:W(async e=>Gr(e.config,ue(e.bql.res)),N("done","success",x(Ht)),lt),success:ie(),error:ie()},e=>e),qo=async e=>new Promise((t,r)=>{fe(Po,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),ze=async(e,t,r,n)=>qo({bql:{raw:e},schema:t,config:r,handles:n,error:null});var Kt="___",xo=Symbol.for("grandChildOfCreate"),Bn=async(e,t,r,n)=>{let o=(w,b)=>Object.keys(w).filter(F=>!F.startsWith("$")&&w[F]!==void 0?b?!q(t,w).dataFields?.find(T=>T.path===F):!0:!1);if(!e)throw new Error("[BQLE-M-PQ-1] No blocks found");if(r.mutation?.preQuery===!1)return;let i=[];if(traverse(e,({parent:w,key:b,value:F})=>{w&&b&&!b.includes("$")&&isObject(w)?(Array.isArray(w[b])?w[b]:[w[b]]).forEach(T=>{if(isObject(T)){if(w.$op!=="create")i.includes(T.$op)||i.push(T.$op);else if(T.$op==="delete"||T.$op==="unlink")throw new Error(`Cannot ${T.$op} under a create`)}}):!w&&isObject(F)&&(i.includes(F.$op)||i.push(F.$op));}),!i.includes("delete")&&!i.includes("unlink")&&!i.includes("replace")&&!i.includes("update")&&!i.includes("link"))return;let s=(w=>{let b=(F,S)=>{let T=[],D={},k=["$op","$bzId","$parentKey"],R=["$relation","$entity","$id",...k];for(let z in F)if(!k.includes(z)&&!(R.includes(z)&&!S))if(!z.includes("$")&&(isObject(F[z])||Array.isArray(F[z]))){let J=F[z];if(Array.isArray(J)&&J.length>0)J.forEach(pe=>{let Le={$path:z,...b(pe),...pe.$filter&&{$as:pe.$bzId}};T.find(H=>H.$path===Le.$path&&!H.$filter)||(T=[...T,Le]);});else {let pe={$path:z,...b(J),...!J.$filter&&{$as:J.$bzId}};T=[...T,pe];}}else D[z]=F[z];return {...D,$fields:T}};return w.map(F=>b(F,!0))})(Array.isArray(e)?e:[e]),$=(await ze(s,t,{...r,query:{...r.query,returnNulls:!0}},n)).bql.res,c=(w,b)=>{let F=w.$id||w.id||w.$bzId;if(w.$objectPath){let{$objectPath:S}=w,T=S?.beforePath||"root",D=Array.isArray(S.ids)?`[${S.ids}]`:S.ids;return {beforePath:`${T}.${D}___${S.key}`,ids:F,key:b}}else return {beforePath:"root",ids:F,key:b}},d=(w,b)=>{let F=w?.beforePath||"root";if(typeof F!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let S=b||(Array.isArray(w?.ids)?`[${w?.ids}]`:w?.ids);return `${F}.${S}___${w?.key}`},l=w=>{if(w.includes("[")&&w.includes("]")){let[b,F,S]=w.split(/[[\]]/);return F.split(",").map(D=>`${b}${D}${S}`)}else return [w]},p={};(w=>produce(w,b=>traverse(b,({key:F,parent:S})=>{if(S&&F&&S.$id&&!F.includes("$")){let T=c(S,F),D=d(T);if(Array.isArray(S[F])){let k=[];S[F].forEach(R=>{isObject(R)?(R.$objectPath=T,k.push(R.$id.toString())):R&&k.push(R.toString());}),p[D]={$objectPath:T,$ids:k};}else {let k=S[F];isObject(k)?(p[D]={$objectPath:T,$ids:[k.$id.toString()]},k.$objectPath=T):k?p[D]={$objectPath:T,$ids:[k.toString()]}:k===null&&(p[D]=null);}}})))($||{});let f=w=>produce(w,b=>traverse(b,({key:F,value:S,parent:T})=>{T&&F&&!F.includes("$")&&(Array.isArray(S)||isObject(S))&&!Array.isArray(T)&&(Array.isArray(T[F])?T[F].forEach(D=>{typeof D!="string"&&(D.$objectPath=c(T,F),D.$parentIsCreate=T.$op==="create",D[xo]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")]);}):isObject(T[F])&&(T[F].$parentIsCreate=T.$op==="create",T[F][Symbol.for("grandChildOfCreate")]=T.$parentIsCreate||T[Symbol.for("grandChildOfCreate")],T[F].$objectPath=c(T,F)));})),y=f(e),m=w=>{let b=[];return w.forEach(S=>{if(!S.$id&&!S.id&&!S.$tempId)if(S.$filter){let T=d({...S.$objectPath,key:S.$bzId}),D=p[T];D&&(Array.isArray(D.$ids)?D.$ids:[D.$ids]).forEach(R=>{let z={...S,$id:R,$bzId:`T4_${v4()}`,$filterBzId:S.$bzId};b.push(z);});}else {let T=d(S.$objectPath),D=p[T];D?D?.$ids?.forEach(k=>{let R={...S,$id:k,$bzId:`T4_${v4()}`};b.push(R);}):b.push(S);}else b.push(S);}),b.map(S=>{let T={...S};return o(T,!0).forEach(D=>{let k=Array.isArray(T[D])?T[D]:[T[D]],R=m(k);T[D]=R;}),T})},E=m(Array.isArray(y)?y:[y]),B=f(E),L=(w=>{let b=F=>{let S=H=>{let te=[],V=[],P=[];return H.forEach(_=>{let de=o(_,!0);if(de.length>0){let O=!1;de.forEach(U=>{(Array.isArray(_[U])?_[U]:[_[U]]).filter(Z=>!Z.$id&&!Z.id&&typeof _=="object").length&&(O=!0);}),O?te.push(_):V.push(_);}else _.$id?P.push({..._,$bzId:_.$tempId||_.$bzId}):P.push({..._,$bzId:_.$tempId||`PQ1_${v4()}`});}),{operationWithMultiples:te,operationWithoutMultiples:V,otherOps:P}},{operationWithMultiples:T,operationWithoutMultiples:D,otherOps:k}=S(F),R=H=>{let V=(()=>{let U={};for(let oe in H){let G=q(t,H);!oe.startsWith("$")&&G.dataFields?.find(Z=>Z.path===oe)&&(U[oe]=H[oe]);}return U})(),P=Object.keys(H),_=o(H,!0),de=[],O=(U,oe)=>{if(U===_.length){let Z={...oe};P.forEach(se=>{se.startsWith("$")&&(Z[se]=H[se]);}),de.push({...Z,...V});return}let G={...oe,[_[U]]:H[_[U]],...we(oe),...V};O(U+1,G),O(U+1,oe);};return O(0,{...we(H)}),de},z=[];return T.forEach(H=>{let te=R(H),V=[];te.forEach(P=>{let _=o(P,!0);if(P.$op==="create")V.push(P);else if(P.$id){let de=d(P.$objectPath),O=[];if(_.forEach(U=>{let oe=`${de.includes("undefined")?"root":de}.${P.$id}${Kt}${U}`,G=p[oe];P[U].filter(se=>se.$op==="unlink"||se.$op==="delete"||se.$op==="update").length>0?G?.$ids&&O.push({key:U,ids:G.$ids}):O.push({key:U,ids:[""]});}),O.length===_.length&&!V.find(U=>U.$id===P.$id))V.push(P);else {let U={...P,$bzId:P.$tempId||`T4_${v4()}`};_.forEach(G=>{let Z=P[G].filter(se=>se.$id);Z.length>0?U[G]=Z:U[G]=void 0;}),o(U,!0).length>0&&V.push(U);}}else if(P.$objectPath){let de=d(P.$objectPath),O=p[de]?.$ids||[];O.forEach(U=>{let oe=[];_.forEach(G=>{let Z=`${de}.${U}${Kt}${G}`,se=p[Z];se&&oe.push({key:G,ids:se.$ids});}),_.length===0?O.filter(Z=>!V.find(se=>se.$id===Z)).forEach(Z=>{V.push({...P,$id:Z,$bzId:P.$tempId||`PQT2_${v4()}`});}):oe.length===_.length&&!V.find(G=>G.$id===U)&&(_.forEach(G=>{let Z=`${d(P.$objectPath)}.${U}${Kt}${G}`,se=p[Z]?.$ids||[],vn=P[G].find(Oe=>!Oe.$id),tr=[...se.map(Oe=>({...vn,$id:Oe,$objectPath:{beforePath:P.$objectPath.beforePath,ids:Oe,key:G}})),...P[G].filter(Oe=>Oe.$id)];tr.length>0&&(P[G]=tr);}),V.push({...P,$id:U,$bzId:P.$tempId||`PQ3_${v4()}`}));});}else V.push(P);}),V.forEach(P=>{z.push(P);});}),[...z,...D,...k].filter(H=>o(H).length>0?!0:H.$op!=="update").map(H=>{let te={...H};return o(te,!0).forEach(V=>{let P=Array.isArray(te[V])?te[V]:[te[V]],_=b(P);te[V]=_;}),te})};return b(w)})(Array.isArray(B)?B:[B]),Q=w=>w.map(b=>{let F=o(b,!0),S={...b};return F.forEach(T=>{let D=Array.isArray(b[T])?b[T]:[b[T]],k=[],R=[],z=[],J={},pe=Et(t,b,T);D.filter(O=>O).forEach(O=>{O.$op==="replace"&&O.$id?(J=O,Array.isArray(O.$id)?R=[...R,...O.$id]:R.push(O.$id)):O.$op==="create"&&pe==="ONE"&&O.id?(J=O,Array.isArray(O.id)?z=[...R,...O.id]:z.push(O.id)):k.push(O);});let Le=d(J.$objectPath),te=l(Le).map(O=>p[O]),V=[];te.filter(O=>O!=null).forEach(O=>{V=[...V,...O?.$ids||[]];});let P=V.filter(O=>!R.includes(O)),_=R.filter(O=>!V.includes(O)),de=we(J);P.length>0&&k.push({...J,$op:"unlink",$id:P,$bzId:J.$tempId||`T4_${v4()}`,id:void 0,...de}),_.length>0&&_.forEach(O=>{k.push({...J,$op:"link",$id:O,$bzId:J.$tempId||`T5_${v4()}`,...de});}),z.length>0&&z.forEach(O=>{k.push({...J,$op:"create",id:O,$bzId:J.$tempId||`T6_${v4()}`,...de});}),S[T]=Q(k);}),S}),I=f(Q(f(L)));(w=>produce(w,b=>traverse(b,F=>{let{key:S,value:T,parent:D}=F;S&&D&&!S?.includes("$")&&(Array.isArray(T)||isObject(T))&&!Array.isArray(D)&&(Array.isArray(T)?T:[T]).forEach(R=>{let z=R.$filter?{...R.$objectPath,key:R.$filterBzId}:R.$objectPath,J=d(z),pe=p[J],Le=(V,P)=>V.every(_=>P.includes(_)),H=R.$id?Array.isArray(R.$id)?Le(R.$id,pe&&pe.$ids?pe.$ids:[]):pe?.$ids?.includes(R.$id):pe,te=Et(t,D,R.$objectPath.key);if(R.$op==="link"&&H&&te==="ONE")throw new Error(`[BQLE-Q-M-2] Cannot link on:"${d(R.$objectPath)}" because it is already occupied.`);if(R.$op)switch(R.$op){case"delete":if(!H&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot delete $id:"${R.$id}" because it is not linked to $id:"${D.$id}"`);break;case"update":if(!H&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot update $id:"${R.$id}" because it is not linked to $id:"${D.$id}"`);break;case"unlink":if(!H&&!r.mutation?.ignoreNonexistingThings)throw new Error(`[BQLE-Q-M-2] Cannot unlink $id:"${R.$id}" because it is not linked to $id:"${D.$id}"`);break;case"link":if(H)throw new Error(`[BQLE-Q-M-2] Cannot link $id:"${R.$id}" because it is already linked to $id:"${D.$id}"`);break;}});})))(I);let K=(w=>produce(w,b=>traverse(b,F=>{let{value:S,meta:T}=F;isObject(S)&&(S[Symbol.for("path")]=T.nodePath,delete S.$objectPath,delete S.$parentIsCreate);})))(I);return [...Array.isArray(K)?K:[K]].sort((w,b)=>w.$op==="create"&&b.$op!=="create"?-1:w.$op!=="create"&&b.$op==="create"?1:0)};var Fn=(e,t)=>produce(e,n=>dt(t,n)),dt=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(o=>dt(e,o,r));return}let n=Y(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([o])=>{o.startsWith("$")||jo(e,t,o,n);});},jo=(e,t,r,n)=>{let o=t[r];if(!o)return;let i=n.dataFields?.find(s=>s.path===r);if(i){i.contentType==="JSON"&&o!=null&&(t[r]=JSON.stringify(o));return}let a=n.linkFields?.find(s=>s.path===r);if(a){let s=a.oppositeLinkFieldsPlayedBy[0]?.thing;dt(e,o,s);return}if(n.thingType==="relation"){let s=n.roles[r];if(!s)throw new Error(`[Schema] Role ${r} in ${n.name} is not defined`);let[u]=s.playedBy||[];if(!u)throw new Error(`Role ${s.path} in ${n} is not played by anything`);dt(e,o,u.thing);}};var wn=async(e,t,r,n)=>{let o=Array.isArray(e)?e:[e],i=o.map(u=>Jt(u,!0)),s=(await ze(i,t,r,n)).bql.res;return o.map((u,$)=>{let c=Y(t,u.$thing);return Ln({mut:u,node:s[$],schema:t,thing:c})})},Sn=new Set(["$op","$bzId","$parentKey"]),zo=new Set(["$relation","$entity","$id",...Sn]),Jt=(e,t)=>{let r={};e.$fields?.forEach(o=>{typeof o=="string"?r[o]=o:r[o.$path]=o;});let n={};for(let o in e){if(Sn.has(o)||zo.has(o)&&!t)continue;let i=e[o];o.startsWith("$")?n[o]=i:Array.isArray(i)?i[0]&&typeof i[0]=="object"&&(r[o]={$path:o,...Jt(i[0],!1)}):isObject(i)&&(r[o]={$path:o,...Jt(i,!1)});}return n.$fields=Object.values(r),n},Ln=e=>{let{mut:t,node:r,schema:n,thing:o}=e,i=Rn(o),a=Wo(r);if(Array.isArray(t))return t.map(u=>{let $=a[u.$id];return $?bn({mut:u,node:$,schema:n,thing:o,...i}):u});let s=a[t.$id];return bn({mut:t,node:s,schema:n,thing:o,...i})},bn=e=>{let{mut:t,node:r,schema:n,thing:o,dataFieldMap:i,linkFieldMap:a,roleFieldMap:s}=e,{$fields:u,...$}=t;if(!r)return $;let c=Qn({$fields:t.$fields,node:r,schema:n,thing:o,dataFieldMap:i,linkFieldMap:a,roleFieldMap:s}),d={...$,[ke]:c};for(let l in t){if(l.startsWith("$"))continue;let p=t[l];if(i[l]||!p||typeof p!="object"){d[l]=p;continue}let f=a[l]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[l]?.playedBy?.[0]?.thing;if(!f)throw new Error(`"${o.name}" does not have field "${l}"`);let y=Y(n,f);d[l]=Ln({mut:p,schema:n,node:r[l],thing:y});}return d},Qn=e=>{let{$fields:t,node:r,schema:n,thing:o,dataFieldMap:i,linkFieldMap:a,roleFieldMap:s}=e,u=t||Uo(o),$={$id:r.$id};return u.forEach(c=>{let d=typeof c!="string",l=d?c.$path:c,p=r[l];if(i[l]){$[l]=p;return}let f=a[l]?.oppositeLinkFieldsPlayedBy?.[0]?.thing||s[l]?.playedBy?.[0]?.thing;if(!f)throw new Error(`"${o.name}" does not have field "${l}"`);if(!d){p&&($[l]=Array.isArray(p)?p.map(Tn):Tn(p));return}let y=Y(n,f),m=Rn(y);$[l]=Array.isArray(p)?p.map(E=>Mn({...m,$fields:c.$fields,value:E,schema:n,thing:y})):Mn({...m,$fields:c.$fields,value:p,schema:n,thing:y});}),$},Uo=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},Tn=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},Mn=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})},Rn=e=>{let t=Object.fromEntries(e.dataFields?.map(o=>[o.path,o])||[]),r=Object.fromEntries(e.linkFields?.map(o=>[o.path,o])||[]),n=e.thingType==="relation"?e.roles||{}:{};return {dataFieldMap:t,linkFieldMap:r,roleFieldMap:n}},Wo=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 vt=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 In=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 n=l=>{let p=l.$op,h=`$${l.$bzId}`,f=q(r,l),{idFields:y,defaultDBConnector:m}=f,E=m?.path||l.$thing,B=l.$id,g=y?.[0],L=listify(l,(C,w)=>{if(C.startsWith("$")||C.startsWith("%")||C===g||w===void 0||w===null)return "";let b=f.dataFields?.find(T=>T.path===C);if(!b?.path)return "";let S=b.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(b.contentType))return `has ${S} '${w}'`;if(["NUMBER","BOOLEAN"].includes(b.contentType))return `has ${S} ${w}`;if(b.contentType==="DATE"){if(Number.isNaN(w.valueOf()))throw new Error("Invalid format, Nan Date");return w instanceof Date?`has ${S} ${w.toISOString().replace("Z","")}`:`has ${S} ${new Date(w).toISOString().replace("Z","")}`}if(b.contentType==="FLEX"){let T=`bza${De()}`,D=isArray(w)?w.map(k=>vt(k)):vt(w);if(Array.isArray(D))throw new Error("Array in FLEX fields not supported yet");return `has ${S} $${T}; $${T} '${T}' isa ${S}, has ${D.type}Attribute ${D.value}`}throw new Error(`Unsupported contentType ${b.contentType}`)}).filter(C=>C),Q=`${h}-atts`,I=listify(l,C=>{if(C.startsWith("$")||C.startsWith("%")||C===g)return "";let w=f.dataFields?.find(S=>S.path===C);if(!w?.path)return "";let F=w.dbPath;return `{${Q} isa ${F};}`}).filter(C=>C),A=isArray(B)?`like '${B.join("|")}'`:`'${B}'`,j=B?[`has ${g} ${A}`]:[],K=[...j,...L].filter(C=>C).join(","),me=()=>{if(p==="delete"||p==="unlink"||p==="match")return `${h} isa ${[E,...j].filter(C=>C).join(",")};`;if(p==="update"){if(!I.length)throw new Error("update without attributes");return `${h} isa ${[E,...j].filter(C=>C).join(",")}, has ${Q};
120
+ ${I.join(" or ")};`}return ""},v=()=>p==="update"||p==="link"||p==="match"?`${h} isa ${[E,...j].filter(C=>C).join(",")};`:"";if(Ge(l))return {op:p,deletionMatch:me(),insertionMatch:v(),insertion:p==="create"?`${h} isa ${[E,K].filter(C=>C).join(",")};`:p==="update"&&L.length?`${h} ${L.join(",")};`:"",deletion:p==="delete"?`${h} isa ${E};`:p==="update"&&I.length?`${h} has ${Q};`:""};throw new Error("in attributes")},o=l=>{let p=l.$op,h=q(r,l),f=`$${l.$bzId}`,y=l.$id,m=h.defaultDBConnector?.path||l.$thing,E="roles"in h?listify(h.roles,w=>w):[],B="roles"in h?mapEntries(h.roles,(w,b)=>[w,b.dbConnector?.path||w]):{},g=listify(l,(w,b)=>{if(!E.includes(w))return null;if(!("roles"in h))throw new Error("This should have roles! ");let F=B[w];return Array.isArray(b)?b.map(S=>({path:F,id:S})):{path:F,id:b}}).filter(w=>w).flat(),L=g.map(w=>{if(!w?.path)throw new Error("Object without path");return `${w.path}: $${w.id}`}),Q=g.length>0?`( ${L.join(" , ")} )`:"",I=l[Re];if(!I)throw new Error("[internal error] Symbol edgeType not defined");let A=Q?`${f} ${Q} ${I==="linkField"||p==="delete"||p==="unlink"?`isa ${m}`:""}`:"",j=`${f} ${I==="linkField"||p==="delete"?`isa ${m}`:""}`,K=()=>A?p==="link"?`${A};`:p==="create"?`${A}, has id '${y}';`:"":"",me=()=>A&&p==="match"?`${A};`:"",v=()=>A?p==="delete"?`${A};`:p==="match"?`${A};`:"":"",C=()=>A?p==="delete"?`${j};`:p==="unlink"?`${f} ${Q};`:"":"";return {deletionMatch:v(),insertionMatch:me(),deletion:C(),insertion:K(),op:""}},i=(l,p)=>{let h=p==="edges"?o:n;if(Array.isArray(l))return l.map(g=>{let{preDeletionBatch:L,insertionMatch:Q,deletionMatch:I,insertion:A,deletion:j}=h(g);return shake({preDeletionBatch:L,insertionMatch:Q,deletionMatch:I,insertion:A,deletion:j},K=>!K)}).filter(g=>g);let{preDeletionBatch:f,insertionMatch:y,deletionMatch:m,insertion:E,deletion:B}=h(l);return shake({preDeletionBatch:f,insertionMatch:y,deletionMatch:m,insertion:E,deletion:B},g=>!g)},a=i(e),s=Array.isArray(a)?a:[a],u=i(t,"edges"),$=Array.isArray(u)?u:[u],c=[...s,...$];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 An=async(e,t,r,n,o)=>{let i=[...t,...r],a=i.map(s=>{let u=e.insertions?.find(d=>d.get(`${s.$bzId}`))?.get(`${s.$bzId}`),$=s.$thing||s.$relation||s.$entity,c=$?Y(n,$):void 0;if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!u&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let d=u?.asThing().iid,l=Object.entries(s).filter(([h,f])=>!h.startsWith("$")).reduce((h,[f,y])=>{if(c?.dataFields?.find(E=>E.path===f)?.contentType==="JSON")return h[f]=JSON.parse(y),h;if(s.$thingType==="relation"){let E=i.filter(B=>B.$id&&B.$bzId===y);return E.length===1?(h[f]=E[0].$id,h):(h[f]=y,h)}return h[f]=y,h},{});if(o.mutation?.noMetadata)return l;let p=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:d,...s,...l,[s.path]:s.$id,...p}}if(s.$op==="delete"||s.$op==="unlink")return s;if(s.$op!=="match")throw new Error(`Unsupported op ${s.$op}`)}).filter(s=>s);return clone(a)};var Cn=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:n}=await at(t,r),o=await n.transaction(TransactionType.WRITE),i=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,a=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{i&&await o.query.delete(i);let s=a&&o.query.insert(a),u=s?await s.collect():void 0;return await o.commit(),{insertions:u}}catch(s){throw new Error(`Transaction failed: ${s.message}`)}finally{await o.close();}};var vo=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),Yo=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),Go=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),Gt=N("error","error",x((e,t)=>({...e,error:t.error}))),Zo=ye("buildMutation",{buildMutation:W(async e=>In(e.bql.things,e.bql.edges,e.schema),N("done","runMutation",x(Yo)),Gt),runMutation:W(async e=>Cn(e.tql.mutation,e.handles,e.config),N("done","parseMutation",x(Go)),Gt),parseMutation:W(async e=>An(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),N("done","success",x(vo)),Gt),success:ie(),error:ie()},e=>e),Xo=async e=>new Promise((t,r)=>{fe(Zo,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),On=async(e,t,r,n,o,i,a)=>Xo({bql:{raw:e,enriched:t,things:r,edges:n,flat:{things:[],edges:[],arcs:[]},res:[]},tql:{},schema:o,config:i,handles:a,error:null});var Zt=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 kn=async(e,t)=>{let r=a=>{let{$filter:s,$thing:u,$bzId:$,$op:c,$id:d,$tempId:l}=a,p=Y(t,u),{usedDataFields:h}=le(p,a),{idFields:f}=p,y=d||a[f[0]],m=X(u),E=ae(a,b=>b.startsWith("$")),B=ae(a,b=>!b.startsWith("$")),g=JSON.stringify(B),L=Object.entries(E).map(([b,F])=>b=="$tempId"?`'$tempId': '_:${F}'`:`'${b}': '${F}'`).join(","),Q=a[Ke],I=h.map(b=>{let F=p.dataFields?.find(T=>T.path===b||T.dbPath===b);if(!F)throw new Error(`Data field schema not found for ${b}`);if(f.includes(b))return;if(a[b]===null)return `${b} = NONE`;let S=a[b];if(["JSON","NUMBER","BOOLEAN"].includes(F.contentType))return `${b} = ${S}`;if(["TEXT","EMAIL"].includes(F.contentType))return `${b} = '${S}'`;if(F.contentType==="DATE")return `${b} = d"${S.toISOString()}"`;if(F.contentType==="FLEX"){let T=isArray(S)?S.map(D=>Zt(D)):Zt(S);return `${b} = ${isArray(T)?T.map(D=>D):T}`}throw new Error(`Unsupported data field type ${F.contentType} for key ${b} in mutation`)}).filter(Boolean),A=`$\u27E8${l||$}\u27E9`,j=Q?.bzId?`$\u27E8${Q.bzId}\u27E9.\u27E8${Q.edgeField}\u27E9`:y?`${m}:\u27E8${y}\u27E9`:`${m}`,K=(()=>{if(Q?.bzId){let b=`array::flatten($\u27E8${Q.bzId}\u27E9.\u27E8${Q.edgeField}\u27E9)`;return y?isArray(y)?`${b}[? $this.id() IN [${y.map(F=>`'${F}'`).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}`}})(),me=s?`WHERE ${$e(he(s,u,t))}`:"",v=I.length>0?`SET ${I.join(", ")}`:"",C=`VALUE (CREATE ONLY Delta SET input = ${g}, meta = {${L}, "$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,w="BEFORE";if(["link","unlink","replace"].includes(c))throw new Error("Edge ops don't belong to things");if(a.$op==="match")return `LET ${A} = (SELECT VALUE id FROM ${K} ${me});`;if(a.$op==="create")return `LET ${A} = (CREATE ONLY ${m}:\u27E8${y}\u27E9 ${v} RETURN ${C});`;if(a.$op==="update")return `LET ${A} = IF (${j}) THEN (UPDATE ${K} ${v} ${me} RETURN ${C}) END;`;if(a.$op==="delete")return `LET ${A} = IF (${j}) THEN (DELETE ${K} ${me} RETURN ${w}) END;`;throw new Error(`Unsupported operation ${a.$op}`)},n=a=>{let{$thing:s,$bzId:u,$op:$,$tempId:c}=a,d=Y(t,s),{usedRoleFields:l}=le(d,a),p=`$\u27E8${c||u}\u27E9`,h="roles"in d?l.flatMap(m=>{let E=d.roles[m];if(!E)throw new Error(`Role field schema not found for ${m}`);let{cardinality:B}=E,g=isArray(a[m])?a[m].map(L=>`$\u27E8${L}\u27E9`):[`$\u27E8${a[m]}\u27E9`];if(B==="ONE"){if(g.length>1)throw new Error(`${$==="link"?"Linking":"Replacing"} multiple values to a ONE field ${m}`);switch($){case"link":case"replace":return `${m} = ((type::is::array(${g[0]}) && array::len(${g[0]})==1) && ${g[0]}[0]) || ${g[0]}`;case"unlink":return `${m} = NONE`;default:throw new Error(`Unsupported operation ${$} for ONE cardinality`)}}else if(B==="MANY"){let L=`array::flatten([${g}])`;switch($){case"link":return `${m} += ${L}`;case"unlink":return `${m} -= ${L}`;case"replace":return `${m} = ${L}`;default:throw new Error(`Unsupported operation ${$} for MANY cardinality`)}}else throw new Error(`Unsupported cardinality ${B}`)}):[],f=h.length>0?`${h.join(", ")}`:"",y=f?`SET ${f}`:"";return `IF ${p} THEN (UPDATE ${p} ${y} RETURN VALUE id) END; ${p};`},o=a=>{let{$thing:s,$op:u}=a,$=Y(t,s),c=X(s),{usedRoleFields:d}=le($,a);if(!["create","delete"].includes(u))throw new Error("Arcs can only be created or deleted");let[l,p]=d,h=isArray(a[l])?a[l]:[a[l]],f=isArray(a[p])?a[p]:[a[p]];if(u==="create"){if(d.length!==2)throw new Error("Not supported: Arcs must have exactly 2 roles");let y=ae(a,A=>!A.startsWith("$")),E=`(CREATE ONLY Delta SET input = ${JSON.stringify(y)}, meta = {"$sid": $parent.id, "$id": record::id($parent.id)}, after = $after, before = $before RETURN VALUE $parent.id )`,g=$.roles[l].cardinality==="MANY",Q=$.roles[p].cardinality==="MANY";return h.flatMap(A=>f.flatMap(j=>`FOR $node1 IN fn::as_array($\u27E8${A}\u27E9) { FOR $node2 IN fn::as_array($\u27E8${j}\u27E9) { CREATE ONLY ${c} SET ${l} = ${g?"fn::as_array($node1)":"$node1"}, ${p} = ${Q?"fn::as_array($node2)":"$node2"} RETURN ${E}; } }`))}if(u==="delete")return `DELETE FROM ${c} WHERE fn::as_array(${l}) CONTAINSANY $\u27E8${h}\u27E9 AND fn::as_array(${p}) CONTAINSANY $\u27E8${f}\u27E9 RETURN BEFORE`};return [...e.things.map(r),...e.edges.map(n),...e.arcs.flatMap(o)]};var Pn=async(e,t)=>{let r=`
54
121
  BEGIN TRANSACTION;
55
122
  ${t.join(";")};
56
123
  LET $DELTAS = SELECT * FROM Delta;
@@ -60,12 +127,12 @@ limit ${f};`),d.join(`
60
127
  LET $LOGS = SELECT * FROM LOG;
61
128
  RETURN $LOGS;
62
129
  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
130
+ `;try{return (await e.query(r)).filter(Boolean)}catch(n){let i=(await e.query_raw(r)).filter(a=>a.result!=="The query was not executed due to a failed transaction"&&a.result!=="There was an error when starting a new datastore transaction"&&a.status==="ERR");throw i.length>0?new Error(`Error running SURQL mutation: ${JSON.stringify(i)}`):n}};var jn=e=>{let{res:t,config:r}=e;return t.flat().filter(Boolean).flatMap(o=>{if(isArray(o))return o.map(i=>{if(!isObject(i)||!("meta"in i))throw new Error("Internal error: Invalid response from DB");return xn(i,r)});if(!isObject(o)||!("meta"in o))throw new Error("Internal error: Invalid response from DB");return xn(o,r)})},xn=(e,t)=>{let r=mapEntries(e.after||{},(i,a)=>[i,isArray(a)&&a.length===0?void 0:a]),n=ae(e.input||{},(i,a)=>a===null),o={...r,...e.meta,...n};return t.mutation?.noMetadata?ae(o,i=>!i.startsWith("$")):o};var rs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),ns=(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}}},is=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},Xt=N("error","error",x((e,t)=>({...e,error:t.error}))),os=ye("buildMutation",{buildMutation:W(async e=>kn(e.bql.flat,e.schema),N("done","runMutation",x(ns)),Xt),runMutation:W(async e=>Pn(e.handles.surrealDB?.get(e.handles.surrealDB?.keys().next().value)?.client,e.surql.mutations),N("done","parseMutation",x(is)),Xt),parseMutation:W(async e=>jn({res:e.surql.res,config:e.config,schema:e.schema}),N("done","success",x(rs)),Xt),success:ie(),error:ie()},e=>e),ss=async e=>new Promise((t,r)=>{fe(os,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),zn=async(e,t,r,n,o,i)=>ss({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:n,config:o,handles:i,error:null});var Wn=(e,t)=>{let r={things:[],edges:[],arcs:[]},n=(i,a)=>{if(!i?.$thing){console.log("block without $thing",i);return}let{$op:s,$bzId:u,$tempId:$}=i,c=t.relations[i.$thing]||t.entities[i.$thing];if(!c)throw new Error(`[Internal] No schema found for ${i.$thing}`);let d=a?.bzId?a:{bzId:"",edgeField:"root"},{usedDataFields:l,usedLinkFields:p,usedRoleFields:h}=le(c,i);if(["create","update","delete","link","unlink","match","replace"].includes(s)){let y={...ae(i,m=>![...h,...p].includes(m)),...s==="link"||s==="unlink"||s==="replace"||s==="update"&&l.length===0?{$op:"match"}:{},...s==="link"||s==="replace"?{}:{[Ke]:d}};r.things.push(y);}let f={link:["link","create"],unlink:["unlink","delete"],replace:["replace"]};if(h){let y=ae(i,m=>isSymbol(m)||m.startsWith("$"));h.forEach(m=>{isArray(i[m])?i[m].forEach(B=>n(B,{bzId:u,edgeField:m,tempId:$})):n(i[m],{bzId:u,edgeField:m,tempId:$});let E=(isArray(i[m])?i[m]:[i[m]]).filter(Boolean);Object.entries(f).forEach(([B,g])=>{let L=E.filter(Q=>g.includes(Q.$op)).map(Q=>Q.$bzId);L.length>0&&r.edges.push({...y,[m]:L,$op:B});});});}p&&p.forEach(y=>{isArray(i[y])?i[y].forEach(B=>n(B,{bzId:u,edgeField:y,tempId:$})):n(i[y],{bzId:u,edgeField:y,tempId:$});let m=c.linkFields?.find(B=>B.path===y),E=isArray(i[y])?i[y]:[i[y]];m.target==="relation"&&Object.entries(f).forEach(([B,g])=>{E.filter(Q=>g.includes(Q.$op)).forEach(Q=>{let I=ae(Q,A=>isSymbol(A)||A.startsWith("$"));r.edges.push({...I,[m.plays]:u,$op:B});});}),m.target==="role"&&Object.entries({create:["link","create"],delete:["unlink","delete"],replace:["replace"]}).forEach(([g,L])=>{E.filter(I=>L.includes(I.$op)).forEach(I=>{let A={$thing:m.relation,$thingType:"relation",$bzId:`arc_${I.$bzId}`,[m.plays]:u,[m.oppositeLinkFieldsPlayedBy[0].plays]:I.$bzId,$op:g};r.arcs.push(A);});});});};return (Array.isArray(e)?e:[e]).forEach(i=>n(i)),r};var Vn=ie,Ue=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,as=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),ls=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),cs=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),ds=async e=>Object.keys(e.bql.enriched).length?Mt(e.bql.enriched,e.schema,e.config):Mt(e.bql.raw,e.schema,e.config),us=async e=>Bn(e.bql.enriched,e.schema,e.config,e.handles),hs=async e=>wn(e.bql.enriched,e.schema,e.config,e.handles),ps=async e=>kr(e.bql.enriched,e.schema),$s=async e=>Wn(e.bql.enriched,e.schema),fs=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}.`)},ms=e=>xe(e.bql.enriched),Ce=N("error","error",x((e,t)=>({...e,error:t.error}))),ys=ye("stringify",{stringify:W(async e=>Fn(e.bql.raw,e.schema),N("done","enrich",x(Ue)),Ce),enrich:W(ds,N("done","preQuery",wt(fs),x(Ue)),N("done","parseBQL",x(Ue)),Ce),preQuery:W(us,N("done","preHookDependencies",wt(ms),x(Ue)),N("done","parseBQL",x(Ue)),Ce),preHookDependencies:W(hs,N("done","enrich",x(Ue)),Ce),parseBQL:W(ps,N("done","flattenBQL",x(as)),Ce),flattenBQL:W($s,N("done","adapter",x(ls)),Ce),adapter:W(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 On(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return zn(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},N("done","success",x(cs)),Ce),success:Vn(),error:Vn()},e=>e),gs=async e=>new Promise((t,r)=>{fe(ys,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),Hn=async(e,t,r,n)=>gs({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[]},res:[]},schema:t,config:r,handles:n,depthLevel:0,error:null});enableMapSet();var er=class{schema;config;dbHandles;constructor({schema:t,config:r}){this.schema=t,this.config=r;}getDbHandles=()=>this.dbHandles;init=async()=>{let t={typeDB:new Map,surrealDB:new Map};await Promise.all(this.config.dbConnectors.map(async n=>{if(n.provider==="surrealDB"){let o=new Surreal;await o.connect(n.url,{namespace:n.namespace,database:n.dbName,auth:{username:n.username,password:n.password},versionCheck:!1}),t.surrealDB.set(n.id,{client:o,providerConfig:n.providerConfig});}if(n.provider==="typeDB"&&n.dbName){let[o,i]=await tryit(TypeDB.coreDriver)(n.url);if(o){let a=`[BORM:${n.provider}:${n.dbName}:core] ${o.message??"Can't create TypeDB Client"}`;throw new Error(a)}try{let a=await i.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:i,session:a});}catch(a){let s=`[BORM:${n.provider}:${n.dbName}:session] ${(a.messageTemplate?._messageBody()||a.message)??"Can't create TypeDB Session"}`;throw new Error(s)}}if(n.provider==="typeDBCluster"&&n.dbName){let o=new TypeDBCredential(n.username,n.password,n.tlsRootCAPath),[i,a]=await tryit(TypeDB.cloudDriver)(n.addresses,o);if(i){let s=`[BORM:${n.provider}:${n.dbName}:core] ${i.message??"Can't create TypeDB Cluster Client"}`;throw new Error(s)}try{let s=await a.session(n.dbName,SessionType.DATA);t.typeDB.set(n.id,{client:a,session:s});}catch(s){let u=`[BORM:${n.provider}:${n.dbName}:session] ${(s.messageTemplate?._messageBody()||s.message)??"Can't create TypeDB Session"}`;throw new Error(u)}}}));let r=$r(this.schema,t);this.schema=r,this.dbHandles=t;};#e=async()=>{if(!this.dbHandles&&(await this.init(),!this.dbHandles))throw new Error("Can't init BormClient")};introspect=async()=>(await this.#e(),this.schema);define=async()=>{if(await this.#e(),!this.dbHandles)throw new Error("dbHandles undefined");return await sr(this.config,this.schema,this.dbHandles)};query=async(t,r)=>{await this.#e();let n={...this.config,query:{...$t.query,...this.config.query,...r}},o=Array.isArray(t),i=o?t:[t],[a,s]=await tryit(ze)(i,this.schema,n,this.dbHandles);if(a){let $=new Error(a.error);throw $.stack=a.error.stack,$}let u=s.bql.res;return o?u:u[0]};mutate=async(t,r)=>{await this.#e();let n={...this.config,mutation:{...$t.mutation,...this.config.mutation,...r}},[o,i]=await tryit(Hn)(t,this.schema,n,this.dbHandles);if(o){let s=new Error(o.error.message);throw s.stack=o.error.stack,s}return i.bql.res};close=async()=>{this.dbHandles&&this.dbHandles.typeDB?.forEach(async({client:t,session:r})=>{r.isOpen()&&await r.close(),await t.close();});}},hu=er;//! Todo: delete when this works with the new $thing and $thingType fields
64
131
  //! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
65
132
  //! Todo: Sandbox the function in computeFunction()
66
133
  //! reads all the insertions and gets the first match. This means each id must be unique
67
134
  //!old
68
135
 
69
- export { Hd as default };
136
+ export { hu as default };
70
137
  //# sourceMappingURL=out.js.map
71
138
  //# sourceMappingURL=index.mjs.map