@blitznocode/blitz-orm 0.10.27 → 0.10.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -33,7 +33,7 @@ var ct={query:{noMetadata:!1,simplifiedLinks:!0,debugger:!1,returnNulls:!1},muta
33
33
  `;else if(g.contentType==="NUMBER")B+=` value long;
34
34
  `;else throw new Error(`Conversion of borm schema to TypeDB schema for data type "${g.contentType}" is not implemented`)}),`${B}
35
35
 
36
- ${y}`})(),n=e.dbConnectors[0].id,l=r.typeDB.get(n)?.session,s=r.typeDB.get(n)?.client;if(!l){console.log("Session Status: ","NO SESSION");return}await l.close();let[{dbName:h}]=e.dbConnectors;await(await s.databases.get(h)).delete(),await s.databases.create(h);let c=await s.session(e.dbConnectors[0].dbName,SessionType.SCHEMA),d=await c.transaction(TransactionType.WRITE);await d.query.define(o),await d.commit(),await d.close();let a=await c.transaction(TransactionType.READ);(await(await a.query.match("match $a sub thing;")).collect()).forEach(async y=>{y.get("a");}),await a.close();};var te=Symbol.for("queryPath"),Ve=Symbol.for("stepPrint"),Se=Symbol.for("edgeType"),Be=Symbol.for("edgeSchema"),Ae=Symbol.for("dbNode"),dt=Symbol.for("isTransformed"),ie=Symbol.for("fieldSchema"),$e=Symbol.for("sharedMetadata"),me=Symbol.for("suqlMetadata");var Yt={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Gt=({linkField:e,originalRelation:t,withExtensionsSchema:r,linkMode:i})=>{if(e.isVirtual)return `$this.${e.path}.id`;let o=r.relations[e.relation].subTypes||[],n=[e.relation,...o],l=`<-\`${t}_${e.plays}\`<-(\`${n.join("`,`")}\`)`;if(e.target==="relation"){if(i==="edges")return l;if(i==="refs")return `$parent.\`${e.path}\``;throw new Error("Unsupported linkMode")}else if(e.target==="role"){let[s]=e.oppositeLinkFieldsPlayedBy,h=r.entities[s.thing]?.subTypes||r.relations[s.thing]?.subTypes||[],p=[s.thing,...h],c=`->\`${t}_${s.plays}\`->(\`${p.join("`,`")}\`)`;return i==="edges"?`${l}${c}`:i==="refs"?`$parent.\`${s.plays}\``:`${l}${c}`}else throw new Error("Unsupported linkField target")};var tr=(e,t,r)=>r?t:`${e}\xB7${t}`;var nr=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))))[0],We=(e,t)=>Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))),ir=(e,t)=>{let r=[],i=produce(e,n=>traverse(n,({key:l,value:s,meta:h})=>{if(h.depth===2&&(l&&(s.dataFields=s.dataFields?.map(p=>({...p,cardinality:p.cardinality||"ONE",dbPath:tr(l,p.path,p.shared)}))),s.extends)){if(!s.defaultDBConnector.as)throw new Error(`[Schema] ${l} is extending a thing but missing the "as" property in its defaultDBConnector. Path:${h.nodePath}`);let p=n.entities[s.extends]||n.relations[s.extends],c=[s.extends,...p.allExtends||[]];if(s.allExtends=c,c.forEach(d=>{if(n.entities[d])n.entities[d].subTypes=[l,...n.entities[d].subTypes||[]];else if(n.relations[d])n.relations[d].subTypes=[l,...n.relations[d].subTypes||[]];else throw new Error(`[Schema] ${l} is extending a thing that does not exist in the schema: ${d}`)}),s.idFields=p.idFields?Array.from(new Set((s.idFields||[]).concat(p.idFields))):s.idFields,s.dataFields=p.dataFields?(s.dataFields||[]).concat(p.dataFields.map(d=>{let a=s.extends,f=e.entities[a]||e.relations[a];for(;!f.dataFields?.find(u=>u.path===d.path);)a="extends"in f?f.extends:void 0,f=e.entities[a]||e.relations[a];return {...d,dbPath:tr(a,d.path,d.shared),[$e]:{inheritanceOrigin:d[$e]?.inheritanceOrigin||s.extends}}})):s.dataFields,"roles"in p){let d=s,a=p;if(a.roles){let f=mapEntries(a.roles,(u,$)=>[u,{...$,[$e]:{inheritanceOrigin:$[$e]?.inheritanceOrigin||s.extends}}]);d.roles={...d.roles||{},...f};}}s.linkFields=p.linkFields?(s.linkFields||[]).concat(p.linkFields.map(d=>({...d,[$e]:{inheritanceOrigin:d[$e]?.inheritanceOrigin||s.extends}}))):s.linkFields,p?.hooks?.pre&&(s.hooks=s.hooks||{},s.hooks.pre=s.hooks.pre||[],s.hooks.pre=[...p?.hooks?.pre||[],...s?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:n,value:l,meta:s})=>{if(n==="linkFields"){let p=(()=>{if(!s.nodePath)throw new Error("No path");let[d,a]=s.nodePath.split(".");return {thing:a,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),c=Array.isArray(l)?l.map(d=>({...d,...p})):[{...l,...p}];r.push(...c);}}),produce(i,n=>traverse(n,({value:l,key:s,meta:h})=>{if(h.depth===2&&l.idFields&&!l.id){l.name=s;let p=()=>{if(h.nodePath?.split(".")[0]==="entities")return "entity";if(h.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};l.thingType=p();let c=Object.keys(t).find(d=>t[d]?.get(l.defaultDBConnector.id));if(l.db=c,l.dbContext=Yt[c],l.dbProviderConfig=c==="surrealDB"?t[c]?.get(l.defaultDBConnector.id)?.providerConfig:void 0,l.computedFields=[],l.virtualFields=[],l.requiredFields=[],l.enumFields=[],l.fnValidatedFields=[],"roles"in l&&Object.entries(l.roles).forEach(([a,f])=>{f.fieldType="roleField";let u=r.filter(w=>w.relation===s&&w.plays===a)||[];f.playedBy=u,f.path=a;let $=[...new Set(u.map(w=>w.thing))];f.$things=$;let y=f[$e]?.inheritanceOrigin||l.name;$.length>1&&console.warn(`Not supported yet: Role ${a} in ${l.name} is played by multiple things: ${$.join(", ")}`);let m=$.flatMap(w=>{let S=G(e,w)?.subTypes||[];return [w,...S]}),B=()=>{if(l.dbProviderConfig.linkMode==="edges")return `->\`${y}_${a}\`->(\`${m.join("`,`")}\`)`;if(l.dbProviderConfig.linkMode==="refs"){if(f.cardinality==="MANY")return `$parent.\`${a}\``;if(f.cardinality==="ONE")return `$parent.[\`${a}\`]`}throw new Error("Unsupported linkMode")};if(l.db==="surrealDB"){let w=B();f[me]={queryPath:w};}}),"linkFields"in l&&l.linkFields){let d=l;d.linkFields?.forEach(a=>{a.fieldType="linkField";let f=i.relations[a.relation];if(!a.isVirtual){if(!f)throw new Error(`The relation ${a.relation} does not exist in the schema`);if(f.roles?.[a.plays]===void 0)throw new Error(`The role ${a.plays} is not defined in the relation ${a.relation} (linkField: ${a.path})`)}if(a.target==="relation"){if(a.isVirtual)throw new Error(`[Schema] Virtual linkFields can't target a relation. Thing: "${d.name}" LinkField: "${a.path}. Path:${h.nodePath}."`);a.$things=[a.relation],a.oppositeLinkFieldsPlayedBy=[{plays:a.path,thing:a.relation,thingType:"relation"}];}if(a.target==="role"){let u=r.filter($=>$.relation===a.relation&&$.plays!==a.plays)||[];if(a.oppositeLinkFieldsPlayedBy=u,a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter($=>$.target==="role"),a.oppositeLinkFieldsPlayedBy.length===0)throw new Error(`[Schema] LinkFields require to have at least one opposite linkField playing an opposite role. Thing: "${d.name}" LinkField: "${a.path}. Path:${h.nodePath}."`);if(a.$things=a.oppositeLinkFieldsPlayedBy.map($=>$.thing),a.oppositeLinkFieldsPlayedBy.length>1)throw new Error(`Not supported: LinkField ${a.path} in ${d.name} has multiple candidates ${a.oppositeLinkFieldsPlayedBy.map($=>$.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`)}if(l.db==="surrealDB"){let u=f?.roles?.[a.plays][$e]?.inheritanceOrigin??a.relation,$=Gt({linkField:a,originalRelation:u,withExtensionsSchema:i,linkMode:l.dbProviderConfig.linkMode});a[me]={queryPath:$};}});}}if(l&&typeof l=="object"&&"playedBy"in l){let p=[...new Set(l.playedBy.map(c=>c.thing))];if(p.length>1)throw new Error(`[Schema] roleFields can be only played by one thing. Role: ${s}, path:${h.nodePath}, played by: ${p.join(", ")}`);if(l.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${s}, path:${h.nodePath}`)}if(h.depth===4){let[p,c]=h.nodePath?.split(".")||[],d=n[p][c];!isArray(l)&&typeof l=="object"&&(l.validations&&(l.validations.required&&d.requiredFields.push(l.path),l.validations.enum&&d.enumFields.push(l.path),l.validations.fn&&d.fnValidatedFields.push(l.path)),l.default?l.isVirtual?d.virtualFields.push(l.path):d.computedFields.push(l.path):l.isVirtual&&d.virtualFields.push(l.path));}}))},G=(e,t)=>{if(t in e.entities)return e.entities[t];if(t in e.relations)return e.relations[t];throw new Error(`${t} is not defined in the schema`)},q=(e,t)=>{if(!t)throw new Error("[Internal] No node for getCurrentSchema");if(t.$thing){if(t.$thingType==="entity"){if(!(t.$thing in e.entities))throw new Error(`Missing entity '${t.$thing}' in the schema`);return e.entities[t.$thing]}if(t.$thingType==="relation"){if(!(t.$thing in e.relations))throw new Error(`Missing relation '${t.$thing}' in the schema`);return e.relations[t.$thing]}if(t.$thing in e.entities&&t.$thing in e.relations)throw new Error(`Ambiguous $thing ${t.$thing}`);if(t.$thing in e.entities)return e.entities[t.$thing];if(t.$thing in e.relations)return e.relations[t.$thing];throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)}if(t.$entity){if(!(t.$entity in e.entities))throw new Error(`Missing entity '${t.$entity}' in the schema`);return e.entities[t.$entity]}if(t.$relation){if(!(t.$relation in e.relations))throw new Error(`Missing relation '${t.$relation}' in the schema`);return e.relations[t.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)},Ie=(e,t)=>{let r=e.dataFields?.find(n=>n.path===t);if(r)return ["dataField",r];let i=e.linkFields?.find(n=>n.path===t);if(i)return ["linkField",i];let o="roles"in e?e.roles[t]:void 0;if(o)return ["roleField",o];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},Ke=(e,t)=>{let r=q(e,t);if(r?.idFields?.length&&r?.idFields?.length>1)throw new Error(`Multiple ids not yet enabled / composite ids: ${r?.idFields}`);let[i]=r.idFields;return i},or=(e,t)=>{let r=e.$thing||e.$entity||e.$relation;if(!r)throw new Error("[Internal] No thing found");if(e.$entity)return "entity";if(e.$relation)return "relation";if(t.entities[r])return "entity";if(t.relations[r])return "relation";throw new Error("No thing found")},pt=(e,t,r)=>{let i=q(e,t),o=i.linkFields?.find(s=>s.path===r);if(o)return o;let n=i.dataFields?.find(s=>s.path===r);if(n)return n;let l="roles"in i?i.roles?.[r]:void 0;if(l)return l;throw new Error(`Field ${r} not found in schema`)},ft=(e,t,r)=>pt(e,t,r)?.cardinality,ue=(e,t)=>{let r=e.dataFields?.map(u=>u.path)||[],i=e.linkFields?.map(u=>u.path)||[],o="roles"in e?listify(e.roles,u=>u):[],n=[...r||[],...i||[],...o||[]],s=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...n];if(!t)return {fields:n,dataFields:r,roleFields:o,linkFields:i};let h=t.$fields?t.$fields.map(u=>{if(typeof u=="string"){if(u.startsWith("$")||u.startsWith("%"))return;if(!n.includes(u))throw new Error(`Field ${u} not found in the schema`);return u}if("$path"in u&&typeof u.$path=="string")return u.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,u=>{if(!(u.startsWith("$")||u.startsWith("%"))){if(!n.includes(u))throw new Error(`[Schema] Field ${u} not found in the schema`);return u}}).filter(u=>u!==void 0),p=t.$filter?listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&r?.includes(u)):[],c=t.$filter?listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&[...o||[],...i||[]].includes(u)):[],d=[...h,...p].filter(u=>!u?.startsWith("%")).filter(u=>!s.includes(u)).filter(u=>u),a=t.$filter?We(t.$filter,(u,$)=>p.includes(u)):{},f=t.$filter?We(t.$filter,(u,$)=>c.includes(u)):{};return {fields:n,dataFields:r,roleFields:o,linkFields:i,usedFields:h,usedLinkFields:i.filter(u=>h.includes(u)),usedRoleFields:o.filter(u=>h.includes(u)),usedDataFields:r.filter(u=>h.includes(u)),unidentifiedFields:d,...p.length?{localFilters:a}:{},...c.length?{nestedFilters:f}:{}}};var sr=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},ar=(e,t,r)=>{let o=(r.nodePath||"").split("."),n=isArray(t)?o.slice(0,-2).join("."):o.slice(0,-1).join(".");return t?getNodeByPath(e,n):{}},Fe=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var Ue=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),pe=e=>{if(Array.isArray(e))return e.map(t=>current(t));if(e&&typeof e=="object"){let t=isDraft(e)?current(e):e,r={};return Object.entries(t).forEach(([i,o])=>{r[i]=isDraft(o)?current(o):o;}),r}else return e},ae=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},T=(e,t)=>{let r="";for(let i=0;i<t;i++)r+=" ";return `${r}${e}`};var ke=(e,t)=>{if(t.fieldType==="linkField"){let r=t.oppositeLinkFieldsPlayedBy;if(r?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(r=>r.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!t.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return t.playedBy}else throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var lr=(e,t,r)=>{let i=isArray(e[t])?e[t]:[e[t]];if(!i.every(o=>typeof o=="object"))if(i.every(o=>typeof o=="string")){let o=ke(t,r),[n]=o,l=e.$op==="create"?"link":"replace",s=n.thing,h=n.thingType;if(i.some(p=>p.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:l,$thing:s,$thingType:h,$bzId:`S_${v4()}`};}else throw new Error(`[Mutation Error] Replace can only be used with a single id or an array of ids. (Field: ${t} Nodes: ${JSON.stringify(i)} Parent: ${JSON.stringify(e,null,2)})`)};var Le=(e,t,r)=>{let i=q(r,t),{usedDataFields:o}=ue(i,t);if(t.$op){if(t.$op==="create"&&t.$id)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(["unlink","delete","update"].includes(t.$op)&&e.$op==="create")throw new Error(`[Wrong format] Cannot ${t.$op} under a create`);if(t.$op==="delete"&&o.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&o.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Je=(e,t,r)=>{let i=q(r,t),{usedFields:o}=ue(i,t);return t.$op?(Le(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(Le(e,{...t,$op:"update"},r),"update"):(Le(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(Le(e,{...t,$op:"create"},r),"create"):(Le(e,{...t,$op:"create"},r),"link"):(Le(e,{...t,$op:"create"},r),"create")};var dr=(e,t)=>{let i=(isArray(e.$root)?e.$root:[e.$root]).map(o=>{let n=Je(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:or(o,t)},...o.$op?{}:{$op:n},...o.$bzId?{}:{$bzId:`R_${v4()}`}},...o}});e.$root=isArray(e.$root)?i:i[0];};var ve=(e,t)=>{let r=t[Ve];return isSet(r)?r.has("clean")?(Reflect.set(t,Ve,r.add("clean")),!0):!1:(Reflect.set(t,Ve,new Set(["clean"])),!0)};var hr=(e,t,r)=>{if(ve("split_ids",e)){let i=(isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(isObject(o)&&"$id"in o&&isArray(o.$id)){let n=o;if(q(r,n),!n.$bzId)throw new Error("[Internal Error] No bzId found");return n.$id.map((l,s)=>({...pe(n),$id:l,$bzId:`${n.$bzId}_${s}`,...Fe(n)}))}return o});(i.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=i);}};var pr=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{let l=ke(t,r),[s]=l,h=Je(e,{...n,$thing:s.thing,$thingType:s.thingType},i),c=n.$bzId?n.$bzId:n.$tempId?n.$tempId:n.$id&&!isArray(n.$id)?`SN_ONE_${s.thing}_${n.$id}`:n.$id&&isArray(n.$id)?`SN_MANY_${s.thing}_${nanoid()}`:`SM_${nanoid()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...n,[Be]:r,$thing:s.thing,$thingType:s.thingType,$op:h,$bzId:c}});e[t]=isArray(e[t])?o:o[0];};var zn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Vn=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,fr=e=>{let r=e.toString().replace(zn,"").trim().split("=>")[0].split("{")[0].replace(Vn,"").trim(),i=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return i?(i.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(n=>n.includes("{")&&n.includes("}")?(n.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(s=>s.split(":")[0].trim().replace(/['"[\]]/g,"")):n.trim()).filter(Boolean):[]};var Oe=({currentThing:e,fieldSchema:t,mandatoryDependencies:r=!1})=>{if(!t||!t.default||!("fn"in t.default||"value"in t.default))throw new Error(`[Internal] Virtual field: No field schema found, or wrongly configured. Field: ${JSON.stringify(t,null,3)}`);if(t.default.type==="value")return t.default.value;if(r){let{fn:o}=t.default,l=fr(o).filter(s=>!(s in e));if(l.length)throw new Error(`Virtual field: Missing arguments ${l.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");return "default"in t?t.default?.fn(e):void 0};var $r=(e,t,r)=>{let i=e[t];i&&(isArray(i)?i:[i]).forEach(o=>{let n=q(r,o),{unidentifiedFields:l}=ue(n,o),{computedFields:s,virtualFields:h}=n,p=listify(o,(a,f)=>f!==void 0?a:void 0),c=p.filter(a=>h?.includes(a));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(s.filter(a=>!p.includes(a)).forEach(a=>{let f=n.dataFields?.find(B=>B.path===a),$=n.linkFields?.find(B=>B.path===a)?.oppositeLinkFieldsPlayedBy[0],y="roles"in n?nr(n.roles,(B,w)=>B===a):void 0,m=f||$||y;if(!m)throw new Error(`no field Def for ${a}`);if(o.$op==="create"&&!o[a]){let B=Oe({currentThing:o,fieldSchema:m,mandatoryDependencies:!0});o[a]=B;}}),l.length>0)throw new Error(`Unknown fields: [${l.join(",")}] in ${JSON.stringify(o)}`)});};var Ye=(e,t)=>{let r=q(t,e).hooks;if(r?.pre){let i=`on${sr(e.$op)}`;return r.pre.filter(l=>!l.triggers||l.triggers[i]?.()).flatMap(l=>l.actions)}return []};var yr=(e,t,r,i)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(n=>{if("$thing"in n){if(n.$fields)return n;let{requiredFields:l,enumFields:s,fnValidatedFields:h,dataFields:p}=q(r,n);if("$op"in n&&n.$op==="create"&&l.forEach(c=>{if(!(c in n))throw new Error(`[Validations] Required field "${c}" is missing.`)}),("$op"in n&&n.$op==="update"||n.$op==="create")&&s.forEach(c=>{if(c in n){let d=p?.find(a=>a.path===c)?.validations?.enum;if(!d)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(isArray(n[c]))n[c].some(a=>{if(!d.includes(a))throw new Error(`[Validations] Option "${a}" is not a valid option for field "${c}".`)});else if(d&&!d.includes(n[c]))throw new Error(`[Validations] Option "${n[c]}" is not a valid option for field "${c}".`)}}),("$op"in n&&n.$op==="update"||n.$op==="create")&&h.forEach(c=>{if(c in n)try{let d=p?.find(a=>a.path===c)?.validations?.fn;if(!d)throw new Error("Missing validation function.");if(!d(n[c]))throw new Error("Failed validation function.")}catch(d){throw new Error(`[Validations:attribute:${c}] ${d.message}`)}}),isObject(n)&&"$thing"in n){let c=n.$thing,d=n,a=clone(pe(e)),f=clone(pe(d)),u=i.mutation?.context||{},$=clone(pe(n[Ae]||{}));Ye(d,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let B=m.fn(f,a,u,$);if(B===!1)throw new Error(`${m.message}.`);if(B!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(B){throw new Error(`[Validations:thing:${c}] ${B.message}`)}}});}}});};var Er=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{if(Ue(n)){if(n.$fields||n[dt])return n;let l=Ye(n,r).filter(d=>d.type==="transform"),s=clone(pe(e)),h=clone(pe(n)),p=i.mutation?.context||{},c=clone(pe(n[Ae]||n.$dbNode));return l.forEach(d=>{let a=d.fn(h,s,p,c||{});Object.keys(a).length!==0&&(n={...h,...a,...Fe(n),[dt]:!0});}),n}});e[t]=isArray(e[t])?o:o[0];};var Br=(e,t,r)=>{let i=ke(t,r),[o]=i;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Be]:r};};var Pe=e=>{if(Array.isArray(e)){for(let t of e)if(Pe(t))return !0;return !1}if(e.$fields)return !0;for(let t in e){if(t.startsWith("$"))continue;let r=e[t];if(r&&typeof r=="object"&&Pe(e[t]))return !0}return !1};var ei=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(ve("set_tempId",e))if(e.$tempId?.startsWith("_:")){let r=e.$tempId.substring(2);e.$tempId=r,e.$bzId=r;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},ti=(e,t)=>{},Et=(e,t,r)=>{let i={$rootWrap:{$root:e}},o=Pe(Array.isArray(e)?e:[e]),n=produce(i,l=>traverse(l,({value:s,parent:h,key:p,meta:c})=>{if(!(!h||!p)&&isObject(s)){let d=c.nodePath?.split(".")||[];if(!("$root"in s)){if(!("$thing"in s||"$entity"in s||"$relation"in s)){let u=["$fields","$dbNode","$filter"],$=d[d.length-1],y=d[d.length-2];if(p==="$root")throw new Error("Root things must specify $entity or $relation");if(!u.includes($)&&!u.includes(y))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(s)?current(s):s)}`)}}let a=s,f=d.includes("$filter");Object.keys(a).forEach(u=>{if(ei(a,u),u!=="$root"&&f||u!=="$root"&&(u.startsWith("$")||u.startsWith("%")))return;let $=u!=="$root"?pt(t,a,u):{fieldType:"rootField"};if(!$)throw new Error(`[Internal] Field ${u} not found in schema`);if("contentType"in $)return ti();if(["rootField","linkField","roleField"].includes($.fieldType)){if(["linkField","roleField"].includes($.fieldType)&&(a[u]===null?Br(a,u,$):lr(a,u,$)),$.fieldType==="rootField"){if(!("$root"in a))throw new Error(`[Internal] Field ${u} is a rootField but the object is not a root`);dr(a,t);}let y=isArray(a[u])?a[u]:[a[u]],m=d.slice(1).join(".");y.forEach(w=>{if(w){if($?.cardinality==="ONE"&&!w.$op&&!w.$id&&!w.$filter&&!w.$tempId&&a.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${m}.${u}`);if(w.$tempId&&!(w.$op===void 0||w.$op==="link"||w.$op==="create"||w.$op==="update"))throw new Error(`Invalid op ${w.$op} for tempId. TempIds can be created, or when created in another part of the same mutation. In the future maybe we can use them to catch stuff in the DB as well and group them under the same tempId.`)}}),["linkField","roleField"].includes($.fieldType)&&pr(a,u,$,t),hr(a,u,t),["rootField","linkField","roleField"].includes($.fieldType)&&$r(a,u,t),(isArray(a[u])?a[u]:[a[u]]).forEach(w=>{let g=q(t,w),{unidentifiedFields:S,usedLinkFields:C,usedFields:A,fields:O}=ue(g,w);if(A.forEach(x=>{if(!O.includes(x))throw new Error(`[Schema] Field ${x} not found in the schema`)}),S.length>0)throw new Error(`Unknown fields: [${S.join(",")}] in ${JSON.stringify(s)}`);if(C.length>1){let x=g.linkFields?.filter(W=>C.includes(W.path));x?.some((W,le)=>x.some((K,D)=>{if(le!==D&&W.target!==K.target&&W.relation===K.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),o||(Er(a,u,t,r),yr(a,u,t,r));}});}}));return isArray(n.$rootWrap.$root),n.$rootWrap.$root};var Ge=async(e,t)=>{let r=t.dbConnectors[0].id,i=e.typeDB?.get(r)?.session,o=e.typeDB?.get(r)?.client;if(!i||!i.isOpen()){if(!o)throw new Error("Client not found");i=await o.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:o,session:i});}return {client:o,session:i}};var Fr=async(e,t,r)=>{if(!e)throw new Error("TQL request not built");if(!(e.deletions&&e.deletionMatches||e.insertions))throw new Error("TQL request error, no things");let{session:i}=await Ge(t,r),o=await i.transaction(TransactionType.WRITE),n=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,l=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{n&&await o.query.delete(n);let s=l&&o.query.insert(l),h=s?await s.collect():void 0;return await o.commit(),{insertions:h}}catch(s){throw new Error(`Transaction failed: ${s.message}`)}finally{await o.close();}};var br=async(e,t,r,i,o)=>{let n=[...t,...r],l=n.map(s=>{let h=e.insertions?.find(d=>d.get(`${s.$bzId}`))?.get(`${s.$bzId}`),p=s.$thing||s.$relation||s.$entity,c=p?G(i,p):void 0;if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!h&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let d=h?.asThing().iid,a=Object.entries(s).filter(([u,$])=>!u.startsWith("$")).reduce((u,[$,y])=>{if(c?.dataFields?.find(B=>B.path===$)?.contentType==="JSON")return u[$]=JSON.parse(y),u;if(s.$thingType==="relation"){let B=n.filter(w=>w.$id&&w.$bzId===y);return B.length===1?(u[$]=B[0].$id,u):(u[$]=y,u)}return u[$]=y,u},{});if(o.mutation?.noMetadata)return a;let f=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:d,...s,...a,[s.path]:s.$id,...f}}if(s.$op==="delete"||s.$op==="unlink")return s;if(s.$op!=="match")throw new Error(`Unsupported op ${s.$op}`)}).filter(s=>s);return clone(l)};var wr=e=>{let t=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(n=>n.startsWith("$")).forEach(n=>delete r[n]),Object.keys(r).filter(n=>typeof n=="symbol").forEach(n=>delete r[n])),r);return produce(e,r=>traverse(r,t))};var Sr=async(e,t)=>{let r=c=>{let d=[],a=[],f=m=>{if(m.$id)return m.$id;let B=q(t,m),{idFields:w}=B;if(!w)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[g]=w;if(!g)throw new Error(`no idField: ${JSON.stringify(m)}`);let S=B.dataFields?.find(O=>O.path===g),C=Oe({currentThing:m,fieldSchema:S,mandatoryDependencies:!0}),A=m[g]||m.$id||C;if(!A)throw new Error(`no idValue: ${JSON.stringify(m)}`);return A},u=m=>{if(m.$op==="create"){let B=f(m);if(d.find(w=>w.$id===B&&w.$op==="create"))throw new Error(`Duplicate id ${B} for node ${JSON.stringify(m)}`);if(a.find(w=>w.$bzId===m.$bzId))throw new Error(`Duplicate $bzId ${m.$bzId} for node ${JSON.stringify(m)}`);d.push({...m,$id:B});return}m.$tempId&&m.$op==="match"||d.push(m);},$=m=>{if(m.$op==="create"){let B=f(m);if(d.find(w=>w.$id===B),a.find(w=>w.$bzId===m.$bzId))throw new Error(`Duplicate %bzId ${m.$bzIdd} for edge ${JSON.stringify(m)}`);a.push({...m,$id:B});return}a.push(m);};return traverse(c,({value:m,parent:B,meta:w})=>{if(!isObject(m))return;let g=m;if(g.$thing){if(!g.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(g)}`);if(!g.$bzId)throw new Error("[internal error] BzId not found");let S=q(t,g),{dataFields:C,roleFields:A,linkFields:O,usedFields:x}=ue(S,g),W=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let D=x.filter(E=>C?.includes(E)),F=x.filter(E=>A?.includes(E)),Q=x.filter(E=>O?.includes(E));if(D.length>0)return "update";if(F.length>0||Q.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},le={...g.$id&&{$id:g.$id},...g.$tempId&&{$tempId:g.$tempId},...g.$filter&&{$filter:g.$filter},$thing:g.$thing,...g.$thingType&&{$thingType:g.$thingType},...shake(pick(g,C||[""])),$op:W(),$bzId:g.$bzId};u(le);let K=g[Be];if(K?.fieldType==="linkField"){if((g.$op==="link"||g.$op==="unlink")&&(g.$id||g.$filter)){if(g.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");d.push({...g,$op:"match"});}let D=K.relation===g.$thing,F=D?g.$bzId:`LT_${v4()}`,E=ar(c,B,w).$bzId;if(!E)throw new Error("No parent id found");let b=()=>{if(g.$op==="delete")return D?"match":"delete";if(g.$op==="unlink")return D?"unlink":"delete";if(g.$op==="link"||g.$op==="create")return D?"link":"create";if(g.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},M=q(t,{$thing:K.relation,$thingType:"relation"});if(!Object.keys(M.roles).includes(K.plays))throw new Error(`[Wrong format] Field ${K.plays} is not a role of relation ${K.relation}`);let k={$bzId:F,$thing:K.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:b(),...D?{}:{[K.path]:g.$bzId},[K.plays]:E,[Be]:K,[Se]:"linkField"};$(k),(g.$op==="unlink"||b()==="unlink")&&D&&$({$thing:K.relation,$thingType:"relation",$bzId:F,$op:"match",[K.plays]:E,[Be]:K,[Se]:"linkField"});}if(g.$thingType==="relation"){let D=We(g,(E,b)=>A.includes(E)),F=mapEntries(D,(E,b)=>isArray(b)?[E,b]:isObject(b)?[E,b.$bzId]:[E,b]),Q=We(m,(E,b)=>E.startsWith("$")||E.startsWith("Symbol"));if(Object.keys(D).filter(E=>!E.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let E=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},b=q(t,g).roles,M=mapEntries(F,(k,L)=>{let N=b[k]?.cardinality;if(!N)throw new Error(`Role ${k} not found in schema`);if(Array.isArray(L)){if(N==="ONE"){if(L.length>1)throw new Error(`[Error] Role ${k} is not a MANY relation`);return [k,L[0].$bzId||L[0]]}return [k,L.map(J=>J.$bzId||J)]}return [k,L.$bzId||L]}),R={...Q,$thing:g.$thing,$thingType:"relation",$op:E(),...M,$bzId:g.$bzId,[Se]:"roleField"};$(R);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(D).length>0){let E=0;Object.entries(D).forEach(([b,M])=>{let R=isArray(M)?M:[M],k=L=>L==="create"||L==="replace"?"link":L;R.forEach(L=>{if(!L)return;let N=k(L.$op);if(N==="replace")throw new Error("Not supported yet: replace on roleFields");if(N==="unlink"&&E>0)throw E+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let J={...Q,$thing:g.$thing,$thingType:"relation",$op:N==="delete"?"unlink":N,[b]:L.$bzId,$bzId:g.$bzId,[Se]:"roleField"};$(J);});});}}}}}),[d,a]},[i,o]=r(e),n=i.reduce((c,d)=>{if(!d.$bzId)return [...c,d];let a=c.findIndex(f=>f.$bzId===d.$bzId);if(a===-1)return [...c,d];if(c[a].$op==="create"&&d.$op==="match")return c;if(c[a].$op==="match"&&(d.$op==="create"||d.$op==="match"))return [...c.slice(0,a),d,...c.slice(a+1)];if(c[a].$op==="update"&&d.$op==="update")return [...c.slice(0,a),{...c[a],...d},...c.slice(a+1)];if(c[a].$op==="update"&&d.$op==="match"||c[a].$op==="match"&&d.$op==="update")return [...c.slice(0,a),{...c[a],...d,$op:"update"},...c.slice(a+1)];if(c[a].$op==="delete"&&d.$op==="delete"){if(JSON.stringify(c[a].$filter)===JSON.stringify(d.$filter))return c;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${c[a].$filter}. Current: ${d.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${d.$tempId||d.$id}". Existing: ${c[a].$op}. Current: ${d.$op}`)},[]),l=o.reduce((c,d)=>{let a=c.find(f=>(f.$id&&f.$id===d.$id||f.$bzId&&f.$bzId===d.$bzId)&&f.$thing===d.$thing&&f.$op===d.$op);if(a){let f={...a};return Object.keys(d).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let y=a[$],m=d[$];Array.isArray(y)&&Array.isArray(m)?f[$]=Array.from(new Set([...y,...m])):!Array.isArray(y)&&Array.isArray(m)?y!==void 0?f[$]=Array.from(new Set([y,...m])):f[$]=m:Array.isArray(y)&&!Array.isArray(m)?m!==void 0&&(f[$]=Array.from(new Set([...y,m]))):y!==null&&m!==null&&y!==void 0&&m!==void 0?f[$]=Array.from(new Set([y,m])):y==null&&(f[$]=m);}),[...c.filter($=>!(($.$id&&$.$id===d.$id||$.$bzId&&$.$bzId===d.$bzId)&&$.$thing===d.$thing&&$.$op===d.$op)),f]}return [...c,d]},[]);n.forEach(c=>{if((c.$thingType==="relation"||"relation"in c)&&l.filter(d=>d.$bzId===c.$bzId||d.$tempId&&d.$tempId===c.$tempId).length===0){if(c.$op==="delete"||c.$op==="match"||c.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(wr(c))}`)}});let s=[...n,...l],h=new Set(s.filter(c=>c.$tempId).map(c=>c.$tempId)),p=Array.from(h).filter(c=>!s.some(d=>d.$tempId===c&&d.$op==="create"));if(p.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${p.join(", ")}`);return {mergedThings:n,mergedEdges:l}};var Bt=e=>{if(isDate(e))return {type:"datetime",value:e.toISOString().replace("Z","")};if(typeof e=="string")return {type:"string",value:`"${e}"`};if(typeof e=="number")return e%1!==0?{type:"double",value:e}:{type:"long",value:e};if(typeof e=="boolean")return {type:"boolean",value:e};throw new Error(`Unsupported type ${typeof e}`)};var Rr=async(e,t,r)=>{let i=a=>{let f=a.$op,u=`$${a.$bzId}`,$=q(r,a),{idFields:y,defaultDBConnector:m}=$,B=m?.path||a.$thing,w=a.$id,g=y?.[0],S=listify(a,(D,F)=>{if(D.startsWith("$")||D.startsWith("%")||D===g||F===void 0||F===null)return "";let Q=$.dataFields?.find(M=>M.path===D);if(!Q?.path)return "";let b=Q.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(Q.contentType))return `has ${b} '${F}'`;if(["NUMBER","BOOLEAN"].includes(Q.contentType))return `has ${b} ${F}`;if(Q.contentType==="DATE"){if(Number.isNaN(F.valueOf()))throw new Error("Invalid format, Nan Date");return F instanceof Date?`has ${b} ${F.toISOString().replace("Z","")}`:`has ${b} ${new Date(F).toISOString().replace("Z","")}`}if(Q.contentType==="FLEX"){let M=`bza${nanoid()}`,R=isArray(F)?F.map(k=>Bt(k)):Bt(F);if(Array.isArray(R))throw new Error("Array in FLEX fields not supported yet");return `has ${b} $${M}; $${M} '${M}' isa ${b}, has ${R.type}Attribute ${R.value}`}throw new Error(`Unsupported contentType ${Q.contentType}`)}).filter(D=>D),C=`${u}-atts`,A=listify(a,D=>{if(D.startsWith("$")||D.startsWith("%")||D===g)return "";let F=$.dataFields?.find(b=>b.path===D);if(!F?.path)return "";let E=F.dbPath;return `{${C} isa ${E};}`}).filter(D=>D),O=isArray(w)?`like '${w.join("|")}'`:`'${w}'`,x=w?[`has ${g} ${O}`]:[],W=[...x,...S].filter(D=>D).join(","),le=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${u} isa ${[B,...x].filter(D=>D).join(",")};`;if(f==="update"){if(!A.length)throw new Error("update without attributes");return `${u} isa ${[B,...x].filter(D=>D).join(",")}, has ${C};
36
+ ${y}`})(),n=e.dbConnectors[0].id,l=r.typeDB.get(n)?.session,s=r.typeDB.get(n)?.client;if(!l){console.log("Session Status: ","NO SESSION");return}await l.close();let[{dbName:h}]=e.dbConnectors;await(await s.databases.get(h)).delete(),await s.databases.create(h);let c=await s.session(e.dbConnectors[0].dbName,SessionType.SCHEMA),d=await c.transaction(TransactionType.WRITE);await d.query.define(o),await d.commit(),await d.close();let a=await c.transaction(TransactionType.READ);(await(await a.query.match("match $a sub thing;")).collect()).forEach(async y=>{y.get("a");}),await a.close();};var te=Symbol.for("queryPath"),Ve=Symbol.for("stepPrint"),Se=Symbol.for("edgeType"),Be=Symbol.for("edgeSchema"),Ae=Symbol.for("dbNode"),dt=Symbol.for("isTransformed"),ie=Symbol.for("fieldSchema"),$e=Symbol.for("sharedMetadata"),me=Symbol.for("suqlMetadata");var Yt={typeDB:{mutation:{splitArray$Ids:!0,requiresParseBQL:!0}},surrealDB:{mutation:{splitArray$Ids:!1,requiresParseBQL:!1}}};var Gt=({linkField:e,originalRelation:t,withExtensionsSchema:r,linkMode:i})=>{if(e.isVirtual)return `$this.${e.path}.id`;let o=r.relations[e.relation].subTypes||[],n=[e.relation,...o],l=`<-\`${t}_${e.plays}\`<-(\`${n.join("`,`")}\`)`;if(e.target==="relation"){if(i==="edges")return l;if(i==="refs")return `$parent.\`${e.path}\``;throw new Error("Unsupported linkMode")}else if(e.target==="role"){let[s]=e.oppositeLinkFieldsPlayedBy,h=r.entities[s.thing]?.subTypes||r.relations[s.thing]?.subTypes||[],p=[s.thing,...h],c=`->\`${t}_${s.plays}\`->(\`${p.join("`,`")}\`)`;return i==="edges"?`${l}${c}`:i==="refs"?`$parent.\`${s.plays}\``:`${l}${c}`}else throw new Error("Unsupported linkField target")};var tr=(e,t,r)=>r?t:`${e}\xB7${t}`;var nr=(e,t)=>Object.values(Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))))[0],We=(e,t)=>Object.fromEntries(Object.entries(e).filter(([r,i])=>t(r,i))),ir=(e,t)=>{let r=[],i=produce(e,n=>traverse(n,({key:l,value:s,meta:h})=>{if(h.depth===2&&(l&&(s.dataFields=s.dataFields?.map(p=>({...p,cardinality:p.cardinality||"ONE",dbPath:tr(l,p.path,p.shared)}))),s.extends)){if(!s.defaultDBConnector.as)throw new Error(`[Schema] ${l} is extending a thing but missing the "as" property in its defaultDBConnector. Path:${h.nodePath}`);let p=n.entities[s.extends]||n.relations[s.extends],c=[s.extends,...p.allExtends||[]];if(s.allExtends=c,c.forEach(d=>{if(n.entities[d])n.entities[d].subTypes=[l,...n.entities[d].subTypes||[]];else if(n.relations[d])n.relations[d].subTypes=[l,...n.relations[d].subTypes||[]];else throw new Error(`[Schema] ${l} is extending a thing that does not exist in the schema: ${d}`)}),s.idFields=p.idFields?Array.from(new Set((s.idFields||[]).concat(p.idFields))):s.idFields,s.dataFields=p.dataFields?(s.dataFields||[]).concat(p.dataFields.map(d=>{let a=s.extends,f=e.entities[a]||e.relations[a];for(;!f.dataFields?.find(u=>u.path===d.path);)a="extends"in f?f.extends:void 0,f=e.entities[a]||e.relations[a];return {...d,dbPath:tr(a,d.path,d.shared),[$e]:{inheritanceOrigin:d[$e]?.inheritanceOrigin||s.extends}}})):s.dataFields,"roles"in p){let d=s,a=p;if(a.roles){let f=mapEntries(a.roles,(u,$)=>[u,{...$,[$e]:{inheritanceOrigin:$[$e]?.inheritanceOrigin||s.extends}}]);d.roles={...d.roles||{},...f};}}s.linkFields=p.linkFields?(s.linkFields||[]).concat(p.linkFields.map(d=>({...d,[$e]:{inheritanceOrigin:d[$e]?.inheritanceOrigin||s.extends}}))):s.linkFields,p?.hooks?.pre&&(s.hooks=s.hooks||{},s.hooks.pre=s.hooks.pre||[],s.hooks.pre=[...p?.hooks?.pre||[],...s?.hooks?.pre||[]]);}},{traversalType:"breadth-first"}));return traverse(e,({key:n,value:l,meta:s})=>{if(n==="linkFields"){let p=(()=>{if(!s.nodePath)throw new Error("No path");let[d,a]=s.nodePath.split(".");return {thing:a,thingType:d==="entities"?"entity":d==="relations"?"relation":""}})(),c=Array.isArray(l)?l.map(d=>({...d,...p})):[{...l,...p}];r.push(...c);}}),produce(i,n=>traverse(n,({value:l,key:s,meta:h})=>{if(h.depth===2&&l.idFields&&!l.id){l.name=s;let p=()=>{if(h.nodePath?.split(".")[0]==="entities")return "entity";if(h.nodePath?.split(".")[0]==="relations")return "relation";throw new Error("Unsupported node attributes")};l.thingType=p();let c=Object.keys(t).find(d=>t[d]?.get(l.defaultDBConnector.id));if(l.db=c,l.dbContext=Yt[c],l.dbProviderConfig=c==="surrealDB"?t[c]?.get(l.defaultDBConnector.id)?.providerConfig:void 0,l.computedFields=[],l.virtualFields=[],l.requiredFields=[],l.enumFields=[],l.fnValidatedFields=[],"roles"in l&&Object.entries(l.roles).forEach(([a,f])=>{f.fieldType="roleField";let u=r.filter(w=>w.relation===s&&w.plays===a)||[];f.playedBy=u,f.path=a;let $=[...new Set(u.map(w=>w.thing))];f.$things=$;let y=f[$e]?.inheritanceOrigin||l.name;$.length>1&&console.warn(`Not supported yet: Role ${a} in ${l.name} is played by multiple things: ${$.join(", ")}`);let m=$.flatMap(w=>{let S=G(e,w)?.subTypes||[];return [w,...S]}),B=()=>{if(l.dbProviderConfig.linkMode==="edges")return `->\`${y}_${a}\`->(\`${m.join("`,`")}\`)`;if(l.dbProviderConfig.linkMode==="refs"){if(f.cardinality==="MANY")return `$parent.\`${a}\``;if(f.cardinality==="ONE")return `$parent.[\`${a}\`]`}throw new Error("Unsupported linkMode")};if(l.db==="surrealDB"){let w=B();f[me]={queryPath:w};}}),"linkFields"in l&&l.linkFields){let d=l;d.linkFields?.forEach(a=>{a.fieldType="linkField";let f=i.relations[a.relation];if(!a.isVirtual){if(!f)throw new Error(`The relation ${a.relation} does not exist in the schema`);if(f.roles?.[a.plays]===void 0)throw new Error(`The role ${a.plays} is not defined in the relation ${a.relation} (linkField: ${a.path})`)}if(a.target==="relation"){if(a.isVirtual)throw new Error(`[Schema] Virtual linkFields can't target a relation. Thing: "${d.name}" LinkField: "${a.path}. Path:${h.nodePath}."`);a.$things=[a.relation],a.oppositeLinkFieldsPlayedBy=[{plays:a.path,thing:a.relation,thingType:"relation"}];}if(a.target==="role"){let u=r.filter($=>$.relation===a.relation&&$.plays!==a.plays)||[];if(a.oppositeLinkFieldsPlayedBy=u,a.oppositeLinkFieldsPlayedBy=a.oppositeLinkFieldsPlayedBy.filter($=>$.target==="role"),a.oppositeLinkFieldsPlayedBy.length===0)throw new Error(`[Schema] LinkFields require to have at least one opposite linkField playing an opposite role. Thing: "${d.name}" LinkField: "${a.path}. Path:${h.nodePath}."`);if(a.$things=a.oppositeLinkFieldsPlayedBy.map($=>$.thing),a.oppositeLinkFieldsPlayedBy.length>1)throw new Error(`Not supported: LinkField ${a.path} in ${d.name} has multiple candidates ${a.oppositeLinkFieldsPlayedBy.map($=>$.thing).join(",")} and this is not yet supported. Please target a single one using targetRoles with a single role`)}if(l.db==="surrealDB"){let u=f?.roles?.[a.plays][$e]?.inheritanceOrigin??a.relation,$=Gt({linkField:a,originalRelation:u,withExtensionsSchema:i,linkMode:l.dbProviderConfig.linkMode});a[me]={queryPath:$};}});}}if(l&&typeof l=="object"&&"playedBy"in l){let p=[...new Set(l.playedBy.map(c=>c.thing))];if(p.length>1&&console.warn(`[Schema] roleFields can be only played by one thing. Role: ${s}, path:${h.nodePath}, played by: ${p.join(", ")}`),l.playedBy.length===0)throw new Error(`[Schema] roleFields should be played at least by one thing. Role: ${s}, path:${h.nodePath}`)}if(h.depth===4){let[p,c]=h.nodePath?.split(".")||[],d=n[p][c];!isArray(l)&&typeof l=="object"&&(l.validations&&(l.validations.required&&d.requiredFields.push(l.path),l.validations.enum&&d.enumFields.push(l.path),l.validations.fn&&d.fnValidatedFields.push(l.path)),l.default?l.isVirtual?d.virtualFields.push(l.path):d.computedFields.push(l.path):l.isVirtual&&d.virtualFields.push(l.path));}}))},G=(e,t)=>{if(t in e.entities)return e.entities[t];if(t in e.relations)return e.relations[t];throw new Error(`${t} is not defined in the schema`)},q=(e,t)=>{if(!t)throw new Error("[Internal] No node for getCurrentSchema");if(t.$thing){if(t.$thingType==="entity"){if(!(t.$thing in e.entities))throw new Error(`Missing entity '${t.$thing}' in the schema`);return e.entities[t.$thing]}if(t.$thingType==="relation"){if(!(t.$thing in e.relations))throw new Error(`Missing relation '${t.$thing}' in the schema`);return e.relations[t.$thing]}if(t.$thing in e.entities&&t.$thing in e.relations)throw new Error(`Ambiguous $thing ${t.$thing}`);if(t.$thing in e.entities)return e.entities[t.$thing];if(t.$thing in e.relations)return e.relations[t.$thing];throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)}if(t.$entity){if(!(t.$entity in e.entities))throw new Error(`Missing entity '${t.$entity}' in the schema`);return e.entities[t.$entity]}if(t.$relation){if(!(t.$relation in e.relations))throw new Error(`Missing relation '${t.$relation}' in the schema`);return e.relations[t.$relation]}throw new Error(`Wrong schema or query for ${JSON.stringify(t,null,2)}`)},Ie=(e,t)=>{let r=e.dataFields?.find(n=>n.path===t);if(r)return ["dataField",r];let i=e.linkFields?.find(n=>n.path===t);if(i)return ["linkField",i];let o="roles"in e?e.roles[t]:void 0;if(o)return ["roleField",o];throw new Error(`Field ${t} not found in schema, Defined in $filter`)},Ke=(e,t)=>{let r=q(e,t);if(r?.idFields?.length&&r?.idFields?.length>1)throw new Error(`Multiple ids not yet enabled / composite ids: ${r?.idFields}`);let[i]=r.idFields;return i},or=(e,t)=>{let r=e.$thing||e.$entity||e.$relation;if(!r)throw new Error("[Internal] No thing found");if(e.$entity)return "entity";if(e.$relation)return "relation";if(t.entities[r])return "entity";if(t.relations[r])return "relation";throw new Error("No thing found")},pt=(e,t,r)=>{let i=q(e,t),o=i.linkFields?.find(s=>s.path===r);if(o)return o;let n=i.dataFields?.find(s=>s.path===r);if(n)return n;let l="roles"in i?i.roles?.[r]:void 0;if(l)return l;throw new Error(`Field ${r} not found in schema`)},ft=(e,t,r)=>pt(e,t,r)?.cardinality,ue=(e,t)=>{let r=e.dataFields?.map(u=>u.path)||[],i=e.linkFields?.map(u=>u.path)||[],o="roles"in e?listify(e.roles,u=>u):[],n=[...r||[],...i||[],...o||[]],s=[...["$entity","$op","$id","$tempId","$bzId","$relation","$parentKey","$filter","$fields","$excludedFields","$thing","$thingType"],...n];if(!t)return {fields:n,dataFields:r,roleFields:o,linkFields:i};let h=t.$fields?t.$fields.map(u=>{if(typeof u=="string"){if(u.startsWith("$")||u.startsWith("%"))return;if(!n.includes(u))throw new Error(`Field ${u} not found in the schema`);return u}if("$path"in u&&typeof u.$path=="string")return u.$path;throw new Error("[Wrong format] Wrongly structured query")}):listify(t,u=>{if(!(u.startsWith("$")||u.startsWith("%"))){if(!n.includes(u))throw new Error(`[Schema] Field ${u} not found in the schema`);return u}}).filter(u=>u!==void 0),p=t.$filter?listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&r?.includes(u)):[],c=t.$filter?listify(t.$filter,u=>u.toString().startsWith("$")?void 0:u.toString()).filter(u=>u&&[...o||[],...i||[]].includes(u)):[],d=[...h,...p].filter(u=>!u?.startsWith("%")).filter(u=>!s.includes(u)).filter(u=>u),a=t.$filter?We(t.$filter,(u,$)=>p.includes(u)):{},f=t.$filter?We(t.$filter,(u,$)=>c.includes(u)):{};return {fields:n,dataFields:r,roleFields:o,linkFields:i,usedFields:h,usedLinkFields:i.filter(u=>h.includes(u)),usedRoleFields:o.filter(u=>h.includes(u)),usedDataFields:r.filter(u=>h.includes(u)),unidentifiedFields:d,...p.length?{localFilters:a}:{},...c.length?{nestedFilters:f}:{}}};var sr=e=>{if(typeof e!="string")throw new Error("capitalizeFirstLetter: string is not a string");return e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()},ar=(e,t,r)=>{let o=(r.nodePath||"").split("."),n=isArray(t)?o.slice(0,-2).join("."):o.slice(0,-1).join(".");return t?getNodeByPath(e,n):{}},Fe=e=>Reflect.ownKeys(e).filter(t=>typeof t=="symbol").reduce((t,r)=>(t[r]=e[r],t),{});var Ue=e=>isObject(e)&&("$entity"in e||"$relation"in e||"$thing"in e),pe=e=>{if(Array.isArray(e))return e.map(t=>current(t));if(e&&typeof e=="object"){let t=isDraft(e)?current(e):e,r={};return Object.entries(t).forEach(([i,o])=>{r[i]=isDraft(o)?current(o):o;}),r}else return e},ae=(e,t)=>{if(e===void 0)throw new Error("Value is undefined");return e},T=(e,t)=>{let r="";for(let i=0;i<t;i++)r+=" ";return `${r}${e}`};var ke=(e,t)=>{if(t.fieldType==="linkField"){let r=t.oppositeLinkFieldsPlayedBy;if(r?.length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!r?.length)throw new Error(`[Internal] Field ${e} should have a player`);return r}else if(t.fieldType==="roleField"){if([...new Set(t.playedBy?.map(r=>r.thing))].length!==1)throw new Error(`[Internal] Field ${e} should have a single player`);if(!t.playedBy?.length)throw new Error(`[Internal] Field ${e} should have a player`);return t.playedBy}else throw new Error(`[Internal] Field ${e} is not a linkField or roleField`)};var lr=(e,t,r)=>{let i=isArray(e[t])?e[t]:[e[t]];if(!i.every(o=>typeof o=="object"))if(i.every(o=>typeof o=="string")){let o=ke(t,r),[n]=o,l=e.$op==="create"?"link":"replace",s=n.thing,h=n.thingType;if(i.some(p=>p.startsWith("_:")))throw new Error("[Not supported] At least one child of a replace is a tempId");e[t]={$id:e[t],$op:l,$thing:s,$thingType:h,$bzId:`S_${v4()}`};}else throw new Error(`[Mutation Error] Replace can only be used with a single id or an array of ids. (Field: ${t} Nodes: ${JSON.stringify(i)} Parent: ${JSON.stringify(e,null,2)})`)};var Le=(e,t,r)=>{let i=q(r,t),{usedDataFields:o}=ue(i,t);if(t.$op){if(t.$op==="create"&&t.$id)throw new Error("[Wrong format] Can't write to computed field $id. Try writing to the id field directly.");if(["unlink","delete","update"].includes(t.$op)&&e.$op==="create")throw new Error(`[Wrong format] Cannot ${t.$op} under a create`);if(t.$op==="delete"&&o.length>0)throw new Error("[Wrong format] Cannot update on deletion");if(["unlink","link"].includes(t.$op)&&o.length>0)throw new Error("[Unsupported] Can't update fields on Link / Unlink");return t.$op}};var Je=(e,t,r)=>{let i=q(r,t),{usedFields:o}=ue(i,t);return t.$op?(Le(e,t,r),t.$op):t.$id||t.$filter?o.length>0?(Le(e,{...t,$op:"update"},r),"update"):(Le(e,{...t,$op:"link"},r),"link"):t.$tempId?o.length>0?(Le(e,{...t,$op:"create"},r),"create"):(Le(e,{...t,$op:"create"},r),"link"):(Le(e,{...t,$op:"create"},r),"create")};var dr=(e,t)=>{let i=(isArray(e.$root)?e.$root:[e.$root]).map(o=>{let n=Je(o,o,t);return {...{...o.$thing?{}:{$thing:o.$entity||o.$relation},...o.$thingType?{}:{$thingType:or(o,t)},...o.$op?{}:{$op:n},...o.$bzId?{}:{$bzId:`R_${v4()}`}},...o}});e.$root=isArray(e.$root)?i:i[0];};var ve=(e,t)=>{let r=t[Ve];return isSet(r)?r.has("clean")?(Reflect.set(t,Ve,r.add("clean")),!0):!1:(Reflect.set(t,Ve,new Set(["clean"])),!0)};var hr=(e,t,r)=>{if(ve("split_ids",e)){let i=(isArray(e[t])?e[t]:[e[t]]).flatMap(o=>{if(isObject(o)&&"$id"in o&&isArray(o.$id)){let n=o;if(q(r,n),!n.$bzId)throw new Error("[Internal Error] No bzId found");return n.$id.map((l,s)=>({...pe(n),$id:l,$bzId:`${n.$bzId}_${s}`,...Fe(n)}))}return o});(i.length>isArray(e[t])?e[t]:[e[t]].length)&&(e[t]=i);}};var pr=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{let l=ke(t,r),[s]=l,h=Je(e,{...n,$thing:s.thing,$thingType:s.thingType},i),c=n.$bzId?n.$bzId:n.$tempId?n.$tempId:n.$id&&!isArray(n.$id)?`SN_ONE_${s.thing}_${n.$id}`:n.$id&&isArray(n.$id)?`SN_MANY_${s.thing}_${nanoid()}`:`SM_${nanoid()}`;if(!r)throw new Error(`[Internal] No fieldSchema found in ${JSON.stringify(r)}`);return {...n,[Be]:r,$thing:s.thing,$thingType:s.thingType,$op:h,$bzId:c}});e[t]=isArray(e[t])?o:o[0];};var zn=/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm,Vn=/(\s*async\s*|\s*function\s*|\s*\(\s*|\s*\)\s*=>|\s*\)\s*\{)/,fr=e=>{let r=e.toString().replace(zn,"").trim().split("=>")[0].split("{")[0].replace(Vn,"").trim(),i=r.substring(r.indexOf("(")+1,r.lastIndexOf(")")).trim();return i?(i.match(/(\{[^}]*\}|[^,]+)/g)||[]).flatMap(n=>n.includes("{")&&n.includes("}")?(n.replace(/^\{|\}$/g,"").match(/(?:[^,"']+|"[^"]*"|'[^']*')+/g)||[]).map(s=>s.split(":")[0].trim().replace(/['"[\]]/g,"")):n.trim()).filter(Boolean):[]};var Oe=({currentThing:e,fieldSchema:t,mandatoryDependencies:r=!1})=>{if(!t||!t.default||!("fn"in t.default||"value"in t.default))throw new Error(`[Internal] Virtual field: No field schema found, or wrongly configured. Field: ${JSON.stringify(t,null,3)}`);if(t.default.type==="value")return t.default.value;if(r){let{fn:o}=t.default,l=fr(o).filter(s=>!(s in e));if(l.length)throw new Error(`Virtual field: Missing arguments ${l.join(", ")}`)}if(!t.default.fn)throw new Error("[Schema] No fn in default field schema");return "default"in t?t.default?.fn(e):void 0};var $r=(e,t,r)=>{let i=e[t];i&&(isArray(i)?i:[i]).forEach(o=>{let n=q(r,o),{unidentifiedFields:l}=ue(n,o),{computedFields:s,virtualFields:h}=n,p=listify(o,(a,f)=>f!==void 0?a:void 0),c=p.filter(a=>h?.includes(a));if(c.length>0)throw new Error(`Virtual fields can't be sent to DB: "${c.join(",")}"`);if(s.filter(a=>!p.includes(a)).forEach(a=>{let f=n.dataFields?.find(B=>B.path===a),$=n.linkFields?.find(B=>B.path===a)?.oppositeLinkFieldsPlayedBy[0],y="roles"in n?nr(n.roles,(B,w)=>B===a):void 0,m=f||$||y;if(!m)throw new Error(`no field Def for ${a}`);if(o.$op==="create"&&!o[a]){let B=Oe({currentThing:o,fieldSchema:m,mandatoryDependencies:!0});o[a]=B;}}),l.length>0)throw new Error(`Unknown fields: [${l.join(",")}] in ${JSON.stringify(o)}`)});};var Ye=(e,t)=>{let r=q(t,e).hooks;if(r?.pre){let i=`on${sr(e.$op)}`;return r.pre.filter(l=>!l.triggers||l.triggers[i]?.()).flatMap(l=>l.actions)}return []};var yr=(e,t,r,i)=>{(isArray(e[t])?e[t]:[e[t]]).forEach(n=>{if("$thing"in n){if(n.$fields)return n;let{requiredFields:l,enumFields:s,fnValidatedFields:h,dataFields:p}=q(r,n);if("$op"in n&&n.$op==="create"&&l.forEach(c=>{if(!(c in n))throw new Error(`[Validations] Required field "${c}" is missing.`)}),("$op"in n&&n.$op==="update"||n.$op==="create")&&s.forEach(c=>{if(c in n){let d=p?.find(a=>a.path===c)?.validations?.enum;if(!d)throw new Error(`[Validations] Enum field "${c}" is missing enum options.`);if(isArray(n[c]))n[c].some(a=>{if(!d.includes(a))throw new Error(`[Validations] Option "${a}" is not a valid option for field "${c}".`)});else if(d&&!d.includes(n[c]))throw new Error(`[Validations] Option "${n[c]}" is not a valid option for field "${c}".`)}}),("$op"in n&&n.$op==="update"||n.$op==="create")&&h.forEach(c=>{if(c in n)try{let d=p?.find(a=>a.path===c)?.validations?.fn;if(!d)throw new Error("Missing validation function.");if(!d(n[c]))throw new Error("Failed validation function.")}catch(d){throw new Error(`[Validations:attribute:${c}] ${d.message}`)}}),isObject(n)&&"$thing"in n){let c=n.$thing,d=n,a=clone(pe(e)),f=clone(pe(d)),u=i.mutation?.context||{},$=clone(pe(n[Ae]||{}));Ye(d,r).forEach(m=>{if(m.type==="validate"){if(m.severity!=="error")return;try{let B=m.fn(f,a,u,$);if(B===!1)throw new Error(`${m.message}.`);if(B!==!0)throw new Error("Validation function's output is not a boolean value.")}catch(B){throw new Error(`[Validations:thing:${c}] ${B.message}`)}}});}}});};var Er=(e,t,r,i)=>{let o=(isArray(e[t])?e[t]:[e[t]]).map(n=>{if(Ue(n)){if(n.$fields||n[dt])return n;let l=Ye(n,r).filter(d=>d.type==="transform"),s=clone(pe(e)),h=clone(pe(n)),p=i.mutation?.context||{},c=clone(pe(n[Ae]||n.$dbNode));return l.forEach(d=>{let a=d.fn(h,s,p,c||{});Object.keys(a).length!==0&&(n={...h,...a,...Fe(n),[dt]:!0});}),n}});e[t]=isArray(e[t])?o:o[0];};var Br=(e,t,r)=>{let i=ke(t,r),[o]=i;e[t]={$thing:o.thing,$thingType:o.thingType,$op:"unlink",$bzId:`U_${v4()}`,[Be]:r};};var Pe=e=>{if(Array.isArray(e)){for(let t of e)if(Pe(t))return !0;return !1}if(e.$fields)return !0;for(let t in e){if(t.startsWith("$"))continue;let r=e[t];if(r&&typeof r=="object"&&Pe(e[t]))return !0}return !1};var ei=(e,t)=>{if(e[t]===void 0&&delete e[t],t==="$tempId")if(ve("set_tempId",e))if(e.$tempId?.startsWith("_:")){let r=e.$tempId.substring(2);e.$tempId=r,e.$bzId=r;}else throw new Error('[Wrong format] TempIds must start with "_:"');else throw new Error("[Internal] TempId already modified")},ti=(e,t)=>{},Et=(e,t,r)=>{let i={$rootWrap:{$root:e}},o=Pe(Array.isArray(e)?e:[e]),n=produce(i,l=>traverse(l,({value:s,parent:h,key:p,meta:c})=>{if(!(!h||!p)&&isObject(s)){let d=c.nodePath?.split(".")||[];if(!("$root"in s)){if(!("$thing"in s||"$entity"in s||"$relation"in s)){let u=["$fields","$dbNode","$filter"],$=d[d.length-1],y=d[d.length-2];if(p==="$root")throw new Error("Root things must specify $entity or $relation");if(!u.includes($)&&!u.includes(y))throw new Error(`[Internal] This object has not been initiated with a $thing: ${JSON.stringify(isDraft(s)?current(s):s)}`)}}let a=s,f=d.includes("$filter");Object.keys(a).forEach(u=>{if(ei(a,u),u!=="$root"&&f||u!=="$root"&&(u.startsWith("$")||u.startsWith("%")))return;let $=u!=="$root"?pt(t,a,u):{fieldType:"rootField"};if(!$)throw new Error(`[Internal] Field ${u} not found in schema`);if("contentType"in $)return ti();if(["rootField","linkField","roleField"].includes($.fieldType)){if(["linkField","roleField"].includes($.fieldType)&&(a[u]===null?Br(a,u,$):lr(a,u,$)),$.fieldType==="rootField"){if(!("$root"in a))throw new Error(`[Internal] Field ${u} is a rootField but the object is not a root`);dr(a,t);}let y=isArray(a[u])?a[u]:[a[u]],m=d.slice(1).join(".");y.forEach(w=>{if(w){if($?.cardinality==="ONE"&&!w.$op&&!w.$id&&!w.$filter&&!w.$tempId&&a.$op!=="create")throw new Error(`Please specify if it is a create or an update. Path: ${m}.${u}`);if(w.$tempId&&!(w.$op===void 0||w.$op==="link"||w.$op==="create"||w.$op==="update"))throw new Error(`Invalid op ${w.$op} for tempId. TempIds can be created, or when created in another part of the same mutation. In the future maybe we can use them to catch stuff in the DB as well and group them under the same tempId.`)}}),["linkField","roleField"].includes($.fieldType)&&pr(a,u,$,t),hr(a,u,t),["rootField","linkField","roleField"].includes($.fieldType)&&$r(a,u,t),(isArray(a[u])?a[u]:[a[u]]).forEach(w=>{let g=q(t,w),{unidentifiedFields:S,usedLinkFields:C,usedFields:A,fields:O}=ue(g,w);if(A.forEach(x=>{if(!O.includes(x))throw new Error(`[Schema] Field ${x} not found in the schema`)}),S.length>0)throw new Error(`Unknown fields: [${S.join(",")}] in ${JSON.stringify(s)}`);if(C.length>1){let x=g.linkFields?.filter(W=>C.includes(W.path));x?.some((W,le)=>x.some((K,D)=>{if(le!==D&&W.target!==K.target&&W.relation===K.relation)throw new Error("[Wrong format]: Can't use a link field with target === 'role' and another with target === 'relation' in the same mutation.")}));}}),o||(Er(a,u,t,r),yr(a,u,t,r));}});}}));return isArray(n.$rootWrap.$root),n.$rootWrap.$root};var Ge=async(e,t)=>{let r=t.dbConnectors[0].id,i=e.typeDB?.get(r)?.session,o=e.typeDB?.get(r)?.client;if(!i||!i.isOpen()){if(!o)throw new Error("Client not found");i=await o.session(t.dbConnectors[0].dbName,SessionType.DATA),e.typeDB?.set(r,{client:o,session:i});}return {client:o,session:i}};var Fr=async(e,t,r)=>{if(!e)throw new Error("TQL request not built");if(!(e.deletions&&e.deletionMatches||e.insertions))throw new Error("TQL request error, no things");let{session:i}=await Ge(t,r),o=await i.transaction(TransactionType.WRITE),n=e.deletionMatches&&e.deletions&&`match ${e.deletionMatches} delete ${e.deletions}`,l=e.insertions&&`${e.insertionMatches?`match ${e.insertionMatches}`:""} insert ${e.insertions}`;try{n&&await o.query.delete(n);let s=l&&o.query.insert(l),h=s?await s.collect():void 0;return await o.commit(),{insertions:h}}catch(s){throw new Error(`Transaction failed: ${s.message}`)}finally{await o.close();}};var br=async(e,t,r,i,o)=>{let n=[...t,...r],l=n.map(s=>{let h=e.insertions?.find(d=>d.get(`${s.$bzId}`))?.get(`${s.$bzId}`),p=s.$thing||s.$relation||s.$entity,c=p?G(i,p):void 0;if(s.$op==="create"||s.$op==="update"||s.$op==="link"){if(s.$op!=="update"&&!h&&s.$id)return {$id:s.$id,$error:"Does not exist or it's not linked to the parent"};let d=h?.asThing().iid,a=Object.entries(s).filter(([u,$])=>!u.startsWith("$")).reduce((u,[$,y])=>{if(c?.dataFields?.find(B=>B.path===$)?.contentType==="JSON")return u[$]=JSON.parse(y),u;if(s.$thingType==="relation"){let B=n.filter(w=>w.$id&&w.$bzId===y);return B.length===1?(u[$]=B[0].$id,u):(u[$]=y,u)}return u[$]=y,u},{});if(o.mutation?.noMetadata)return a;let f=s.$tempId&&!s.$tempId.startsWith("_:")?{$tempId:`_:${s.$tempId}`}:{};return {$dbId:d,...s,...a,[s.path]:s.$id,...f}}if(s.$op==="delete"||s.$op==="unlink")return s;if(s.$op!=="match")throw new Error(`Unsupported op ${s.$op}`)}).filter(s=>s);return clone(l)};var wr=e=>{let t=({value:r})=>(r&&typeof r=="object"&&"$id"in r&&(Object.keys(r).filter(n=>n.startsWith("$")).forEach(n=>delete r[n]),Object.keys(r).filter(n=>typeof n=="symbol").forEach(n=>delete r[n])),r);return produce(e,r=>traverse(r,t))};var Sr=async(e,t)=>{let r=c=>{let d=[],a=[],f=m=>{if(m.$id)return m.$id;let B=q(t,m),{idFields:w}=B;if(!w)throw new Error(`no idFields: ${JSON.stringify(m)}`);let[g]=w;if(!g)throw new Error(`no idField: ${JSON.stringify(m)}`);let S=B.dataFields?.find(O=>O.path===g),C=Oe({currentThing:m,fieldSchema:S,mandatoryDependencies:!0}),A=m[g]||m.$id||C;if(!A)throw new Error(`no idValue: ${JSON.stringify(m)}`);return A},u=m=>{if(m.$op==="create"){let B=f(m);if(d.find(w=>w.$id===B&&w.$op==="create"))throw new Error(`Duplicate id ${B} for node ${JSON.stringify(m)}`);if(a.find(w=>w.$bzId===m.$bzId))throw new Error(`Duplicate $bzId ${m.$bzId} for node ${JSON.stringify(m)}`);d.push({...m,$id:B});return}m.$tempId&&m.$op==="match"||d.push(m);},$=m=>{if(m.$op==="create"){let B=f(m);if(d.find(w=>w.$id===B),a.find(w=>w.$bzId===m.$bzId))throw new Error(`Duplicate %bzId ${m.$bzIdd} for edge ${JSON.stringify(m)}`);a.push({...m,$id:B});return}a.push(m);};return traverse(c,({value:m,parent:B,meta:w})=>{if(!isObject(m))return;let g=m;if(g.$thing){if(!g.$op)throw new Error(`Operation should be defined at this step ${JSON.stringify(g)}`);if(!g.$bzId)throw new Error("[internal error] BzId not found");let S=q(t,g),{dataFields:C,roleFields:A,linkFields:O,usedFields:x}=ue(S,g),W=()=>{if(g.$op==="create"||g.$op==="delete")return g.$op;if(g.$op==="update"){let D=x.filter(E=>C?.includes(E)),F=x.filter(E=>A?.includes(E)),Q=x.filter(E=>O?.includes(E));if(D.length>0)return "update";if(F.length>0||Q.length>0)return "match";throw new Error(`No fields on an $op:"update" for node ${JSON.stringify(g)}`)}return "match"},le={...g.$id&&{$id:g.$id},...g.$tempId&&{$tempId:g.$tempId},...g.$filter&&{$filter:g.$filter},$thing:g.$thing,...g.$thingType&&{$thingType:g.$thingType},...shake(pick(g,C||[""])),$op:W(),$bzId:g.$bzId};u(le);let K=g[Be];if(K?.fieldType==="linkField"){if((g.$op==="link"||g.$op==="unlink")&&(g.$id||g.$filter)){if(g.$tempId)throw new Error("can't specify a existing and a new element at once. Use an id/filter or a tempId");d.push({...g,$op:"match"});}let D=K.relation===g.$thing,F=D?g.$bzId:`LT_${v4()}`,E=ar(c,B,w).$bzId;if(!E)throw new Error("No parent id found");let b=()=>{if(g.$op==="delete")return D?"match":"delete";if(g.$op==="unlink")return D?"unlink":"delete";if(g.$op==="link"||g.$op==="create")return D?"link":"create";if(g.$op==="replace")throw new Error("Unsupported: Nested replaces not implemented yet");return "match"},M=q(t,{$thing:K.relation,$thingType:"relation"});if(!Object.keys(M.roles).includes(K.plays))throw new Error(`[Wrong format] Field ${K.plays} is not a role of relation ${K.relation}`);let k={$bzId:F,$thing:K.relation,$thingType:"relation",...g.$tempId?{$tempId:g.$tempId}:{},$op:b(),...D?{}:{[K.path]:g.$bzId},[K.plays]:E,[Be]:K,[Se]:"linkField"};$(k),(g.$op==="unlink"||b()==="unlink")&&D&&$({$thing:K.relation,$thingType:"relation",$bzId:F,$op:"match",[K.plays]:E,[Be]:K,[Se]:"linkField"});}if(g.$thingType==="relation"){let D=We(g,(E,b)=>A.includes(E)),F=mapEntries(D,(E,b)=>isArray(b)?[E,b]:isObject(b)?[E,b.$bzId]:[E,b]),Q=We(m,(E,b)=>E.startsWith("$")||E.startsWith("Symbol"));if(Object.keys(D).filter(E=>!E.startsWith("$")).length>0){if(g.$op==="create"||g.$op==="delete"){let E=()=>{if(g.$op==="create")return "link";if(g.$op==="delete")return "match";throw new Error("Unsupported parent of edge op")},b=q(t,g).roles,M=mapEntries(F,(k,L)=>{let N=b[k]?.cardinality;if(!N)throw new Error(`Role ${k} not found in schema`);if(Array.isArray(L)){if(N==="ONE"){if(L.length>1)throw new Error(`[Error] Role ${k} is not a MANY relation`);return [k,L[0].$bzId||L[0]]}return [k,L.map(J=>J.$bzId||J)]}return [k,L.$bzId||L]}),R={...Q,$thing:g.$thing,$thingType:"relation",$op:E(),...M,$bzId:g.$bzId,[Se]:"roleField"};$(R);return}if(g.$op==="match"||g.$op==="update"&&Object.keys(D).length>0){let E=0;Object.entries(D).forEach(([b,M])=>{let R=isArray(M)?M:[M],k=L=>L==="create"||L==="replace"?"link":L;R.forEach(L=>{if(!L)return;let N=k(L.$op);if(N==="replace")throw new Error("Not supported yet: replace on roleFields");if(N==="unlink"&&E>0)throw E+=1,new Error("Not supported yet: Cannot unlink more than one role at a time, please split into two mutations");let J={...Q,$thing:g.$thing,$thingType:"relation",$op:N==="delete"?"unlink":N,[b]:L.$bzId,$bzId:g.$bzId,[Se]:"roleField"};$(J);});});}}}}}),[d,a]},[i,o]=r(e),n=i.reduce((c,d)=>{if(!d.$bzId)return [...c,d];let a=c.findIndex(f=>f.$bzId===d.$bzId);if(a===-1)return [...c,d];if(c[a].$op==="create"&&d.$op==="match")return c;if(c[a].$op==="match"&&(d.$op==="create"||d.$op==="match"))return [...c.slice(0,a),d,...c.slice(a+1)];if(c[a].$op==="update"&&d.$op==="update")return [...c.slice(0,a),{...c[a],...d},...c.slice(a+1)];if(c[a].$op==="update"&&d.$op==="match"||c[a].$op==="match"&&d.$op==="update")return [...c.slice(0,a),{...c[a],...d,$op:"update"},...c.slice(a+1)];if(c[a].$op==="delete"&&d.$op==="delete"){if(JSON.stringify(c[a].$filter)===JSON.stringify(d.$filter))return c;throw new Error(`[Wrong format] Can't delete the same thing with different filters. Existing: ${c[a].$filter}. Current: ${d.$filter}`)}throw new Error(`[Wrong format] Wrong operation combination for $tempId/$id "${d.$tempId||d.$id}". Existing: ${c[a].$op}. Current: ${d.$op}`)},[]),l=o.reduce((c,d)=>{let a=c.find(f=>(f.$id&&f.$id===d.$id||f.$bzId&&f.$bzId===d.$bzId)&&f.$thing===d.$thing&&f.$op===d.$op);if(a){let f={...a};return Object.keys(d).forEach($=>{if(typeof $=="symbol"||$.startsWith("$"))return;let y=a[$],m=d[$];Array.isArray(y)&&Array.isArray(m)?f[$]=Array.from(new Set([...y,...m])):!Array.isArray(y)&&Array.isArray(m)?y!==void 0?f[$]=Array.from(new Set([y,...m])):f[$]=m:Array.isArray(y)&&!Array.isArray(m)?m!==void 0&&(f[$]=Array.from(new Set([...y,m]))):y!==null&&m!==null&&y!==void 0&&m!==void 0?f[$]=Array.from(new Set([y,m])):y==null&&(f[$]=m);}),[...c.filter($=>!(($.$id&&$.$id===d.$id||$.$bzId&&$.$bzId===d.$bzId)&&$.$thing===d.$thing&&$.$op===d.$op)),f]}return [...c,d]},[]);n.forEach(c=>{if((c.$thingType==="relation"||"relation"in c)&&l.filter(d=>d.$bzId===c.$bzId||d.$tempId&&d.$tempId===c.$tempId).length===0){if(c.$op==="delete"||c.$op==="match"||c.$op==="update")return;throw new Error(`[Wrong format] Can't create a relation without any player. Node: ${JSON.stringify(wr(c))}`)}});let s=[...n,...l],h=new Set(s.filter(c=>c.$tempId).map(c=>c.$tempId)),p=Array.from(h).filter(c=>!s.some(d=>d.$tempId===c&&d.$op==="create"));if(p.length>0)throw new Error(`Can't link a $tempId that has not been created in the current mutation: ${p.join(", ")}`);return {mergedThings:n,mergedEdges:l}};var Bt=e=>{if(isDate(e))return {type:"datetime",value:e.toISOString().replace("Z","")};if(typeof e=="string")return {type:"string",value:`"${e}"`};if(typeof e=="number")return e%1!==0?{type:"double",value:e}:{type:"long",value:e};if(typeof e=="boolean")return {type:"boolean",value:e};throw new Error(`Unsupported type ${typeof e}`)};var Rr=async(e,t,r)=>{let i=a=>{let f=a.$op,u=`$${a.$bzId}`,$=q(r,a),{idFields:y,defaultDBConnector:m}=$,B=m?.path||a.$thing,w=a.$id,g=y?.[0],S=listify(a,(D,F)=>{if(D.startsWith("$")||D.startsWith("%")||D===g||F===void 0||F===null)return "";let Q=$.dataFields?.find(M=>M.path===D);if(!Q?.path)return "";let b=Q.dbPath;if(["TEXT","ID","EMAIL","JSON"].includes(Q.contentType))return `has ${b} '${F}'`;if(["NUMBER","BOOLEAN"].includes(Q.contentType))return `has ${b} ${F}`;if(Q.contentType==="DATE"){if(Number.isNaN(F.valueOf()))throw new Error("Invalid format, Nan Date");return F instanceof Date?`has ${b} ${F.toISOString().replace("Z","")}`:`has ${b} ${new Date(F).toISOString().replace("Z","")}`}if(Q.contentType==="FLEX"){let M=`bza${nanoid()}`,R=isArray(F)?F.map(k=>Bt(k)):Bt(F);if(Array.isArray(R))throw new Error("Array in FLEX fields not supported yet");return `has ${b} $${M}; $${M} '${M}' isa ${b}, has ${R.type}Attribute ${R.value}`}throw new Error(`Unsupported contentType ${Q.contentType}`)}).filter(D=>D),C=`${u}-atts`,A=listify(a,D=>{if(D.startsWith("$")||D.startsWith("%")||D===g)return "";let F=$.dataFields?.find(b=>b.path===D);if(!F?.path)return "";let E=F.dbPath;return `{${C} isa ${E};}`}).filter(D=>D),O=isArray(w)?`like '${w.join("|")}'`:`'${w}'`,x=w?[`has ${g} ${O}`]:[],W=[...x,...S].filter(D=>D).join(","),le=()=>{if(f==="delete"||f==="unlink"||f==="match")return `${u} isa ${[B,...x].filter(D=>D).join(",")};`;if(f==="update"){if(!A.length)throw new Error("update without attributes");return `${u} isa ${[B,...x].filter(D=>D).join(",")}, has ${C};
37
37
  ${A.join(" or ")};`}return ""},K=()=>f==="update"||f==="link"||f==="match"?`${u} isa ${[B,...x].filter(D=>D).join(",")};`:"";if(Ue(a))return {op:f,deletionMatch:le(),insertionMatch:K(),insertion:f==="create"?`${u} isa ${[B,W].filter(D=>D).join(",")};`:f==="update"&&S.length?`${u} ${S.join(",")};`:"",deletion:f==="delete"?`${u} isa ${B};`:f==="update"&&A.length?`${u} has ${C};`:""};throw new Error("in attributes")},o=a=>{let f=a.$op,u=q(r,a),$=`$${a.$bzId}`,y=a.$id,m=u.defaultDBConnector?.path||a.$thing,B="roles"in u?listify(u.roles,F=>F):[],w="roles"in u?mapEntries(u.roles,(F,Q)=>[F,Q.dbConnector?.path||F]):{},g=listify(a,(F,Q)=>{if(!B.includes(F))return null;if(!("roles"in u))throw new Error("This should have roles! ");let E=w[F];return Array.isArray(Q)?Q.map(b=>({path:E,id:b})):{path:E,id:Q}}).filter(F=>F).flat(),S=g.map(F=>{if(!F?.path)throw new Error("Object without path");return `${F.path}: $${F.id}`}),C=g.length>0?`( ${S.join(" , ")} )`:"",A=a[Se];if(!A)throw new Error("[internal error] Symbol edgeType not defined");let O=C?`${$} ${C} ${A==="linkField"||f==="delete"||f==="unlink"?`isa ${m}`:""}`:"",x=`${$} ${A==="linkField"||f==="delete"?`isa ${m}`:""}`,W=()=>O?f==="link"?`${O};`:f==="create"?`${O}, has id '${y}';`:"":"",le=()=>O&&f==="match"?`${O};`:"",K=()=>O?f==="delete"?`${O};`:f==="match"?`${O};`:"":"",D=()=>O?f==="delete"?`${x};`:f==="unlink"?`${$} ${C};`:"":"";return {deletionMatch:K(),insertionMatch:le(),deletion:D(),insertion:W(),op:""}},n=(a,f)=>{let u=f==="edges"?o:i;if(Array.isArray(a))return a.map(g=>{let{preDeletionBatch:S,insertionMatch:C,deletionMatch:A,insertion:O,deletion:x}=u(g);return shake({preDeletionBatch:S,insertionMatch:C,deletionMatch:A,insertion:O,deletion:x},W=>!W)}).filter(g=>g);let{preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:w}=u(a);return shake({preDeletionBatch:$,insertionMatch:y,deletionMatch:m,insertion:B,deletion:w},g=>!g)},l=n(e),s=Array.isArray(l)?l:[l],h=n(t,"edges"),p=Array.isArray(h)?h:[h],c=[...s,...p];return shake({insertionMatches:c.map(a=>a.insertionMatch).join(" ").trim(),deletionMatches:c.map(a=>a.deletionMatch).join(" ").trim(),insertions:c.map(a=>a.insertion).join(" ").trim(),deletions:c.map(a=>a.deletion).join(" ").trim()},a=>!a)};var qe={};function X(e){return {enumerable:!0,value:e}}function Cr(e){return {enumerable:!0,writable:!0,value:e}}var fi=()=>!0,Dr=()=>({}),Ir=e=>e,$i=(e,t,r,i)=>e.apply(r,i)&&t.apply(r,i),mi=(e,t,r,[i,o])=>t.call(r,e.call(r,i,o),o),be=(e,t)=>Object.freeze(Object.create(e,t));function Ar(e,t,r){return e.reduce((i,o)=>function(...n){return r(i,o,this,n)},t)}function kr(e){return be(this,{fn:X(e)})}var Or={},V=kr.bind(Or);var Pr={},bt=kr.bind(Pr);function et(e,t){return t.filter(r=>e.isPrototypeOf(r))}function qr(e,t,...r){let i=Ar(et(Pr,r).map(n=>n.fn),fi,$i),o=Ar(et(Or,r).map(n=>n.fn),Ir,mi);return be(this,{from:X(e),to:X(t),guards:X(i),reducers:X(o)})}var xr={},jr={},H=qr.bind(xr);qr.bind(jr,null);function yi(e,t,r){return Mt(t,e,r,this.immediates)||e}function Nr(e){let t=new Map;for(let r of e)t.has(r.from)||t.set(r.from,[]),t.get(r.from).push(r);return t}var gi={enter:Ir};function he(...e){let t=et(xr,e),r=et(jr,e),i={final:X(e.length===0),transitions:X(Nr(t))};return r.length&&(i.immediates=X(r),i.enter=X(yi)),be(gi,i)}var Ei={enter(e,t,r){let i=this.fn.call(t,t.context,r);return wt.isPrototypeOf(i)?be(Wr,{machine:X(i),transitions:X(this.transitions)}).enter(e,t,r):(i.then(o=>t.send({type:"done",data:o})).catch(o=>t.send({type:"error",error:o})),e)}},Wr={enter(e,t,r){if(t.child=ye(this.machine,i=>{t.onChange(i),t.child==i&&i.machine.state.value.final&&(delete t.child,t.send({type:"done",data:i.context}));},t.context,r),t.child.machine.state.value.final){let i=t.child.context;return delete t.child,Mt(t,e,{type:"done",data:i},this.transitions.get("done"))}return e}};function Z(e,...t){let r=X(Nr(t));return wt.isPrototypeOf(e)?be(Wr,{machine:X(e),transitions:r}):be(Ei,{fn:X(e),transitions:r})}var wt={get state(){return {name:this.current,value:this.states[this.current]}}};function we(e,t,r=Dr){return typeof e!="string"&&(r=t||Dr,t=e,e=Object.keys(t)[0]),qe._create&&qe._create(e,t),be(wt,{context:X(r),current:X(e),states:X(t)})}function Mt(e,t,r,i){let{context:o}=e;for(let{to:n,guards:l,reducers:s}of i)if(l(o,r)){e.context=s.call(e,o,r);let h=t.original||t,p=be(h,{current:X(n),original:{value:h}});qe._onEnter&&qe._onEnter(t,n,e.context,o,r);let c=p.state.value;return e.machine=p,e.onChange(e),c.enter(p,e,r)}}function Bi(e,t){let r=t.type||t,{machine:i}=e,{value:o,name:n}=i.state;return o.transitions.has(r)?Mt(e,i,t,o.transitions.get(r))||i:(qe._send&&qe._send(r,n),i)}var Fi={send(e){Bi(this,e);}};function ye(e,t,r,i){let o=Object.create(Fi,{machine:Cr(e),context:Cr(e.context(r,i)),onChange:X(t)});return o.send=o.send.bind(o),o.machine=o.machine.state.value.enter(o.machine,o,i),o}var Hr=(e,t)=>{if(!t)return;let r=wi(t);return Mi(r,e.query)},wi=e=>produce(e,t=>traverse(t,({value:r})=>{isObject(r);})),Mi=(e,t)=>produce(e,r=>traverse(r,({value:i})=>{if(isObject(i)){let o=i;Object.keys(o).forEach(n=>{(o[n]===void 0||o[n]===null||isArray(o[n])&&o[n].length===0)&&(t?.returnNulls?o[n]=null:delete o[n]),o[n]===void 0&&delete o[n];}),Object.getOwnPropertySymbols(o).forEach(n=>{delete o[n];}),t?.noMetadata===!0&&Object.keys(o).forEach(n=>{n.startsWith("$")&&delete o[n];});}}));var Ur=(e,t)=>{for(let o of e)if(!("$entity"in o)&&!("$relation"in o)&&(!("$thing"in o)||!("$thingType"in o)))throw new Error("No entity specified in query");let r=Array.isArray(e)?e:[e];return produce(r,o=>traverse(o,n=>{let{value:l,meta:s}=n,h=l;if(isObject(h)){if(h.$id){if(s.nodePath?.includes(".$filter"))return;let p=h.$entity||h.$relation?h:{[`$${h.$thingType}`]:h.$thing},c=q(t,p);if(!c?.name)throw new Error(`Schema not found for ${h.$thing}`);if(h.$path=c.name,Array.isArray(h.$id)||(h.$filterByUnique=!0),c?.idFields?.length!==1)throw new Error("Multiple ids not yet enabled / composite ids")}else if("$entity"in h||"$relation"in h||"$thing"in h){let p=q(t,h);if(!p?.name)throw new Error(`Schema not found for ${h.$thing}`);h.$path=p.name;}if(h.$entity?(h.$thing=h.$entity,h.$thingType="entity",delete h.$entity):h.$relation&&(h.$thing=h.$relation,h.$thingType="relation",delete h.$relation),isObject(h)&&"$thing"in h&&h.$thing){let p=h.$entity||h.$relation?h:{[`$${h.$thingType}`]:h.$thing};h[te]=s.nodePath;let c=q(t,p);if(h.$filter&&(h.$filterByUnique=Lt(h.$filter,c),h.$filter=xe(h.$filter,h.$thing,t)),h.$fields){h.$fields.some(f=>c?.idFields?.includes(f?.$path||f))||(h.$fields=[...h.$fields,...Array.isArray(c.idFields)?c.idFields:[]],h.$idNotIncluded=!0);let a=h.$fields?.flatMap(f=>{let u=Kr(f,c,t);return Array.isArray(u)?u:[u]}).filter(Boolean);h.$fields=a;}else {let a=St(c)?.flatMap(f=>{let u=Kr(f,c,t);return Array.isArray(u)?u:[u]}).filter(Boolean);h.$fields=a;}h.$excludedFields&&(h.$fields=h.$fields.filter(d=>tt(c,d)?!0:!h.$excludedFields.includes(d.$path)));}}}))},St=e=>{let t=e.dataFields?.map(n=>n.path)||[],r=e.linkFields?.map(n=>n.path)||[],i=Object.keys(e.roles||{})||[];return [...t,...r,...i]},Lt=(e,t)=>Object.keys(e||{}).some(i=>{if(!Array.isArray(e[i])){let o=t.idFields?.includes(i),n=t.dataFields?.some(s=>(s.dbPath===i||s.path===i)&&s?.validations?.unique),l=i==="$id"&&!Array.isArray(e[i]);return o||n||l}return !1}),tt=(e,t)=>typeof t=="string"?e.idFields?.includes(t):e.idFields?.includes(t.$path),Si=e=>{let{field:t,fieldStr:r,$justId:i,dbPath:o,isVirtual:n,fieldSchema:l}=e;return {$path:r,$dbPath:o,$thingType:"attribute",$as:t.$as||r,$var:r,$fieldType:"data",$justId:i,$id:t.$id,$isVirtual:n,[ie]:l}},Li=e=>{let{field:t,fieldStr:r,linkField:i,$justId:o,dbPath:n,schema:l,fieldSchema:s}=e,{target:h,oppositeLinkFieldsPlayedBy:p}=i;return p.map(c=>{let d=h==="role"?c.thingType:"relation",a=h==="role"?c.thing:i.relation,f={[`$${d}`]:a},u=q(l,f),$=t?.$fields?.filter(B=>tt(u,B)).length===0,y=[];if(typeof t!="string")if(t.$fields)if($){let B=u.idFields||[];y=[...t.$fields,...B];}else y=t.$fields;else y=St(u);else y=["id"];t.$excludedFields&&(y=y.filter(B=>tt(u,B)?!0:!t.$excludedFields.includes(B.$path)));let m=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...xe(t.$filter,a,l)}:void 0;return {$thingType:d,$plays:i.plays,$playedBy:c,$path:c.path,$dbPath:n,$as:t.$as||r,$var:r,$thing:a,$fields:y,$excludedFields:t.$excludedFields,$fieldType:"link",$target:h,$intermediary:c.relation,$justId:o,$id:t.$id,$filter:m,$idNotIncluded:$,$filterByUnique:Lt(t.$filter,u),$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:s}})},Ri=e=>{let{field:t,fieldStr:r,roleField:i,$justId:o,dbPath:n,schema:l,fieldSchema:s}=e;return i.playedBy.map(h=>{let{thing:p,thingType:c,relation:d}=h,a={[`$${c}`]:p},f=q(l,a),u=t?.$fields?.filter(m=>f?.idFields?.includes(m)||f?.idFields?.includes(m.$path)).length===0,$=[];if(typeof t!="string")if(t.$fields)if(u){let m=f.idFields||[];$=[...t.$fields,...m];}else $=t.$fields;else $=St(f);else $=["id"];t.$excludedFields&&($=$.filter(m=>tt(f,m)?!0:!t.$excludedFields.includes(m.$path)));let y=t.$id||t.$filter?{...t.$id?{$id:t.$id}:{},...xe(t.$filter,p,l)}:void 0;return {$thingType:c,$path:r,$dbPath:n,$as:t.$as||r,$var:r,$thing:p,$fields:$,$excludedFields:t.$excludedFields,$fieldType:"role",$intermediary:d,$justId:o,$id:t.$id,$filter:y,$idNotIncluded:u,$filterByUnique:Lt(t.$filter,f),$playedBy:h,$sort:t.$sort,$offset:t.$offset,$limit:t.$limit,[ie]:s}})},Kr=(e,t,r)=>{let i=typeof e=="string"?e:e.$path,o=typeof e=="string",n=t.dataFields?.find(h=>h.path===i),l=t.linkFields?.find(h=>h.path===i),s=t.roles?.[i];if(n){let h=!!n.isVirtual&&!!n.default;return Si({field:e,fieldStr:i,$justId:o,dbPath:n.dbPath,isVirtual:h,fieldSchema:n})}else {if(l)return Li({field:e,fieldStr:i,linkField:l,$justId:o,dbPath:l.path,schema:r,fieldSchema:l});if(s)return Ri({field:e,fieldStr:i,roleField:s,$justId:o,dbPath:i,schema:r,fieldSchema:s})}return null},xe=(e,t,r)=>{if(e==null)return e;let i=isArray(e),n=(i?e:[e]).map(l=>Object.keys(l).reduce((p,c)=>{let d=l[c],a=isArray(d)?d:[d];if(c.startsWith("$"))["$id","$thing"].includes(c)?p[c]=d:p[c]=xe(d,t,r);else {let f=t in r.entities?r.entities[t]:r.relations[t],[u,$]=Ie(f,c);if(u==="dataField")p[c]=d;else if(u==="linkField"||u==="roleField"){let y=$,[m]=y.$things;return a.every(B=>typeof B=="string")?p[c]={$id:a,$thing:m}:a.every(B=>isObject(B))&&(p[c]=isArray(d)?{$or:xe(d,m,r)}:xe(d,m,r)),p}else throw new Error(`Field ${c} not found in schema of ${t}`)}return p},{}));return i?n.length===1?n[0]:{$or:n}:n[0]};var Jr=async(e,t,r)=>r?(n=>produce(n,l=>traverse(l,({value:s})=>{if(isObject(s)){let h=s;if(!h.$thing)return;if(h.$thing){let p=q(e,h),{virtualFields:c}=p,d=h[te];if(!d)throw new Error("[Internal] QueryPath is missing");let a=getNodeByPath(t,d),f=a.$fields.map($=>$.$path),u=a.$excludedFields;c.forEach($=>{if(u?.includes($)||f.length>0&&!f.includes($))return;let y=p.dataFields?.find(m=>m.path===$);if(y?.default){let m=Oe({currentThing:h,fieldSchema:y,mandatoryDependencies:!0});h[$]=m;}else if(h[$]===void 0)throw new Error(`[Internal] Virtual field: No db value found for virtual field: ${$}`)}),u&&u.forEach($=>{if(typeof $!="string")throw new Error("[Internal] ExcludedField is not a string");delete h[$];});}}})))(r):void 0;var vr=e=>e.replace(/`/g,""),ki=[" ","-","+","*","/","=","!","@","#","$","%","^","&","(",")","[","]","{","}","|","\\",";",":","'",'"',",","<",">",".","?","~","`"],rt=e=>ki.some(t=>e.includes(t))?`\u27E8\`${e}\`\u27E9`:e;var Yr=e=>{let{queries:t,schema:r}=e;return t.map(i=>Pi({query:i,schema:r}))},Pi=e=>{let{query:t,schema:r}=e,{$thing:i,$fields:o,$filter:n,$offset:l,$limit:s,$sort:h}=t;if(o.length===0)return null;let p=[];p.push("SELECT");let c=Rt({parentQuery:t,queries:o,level:1,schema:r});c&&p.push(c);let d=r.entities[i]||r.relations[i];if(!d)throw new Error(`Schema for ${i} not found`);let f=(d.subTypes?[i,...d.subTypes]:[i]).map(u=>rt(u));if(t.$id)if(typeof t.$id=="string")p.push(`FROM ${f.map(u=>`${u}:\`${t.$id}\``).join(",")}`);else if(isArray(t.$id)){let u=t.$id,$=f.flatMap(y=>u?.map(m=>`${y}:\`${m}\``));p.push(`FROM ${$.join(",")}`);}else throw new Error("Invalid $id");else p.push(`FROM ${f.join(",")}`);if(n){let u=ge(n,i,r),$=Re(u);p.push(`WHERE ${$}`);}return h&&p.push(Gr(h)),typeof s=="number"&&p.push(`LIMIT ${s}`),typeof l=="number"&&p.push(`START ${l}`),p.join(`
38
38
  `)},Rt=e=>{let{queries:t,schema:r,level:i,parentQuery:o}=e,n=[],l=o[te];return n.push(T(`"${l}" as \`$$queryPath\``,i)),n.push(T("meta::id(id) as `$id`",i)),n.push(T("meta::tb(id) as `$thing`",i)),t.forEach(s=>{let h=qi({query:s,level:i,schema:r});h&&n.push(h);}),n.length===0?null:n.join(`,
39
39
  `)},qi=e=>{let{query:t,schema:r,level:i}=e;return t.$fieldType==="data"?xi({query:t,level:i}):t.$fieldType==="link"?ji({query:t,level:i,schema:r}):t.$fieldType==="role"?Ni({query:t,level:i,schema:r}):null},xi=e=>{let{query:t,level:r}=e;return t.$isVirtual?null:t.$path==="id"?T(`meta::id(${t.$path}) AS ${t.$as}`,r):t.$path===t.$as?T(`\`${t.$path}\``,r):T(`\`${t.$path}\` AS \`${t.$as}\``,r)},ji=e=>{let{query:t,schema:r,level:i}=e,{$fields:o,$filter:n,$offset:l,$limit:s,$sort:h}=t;if(o.length===0)return null;let p=[];p.push(T("(",i));let c=i+1;p.push(T("SELECT",c));let d=Rt({parentQuery:t,queries:o,level:c+1,schema:r});d&&p.push(d);let a=t[ie][me].queryPath;if(p.push(T(`FROM ${a}`,c)),n){let f=ge(n,t.$thing,r),u=Re(f);p.push(`WHERE ${u}`);}return h&&p.push(T(Gr(h),c)),typeof s=="number"&&p.push(T(`LIMIT ${s}`,c)),typeof l=="number"&&p.push(T(`START ${l}`,c)),p.push(T(`) AS \`${t.$as}\``,i)),p.join(`