@blitznocode/blitz-orm 0.11.3 → 0.11.4

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
@@ -47,8 +47,8 @@ flexAttribute sub attribute, abstract, value string,
47
47
  owns doubleAttribute,
48
48
  owns booleanAttribute,
49
49
  owns datetimeAttribute;
50
- `},nr=async(e,t,r,n)=>{if(!n.typeDB)throw new Error("No TypeDB handles found");let o=ri(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 ir=e=>e.replace(/`/g,""),ni=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],X=e=>ni.some(t=>e.includes(t))?`\u27E8${e}\u27E9`:e;var mt=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 sr={TEXT:"string",RICH_TEXT:"string",LANGUAGE_TEXT:"string",PASSWORD:"string",URL:"string",PHONE:"string",ID:"string",EMAIL:"string",NUMBER:"number",NUMBER_DECIMAL:"decimal",BOOLEAN:"bool",DATE:"datetime",JSON:"object",FLEX:"bool|bytes|datetime|duration|geometry|number|object|string"},He=(e,t)=>{if(e===null)return "NONE";if(t)switch(t){case"TEXT":case"RICH_TEXT":case"LANGUAGE_TEXT":case"PASSWORD":case"URL":case"PHONE":case"ID":case"EMAIL":if(typeof e!="string")throw new Error(`Invalid value for TEXT type: ${e}`);return JSON.stringify(e);case"NUMBER":case"NUMBER_DECIMAL":case"BOOLEAN":case"JSON":return e;case"DATE":return typeof e=="string"?`<datetime>"${e}"`:isDate(e)?`d"${e.toISOString()}"`:`$<datetime>"${e}"`;case"FLEX":{let r=isArray(e)?e.map(n=>mt(n)):mt(e);return `${isArray(r)?r.map(n=>n):r}`}default:throw new Error(`Unsupported data field type ${t}.`)}throw new Error(`Failed parsing value ${e} with content type ${t}`)};var si=" ",Qe=e=>si.repeat(e),Ke=(e,t)=>e.split(`
51
- `).map(r=>r.trim()?`${Qe(t)}${r}`:r).join(`
50
+ `},nr=async(e,t,r,n)=>{if(!n.typeDB)throw new Error("No TypeDB handles found");let o=ri(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 ir=e=>e.replace(/`/g,""),ni=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],X=e=>ni.some(t=>e.includes(t))?`\u27E8${e}\u27E9`:e;var mt=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 sr={TEXT:"string",RICH_TEXT:"string",LANGUAGE_TEXT:"string",PASSWORD:"string",URL:"string",PHONE:"string",ID:"string",EMAIL:"string",NUMBER:"number",NUMBER_DECIMAL:"decimal",BOOLEAN:"bool",DATE:"datetime",JSON:"object",FLEX:"bool|bytes|datetime|duration|geometry|number|object|string"},He=(e,t)=>{if(e===null)return "NONE";if(t)switch(t){case"TEXT":case"RICH_TEXT":case"LANGUAGE_TEXT":case"PASSWORD":case"URL":case"PHONE":case"ID":case"EMAIL":if(typeof e!="string")throw new Error(`Invalid value for TEXT type: ${e}`);return JSON.stringify(e);case"NUMBER":case"NUMBER_DECIMAL":case"BOOLEAN":case"JSON":return e;case"DATE":return typeof e=="string"?`<datetime>"${e}"`:isDate(e)?`d"${e.toISOString()}"`:`$<datetime>"${e}"`;case"FLEX":{let r=isArray(e)?e.map(n=>mt(n)):mt(e);return `${isArray(r)?r.map(n=>n):r}`}default:throw new Error(`Unsupported data field type ${t}.`)}throw new Error(`Failed parsing value ${e} with content type ${t}`)};var si=" ",Re=e=>si.repeat(e),Ke=(e,t)=>e.split(`
51
+ `).map(r=>r.trim()?`${Re(t)}${r}`:r).join(`
52
52
  `),ai=e=>{let t=`USE NS test;
53
53
  USE DB test;
54
54
 
@@ -58,16 +58,16 @@ ${ar(e.entities)}`,n=`
58
58
  -- RELATIONS
59
59
  ${ar(e.relations)}`,o=$i();return `${t}${r}${n}${o}COMMIT TRANSACTION;`},ar=e=>Object.entries(e).map(([t,r])=>li(X(t),r,1)).join(`
60
60
 
61
- `),li=(e,t,r)=>{let n=`${Qe(r)}DEFINE TABLE ${e} SCHEMAFULL PERMISSIONS FULL;${"extends"in t&&t.extends?` //EXTENDS ${t.extends};`:""}`,o=Ke(`-- DATA FIELDS
61
+ `),li=(e,t,r)=>{let n=`${Re(r)}DEFINE TABLE ${e} SCHEMAFULL PERMISSIONS FULL;${"extends"in t&&t.extends?` //EXTENDS ${t.extends};`:""}`,o=Ke(`-- DATA FIELDS
62
62
  ${ci(t.dataFields??[],e,r)}`,r+1),i=Ke(`
63
63
  -- LINK FIELDS
64
64
  ${di(t.linkFields??[],e,r)}`,r+1),a="roles"in t?Ke(`
65
65
  -- ROLES
66
66
  ${ui(t.roles,e,r)}`,r+1):"";return `${n}
67
- ${o}${i}${a}`},ci=(e,t,r)=>e.map(n=>{if(n.path==="id")return "";let o=pi(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
- `),di=(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
- `),ui=(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=hi(n,t,o,r);return `${a}
67
+ ${o}${i}${a}`},ci=(e,t,r)=>e.map(n=>{if(n.path==="id")return "";let o=pi(n.contentType,n.validations),i=`${Re(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
+ `),di=(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=`${Re(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?"":`${Re(r+1)}DEFINE FIELD ${c} ON TABLE ${t} TYPE option<${$}>;`;return [l,p].join(`
69
+ `)}if(n.target==="relation")return `${`${Re(r)}DEFINE FIELD ${X(n.path)} ON TABLE ${t} TYPE ${o};`}`;throw new Error(`Invalid link field: ${JSON.stringify(n)}`)}).join(`
70
+ `),ui=(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=`${Re(r)}DEFINE FIELD ${n} ON TABLE ${t} TYPE option<${i}>;`,s=hi(n,t,o,r);return `${a}
71
71
  ${s}`}).join(`
72
72
  `),hi=(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
73
  IF ($before.${e}) THEN {UPDATE $before.${e} SET ${f}} END;
@@ -100,24 +100,24 @@ ${s}`}).join(`
100
100
  DEFINE FUNCTION fn::as_array($var: option<array<record>|record>) {
101
101
  RETURN (type::is::array($var) AND $var) OR [$var]
102
102
  };
103
- `,lr=e=>ai(e);var cr=async(e,t,r)=>await(async()=>{let i=(await Promise.all([...r.typeDB||[]].map(async([u])=>[u,await nr(u,e,t,r)]))).map(u=>[u[0],u[1]]),s=(await Promise.all([...r.surrealDB||[]].map(async([u])=>[u,lr(t)]))).map(u=>[u[0],u[1]]);return {typeDB:Object.fromEntries(i),surrealDB:Object.fromEntries(s)}})();var re=Symbol.for("queryPath"),Je=Symbol.for("stepPrint"),Re=Symbol.for("edgeType"),Ee=Symbol.for("edgeSchema"),ke=Symbol.for("dbNode"),yt=Symbol.for("isTransformed"),Ye=Symbol.for("parent"),ne=Symbol.for("fieldSchema"),be=Symbol.for("sharedMetadata"),Me=Symbol.for("suqlMetadata");var dr={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var ur=({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 $r=(e,t,r)=>r?t:`${e}\xB7${t}`;var mr=(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}))},yr=(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:$r(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:$r(l,d.path,d.shared),[be]:{inheritanceOrigin:d[be]?.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,[be]:{inheritanceOrigin:f[be]?.inheritanceOrigin||s.extends}}]);d.roles={...d.roles||{},...p};}}s.linkFields=$.linkFields?(s.linkFields||[]).concat($.linkFields.map(d=>({...d,inherited:!0,[be]:{inheritanceOrigin:d[be]?.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=dr[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"){if(l.oppositeLinkFieldsPlayedBy=r.filter(h=>h.relation===l.relation&&h.plays!==l.plays&&h.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(h=>h.target==="relation"&&h.relation===l.relation)?.path??l.relation.toLocaleLowerCase(),l.$things=[...new Set(l.oppositeLinkFieldsPlayedBy.flatMap(h=>[h.thing,...Y(n,h.thing)?.subTypes||[]]))],l.oppositeLinkFieldsPlayedBy.length>1&&console.warn(`[Schema] LinkField ${l.path} in ${d.name} has multiple candidates ${l.oppositeLinkFieldsPlayedBy.map(h=>h.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][be]?.inheritanceOrigin??l.relation,f=ur({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[be]?.inheritanceOrigin||a.name;y.length>1&&console.warn(`Not supported yet: Role ${l} in ${"name"in a?a.name:JSON.stringify(a)} 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)}`)},Ge=(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`)},Xe=(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},gr=(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")},Bt=(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`)},Ft=(e,t,r)=>Bt(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 Er=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},Br=(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 Ze=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),Be=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},T=(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 br=(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 et=(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 Mr=(e,t)=>{let n=(isArray(e.$root)?e.$root:[e.$root]).map(o=>{let i=et(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:gr(o,t)},...o.$op?{}:{$op:i},...o.$bzId?{}:{$bzId:`R_${De()}`}},...o}});e.$root=isArray(e.$root)?n:n[0];};var tt=(e,t)=>{let r=t[Je];return isSet(r)?r.has("clean")?(Reflect.set(t,Je,r.add("clean")),!0):!1:(Reflect.set(t,Je,new Set(["clean"])),!0)};var wr=(e,t,r)=>{if(tt("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)=>({...Be(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 Sr=(e,t,r,n)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(i=>{let a=Pe(t,r),[s]=a,u=et(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,[Ee]:r,$thing:s.thing,$thingType:s.thingType,$op:u,$bzId:c}});e[t]=isArray(e[t])?o:o[0];};var Mi=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,wi=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Lr=e=>{let r=e.toString().replace(Mi,"").trim().split("=>")[0].split("{")[0].replace(wi,"").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:n}=t.default,i=Lr(n).filter(a=>!(a in e));if(i.length)throw new Error(`Virtual field: Missing arguments ${i.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");if("default"in t){if(t.default.type==="value")return t.default.value;if(t.default.type==="fn")return t.default.fn(e);throw new Error("[Schema] No default field definition")}};var Qr=(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?mr(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 nt=(e,t)=>{let r=q(t,e).hooks;if(r?.pre){let n=`on${Er(e.$op)}`;return r.pre.filter(a=>!a.triggers||a.triggers[n]?.()).flatMap(a=>a.actions)}return []};var Dr=(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(Be(e)),p=clone(Be(d)),h=n.mutation?.context||{},f=clone(Be(i[ke]||{}));nt(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 Ar=(e,t,r,n)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(i=>{if(Ze(i)){if(i.$fields||i[yt])return i;let a=nt(i,r).filter(d=>d.type==="transform"),s=clone(Be(e)),u=clone(Be(i)),$=n.mutation?.context||{},c=clone(Be(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),[yt]:!0});}),i}});e[t]=isArray(e[t])?o:o[0];};var Cr=(e,t,r)=>{let n=Pe(t,r),[o]=n;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Ee]:r};};var Ne=e=>{if(Array.isArray(e)){for(let t of e)if(Ne(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"&&Ne(e[t]))return !0}return !1};var ki=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(tt("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")},Pi=(e,t)=>{},St=(e,t,r)=>{let n={$rootWrap:{$root:e}},o=Ne(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(ki(l,h),h!=="$root"&&p||h!=="$root"&&(h.startsWith("$")||h.startsWith("%")))return;let f=h!=="$root"?Bt(t,l,h):{fieldType:"rootField"};if(!f)throw new Error(`[Internal] Field ${h} not found in schema`);if("contentType"in f)return Pi();if(["rootField","linkField","roleField"].includes(f.fieldType)){if(["linkField","roleField"].includes(f.fieldType)&&(l[h]===null?Cr(l,h,f):br(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`);Mr(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)&&Sr(l,h,f,t),wr(l,h,t),["rootField","linkField","roleField"].includes(f.fieldType)&&Qr(l,h,t),(isArray(l[h])?l[h]:[l[h]]).forEach(B=>{let g=q(t,B),{unidentifiedFields:L,usedLinkFields:Q,usedFields:D,fields:A}=le(g,B);if(D.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||(Ar(l,h,t,r),Dr(l,h,t,r));}});}}));return isArray(i.$rootWrap.$root),i.$rootWrap.$root};var Or=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 Nr=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}),D=m[g]||m.$id||Q;if(!D)throw new Error(`no idValue: ${JSON.stringify(m)}`);return D},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:D,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(b=>Q?.includes(b)),w=j.filter(b=>D?.includes(b)),F=j.filter(b=>A?.includes(b));if(C.length>0)return "update";if(w.length>0||F.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[Ee];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()}`,b=Br(c,E,B).$bzId;if(!b)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",M=q(t,{$thing:v.relation,$thingType:"relation"});if(!Object.keys(M.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]:b,[Ee]:v,[Re]:"linkField"};f(k),(g.$op==="unlink"||S()==="unlink")&&C&&f({$thing:v.relation,$thingType:"relation",$bzId:w,$op:"match",[v.plays]:b,[Ee]:v,[Re]:"linkField"});}if(g.$thingType==="relation"){let C=ae(g,(b,S)=>D.includes(b)),w=mapEntries(C,(b,S)=>isArray(S)?[b,S]:isObject(S)?[b,S.$bzId]:[b,S]),F=ae(m,(b,S)=>b.startsWith("$")||b.startsWith("Symbol"));if(Object.keys(C).filter(b=>!b.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let b=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},S=q(t,g).roles,M=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]}),I={...F,$thing:g.$thing,$thingType:"relation",$op:b(),...M,$bzId:g.$bzId,[Re]:"roleField"};f(I);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(C).length>0){let b=0;Object.entries(C).forEach(([S,M])=>{let I=isArray(M)?M:[M],k=R=>R==="create"||R==="replace"?"link":R;I.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"&&b>0)throw b+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let J={...F,$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(Or(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 xe={};function ee(e){return {enumerable:!0,value:e}}function xr(e){return {enumerable:!0,writable:!0,value:e}}var Ui=()=>!0,jr=()=>({}),zr=e=>e,Wi=(e,t,r,n)=>e.apply(r,n)&&t.apply(r,n),Vi=(e,t,r,[n,o])=>t.call(r,e.call(r,n,o),o),Se=(e,t)=>Object.freeze(Object.create(e,t));function _r(e,t,r){return e.reduce((n,o)=>function(...i){return r(n,o,this,i)},t)}function Ur(e){return Se(this,{fn:ee(e)})}var Wr={},N=Ur.bind(Wr);var Vr={},Lt=Ur.bind(Vr);function it(e,t){return t.filter(r=>e.isPrototypeOf(r))}function Hr(e,t,...r){let n=_r(it(Vr,r).map(i=>i.fn),Ui,Wi),o=_r(it(Wr,r).map(i=>i.fn),zr,Vi);return Se(this,{from:ee(e),to:ee(t),guards:ee(n),reducers:ee(o)})}var Kr={},Jr={},x=Hr.bind(Kr);Hr.bind(Jr,null);function Hi(e,t,r){return Rt(t,e,r,this.immediates)||e}function Yr(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 Ki={enter:zr};function ie(...e){let t=it(Kr,e),r=it(Jr,e),n={final:ee(e.length===0),transitions:ee(Yr(t))};return r.length&&(n.immediates=ee(r),n.enter=ee(Hi)),Se(Ki,n)}var Ji={enter(e,t,r){let n=this.fn.call(t,t.context,r);return Qt.isPrototypeOf(n)?Se(vr,{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)}},vr={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,Rt(t,e,{type:"done",data:n},this.transitions.get("done"))}return e}};function W(e,...t){let r=ee(Yr(t));return Qt.isPrototypeOf(e)?Se(vr,{machine:ee(e),transitions:r}):Se(Ji,{fn:ee(e),transitions:r})}var Qt={get state(){return {name:this.current,value:this.states[this.current]}}};function ye(e,t,r=jr){return typeof e!="string"&&(r=t||jr,t=e,e=Object.keys(t)[0]),xe._create&&xe._create(e,t),Se(Qt,{context:ee(r),current:ee(e),states:ee(t)})}function Rt(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}});xe._onEnter&&xe._onEnter(t,i,e.context,o,r);let c=$.state.value;return e.machine=$,e.onChange(e),c.enter($,e,r)}}function Yi(e,t){let r=t.type||t,{machine:n}=e,{value:o,name:i}=n.state;return o.transitions.has(r)?Rt(e,n,t,o.transitions.get(r))||n:(xe._send&&xe._send(r,i),n)}var vi={send(e){Yi(this,e);}};function fe(e,t,r,n){let o=Object.create(vi,{machine:xr(e),context:xr(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 en=(e,t)=>{if(!t)return;let r=Xi(t);return Zi(r,e.query)},Xi=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),Zi=(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 rn=(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=Ct(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=tn(p,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);u.$fields=l;}else {let l=At(c)?.flatMap(p=>{let h=tn(p,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);u.$fields=l;}u.$excludedFields&&(u.$fields=u.$fields.filter(d=>ot(c,d)?!0:!u.$excludedFields.includes(d.$path)));}}}))},At=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]},Ct=(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}),ot=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),ro=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}},no=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=>ot(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=At(h);else y=["id"];t.$excludedFields&&(y=y.filter(E=>ot(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,oppositeLinkFieldsPlayedBy:void 0},$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:Ct(t.$filter,h),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ne]:s}})},io=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=At(p);else f=["id"];t.$excludedFields&&(f=f.filter(m=>ot(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:Ct(t.$filter,p),$playedBy:{...u,oppositeLinkFieldsPlayedBy:void 0},$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ne]:s}})},tn=(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 ro({field:e,fieldStr:n,$justId:o,dbPath:i.dbPath,isVirtual:u,fieldSchema:i})}else {if(a)return no({field:e,fieldStr:n,linkField:a,$justId:o,dbPath:a.path,schema:r,fieldSchema:a});if(s)return io({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]=Ge(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 nn=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]=Ge(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 y=h[Me].queryPath;return {...$,[y]:he(d,t,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===null?"NONE":`'${s}'`).join(", ")}]`);else if(isObject(a)){let s=$e(a);r.push(`${n} ${i.replace("$","")} ${s}`);}else r.push(`${n} ${i.replace("$","")} ${a===null?"NONE":`'${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===null?"NONE":`'${a}'`).join(", ")}]`);}else {let i=n.startsWith("$")?n.replace("$",""):"=";r.push(`${n} ${i} ${o===null?"NONE":`'${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 sn=e=>{let{queries:t,schema:r}=e;return t.map(n=>ho({query:n,schema:r}))},ho=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=Ot({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(`
103
+ `,lr=e=>ai(e);var cr=async(e,t,r)=>await(async()=>{let i=(await Promise.all([...r.typeDB||[]].map(async([u])=>[u,await nr(u,e,t,r)]))).map(u=>[u[0],u[1]]),s=(await Promise.all([...r.surrealDB||[]].map(async([u])=>[u,lr(t)]))).map(u=>[u[0],u[1]]);return {typeDB:Object.fromEntries(i),surrealDB:Object.fromEntries(s)}})();var re=Symbol.for("queryPath"),Je=Symbol.for("stepPrint"),De=Symbol.for("edgeType"),Ee=Symbol.for("edgeSchema"),Pe=Symbol.for("dbNode"),yt=Symbol.for("isTransformed"),Ye=Symbol.for("parent"),ne=Symbol.for("fieldSchema"),be=Symbol.for("sharedMetadata"),Me=Symbol.for("suqlMetadata");var dr={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var ur=({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 e.cardinality==="MANY"?`$parent.[\`${e.path}\`]`:`$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"?e.cardinality==="MANY"?`$parent.[\`${s.plays}\`]`:`$parent.\`${s.plays}\``:`${a}${c}`}else throw new Error("Unsupported linkField target")};var $r=(e,t,r)=>r?t:`${e}\xB7${t}`;var mr=(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}))},yr=(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:$r(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:$r(l,d.path,d.shared),[be]:{inheritanceOrigin:d[be]?.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,[be]:{inheritanceOrigin:f[be]?.inheritanceOrigin||s.extends}}]);d.roles={...d.roles||{},...p};}}s.linkFields=$.linkFields?(s.linkFields||[]).concat($.linkFields.map(d=>({...d,inherited:!0,[be]:{inheritanceOrigin:d[be]?.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=dr[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"){if(l.oppositeLinkFieldsPlayedBy=r.filter(h=>h.relation===l.relation&&h.plays!==l.plays&&h.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(h=>h.target==="relation"&&h.relation===l.relation)?.path??l.relation.toLocaleLowerCase(),l.$things=[...new Set(l.oppositeLinkFieldsPlayedBy.flatMap(h=>[h.thing,...Y(n,h.thing)?.subTypes||[]]))],l.oppositeLinkFieldsPlayedBy.length>1&&console.warn(`[Schema] LinkField ${l.path} in ${d.name} has multiple candidates ${l.oppositeLinkFieldsPlayedBy.map(h=>h.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][be]?.inheritanceOrigin??l.relation,f=ur({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[be]?.inheritanceOrigin||a.name;y.length>1&&console.warn(`Not supported yet: Role ${l} in ${"name"in a?a.name:JSON.stringify(a)} 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)}`)},Ge=(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`)},Xe=(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},gr=(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")},Bt=(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`)},Ft=(e,t,r)=>Bt(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 Er=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},Br=(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 Ze=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),Be=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},T=(e,t)=>{let r="";for(let n=0;n<t;n++)r+=" ";return `${r}${e}`},Ie=e=>customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz",e??21)();var qe=(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 br=(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=qe(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 Ae=(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 et=(e,t,r)=>{let n=q(r,t),{usedFields:o}=le(n,t);return t.$op?(Ae(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(Ae(e,{...t,$op:"update"},r),"update"):(Ae(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(Ae(e,{...t,$op:"create"},r),"create"):(Ae(e,{...t,$op:"create"},r),"link"):(Ae(e,{...t,$op:"create"},r),"create")};var Mr=(e,t)=>{let n=(isArray(e.$root)?e.$root:[e.$root]).map(o=>{let i=et(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:gr(o,t)},...o.$op?{}:{$op:i},...o.$bzId?{}:{$bzId:`R_${Ie()}`}},...o}});e.$root=isArray(e.$root)?n:n[0];};var tt=(e,t)=>{let r=t[Je];return isSet(r)?r.has("clean")?(Reflect.set(t,Je,r.add("clean")),!0):!1:(Reflect.set(t,Je,new Set(["clean"])),!0)};var wr=(e,t,r)=>{if(tt("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)=>({...Be(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 Sr=(e,t,r,n)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(i=>{let a=qe(t,r),[s]=a,u=et(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}_${Ie()}`:`SM_${Ie()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...i,[Ee]:r,$thing:s.thing,$thingType:s.thingType,$op:u,$bzId:c}});e[t]=isArray(e[t])?o:o[0];};var Mi=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,wi=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,Lr=e=>{let r=e.toString().replace(Mi,"").trim().split("=>")[0].split("{")[0].replace(wi,"").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 Ne=({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:n}=t.default,i=Lr(n).filter(a=>!(a in e));if(i.length)throw new Error(`Virtual field: Missing arguments ${i.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");if("default"in t){if(t.default.type==="value")return t.default.value;if(t.default.type==="fn")return t.default.fn(e);throw new Error("[Schema] No default field definition")}};var Qr=(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?mr(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=Ne({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 nt=(e,t)=>{let r=q(t,e).hooks;if(r?.pre){let n=`on${Er(e.$op)}`;return r.pre.filter(a=>!a.triggers||a.triggers[n]?.()).flatMap(a=>a.actions)}return []};var Dr=(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(Be(e)),p=clone(Be(d)),h=n.mutation?.context||{},f=clone(Be(i[Pe]||{}));nt(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 Ar=(e,t,r,n)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(i=>{if(Ze(i)){if(i.$fields||i[yt])return i;let a=nt(i,r).filter(d=>d.type==="transform"),s=clone(Be(e)),u=clone(Be(i)),$=n.mutation?.context||{},c=clone(Be(i[Pe]||i.$dbNode));return a.forEach(d=>{let l=d.fn(u,s,$,c||{});Object.keys(l).length!==0&&(i={...u,...l,...we(i),[yt]:!0});}),i}});e[t]=isArray(e[t])?o:o[0];};var Cr=(e,t,r)=>{let n=qe(t,r),[o]=n;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Ee]: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 kr=(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=Qt(u.$filter,c),u.$filter=Se(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=Or(p,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);u.$fields=l;}else {let l=Lt(c)?.flatMap(p=>{let h=Or(p,c,t);return Array.isArray(h)?h:[h]}).filter(Boolean);u.$fields=l;}u.$excludedFields&&(u.$fields=u.$fields.filter(d=>it(c,d)?!0:!u.$excludedFields.includes(d.$path)));}}}))},Lt=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]},Qt=(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}),it=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),Ai=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}},Ci=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=>it(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=Lt(h);else y=["id"];t.$excludedFields&&(y=y.filter(E=>it(h,E)?!0:!t.$excludedFields.includes(E.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...Se(t.$filter,l,a)}:void 0;return {$thingType:d,$plays:n.plays,$playedBy:{...c,oppositeLinkFieldsPlayedBy:void 0},$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:Qt(t.$filter,h),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ne]:s}})},Oi=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=Lt(p);else f=["id"];t.$excludedFields&&(f=f.filter(m=>it(p,m)?!0:!t.$excludedFields.includes(m.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...Se(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:Qt(t.$filter,p),$playedBy:{...u,oppositeLinkFieldsPlayedBy:void 0},$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ne]:s}})},Or=(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 Ai({field:e,fieldStr:n,$justId:o,dbPath:i.dbPath,isVirtual:u,fieldSchema:i})}else {if(a)return Ci({field:e,fieldStr:n,linkField:a,$justId:o,dbPath:a.path,schema:r,fieldSchema:a});if(s)return Oi({field:e,fieldStr:n,roleField:s,$justId:o,dbPath:n,schema:r,fieldSchema:s})}return null},Se=(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]=Se(d,t,r);else {let p=t in r.entities?r.entities[t]:r.relations[t],[h,f]=Ge(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:Se(d,m,r)}:Se(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 ji=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(tt("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)=>{},Dt=(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");"$filter"in l&&l.$filter&&(l.$filter=Se(l.$filter,l.$thing,t)),Object.keys(l).forEach(h=>{if(ji(l,h),h!=="$root"&&p||h!=="$root"&&(h.startsWith("$")||h.startsWith("%")))return;let f=h!=="$root"?Bt(t,l,h):{fieldType:"rootField"};if(!f)throw new Error(`[Internal] Field ${h} not found in schema`);if("contentType"in f)return _i();if(["rootField","linkField","roleField"].includes(f.fieldType)){if(["linkField","roleField"].includes(f.fieldType)&&(l[h]===null?Cr(l,h,f):br(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`);Mr(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)&&Sr(l,h,f,t),wr(l,h,t),["rootField","linkField","roleField"].includes(f.fieldType)&&Qr(l,h,t),(isArray(l[h])?l[h]:[l[h]]).forEach(B=>{let g=q(t,B),{unidentifiedFields:L,usedLinkFields:Q,usedFields:D,fields:A}=le(g,B);if(D.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||(Ar(l,h,t,r),Dr(l,h,t,r));}});}}));return isArray(i.$rootWrap.$root),i.$rootWrap.$root};var Pr=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 jr=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=Ne({currentThing:m,fieldSchema:L,mandatoryDependencies:!0}),D=m[g]||m.$id||Q;if(!D)throw new Error(`no idValue: ${JSON.stringify(m)}`);return D},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(!B.nodePath?.includes(".$filter")&&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:D,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(b=>Q?.includes(b)),w=j.filter(b=>D?.includes(b)),F=j.filter(b=>A?.includes(b));if(C.length>0)return "update";if(w.length>0||F.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[Ee];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()}`,b=Br(c,E,B).$bzId;if(!b)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",M=q(t,{$thing:v.relation,$thingType:"relation"});if(!Object.keys(M.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]:b,[Ee]:v,[De]:"linkField"};f(k),(g.$op==="unlink"||S()==="unlink")&&C&&f({$thing:v.relation,$thingType:"relation",$bzId:w,$op:"match",[v.plays]:b,[Ee]:v,[De]:"linkField"});}if(g.$thingType==="relation"){let C=ae(g,(b,S)=>D.includes(b)),w=mapEntries(C,(b,S)=>isArray(S)?[b,S]:isObject(S)?[b,S.$bzId]:[b,S]),F=ae(m,(b,S)=>b.startsWith("$")||b.startsWith("Symbol"));if(Object.keys(C).filter(b=>!b.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let b=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},S=q(t,g).roles,M=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]}),I={...F,$thing:g.$thing,$thingType:"relation",$op:b(),...M,$bzId:g.$bzId,[De]:"roleField"};f(I);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(C).length>0){let b=0;Object.entries(C).forEach(([S,M])=>{let I=isArray(M)?M:[M],k=R=>R==="create"||R==="replace"?"link":R;I.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"&&b>0)throw b+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let J={...F,$thing:g.$thing,$thingType:"relation",$op:z==="delete"?"unlink":z,[S]:R.$bzId,$bzId:g.$bzId,[De]:"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(Pr(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 je={};function ee(e){return {enumerable:!0,value:e}}function _r(e){return {enumerable:!0,writable:!0,value:e}}var Ji=()=>!0,zr=()=>({}),Wr=e=>e,Yi=(e,t,r,n)=>e.apply(r,n)&&t.apply(r,n),vi=(e,t,r,[n,o])=>t.call(r,e.call(r,n,o),o),Le=(e,t)=>Object.freeze(Object.create(e,t));function Ur(e,t,r){return e.reduce((n,o)=>function(...i){return r(n,o,this,i)},t)}function Vr(e){return Le(this,{fn:ee(e)})}var Hr={},N=Vr.bind(Hr);var Kr={},It=Vr.bind(Kr);function ot(e,t){return t.filter(r=>e.isPrototypeOf(r))}function Jr(e,t,...r){let n=Ur(ot(Kr,r).map(i=>i.fn),Ji,Yi),o=Ur(ot(Hr,r).map(i=>i.fn),Wr,vi);return Le(this,{from:ee(e),to:ee(t),guards:ee(n),reducers:ee(o)})}var Yr={},vr={},x=Jr.bind(Yr);Jr.bind(vr,null);function Gi(e,t,r){return Ct(t,e,r,this.immediates)||e}function Gr(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 Xi={enter:Wr};function ie(...e){let t=ot(Yr,e),r=ot(vr,e),n={final:ee(e.length===0),transitions:ee(Gr(t))};return r.length&&(n.immediates=ee(r),n.enter=ee(Gi)),Le(Xi,n)}var Zi={enter(e,t,r){let n=this.fn.call(t,t.context,r);return At.isPrototypeOf(n)?Le(Xr,{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)}},Xr={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,Ct(t,e,{type:"done",data:n},this.transitions.get("done"))}return e}};function W(e,...t){let r=ee(Gr(t));return At.isPrototypeOf(e)?Le(Xr,{machine:ee(e),transitions:r}):Le(Zi,{fn:ee(e),transitions:r})}var At={get state(){return {name:this.current,value:this.states[this.current]}}};function ye(e,t,r=zr){return typeof e!="string"&&(r=t||zr,t=e,e=Object.keys(t)[0]),je._create&&je._create(e,t),Le(At,{context:ee(r),current:ee(e),states:ee(t)})}function Ct(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,$=Le(u,{current:ee(i),original:{value:u}});je._onEnter&&je._onEnter(t,i,e.context,o,r);let c=$.state.value;return e.machine=$,e.onChange(e),c.enter($,e,r)}}function eo(e,t){let r=t.type||t,{machine:n}=e,{value:o,name:i}=n.state;return o.transitions.has(r)?Ct(e,n,t,o.transitions.get(r))||n:(je._send&&je._send(r,i),n)}var to={send(e){eo(this,e);}};function fe(e,t,r,n){let o=Object.create(to,{machine:_r(e),context:_r(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 rn=(e,t)=>{if(!t)return;let r=no(t);return io(r,e.query)},no=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),io=(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 nn=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=Ne({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]=Ge(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 y=h[Me].queryPath;return {...$,[y]:he(d,t,r)}}throw new Error(`Field ${c} not found in schema, Defined in $filter`)},{});return shake(u)});return n?i:i[0]},pe=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=>pe(s)):[pe(o)];i==="!"?r.push(`!(${a.join(` ${i} `)})`):r.push(`(${a.join(` ${i} `)})`);return}if(isObject(o))if(n.includes("<-")||n.includes("->")){let i=pe(o);r.push(`${n}[WHERE ${i}]`);}else if(n.startsWith("$parent.[")){let i=pe(o),a=`${n.replace("$parent.","").replace(/^\[(.*)\]$/,"$1")}`;r.push(`fn::as_array(${a})[WHERE id && ${i}]`);}else if(n.startsWith("$parent")){let i=pe(o),a=`${n.replace("$parent.","")}`;r.push(`fn::as_array(${a})[WHERE id && ${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===null?"NONE":`'${s}'`).join(", ")}]`);else if(isObject(a)){let s=pe(a);r.push(`${n} ${i.replace("$","")} ${s}`);}else r.push(`${n} ${i.replace("$","")} ${a===null?"NONE":`'${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===null?"NONE":`'${a}'`).join(", ")}]`);}else {let i=n.startsWith("$")?n.replace("$",""):"=";r.push(`${n} ${i} ${o===null?"NONE":`'${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 sn=e=>{let{queries:t,schema:r}=e;return t.map(n=>ho({query:n,schema:r}))},ho=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=Ot({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=pe(h);$.push(`WHERE ${f}`);}return u&&$.push(_e(u)),typeof s=="number"&&$.push(`LIMIT ${s}`),typeof a=="number"&&$.push(`START ${a}`),$.join(`
104
104
  `)},Ot=e=>{let{queries:t,schema:r,level:n,parentQuery:o}=e,i=[],a=o[re];return i.push(T(`"${a}" as \`$$queryPath\``,n)),i.push(T("record::id(id) as `$id`",n)),i.push(T("record::tb(id) as `$thing`",n)),t.forEach(s=>{let u=po({query:s,level:n,schema:r});u&&i.push(u);}),i.length===0?null:i.join(`,
105
- `)},po=e=>{let{query:t,schema:r,level:n}=e;return t.$fieldType==="data"?$o({query:t,level:n}):t.$fieldType==="link"?fo({query:t,level:n,schema:r}):t.$fieldType==="role"?mo({query:t,level:n,schema:r}):null},$o=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?T(`record::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?T(`\`${t.$path}\``,r):T(`\`${t.$path}\` AS \`${t.$as}\``,r)},fo=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(T("(",n));let c=n+1;$.push(T("SELECT",c));let d=Ot({parentQuery:t,queries:o,level:c+1,schema:r});d&&$.push(d);let l=t[ne][Me].queryPath;if($.push(T(`FROM ${l}`,c)),i){let p=he(i,t.$thing,r),h=$e(p);$.push(`WHERE ${h}`);}return u&&$.push(T(_e(u),c)),typeof s=="number"&&$.push(T(`LIMIT ${s}`,c)),typeof a=="number"&&$.push(T(`START ${a}`,c)),$.push(T(`) AS \`${t.$as}\``,n)),$.join(`
106
- `)},mo=e=>{let{query:t,schema:r,level:n}=e;if(t.$fields.length===0)return null;let o=[];o.push(T("(",n));let i=n+1;o.push(T("SELECT",i));let a=i+1,s=Ot({parentQuery:t,queries:t.$fields,level:a,schema:r});s&&o.push(s);let u=t[ne][Me].queryPath;if(o.push(T(`FROM ${u}`,i)),t.$filter){let $=he(t.$filter,t.$playedBy.thing,r),c=$e($);o.push(`WHERE ${c}`);}return o.push(T(`) AS \`${t.$as}\``,n)),o.join(`
105
+ `)},po=e=>{let{query:t,schema:r,level:n}=e;return t.$fieldType==="data"?$o({query:t,level:n}):t.$fieldType==="link"?fo({query:t,level:n,schema:r}):t.$fieldType==="role"?mo({query:t,level:n,schema:r}):null},$o=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?T(`record::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?T(`\`${t.$path}\``,r):T(`\`${t.$path}\` AS \`${t.$as}\``,r)},fo=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(T("(",n));let c=n+1;$.push(T("SELECT",c));let d=Ot({parentQuery:t,queries:o,level:c+1,schema:r});d&&$.push(d);let l=t[ne][Me].queryPath;if($.push(T(`FROM ${l}`,c)),i){let p=he(i,t.$thing,r),h=pe(p);$.push(`WHERE ${h}`);}return u&&$.push(T(_e(u),c)),typeof s=="number"&&$.push(T(`LIMIT ${s}`,c)),typeof a=="number"&&$.push(T(`START ${a}`,c)),$.push(T(`) AS \`${t.$as}\``,n)),$.join(`
106
+ `)},mo=e=>{let{query:t,schema:r,level:n}=e;if(t.$fields.length===0)return null;let o=[];o.push(T("(",n));let i=n+1;o.push(T("SELECT",i));let a=i+1,s=Ot({parentQuery:t,queries:t.$fields,level:a,schema:r});s&&o.push(s);let u=t[ne][Me].queryPath;if(o.push(T(`FROM ${u}`,i)),t.$filter){let $=he(t.$filter,t.$playedBy.thing,r),c=pe($);o.push(`WHERE ${c}`);}return o.push(T(`) AS \`${t.$as}\``,n)),o.join(`
107
107
  `)};var an=async e=>{let{client:t,queries:r}=e,n=`
108
108
  BEGIN TRANSACTION;
109
109
  ${r.join(";")};
110
110
  COMMIT TRANSACTION;
111
111
  `;return await t.query(n)};var cn=e=>{let{res:t,queries:r}=e;return t.map((o,i)=>dn(r[i],o))},dn=(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 kt(e,t[0])}if(t.length>=1)return t.map(r=>kt(e,r))}else throw new Error("res is unexpectedly not an array")},kt=(e,t)=>{let r={[re]:t.$$queryPath,$id:t.$id,$thing:ir(t.$thing),$thingType:e.$thingType};return e.$fields.forEach(n=>{let o=n.$as,i=t[o];n.$path==="id"&&e.$idNotIncluded||(r[o]=go(n,i));}),r},go=(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"&&ln(t,r),ln(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"?kt(e,t[0]):dn(e,t)},ln=(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]}if(t==="FLEX"){let n=r.map(o=>isDate(o)?new Date(o).toISOString():o);return isArray(e)?n:n[0]}return e};var un=e=>{let{queries:t,schema:r}=e;return t.map(n=>Eo({query:n,schema:r}))},Eo=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=hn(c),l=pn(o.filter(g=>g.$fieldType==="data")),p=$n(o.filter(g=>g.$fieldType==="link"||g.$fieldType==="role"),r),h=[...d,...l,...p].join(`,
112
- `),f=Bo(t,$),y=i?`WHERE id AND (${$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}`},Bo=(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")},hn=e=>[`"${e}" as \`$$queryPath\``,"record::id(id) as `$id`","record::tb(id) as `$thing`"],pn=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}\``),$n=(e,t)=>e.map(r=>{let n=hn(r[re]),o=pn(r.$fields.filter(l=>l.$fieldType==="data")),i=$n(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 id AND(${$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 Pt=x("error","error",N((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 sn({queries:e.bql.queries,schema:e.schema});if(t==="refs")return un({queries:e.bql.queries,schema:e.schema})},x("done","run",N((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),Pt),run:W(async e=>an({client:e.client,queries:ue(e.surql.queries)}),x("done","parse",N((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),Pt),parse:W(async e=>cn({res:ue(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),x("done","success",N((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),Pt),success:ie(),error:ie()},e=>e),bo=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);}),fn=async(e,t,r,n)=>bo({bql:{queries:e},surql:{},schema:t,config:r,client:n,error:null});var qt="___",yn=async e=>{let{queries:t,schema:r}=e;return t.map(n=>wo({query:n,schema:r}))},wo=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=Xe(r,t),y={...i,...c?{[f]:c}:{}},m=_t({$filter:y,$var:n,$thing:o,schema:r,depth:0});d.push(`
112
+ `),f=Bo(t,$),y=i?`WHERE id AND (${pe(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}`},Bo=(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")},hn=e=>[`"${e}" as \`$$queryPath\``,"record::id(id) as `$id`","record::tb(id) as `$thing`"],pn=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}\``),$n=(e,t)=>e.map(r=>{let n=hn(r[re]),o=pn(r.$fields.filter(l=>l.$fieldType==="data")),i=$n(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 id AND(${pe(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 Pt=x("error","error",N((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 sn({queries:e.bql.queries,schema:e.schema});if(t==="refs")return un({queries:e.bql.queries,schema:e.schema})},x("done","run",N((e,t)=>({...e,surql:{...e.surql,queries:t.data}}))),Pt),run:W(async e=>an({client:e.client,queries:ue(e.surql.queries)}),x("done","parse",N((e,t)=>({...e,surql:{...e.surql,res:t.data}}))),Pt),parse:W(async e=>cn({res:ue(e.surql.res),queries:e.bql.queries,schema:e.schema,config:e.config}),x("done","success",N((e,t)=>({...e,bql:{...e.bql,res:t.data}}))),Pt),success:ie(),error:ie()},e=>e),bo=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);}),fn=async(e,t,r,n)=>bo({bql:{queries:e},surql:{},schema:t,config:r,client:n,error:null});var qt="___",yn=async e=>{let{queries:t,schema:r}=e;return t.map(n=>wo({query:n,schema:r}))},wo=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=Xe(r,t),y={...i,...c?{[f]:c}:{}},m=_t({$filter:y,$var:n,$thing:o,schema:r,depth:0});d.push(`
114
114
  ${m}`);}let p=zt({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(...Nt(f,n,0));let y=a.filter(E=>E.$fieldType==="link");y&&y.length>0&&d.push(...jt(y,n,n,0,r));let m=a.filter(E=>E.$fieldType==="role");m&&m.length>0&&d.push(...xt(m,n,n,0,r));}return p&&d.push(p.sort),typeof u=="number"&&d.push(`
115
115
  offset ${u};`),typeof $=="number"&&d.push(`
116
116
  limit ${$};`),d.join(`
117
117
  `)},Nt=(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(",")}]}`,$=[T(`$${t} as "${t}.${u}.$dataFields": ${a};`,r)];return i.length>0&&i.forEach(c=>{$.push(T(`"${c.path}.$multiVal": {match $${t} has ${c.path} $${c.path}; fetch $${c.path}: attribute;};`,r));}),$},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,$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(T(`"${r}.${E}.${s.$var}": {`,n)),a.push(T("match",i));let B=`${t}${qt}${s.$var}`;if(a.push(T(`$${B} isa ${s.$thing};`,i)),a.push(T(`$${t} (${s.$var}: $${t}${qt}${s.$var}) isa ${s.$intermediary};`,i)),s.$filter||s.$id){let L=Xe(o,s),Q=s.$id?{[L]:s.$id}:{},D={...s.$filter,...Q};a.push(_t({$filter:D,$var:B,$thing:s.$thing,schema:o,depth:i}));}let g=zt({schema:o,$thing:p,$var:B,$sort:h,depth:i});if(g&&a.push(g.match),u){let L=`M_${v4()}`;a.push(T(`
118
118
  ?queryPath${L} = "${m}";`,i)),a.push(T("fetch",i)),a.push(T(`?queryPath${L} as "queryPath";`,i));let Q=u?.filter(j=>j.$fieldType==="data");Q&&Q.length>0&&a.push(...Nt(Q,B,i));let D=u?.filter(j=>j.$fieldType==="link");D&&D.length>0&&a.push(...jt(D,B,`${t}.${s.$var}`,i,o));let A=u?.filter(j=>j.$fieldType==="role");A&&A.length>0&&a.push(...xt(A,B,`${t}.${s.$var}`,i,o));}g&&a.push(g.sort),typeof f=="number"&&a.push(T(`offset ${f};`,i)),typeof y=="number"&&a.push(T(`limit ${y};`,i)),a.push(T("};",n));}return a},jt=(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(T(`"${r}.${B}.${s.$var}": {`,n)),a.push(T("match",i));let g=`${t}${qt}${s.$var}`;if(a.push(T(`$${g} isa ${s.$thing};`,i)),s.$filter||s.$id){let Q=Xe(o,s),D=s.$id?{[Q]:s.$id}:{},A={...s.$filter,...D};a.push(_t({$filter:A,$var:g,$thing:s.$thing,schema:o,depth:i}));}let L=zt({schema:o,$thing:h,$var:g,$sort:f,depth:i});if(L&&a.push(L.match),s.$target==="role"?a.push(T(`$${t}_intermediary (${s.$plays}: $${t}, ${p.plays}: $${g}) isa ${s.$intermediary};`,i)):a.push(T(`$${g} (${s.$plays}: $${t});`,i)),u){let Q=`M_${v4()}`;a.push(T(`?queryPath${Q} = "${E}";`,i)),a.push(T("fetch",i)),a.push(T(`?queryPath${Q} as "queryPath";`,i));let D=u?.filter(K=>K.$fieldType==="data");D&&D.length>0&&a.push(...Nt(D,g,i));let A=u?.filter(K=>K.$fieldType==="link");A&&A.length>0&&a.push(...jt(A,g,`${t}.${s.$var}`,i,o));let j=u?.filter(K=>K.$fieldType==="role");j&&j.length>0&&a.push(...xt(j,g,`${t}.${s.$var}`,i,o));}L&&a.push(L.sort),typeof y=="number"&&a.push(T(`offset ${y};`,i)),typeof m=="number"&&a.push(T(`limit ${m};`,i)),a.push(T("};",n));}return a},So=(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=mn(o,r);return n&&(i.$not=mn(n,r)),i},mn=(e,t)=>{let r={};return Object.entries(e).forEach(([n,o])=>{let i=t[n]||n;r[i]=o;}),r},_t=e=>{let{$filter:t,$var:r,$thing:n,schema:o,depth:i}=e,a=So(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(T(`$${r} has ${d} $${d}_${v4()};`,i)):Array.isArray(l)?l.forEach(f=>{c.push(T(`not { $${r} has ${d} ${ce(f)}; };`,i));}):c.push(T(`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(T(`(${h.plays}: $${r}) isa ${h.relation};`,i)):Array.isArray(l)?l.forEach(E=>{c.push(T(`not { (${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ce(E)}; };`,i));}):c.push(T(`not { (${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ce(l)}; };`,i));else {let E=`${f.thing}_${v4()}`;l===null?c.push(T(`$${E} isa ${f.thing}; (${h.plays}: $${r}, ${f.plays}: $${E}) isa ${h.relation};`,i)):Array.isArray(l)?l.forEach(B=>{c.push(T(`not { $${E} isa ${f.thing}, has ${m} ${ce(B)}; (${h.plays}: $${r}, ${f.plays}: $${E}) isa ${h.relation}; };`,i));}):c.push(T(`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(T(`$${L} isa ${n};`,i)),c.push(T(`$${L} (${y.plays}: ${B});`,i)),c.push(T(`$${r} is $${L};`,i))):Array.isArray(l)?l.forEach(Q=>{c.push(T(`$${L} isa ${n};`,i)),c.push(T(`not { $${B} isa ${y.thing}, has ${E} ${ce(Q)}; $${L} (${y.plays}: $${B}); };`,i)),c.push(T(`$${r} is $${L};`,i));}):(c.push(T(`$${L} isa ${n};`,i)),c.push(T(`not { $${B} isa ${y.thing}, has ${E} ${ce(l)}; $${L} (${y.plays}: $${B}); };`,i)),c.push(T(`$${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(T(`not { $${r} has ${d} $${d}_${v4()}; };`,i));else if(Array.isArray(l)){let f=l.map(m=>`$${r} has ${d} ${ce(m)};`),y=at(f);y&&c.push(T(y,i));}else c.push(T(`$${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(T(`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=at(E);B&&c.push(T(B,i));}else c.push(T(`(${h.plays}: $${r}) isa ${h.relation}, has ${m} ${ce(l)};`,i));else {let E=`${f.thing}_${v4()}`;if(l===null)c.push(T(`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=at(B);g&&c.push(T(g,i));}else c.push(T(`$${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(T(`$${L} isa ${n};`,i)),c.push(T(`not { $${L} (${y.plays}: ${B}); };`,i)),c.push(T(`$${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});`),D=at(Q);D&&(c.push(T(`$${L} isa ${n};`,i)),c.push(T(D,i)),c.push(T(`$${r} is $${L};`,i)));}else c.push(T(`$${L} isa ${n};`,i)),c.push(T(`$${B} isa ${y.thing}, has ${E} ${ce(l)}; $${L} (${y.plays}: $${B});`,i)),c.push(T(`$${r} is $${L};`,i));return}}throw new Error(`"${n}" does not have property "${d}"`)}),c.join(`
119
- `)},at=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}`,Lo=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},zt=e=>{let{$var:t,$thing:r,schema:n,$sort:o,depth:i}=e,a=Y(n,r),s=[],u=[];if(o?.forEach($=>{let c=Lo($),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(T("{",i)),s.push(T(`$${t} has ${d.dbPath} $${l}_1;`,i+1)),s.push(T("not {",i+1)),s.push(T(`$${t} has ${d.dbPath} $${l}_2;`,i+2)),s.push(T(`$${l}_2 < $${l}_1;`,i+2)),s.push(T("};",i+1)),s.push(T(`?${l}_ = $${l}_1;`,i+1)),s.push(T("} or {",i)),s.push(T(`not { $${t} has ${d.dbPath} $${l}_1; };`,i+1)),s.push(T(`?${l}_ = "~";`,i+1)),s.push(T("};",i)),s.push(T(`?${l} = ?${l}_;`,i));let p=c.desc?"desc":"asc";u.push(`?${l} ${p}`);}),s.length!==0)return {match:s.join(""),sort:T(`sort ${u.join(", ")};`,i)}};var En=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 Ro(a,u,$,n,o)})},Ro=(e,t,r,n,o)=>e.length===0?null:r.$filterByUnique?gn(e[0],t,n,o):e.map(i=>gn(i,t,n,o)),gn=(e,t,r,n)=>{let{dataFields:o,currentSchema:i,linkFields:a,roleFields:s,schemaValue:u}=Ut(e,r),$=Wt(o,i,n),c=Ht(a,r,n),d=Vt(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))):$}},Ut=(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}},Wt=(e,t,r)=>{let{$metaData:n}=e,{as:o}=Do(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])},Vt=(e,t,r)=>{let n={};return e.forEach(o=>{let{$roleFields:i,$metaData:a,$cardinality:s}=o,{as:u,justId:$,idNotIncluded:c,filterByUnique:d}=Bn(a);if(u===null)return;let l=i.map(p=>{let{dataFields:h,currentSchema:f,linkFields:y,roleFields:m,schemaValue:E}=Ut(p,t),B=Wt(h,f,r);if($==="T")return B.id;{let g=Ht(y,t,r),L=Vt(m,t,r),Q={...B};return c==="true"&&f?.idFields?.forEach(D=>delete Q[D]),{...Q,...g,...L,...E}}});l.length>0?n[u]=s==="MANY"&&d==="false"?l:l[0]:r.query?.returnNulls&&(n[u]=null);}),n},Ht=(e,t,r)=>{let n={};return e.forEach(o=>{let{$linkFields:i,$metaData:a,$cardinality:s}=o,{as:u,justId:$,idNotIncluded:c,filterByUnique:d}=Bn(a);if(u===null)return;let l=i.map(p=>{let{dataFields:h,currentSchema:f,linkFields:y,roleFields:m,schemaValue:E}=Ut(p,t),B=Wt(h,f,r);if($==="T")return B.id;{let g=Ht(y,t,r),L=Vt(m,t,r),Q={...B};return c==="true"&&f.idFields?.forEach(D=>delete Q[D]),{...Q,...g,...L,...E}}});n[u]=l.length>0?s==="MANY"&&d==="false"?l:l[0]:r.query?.returnNulls?null:void 0;}),n},Bn=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}},Do=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 lt=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 Fn=async e=>{let{tqlRequest:t,dbHandles:r,config:n}=e,o=new TypeDBOptions;o.infer=!0;let{session:i}=await lt(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 Po=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,qo=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,No=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,Kt=x("error","error",N((e,t)=>({...e,error:t.error}))),xo=ye("build",{build:W(async e=>yn({queries:e.bql.queries,schema:e.schema}),x("done","run",N(qo)),Kt),run:W(async e=>Fn({dbHandles:e.handles,tqlRequest:ue(e.tql.queries),config:e.config}),x("done","parse",N(No)),Kt),parse:W(async e=>En({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:ue(e.tql.res)}),x("done","success",N(Po)),Kt),success:ie(),error:ie()},e=>e),jo=async e=>new Promise((t,r)=>{fe(xo,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),bn=async(e,t,r,n,o)=>jo({bql:{raw:e,queries:t},tql:{},schema:r,config:n,handles:o,error:null});var _o=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Jt=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,ct=x("error","error",N((e,t)=>({...e,error:t.error}))),zo=ye("enrich",{enrich:W(async e=>rn(e.bql.raw,e.schema),x("done","adapter",N(_o)),ct),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 bn(s.rawBql,s.bqlQueries,e.schema,e.config,e.handles);if(s.db==="surrealDB")return fn(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)},x("done","postHooks",N(Jt)),ct),postHooks:W(async e=>nn(e.schema,ue(e.bql.queries),ue(e.bql.res)),x("done","clean",N(Jt)),ct),clean:W(async e=>en(e.config,ue(e.bql.res)),x("done","success",N(Jt)),ct),success:ie(),error:ie()},e=>e),Uo=async e=>new Promise((t,r)=>{fe(zo,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),ze=async(e,t,r,n)=>Uo({bql:{raw:e},schema:t,config:r,handles:n,error:null});var Yt="___",Wo=Symbol.for("grandChildOfCreate"),Tn=async(e,t,r,n)=>{let o=(w,F)=>Object.keys(w).filter(b=>!b.startsWith("$")&&w[b]!==void 0?F?!q(t,w).dataFields?.find(M=>M.path===b):!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:F,value:b})=>{w&&F&&!F.includes("$")&&isObject(w)?(Array.isArray(w[F])?w[F]:[w[F]]).forEach(M=>{if(isObject(M)){if(w.$op!=="create")i.includes(M.$op)||i.push(M.$op);else if(M.$op==="delete"||M.$op==="unlink")throw new Error(`Cannot ${M.$op} under a create`)}}):!w&&isObject(b)&&(i.includes(b.$op)||i.push(b.$op));}),!i.includes("delete")&&!i.includes("unlink")&&!i.includes("replace")&&!i.includes("update")&&!i.includes("link"))return;let s=(w=>{let F=(b,S)=>{let M=[],I={},k=["$op","$bzId","$parentKey"],R=["$relation","$entity","$id",...k];for(let z in b)if(!k.includes(z)&&!(R.includes(z)&&!S))if(!z.includes("$")&&(isObject(b[z])||Array.isArray(b[z]))){let J=b[z];if(Array.isArray(J)&&J.length>0)J.forEach(pe=>{let Le={$path:z,...F(pe),...pe.$filter&&{$as:pe.$bzId}};M.find(H=>H.$path===Le.$path&&!H.$filter)||(M=[...M,Le]);});else {let pe={$path:z,...F(J),...!J.$filter&&{$as:J.$bzId}};M=[...M,pe];}}else I[z]=b[z];return {...I,$fields:M}};return w.map(b=>F(b,!0))})(Array.isArray(e)?e:[e]),$=(await ze(s,t,{...r,query:{...r.query,returnNulls:!0}},n)).bql.res,c=(w,F)=>{let b=w.$id||w.id||w.$bzId;if(w.$objectPath){let{$objectPath:S}=w,M=S?.beforePath||"root",I=Array.isArray(S.ids)?`[${S.ids}]`:S.ids;return {beforePath:`${M}.${I}___${S.key}`,ids:b,key:F}}else return {beforePath:"root",ids:b,key:F}},d=(w,F)=>{let b=w?.beforePath||"root";if(typeof b!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let S=F||(Array.isArray(w?.ids)?`[${w?.ids}]`:w?.ids);return `${b}.${S}___${w?.key}`},l=w=>{if(w.includes("[")&&w.includes("]")){let[F,b,S]=w.split(/[[\]]/);return b.split(",").map(I=>`${F}${I}${S}`)}else return [w]},p={};(w=>produce(w,F=>traverse(F,({key:b,parent:S})=>{if(S&&b&&S.$id&&!b.includes("$")){let M=c(S,b),I=d(M);if(Array.isArray(S[b])){let k=[];S[b].forEach(R=>{isObject(R)?(R.$objectPath=M,k.push(R.$id.toString())):R&&k.push(R.toString());}),p[I]={$objectPath:M,$ids:k};}else {let k=S[b];isObject(k)?(p[I]={$objectPath:M,$ids:[k.$id.toString()]},k.$objectPath=M):k?p[I]={$objectPath:M,$ids:[k.toString()]}:k===null&&(p[I]=null);}}})))($||{});let f=w=>produce(w,F=>traverse(F,({key:b,value:S,parent:M})=>{M&&b&&!b.includes("$")&&(Array.isArray(S)||isObject(S))&&!Array.isArray(M)&&(Array.isArray(M[b])?M[b].forEach(I=>{typeof I!="string"&&(I.$objectPath=c(M,b),I.$parentIsCreate=M.$op==="create",I[Wo]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")]);}):isObject(M[b])&&(M[b].$parentIsCreate=M.$op==="create",M[b][Symbol.for("grandChildOfCreate")]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")],M[b].$objectPath=c(M,b)));})),y=f(e),m=w=>{let F=[];return w.forEach(S=>{if(!S.$id&&!S.id&&!S.$tempId)if(S.$filter){let M=d({...S.$objectPath,key:S.$bzId}),I=p[M];I&&(Array.isArray(I.$ids)?I.$ids:[I.$ids]).forEach(R=>{let z={...S,$id:R,$bzId:`T4_${v4()}`,$filterBzId:S.$bzId};F.push(z);});}else {let M=d(S.$objectPath),I=p[M];I?I?.$ids?.forEach(k=>{let R={...S,$id:k,$bzId:`T4_${v4()}`};F.push(R);}):F.push(S);}else F.push(S);}),F.map(S=>{let M={...S};return o(M,!0).forEach(I=>{let k=Array.isArray(M[I])?M[I]:[M[I]],R=m(k);M[I]=R;}),M})},E=m(Array.isArray(y)?y:[y]),B=f(E),L=(w=>{let F=b=>{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:M,operationWithoutMultiples:I,otherOps:k}=S(b),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 M.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}${Yt}${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}${Yt}${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}${Yt}${G}`,se=p[Z]?.$ids||[],Xn=P[G].find(Oe=>!Oe.$id),rr=[...se.map(Oe=>({...Xn,$id:Oe,$objectPath:{beforePath:P.$objectPath.beforePath,ids:Oe,key:G}})),...P[G].filter(Oe=>Oe.$id)];rr.length>0&&(P[G]=rr);}),V.push({...P,$id:U,$bzId:P.$tempId||`PQ3_${v4()}`}));});}else V.push(P);}),V.forEach(P=>{z.push(P);});}),[...z,...I,...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]],_=F(P);te[V]=_;}),te})};return F(w)})(Array.isArray(B)?B:[B]),Q=w=>w.map(F=>{let b=o(F,!0),S={...F};return b.forEach(M=>{let I=Array.isArray(F[M])?F[M]:[F[M]],k=[],R=[],z=[],J={},pe=Ft(t,F,M);I.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[M]=Q(k);}),S}),D=f(Q(f(L)));(w=>produce(w,F=>traverse(F,b=>{let{key:S,value:M,parent:I}=b;S&&I&&!S?.includes("$")&&(Array.isArray(M)||isObject(M))&&!Array.isArray(I)&&(Array.isArray(M)?M:[M]).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=Ft(t,I,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:"${I.$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:"${I.$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:"${I.$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:"${I.$id}"`);break;}});})))(D);let K=(w=>produce(w,F=>traverse(F,b=>{let{value:S,meta:M}=b;isObject(S)&&(S[Symbol.for("path")]=M.nodePath,delete S.$objectPath,delete S.$parentIsCreate);})))(D);return [...Array.isArray(K)?K:[K]].sort((w,F)=>w.$op==="create"&&F.$op!=="create"?-1:w.$op!=="create"&&F.$op==="create"?1:0)};var Mn=(e,t)=>produce(e,n=>ut(t,n)),ut=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(o=>ut(e,o,r));return}let n=Y(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([o])=>{o.startsWith("$")||Ho(e,t,o,n);});},Ho=(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;ut(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`);ut(e,o,u.thing);}};var Qn=async(e,t,r,n)=>{let o=Array.isArray(e)?e:[e],i=o.map(u=>vt(u,!0)),s=(await ze(i,t,r,n)).bql.res;return o.map((u,$)=>{let c=Y(t,u.$thing);return Dn({mut:u,node:s[$],schema:t,thing:c})})},Rn=new Set(["$op","$bzId","$parentKey"]),Jo=new Set(["$relation","$entity","$id",...Rn]),vt=(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(Rn.has(o)||Jo.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,...vt(i[0],!1)}):isObject(i)&&(r[o]={$path:o,...vt(i,!1)});}return n.$fields=Object.values(r),n},Dn=e=>{let{mut:t,node:r,schema:n,thing:o}=e,i=An(o),a=vo(r);if(Array.isArray(t))return t.map(u=>{let $=a[u.$id];return $?wn({mut:u,node:$,schema:n,thing:o,...i}):u});let s=a[t.$id];return wn({mut:t,node:s,schema:n,thing:o,...i})},wn=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=In({$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]=Dn({mut:p,schema:n,node:r[l],thing:y});}return d},In=e=>{let{$fields:t,node:r,schema:n,thing:o,dataFieldMap:i,linkFieldMap:a,roleFieldMap:s}=e,u=t||Yo(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(Sn):Sn(p));return}let y=Y(n,f),m=An(y);$[l]=Array.isArray(p)?p.map(E=>Ln({...m,$fields:c.$fields,value:E,schema:n,thing:y})):Ln({...m,$fields:c.$fields,value:p,schema:n,thing:y});}),$},Yo=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},Sn=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},Ln=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 In({...e,node:t})},An=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}},vo=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 Gt=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 On=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 F=f.dataFields?.find(M=>M.path===C);if(!F?.path)return "";let S=F.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(F.contentType))return `has ${S} '${w}'`;if(["NUMBER","BOOLEAN"].includes(F.contentType))return `has ${S} ${w}`;if(F.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(F.contentType==="FLEX"){let M=`bza${De()}`,I=isArray(w)?w.map(k=>Gt(k)):Gt(w);if(Array.isArray(I))throw new Error("Array in FLEX fields not supported yet");return `has ${S} $${M}; $${M} '${M}' isa ${S}, has ${I.type}Attribute ${I.value}`}throw new Error(`Unsupported contentType ${F.contentType}`)}).filter(C=>C),Q=`${h}-atts`,D=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 b=w.dbPath;return `{${Q} isa ${b};}`}).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(!D.length)throw new Error("update without attributes");return `${h} isa ${[E,...j].filter(C=>C).join(",")}, has ${Q};
120
- ${D.join(" or ")};`}return ""},v=()=>p==="update"||p==="link"||p==="match"?`${h} isa ${[E,...j].filter(C=>C).join(",")};`:"";if(Ze(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"&&D.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,F)=>[w,F.dbConnector?.path||w]):{},g=listify(l,(w,F)=>{if(!E.includes(w))return null;if(!("roles"in h))throw new Error("This should have roles! ");let b=B[w];return Array.isArray(F)?F.map(S=>({path:b,id:S})):{path:b,id:F}}).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(" , ")} )`:"",D=l[Re];if(!D)throw new Error("[internal error] Symbol edgeType not defined");let A=Q?`${f} ${Q} ${D==="linkField"||p==="delete"||p==="unlink"?`isa ${m}`:""}`:"",j=`${f} ${D==="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:D,insertion:A,deletion:j}=h(g);return shake({preDeletionBatch:L,insertionMatch:Q,deletionMatch:D,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 kn=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 Pn=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 lt(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 ts=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),rs=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),ns=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),Zt=x("error","error",N((e,t)=>({...e,error:t.error}))),is=ye("buildMutation",{buildMutation:W(async e=>On(e.bql.things,e.bql.edges,e.schema),x("done","runMutation",N(rs)),Zt),runMutation:W(async e=>Pn(e.tql.mutation,e.handles,e.config),x("done","parseMutation",N(ns)),Zt),parseMutation:W(async e=>kn(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),x("done","success",N(ts)),Zt),success:ie(),error:ie()},e=>e),os=async e=>new Promise((t,r)=>{fe(is,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),qn=async(e,t,r,n,o,i,a)=>os({bql:{raw:e,enriched:t,things:r,edges:n,flat:{things:[],edges:[],arcs:[]},res:[]},tql:{},schema:o,config:i,handles:a,error:null});var Nn=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=(a[Ee]?.$things||[u]).map(X),E=ae(a,F=>F.startsWith("$")),B=ae(a,F=>!F.startsWith("$")),g=JSON.stringify(B),L=Object.entries(E).map(([F,b])=>F=="$tempId"?`'$tempId': '_:${b}'`:`'${F}': '${b}'`).join(","),Q=a[Ye],D=h.filter(F=>!f.includes(F)).map(F=>{let b=p.dataFields?.find(M=>M.path===F||M.dbPath===F);if(!b)throw new Error(`Data field schema not found for ${F}`);let S=a[F];return S===null?`${F} = NONE`:`${F} = ${He(S,b.contentType)}`}).filter(Boolean),A=`$\u27E8${l||$}\u27E9`,j=Q?.bzId?`array::flatten($\u27E8${Q.bzId}\u27E9.\u27E8${Q.edgeField}\u27E9).filter(|$v| $v != NONE).len`:y?isArray(y)?m.flatMap(F=>y.map(b=>`${F}:\u27E8${b}\u27E9`)).join(", "):m.map(F=>`${F}:\u27E8${y}\u27E9`).join(", "):m.join(", "),K=(()=>{if(Q?.bzId){let F=`array::flatten($\u27E8${Q.bzId}\u27E9.\u27E8${Q.edgeField}\u27E9).filter(|$v| $v != NONE)`;return y?isArray(y)?`${F}[? $this.id() IN [${y.map(b=>`'${b}'`).join(", ")}] ]`:`${F}[? $this.id() IN ['${y}'] ]`:F}else return y?isArray(y)?m.flatMap(F=>y.map(b=>`${F}:\u27E8${b}\u27E9`)).join(", "):m.map(F=>`${F}:\u27E8${y}\u27E9`).join(", "):m.join(", ")})(),me=s?`WHERE ${$e(he(s,u,t))}`:"",v=D.length>0?`SET ${D.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 l?"":`LET ${A} = (SELECT VALUE id FROM ${K} ${me});`;if(a.$op==="create"){if(isArray(y))throw new Error("Cannot create multiple things at once");let F=X(u);return `LET ${A} = (CREATE ONLY ${F}:\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 xn=async(e,t)=>{let r=`
119
+ `)},at=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}`,Lo=e=>typeof e=="string"?{field:e,desc:!1}:{...e,desc:e.desc??!1},zt=e=>{let{$var:t,$thing:r,schema:n,$sort:o,depth:i}=e,a=Y(n,r),s=[],u=[];if(o?.forEach($=>{let c=Lo($),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(T("{",i)),s.push(T(`$${t} has ${d.dbPath} $${l}_1;`,i+1)),s.push(T("not {",i+1)),s.push(T(`$${t} has ${d.dbPath} $${l}_2;`,i+2)),s.push(T(`$${l}_2 < $${l}_1;`,i+2)),s.push(T("};",i+1)),s.push(T(`?${l}_ = $${l}_1;`,i+1)),s.push(T("} or {",i)),s.push(T(`not { $${t} has ${d.dbPath} $${l}_1; };`,i+1)),s.push(T(`?${l}_ = "~";`,i+1)),s.push(T("};",i)),s.push(T(`?${l} = ?${l}_;`,i));let p=c.desc?"desc":"asc";u.push(`?${l} ${p}`);}),s.length!==0)return {match:s.join(""),sort:T(`sort ${u.join(", ")};`,i)}};var En=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 Ro(a,u,$,n,o)})},Ro=(e,t,r,n,o)=>e.length===0?null:r.$filterByUnique?gn(e[0],t,n,o):e.map(i=>gn(i,t,n,o)),gn=(e,t,r,n)=>{let{dataFields:o,currentSchema:i,linkFields:a,roleFields:s,schemaValue:u}=Ut(e,r),$=Wt(o,i,n),c=Ht(a,r,n),d=Vt(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))):$}},Ut=(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}},Wt=(e,t,r)=>{let{$metaData:n}=e,{as:o}=Do(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])},Vt=(e,t,r)=>{let n={};return e.forEach(o=>{let{$roleFields:i,$metaData:a,$cardinality:s}=o,{as:u,justId:$,idNotIncluded:c,filterByUnique:d}=Bn(a);if(u===null)return;let l=i.map(p=>{let{dataFields:h,currentSchema:f,linkFields:y,roleFields:m,schemaValue:E}=Ut(p,t),B=Wt(h,f,r);if($==="T")return B.id;{let g=Ht(y,t,r),L=Vt(m,t,r),Q={...B};return c==="true"&&f?.idFields?.forEach(D=>delete Q[D]),{...Q,...g,...L,...E}}});l.length>0?n[u]=s==="MANY"&&d==="false"?l:l[0]:r.query?.returnNulls&&(n[u]=null);}),n},Ht=(e,t,r)=>{let n={};return e.forEach(o=>{let{$linkFields:i,$metaData:a,$cardinality:s}=o,{as:u,justId:$,idNotIncluded:c,filterByUnique:d}=Bn(a);if(u===null)return;let l=i.map(p=>{let{dataFields:h,currentSchema:f,linkFields:y,roleFields:m,schemaValue:E}=Ut(p,t),B=Wt(h,f,r);if($==="T")return B.id;{let g=Ht(y,t,r),L=Vt(m,t,r),Q={...B};return c==="true"&&f.idFields?.forEach(D=>delete Q[D]),{...Q,...g,...L,...E}}});n[u]=l.length>0?s==="MANY"&&d==="false"?l:l[0]:r.query?.returnNulls?null:void 0;}),n},Bn=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}},Do=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 lt=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 Fn=async e=>{let{tqlRequest:t,dbHandles:r,config:n}=e,o=new TypeDBOptions;o.infer=!0;let{session:i}=await lt(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 Po=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,qo=(e,t)=>t.data?{...e,tql:{...e.tql,queries:t.data}}:e,No=(e,t)=>t.data?{...e,tql:{...e.tql,res:t.data}}:e,Kt=x("error","error",N((e,t)=>({...e,error:t.error}))),xo=ye("build",{build:W(async e=>yn({queries:e.bql.queries,schema:e.schema}),x("done","run",N(qo)),Kt),run:W(async e=>Fn({dbHandles:e.handles,tqlRequest:ue(e.tql.queries),config:e.config}),x("done","parse",N(No)),Kt),parse:W(async e=>En({rawBqlRequest:e.bql.raw,enrichedBqlQuery:e.bql.queries,schema:e.schema,config:e.config,rawTqlRes:ue(e.tql.res)}),x("done","success",N(Po)),Kt),success:ie(),error:ie()},e=>e),jo=async e=>new Promise((t,r)=>{fe(xo,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),bn=async(e,t,r,n,o)=>jo({bql:{raw:e,queries:t},tql:{},schema:r,config:n,handles:o,error:null});var _o=(e,t)=>t.data?{...e,bql:{...e.bql,queries:t.data}}:e,Jt=(e,t)=>t.data?{...e,bql:{...e.bql,res:t.data}}:e,ct=x("error","error",N((e,t)=>({...e,error:t.error}))),zo=ye("enrich",{enrich:W(async e=>kr(e.bql.raw,e.schema),x("done","adapter",N(_o)),ct),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 bn(s.rawBql,s.bqlQueries,e.schema,e.config,e.handles);if(s.db==="surrealDB")return fn(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)},x("done","postHooks",N(Jt)),ct),postHooks:W(async e=>nn(e.schema,ue(e.bql.queries),ue(e.bql.res)),x("done","clean",N(Jt)),ct),clean:W(async e=>rn(e.config,ue(e.bql.res)),x("done","success",N(Jt)),ct),success:ie(),error:ie()},e=>e),Uo=async e=>new Promise((t,r)=>{fe(zo,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),ze=async(e,t,r,n)=>Uo({bql:{raw:e},schema:t,config:r,handles:n,error:null});var Yt="___",Wo=Symbol.for("grandChildOfCreate"),Tn=async(e,t,r,n)=>{let o=(w,F)=>Object.keys(w).filter(b=>!b.startsWith("$")&&w[b]!==void 0?F?!q(t,w).dataFields?.find(M=>M.path===b):!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:F,value:b})=>{w&&F&&!F.includes("$")&&isObject(w)?(Array.isArray(w[F])?w[F]:[w[F]]).forEach(M=>{if(isObject(M)){if(w.$op!=="create")i.includes(M.$op)||i.push(M.$op);else if(M.$op==="delete"||M.$op==="unlink")throw new Error(`Cannot ${M.$op} under a create`)}}):!w&&isObject(b)&&(i.includes(b.$op)||i.push(b.$op));}),!i.includes("delete")&&!i.includes("unlink")&&!i.includes("replace")&&!i.includes("update")&&!i.includes("link"))return;let s=(w=>{let F=(b,S)=>{let M=[],I={},k=["$op","$bzId","$parentKey"],R=["$relation","$entity","$id",...k];for(let z in b)if(!k.includes(z)&&!(R.includes(z)&&!S))if(!z.includes("$")&&(isObject(b[z])||Array.isArray(b[z]))){let J=b[z];if(Array.isArray(J)&&J.length>0)J.forEach($e=>{let Qe={$path:z,...F($e),...$e.$filter&&{$as:$e.$bzId}};M.find(H=>H.$path===Qe.$path&&!H.$filter)||(M=[...M,Qe]);});else {let $e={$path:z,...F(J),...!J.$filter&&{$as:J.$bzId}};M=[...M,$e];}}else I[z]=b[z];return {...I,$fields:M}};return w.map(b=>F(b,!0))})(Array.isArray(e)?e:[e]),$=(await ze(s,t,{...r,query:{...r.query,returnNulls:!0}},n)).bql.res,c=(w,F)=>{let b=w.$id||w.id||w.$bzId;if(w.$objectPath){let{$objectPath:S}=w,M=S?.beforePath||"root",I=Array.isArray(S.ids)?`[${S.ids}]`:S.ids;return {beforePath:`${M}.${I}___${S.key}`,ids:b,key:F}}else return {beforePath:"root",ids:b,key:F}},d=(w,F)=>{let b=w?.beforePath||"root";if(typeof b!="string")throw new Error("[PQ]objectPathToKey: root is not a string");let S=F||(Array.isArray(w?.ids)?`[${w?.ids}]`:w?.ids);return `${b}.${S}___${w?.key}`},l=w=>{if(w.includes("[")&&w.includes("]")){let[F,b,S]=w.split(/[[\]]/);return b.split(",").map(I=>`${F}${I}${S}`)}else return [w]},p={};(w=>produce(w,F=>traverse(F,({key:b,parent:S})=>{if(S&&b&&S.$id&&!b.includes("$")){let M=c(S,b),I=d(M);if(Array.isArray(S[b])){let k=[];S[b].forEach(R=>{isObject(R)?(R.$objectPath=M,k.push(R.$id.toString())):R&&k.push(R.toString());}),p[I]={$objectPath:M,$ids:k};}else {let k=S[b];isObject(k)?(p[I]={$objectPath:M,$ids:[k.$id.toString()]},k.$objectPath=M):k?p[I]={$objectPath:M,$ids:[k.toString()]}:k===null&&(p[I]=null);}}})))($||{});let f=w=>produce(w,F=>traverse(F,({key:b,value:S,parent:M})=>{M&&b&&!b.includes("$")&&(Array.isArray(S)||isObject(S))&&!Array.isArray(M)&&(Array.isArray(M[b])?M[b].forEach(I=>{typeof I!="string"&&(I.$objectPath=c(M,b),I.$parentIsCreate=M.$op==="create",I[Wo]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")]);}):isObject(M[b])&&(M[b].$parentIsCreate=M.$op==="create",M[b][Symbol.for("grandChildOfCreate")]=M.$parentIsCreate||M[Symbol.for("grandChildOfCreate")],M[b].$objectPath=c(M,b)));})),y=f(e),m=w=>{let F=[];return w.forEach(S=>{if(!S.$id&&!S.id&&!S.$tempId)if(S.$filter){let M=d({...S.$objectPath,key:S.$bzId}),I=p[M];I&&(Array.isArray(I.$ids)?I.$ids:[I.$ids]).forEach(R=>{let z={...S,$id:R,$bzId:`T4_${v4()}`,$filterBzId:S.$bzId};F.push(z);});}else {let M=d(S.$objectPath),I=p[M];I?I?.$ids?.forEach(k=>{let R={...S,$id:k,$bzId:`T4_${v4()}`};F.push(R);}):F.push(S);}else F.push(S);}),F.map(S=>{let M={...S};return o(M,!0).forEach(I=>{let k=Array.isArray(M[I])?M[I]:[M[I]],R=m(k);M[I]=R;}),M})},E=m(Array.isArray(y)?y:[y]),B=f(E),L=(w=>{let F=b=>{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:M,operationWithoutMultiples:I,otherOps:k}=S(b),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 M.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}${Yt}${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}${Yt}${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}${Yt}${G}`,se=p[Z]?.$ids||[],Xn=P[G].find(ke=>!ke.$id),rr=[...se.map(ke=>({...Xn,$id:ke,$objectPath:{beforePath:P.$objectPath.beforePath,ids:ke,key:G}})),...P[G].filter(ke=>ke.$id)];rr.length>0&&(P[G]=rr);}),V.push({...P,$id:U,$bzId:P.$tempId||`PQ3_${v4()}`}));});}else V.push(P);}),V.forEach(P=>{z.push(P);});}),[...z,...I,...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]],_=F(P);te[V]=_;}),te})};return F(w)})(Array.isArray(B)?B:[B]),Q=w=>w.map(F=>{let b=o(F,!0),S={...F};return b.forEach(M=>{let I=Array.isArray(F[M])?F[M]:[F[M]],k=[],R=[],z=[],J={},$e=Ft(t,F,M);I.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"&&$e==="ONE"&&O.id?(J=O,Array.isArray(O.id)?z=[...R,...O.id]:z.push(O.id)):k.push(O);});let Qe=d(J.$objectPath),te=l(Qe).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[M]=Q(k);}),S}),D=f(Q(f(L)));(w=>produce(w,F=>traverse(F,b=>{let{key:S,value:M,parent:I}=b;S&&I&&!S?.includes("$")&&(Array.isArray(M)||isObject(M))&&!Array.isArray(I)&&(Array.isArray(M)?M:[M]).forEach(R=>{let z=R.$filter?{...R.$objectPath,key:R.$filterBzId}:R.$objectPath,J=d(z),$e=p[J],Qe=(V,P)=>V.every(_=>P.includes(_)),H=R.$id?Array.isArray(R.$id)?Qe(R.$id,$e&&$e.$ids?$e.$ids:[]):$e?.$ids?.includes(R.$id):$e,te=Ft(t,I,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:"${I.$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:"${I.$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:"${I.$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:"${I.$id}"`);break;}});})))(D);let K=(w=>produce(w,F=>traverse(F,b=>{let{value:S,meta:M}=b;isObject(S)&&(S[Symbol.for("path")]=M.nodePath,delete S.$objectPath,delete S.$parentIsCreate);})))(D);return [...Array.isArray(K)?K:[K]].sort((w,F)=>w.$op==="create"&&F.$op!=="create"?-1:w.$op!=="create"&&F.$op==="create"?1:0)};var Mn=(e,t)=>produce(e,n=>ut(t,n)),ut=(e,t,r)=>{if(typeof t=="string")return;if(Array.isArray(t)){t.forEach(o=>ut(e,o,r));return}let n=Y(e,r||t.$entity||t.$relation||t.$thing);Object.entries(t).forEach(([o])=>{o.startsWith("$")||Ho(e,t,o,n);});},Ho=(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;ut(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`);ut(e,o,u.thing);}};var Qn=async(e,t,r,n)=>{let o=Array.isArray(e)?e:[e],i=o.map(u=>vt(u,!0)),s=(await ze(i,t,r,n)).bql.res;return o.map((u,$)=>{let c=Y(t,u.$thing);return Dn({mut:u,node:s[$],schema:t,thing:c})})},Rn=new Set(["$op","$bzId","$parentKey"]),Jo=new Set(["$relation","$entity","$id",...Rn]),vt=(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(Rn.has(o)||Jo.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,...vt(i[0],!1)}):isObject(i)&&(r[o]={$path:o,...vt(i,!1)});}return n.$fields=Object.values(r),n},Dn=e=>{let{mut:t,node:r,schema:n,thing:o}=e,i=An(o),a=vo(r);if(Array.isArray(t))return t.map(u=>{let $=a[u.$id];return $?wn({mut:u,node:$,schema:n,thing:o,...i}):u});let s=a[t.$id];return wn({mut:t,node:s,schema:n,thing:o,...i})},wn=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=In({$fields:t.$fields,node:r,schema:n,thing:o,dataFieldMap:i,linkFieldMap:a,roleFieldMap:s}),d={...$,[Pe]: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]=Dn({mut:p,schema:n,node:r[l],thing:y});}return d},In=e=>{let{$fields:t,node:r,schema:n,thing:o,dataFieldMap:i,linkFieldMap:a,roleFieldMap:s}=e,u=t||Yo(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(Sn):Sn(p));return}let y=Y(n,f),m=An(y);$[l]=Array.isArray(p)?p.map(E=>Ln({...m,$fields:c.$fields,value:E,schema:n,thing:y})):Ln({...m,$fields:c.$fields,value:p,schema:n,thing:y});}),$},Yo=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},Sn=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},Ln=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 In({...e,node:t})},An=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}},vo=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 Gt=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 On=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 F=f.dataFields?.find(M=>M.path===C);if(!F?.path)return "";let S=F.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(F.contentType))return `has ${S} '${w}'`;if(["NUMBER","BOOLEAN"].includes(F.contentType))return `has ${S} ${w}`;if(F.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(F.contentType==="FLEX"){let M=`bza${Ie()}`,I=isArray(w)?w.map(k=>Gt(k)):Gt(w);if(Array.isArray(I))throw new Error("Array in FLEX fields not supported yet");return `has ${S} $${M}; $${M} '${M}' isa ${S}, has ${I.type}Attribute ${I.value}`}throw new Error(`Unsupported contentType ${F.contentType}`)}).filter(C=>C),Q=`${h}-atts`,D=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 b=w.dbPath;return `{${Q} isa ${b};}`}).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(!D.length)throw new Error("update without attributes");return `${h} isa ${[E,...j].filter(C=>C).join(",")}, has ${Q};
120
+ ${D.join(" or ")};`}return ""},v=()=>p==="update"||p==="link"||p==="match"?`${h} isa ${[E,...j].filter(C=>C).join(",")};`:"";if(Ze(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"&&D.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,F)=>[w,F.dbConnector?.path||w]):{},g=listify(l,(w,F)=>{if(!E.includes(w))return null;if(!("roles"in h))throw new Error("This should have roles! ");let b=B[w];return Array.isArray(F)?F.map(S=>({path:b,id:S})):{path:b,id:F}}).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(" , ")} )`:"",D=l[De];if(!D)throw new Error("[internal error] Symbol edgeType not defined");let A=Q?`${f} ${Q} ${D==="linkField"||p==="delete"||p==="unlink"?`isa ${m}`:""}`:"",j=`${f} ${D==="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:D,insertion:A,deletion:j}=h(g);return shake({preDeletionBatch:L,insertionMatch:Q,deletionMatch:D,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 kn=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 Pn=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 lt(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 ts=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),rs=(e,t)=>({...e,tql:{...e.tql,mutation:t.data}}),ns=(e,t)=>({...e,tql:{...e.tql,res:t.data}}),Zt=x("error","error",N((e,t)=>({...e,error:t.error}))),is=ye("buildMutation",{buildMutation:W(async e=>On(e.bql.things,e.bql.edges,e.schema),x("done","runMutation",N(rs)),Zt),runMutation:W(async e=>Pn(e.tql.mutation,e.handles,e.config),x("done","parseMutation",N(ns)),Zt),parseMutation:W(async e=>kn(e.tql.res,e.bql.things,e.bql.edges,e.schema,e.config),x("done","success",N(ts)),Zt),success:ie(),error:ie()},e=>e),os=async e=>new Promise((t,r)=>{fe(is,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),qn=async(e,t,r,n,o,i,a)=>os({bql:{raw:e,enriched:t,things:r,edges:n,flat:{things:[],edges:[],arcs:[]},res:[]},tql:{},schema:o,config:i,handles:a,error:null});var Nn=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=(a[Ee]?.$things||[u]).map(X),E=ae(a,F=>F.startsWith("$")),B=ae(a,F=>!F.startsWith("$")),g=JSON.stringify(B),L=Object.entries(E).map(([F,b])=>F=="$tempId"?`'$tempId': '_:${b}'`:`'${F}': '${b}'`).join(","),Q=a[Ye],D=h.filter(F=>!f.includes(F)).map(F=>{let b=p.dataFields?.find(M=>M.path===F||M.dbPath===F);if(!b)throw new Error(`Data field schema not found for ${F}`);let S=a[F];return S===null?`${F} = NONE`:`${F} = ${He(S,b.contentType)}`}).filter(Boolean),A=`$\u27E8${l||$}\u27E9`,j=Q?.bzId?`array::flatten($\u27E8${Q.bzId}\u27E9.\u27E8${Q.edgeField}\u27E9).filter(|$v| $v != NONE).len`:y?isArray(y)?m.flatMap(F=>y.map(b=>`${F}:\u27E8${b}\u27E9`)).join(", "):m.map(F=>`${F}:\u27E8${y}\u27E9`).join(", "):!0,K=(()=>{if(Q?.bzId){let F=`array::flatten($\u27E8${Q.bzId}\u27E9.\u27E8${Q.edgeField}\u27E9).filter(|$v| $v != NONE)`;return y?isArray(y)?`${F}[? $this.id() IN [${y.map(b=>`'${b}'`).join(", ")}] ]`:`${F}[? $this.id() IN ['${y}'] ]`:F}else return y?isArray(y)?m.flatMap(F=>y.map(b=>`${F}:\u27E8${b}\u27E9`)).join(", "):m.map(F=>`${F}:\u27E8${y}\u27E9`).join(", "):m.join(", ")})(),me=s?`WHERE ${pe(he(s,u,t))}`:"",v=D.length>0?`SET ${D.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 l?"":`LET ${A} = (SELECT VALUE id FROM ${K} ${me});`;if(a.$op==="create"){if(isArray(y))throw new Error("Cannot create multiple things at once");let F=X(u);return `LET ${A} = (CREATE ONLY ${F}:\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 xn=async(e,t)=>{let r=`
121
121
  BEGIN TRANSACTION;
122
122
  ${t.join(";")};
123
123
  LET $DELTAS = SELECT * FROM Delta;
@@ -127,12 +127,12 @@ limit ${$};`),d.join(`
127
127
  LET $LOGS = SELECT * FROM LOG;
128
128
  RETURN $LOGS;
129
129
  COMMIT TRANSACTION;
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 Un=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: ${JSON.stringify(i)}`);return _n(i,r)});if(!isObject(o)||!("meta"in o))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(o)}`);return _n(o,r)})},_n=(e,t)=>{let r=mapEntries(e.after||{},(i,a)=>[i,i==="id"?a.id: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 as=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),ls=(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}}},cs=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},er=x("error","error",N((e,t)=>({...e,error:t.error}))),ds=ye("buildMutation",{buildMutation:W(async e=>Nn(e.bql.flat,e.schema),x("done","runMutation",N(ls)),er),runMutation:W(async e=>xn(e.handles.surrealDB?.get(e.handles.surrealDB?.keys().next().value)?.client,e.surql.mutations),x("done","parseMutation",N(cs)),er),parseMutation:W(async e=>Un({res:e.surql.res,config:e.config,schema:e.schema}),x("done","success",N(as)),er),success:ie(),error:ie()},e=>e),us=async e=>new Promise((t,r)=>{fe(ds,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Vn=async(e,t,r,n,o,i)=>us({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:n,config:o,handles:i,error:null});var Kn=(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"?{}:{[Ye]: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 D=ae(Q,A=>isSymbol(A)||A.startsWith("$"));r.edges.push({...D,[m.plays]:u,$op:B});});}),m.target==="role"&&Object.entries({create:["link","create"],delete:["unlink","delete"],replace:["replace"]}).forEach(([g,L])=>{E.filter(D=>L.includes(D.$op)).forEach(D=>{let A={$thing:m.relation,$thingType:"relation",$bzId:`arc_${D.$bzId}`,[m.plays]:u,[m.oppositeLinkFieldsPlayedBy[0].plays]:D.$bzId,$op:g};r.arcs.push(A);});});});};return (Array.isArray(e)?e:[e]).forEach(i=>n(i)),r};var Jn=ie,Ue=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,hs=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),ps=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),$s=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),fs=async e=>Object.keys(e.bql.enriched).length?St(e.bql.enriched,e.schema,e.config):St(e.bql.raw,e.schema,e.config),ms=async e=>Tn(e.bql.enriched,e.schema,e.config,e.handles),ys=async e=>Qn(e.bql.enriched,e.schema,e.config,e.handles),gs=async e=>Nr(e.bql.enriched,e.schema),Es=async e=>Kn(e.bql.enriched,e.schema),Bs=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}.`)},Fs=e=>Ne(e.bql.enriched),Ce=x("error","error",N((e,t)=>({...e,error:t.error}))),bs=ye("stringify",{stringify:W(async e=>Mn(e.bql.raw,e.schema),x("done","enrich",N(Ue)),Ce),enrich:W(fs,x("done","preQuery",Lt(Bs),N(Ue)),x("done","parseBQL",N(Ue)),Ce),preQuery:W(ms,x("done","preHookDependencies",Lt(Fs),N(Ue)),x("done","parseBQL",N(Ue)),Ce),preHookDependencies:W(ys,x("done","enrich",N(Ue)),Ce),parseBQL:W(gs,x("done","flattenBQL",N(hs)),Ce),flattenBQL:W(Es,x("done","adapter",N(ps)),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 qn(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return Vn(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},x("done","success",N($s)),Ce),success:Jn(),error:Jn()},e=>e),Ts=async e=>new Promise((t,r)=>{fe(bs,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),Yn=async(e,t,r,n)=>Ts({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[]},res:[]},schema:t,config:r,handles:n,depthLevel:0,error:null});enableMapSet();var tr=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=yr(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 cr(this.config,this.schema,this.dbHandles)};query=async(t,r)=>{await this.#e();let n={...this.config,query:{...ft.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:{...ft.mutation,...this.config.mutation,...r}},[o,i]=await tryit(Yn)(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();});}},Fu=tr;//! 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 Un=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: ${JSON.stringify(i)}`);return _n(i,r)});if(!isObject(o)||!("meta"in o))throw new Error(`Internal error: Invalid response from DB: ${JSON.stringify(o)}`);return _n(o,r)})},_n=(e,t)=>{let r=mapEntries(e.after||{},(i,a)=>[i,i==="id"?a.id: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 as=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),ls=(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}}},cs=(e,t)=>{if(!t.data||!isArray(t.data))throw new Error("Invalid event data");return {...e,surql:{...e.surql,res:t.data}}},er=x("error","error",N((e,t)=>({...e,error:t.error}))),ds=ye("buildMutation",{buildMutation:W(async e=>Nn(e.bql.flat,e.schema),x("done","runMutation",N(ls)),er),runMutation:W(async e=>xn(e.handles.surrealDB?.get(e.handles.surrealDB?.keys().next().value)?.client,e.surql.mutations),x("done","parseMutation",N(cs)),er),parseMutation:W(async e=>Un({res:e.surql.res,config:e.config,schema:e.schema}),x("done","success",N(as)),er),success:ie(),error:ie()},e=>e),us=async e=>new Promise((t,r)=>{fe(ds,n=>{n.machine.state.name==="success"&&t(n.context.bql.res),n.machine.state.name==="error"&&r(n.context.error);},e);}),Vn=async(e,t,r,n,o,i)=>us({bql:{raw:e,enriched:t,flat:r,things:[],edges:[],res:[]},surql:{mutations:[],res:[]},schema:n,config:o,handles:i,error:null});var Kn=(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"?{}:{[Ye]: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 D=ae(Q,A=>isSymbol(A)||A.startsWith("$"));r.edges.push({...D,[m.plays]:u,$op:B});});}),m.target==="role"&&Object.entries({create:["link","create"],delete:["unlink","delete"],replace:["replace"]}).forEach(([g,L])=>{E.filter(D=>L.includes(D.$op)).forEach(D=>{let A={$thing:m.relation,$thingType:"relation",$bzId:`arc_${D.$bzId}`,[m.plays]:u,[m.oppositeLinkFieldsPlayedBy[0].plays]:D.$bzId,$op:g};r.arcs.push(A);});});});};return (Array.isArray(e)?e:[e]).forEach(i=>n(i)),r};var Jn=ie,Ue=(e,t)=>t.data?{...e,bql:{...e.bql,enriched:t.data}}:e,hs=(e,t)=>({...e,bql:{...e.bql,things:t.data.mergedThings,edges:t.data.mergedEdges}}),ps=(e,t)=>({...e,bql:{...e.bql,flat:t.data||"test"}}),$s=(e,t)=>({...e,bql:{...e.bql,res:t.data}}),fs=async e=>Object.keys(e.bql.enriched).length?Dt(e.bql.enriched,e.schema,e.config):Dt(e.bql.raw,e.schema,e.config),ms=async e=>Tn(e.bql.enriched,e.schema,e.config,e.handles),ys=async e=>Qn(e.bql.enriched,e.schema,e.config,e.handles),gs=async e=>jr(e.bql.enriched,e.schema),Es=async e=>Kn(e.bql.enriched,e.schema),Bs=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}.`)},Fs=e=>xe(e.bql.enriched),Oe=x("error","error",N((e,t)=>({...e,error:t.error}))),bs=ye("stringify",{stringify:W(async e=>Mn(e.bql.raw,e.schema),x("done","enrich",N(Ue)),Oe),enrich:W(fs,x("done","preQuery",It(Bs),N(Ue)),x("done","parseBQL",N(Ue)),Oe),preQuery:W(ms,x("done","preHookDependencies",It(Fs),N(Ue)),x("done","parseBQL",N(Ue)),Oe),preHookDependencies:W(ys,x("done","enrich",N(Ue)),Oe),parseBQL:W(gs,x("done","flattenBQL",N(hs)),Oe),flattenBQL:W(Es,x("done","adapter",N(ps)),Oe),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 qn(e.bql.raw,e.bql.enriched,e.bql.things,e.bql.edges,e.schema,e.config,e.handles);if(r==="surrealDB")return Vn(e.bql.raw,e.bql.enriched,e.bql.flat,e.schema,e.config,e.handles);throw new Error(`Unsupported provider ${r}.`)},x("done","success",N($s)),Oe),success:Jn(),error:Jn()},e=>e),Ts=async e=>new Promise((t,r)=>{fe(bs,n=>{n.machine.state.name==="success"&&t(n.context),n.machine.state.name==="error"&&r(n.context);},e);}),Yn=async(e,t,r,n)=>Ts({bql:{raw:e,enriched:{},things:[],edges:[],flat:{things:[],edges:[],arcs:[]},res:[]},schema:t,config:r,handles:n,depthLevel:0,error:null});enableMapSet();var tr=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=yr(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 cr(this.config,this.schema,this.dbHandles)};query=async(t,r)=>{await this.#e();let n={...this.config,query:{...ft.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:{...ft.mutation,...this.config.mutation,...r}},[o,i]=await tryit(Yn)(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();});}},bu=tr;//! Todo: delete when this works with the new $thing and $thingType fields
131
131
  //! Todo: Sandbox the function in nodeCompute() instead of the existing fieldCompute()
132
132
  //! Todo: Sandbox the function in computeFunction()
133
133
  //! reads all the insertions and gets the first match. This means each id must be unique
134
134
  //!old
135
135
 
136
- export { Fu as default };
136
+ export { bu as default };
137
137
  //# sourceMappingURL=out.js.map
138
138
  //# sourceMappingURL=index.mjs.map