@blitznocode/blitz-orm 0.11.4 → 0.11.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +4 -4
- package/dist/index.mjs.map +1 -1
- package/dist/magic-string.es-Y46ICLQT.mjs +17 -0
- package/dist/magic-string.es-Y46ICLQT.mjs.map +1 -0
- package/package.json +18 -18
- package/dist/magic-string.es-JUEGH7DX.mjs +0 -17
- package/dist/magic-string.es-JUEGH7DX.mjs.map +0 -1
package/dist/index.d.mts
CHANGED
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { isObject, isArray, isDate, tryit, parallel, shake, clone, mapEntries, listify, pick, isSymbol } from 'radash';
|
|
2
2
|
import { TypeDBOptions, TransactionType, SessionType, TypeDB, TypeDBCredential } from 'typedb-driver';
|
|
3
|
-
import { Surreal } from 'surrealdb
|
|
3
|
+
import { Surreal } from 'surrealdb';
|
|
4
4
|
import { enableMapSet, produce, isDraft, current } from 'immer';
|
|
5
5
|
import { traverse, getNodeByPath } from 'object-traversal';
|
|
6
6
|
import { nanoid, customAlphabet } from 'nanoid';
|
|
@@ -100,7 +100,7 @@ ${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"),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(`
|
|
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 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",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
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
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(`
|
|
@@ -116,7 +116,7 @@ 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=>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};
|
|
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=(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
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(";")};
|
|
@@ -134,5 +134,5 @@ limit ${$};`),d.join(`
|
|
|
134
134
|
//!old
|
|
135
135
|
|
|
136
136
|
export { bu as default };
|
|
137
|
-
//# sourceMappingURL=
|
|
137
|
+
//# sourceMappingURL=index.mjs.map
|
|
138
138
|
//# sourceMappingURL=index.mjs.map
|